From b8fadffc4b9d7369ef0da31dd93fab4a527665db Mon Sep 17 00:00:00 2001 From: Theodore Ni <3806110+tjni@users.noreply.github.com> Date: Thu, 24 Jun 2021 15:32:28 -0700 Subject: [PATCH] Use the Java 7 diamond operator everywhere. (#643) --- CHANGELOG.md | 1 + .../hashing/ConsistentHashRingBenchmark.java | 4 +- .../d2/contrib/RouteLookupClient.java | 2 +- .../d2/contrib/TestRouteLookupClient.java | 13 +- .../test/java/com/linkedin/d2/D2BaseTest.java | 14 +- .../TestD2ConfigWithSingleZKFailover.java | 8 +- .../discovery/TestPartitionsWithZKQuorum.java | 10 +- .../loadbalancer/TestD2ZKQuorumFailover.java | 4 +- .../java/com/linkedin/d2/quorum/ZKQuorum.java | 12 +- .../d2/backuprequests/LatencyMetric.java | 4 +- .../linkedin/d2/balancer/D2ClientBuilder.java | 2 +- .../clients/BackupRequestsClient.java | 2 +- .../clients/DegraderTrackerClientImpl.java | 2 +- .../d2/balancer/config/ConfigWriter.java | 6 +- .../balancer/config/PartitionDataFactory.java | 2 +- .../properties/AllowedClientPropertyKeys.java | 2 +- .../ServicePropertiesJsonSerializer.java | 2 +- .../d2/balancer/properties/UriProperties.java | 11 +- .../UriPropertiesJsonSerializer.java | 13 +- .../properties/UriPropertiesMerger.java | 4 +- .../balancer/servers/ZKUriStoreFactory.java | 4 +- .../servers/ZooKeeperConnectionManager.java | 4 +- .../d2/balancer/servers/ZooKeeperServer.java | 2 +- .../AbstractLoadBalancerSubscriber.java | 4 +- .../balancer/simple/SimpleLoadBalancer.java | 16 +- .../simple/SimpleLoadBalancerState.java | 8 +- .../strategies/LoadBalancerStrategy.java | 2 +- .../PointBasedConsistentHashRingFactory.java | 2 +- .../degrader/DegraderLoadBalancerState.java | 6 +- .../DegraderLoadBalancerStrategyV3.java | 5 +- .../PartitionDegraderLoadBalancerState.java | 2 +- .../d2/balancer/util/HostToKeyMapper.java | 26 +- .../balancer/util/LoadBalancerClientCli.java | 43 +- .../d2/balancer/util/LoadBalancerUtil.java | 7 +- .../d2/balancer/util/MapKeyResult.java | 2 +- .../util/hashing/ConsistentHashKeyMapper.java | 18 +- .../util/hashing/ConsistentHashRing.java | 14 +- .../hashing/DistributionNonDiscreteRing.java | 2 +- .../util/hashing/RingBasedUriMapper.java | 2 +- .../util/hashing/StaticRingProvider.java | 16 +- .../balancer/util/hashing/URIRegexHash.java | 2 +- .../d2/balancer/zkfs/ZKFSLoadBalancer.java | 2 +- .../ZKFSTogglingLoadBalancerFactoryImpl.java | 11 +- .../discovery/event/PropertyEventBusImpl.java | 13 +- .../discovery/event/PropertyEventThread.java | 2 +- .../stores/toggling/TogglingPublisher.java | 6 +- .../util/AbstractPropertyStoreAsync.java | 6 +- .../discovery/stores/zk/RetryZooKeeper.java | 4 +- .../d2/discovery/stores/zk/ZKConnection.java | 4 +- .../zk/ZooKeeperChildrenDataPublisher.java | 12 +- .../stores/zk/ZooKeeperEphemeralStore.java | 12 +- .../linkedin/d2/discovery/util/D2Config.java | 48 +- .../DegraderLoadBalancerStrategyV3Jmx.java | 2 +- .../java/com/linkedin/d2/jmx/JmxManager.java | 6 +- .../d2/jmx/SimpleLoadBalancerStateJmx.java | 4 +- .../d2/jmx/ZooKeeperAnnouncerJmx.java | 8 +- .../linkedin/d2/jmx/ZooKeeperServerJmx.java | 8 +- .../d2/balancer/LoadBalancerTestState.java | 44 +- .../PartitionedLoadBalancerTestState.java | 16 +- .../balancer/clients/DynamicClientTest.java | 4 +- .../d2/balancer/clients/LazyClientTest.java | 4 +- .../d2/balancer/clients/RetryClientTest.java | 32 +- .../RewriteLoadBalancerClientTest.java | 25 +- ...teLoadBalancerClientTestStreamRequest.java | 25 +- .../clients/TestBackupRequestsClient.java | 2 +- .../balancer/clients/TrackerClientTest.java | 10 +- .../ClientServiceConfigValidatorTest.java | 16 +- .../ClusterPropertiesSerializerTest.java | 10 +- .../ServicePropertiesSerializerTest.java | 4 +- .../UriPropertiesSerializerTest.java | 24 +- .../properties/UriPropertiesTest.java | 12 +- .../balancer/servers/ZooKeeperServerTest.java | 28 +- .../ZookeeperConnectionManagerTest.java | 14 +- .../simple/LoadBalancerSimulator.java | 2 +- .../simple/SimpleLoadBalancerDelayTest.java | 8 +- .../simple/SimpleLoadBalancerStateTest.java | 190 +++--- .../simple/SimpleLoadBalancerStrawMan.java | 11 +- .../simple/SimpleLoadBalancerTest.java | 201 +++--- .../d2/balancer/simulator/R2D2Server.java | 18 +- .../SimpleLoadBalancerSimulation.java | 49 +- .../degrader/DegraderConfigFactoryTest.java | 2 +- .../DegraderLoadBalancerStateTest.java | 8 +- ...egraderLoadBalancerStrategyConfigTest.java | 12 +- .../degrader/DegraderLoadBalancerTest.java | 68 +-- .../random/RandomLoadBalancerTest.java | 2 +- .../d2/balancer/util/HostToKeyMapperTest.java | 50 +- .../balancer/util/LoadBalancerEchoClient.java | 59 +- .../balancer/util/LoadBalancerEchoServer.java | 18 +- .../linkedin/d2/balancer/util/TestHelper.java | 8 +- .../hashing/ConsistentHashKeyMapperTest.java | 66 +- .../ConsistentHashRingIteratorTest.java | 10 +- .../util/hashing/ConsistentHashRingTest.java | 24 +- .../DistributionNonDiscreteRingTest.java | 2 +- .../MPConsistentHashRingIteratorTest.java | 14 +- .../d2/balancer/zkfs/ConnectionLostTest.java | 6 +- .../linkedin/d2/balancer/zkfs/ZKFSTest.java | 79 ++- .../event/PropertyEventBusImplTest.java | 4 +- .../discovery/event/PropertyEventBusTest.java | 10 +- .../event/PropertyEventTestSubscriber.java | 2 +- .../d2/discovery/event/PublisherTest.java | 2 +- .../event/SynchronousExecutorService.java | 2 +- .../ZooKeeperEphemeralStorePublisherTest.java | 4 +- .../ZooKeeperPermanentStorePublisherTest.java | 4 +- .../d2/discovery/stores/mock/MockStore.java | 4 +- .../discovery/stores/mock/MockStoreTest.java | 2 +- .../stores/toggling/TogglingStoreTest.java | 2 +- .../stores/zk/RetryZooKeeperTest.java | 10 +- .../zk/SharedZkConnectionProviderTest.java | 44 +- .../stores/zk/SymlinkAwareZooKeeperTest.java | 38 +- .../stores/zk/TestZKPersistentConnection.java | 2 +- .../ZooKeeperChildrenDataPublisherTest.java | 30 +- ...eperEphemeralStoreChildrenWatcherTest.java | 6 +- ...StoreChildrenWatcherWithFIleStoreTest.java | 6 +- .../zk/ZooKeeperEphemeralStoreStrawMan.java | 16 +- .../zk/ZooKeeperEphemeralStoreTest.java | 4 +- .../zk/ZooKeeperPermanentStoreStrawMan.java | 10 +- .../zk/ZooKeeperPermanentStoreTest.java | 4 +- .../d2/discovery/util/D2ConfigTestUtil.java | 54 +- .../d2/discovery/util/TestD2Config.java | 481 ++++++++------- .../d2/discovery/util/TestHashFunctions.java | 10 +- .../impl/BaseDarkClusterDispatcherImpl.java | 2 +- .../avro/generator/AvroSchemaGenerator.java | 8 +- .../linkedin/data/avro/AvroOverrideMap.java | 2 +- .../linkedin/data/avro/DataTranslator.java | 12 +- .../data/avro/SchemaToAvroJsonEncoder.java | 4 +- .../com/linkedin/data/avro/util/AvroUtil.java | 8 +- .../data/avro/TestAvroOverrideFactory.java | 2 +- .../data/transform/FILOScheduler.java | 2 +- .../data/transform/ImmutableList.java | 2 +- .../data/transform/InterpreterContext.java | 4 +- .../data/transform/ProjectionUtil.java | 2 +- .../data/transform/filter/AbstractFilter.java | 2 +- .../filter/DefaultNodeModeCalculator.java | 2 +- .../transform/filter/MaskComposition.java | 2 +- .../transform/filter/request/MaskTree.java | 2 +- .../linkedin/data/transform/patch/Patch.java | 4 +- .../patch/validator/PatchFilterValidator.java | 2 +- .../data/transform/TestProjectionUtil.java | 24 +- .../validator/TestPatchFilterValidator.java | 3 +- .../antlr/com/linkedin/data/grammar/Pdl.g4 | 2 +- .../java/com/linkedin/data/ByteString.java | 6 +- .../main/java/com/linkedin/data/DataList.java | 2 +- .../main/java/com/linkedin/data/DataMap.java | 2 +- .../linkedin/data/InstrumentationUtil.java | 2 +- .../data/codec/AbstractJacksonDataCodec.java | 2 +- .../linkedin/data/codec/BsonDataCodec.java | 2 +- .../com/linkedin/data/codec/BufferChain.java | 4 +- .../linkedin/data/codec/PsonDataCodec.java | 3 +- .../data/collections/CheckedList.java | 12 +- .../linkedin/data/collections/CowList.java | 14 +- .../com/linkedin/data/collections/CowMap.java | 16 +- .../com/linkedin/data/collections/CowSet.java | 4 +- .../linkedin/data/collections/CowUtil.java | 6 +- .../data/element/DataElementUtil.java | 4 +- .../java/com/linkedin/data/it/Builder.java | 20 +- .../com/linkedin/data/it/ObjectIterator.java | 2 +- .../data/it/PathMatchesPatternPredicate.java | 6 +- .../java/com/linkedin/data/it/Remover.java | 2 +- .../com/linkedin/data/it/Transformer.java | 14 +- .../linkedin/data/it/ValueAccumulator.java | 10 +- .../data/schema/AbstractSchemaParser.java | 8 +- .../data/schema/DataSchemaConstants.java | 6 +- .../data/schema/DataSchemaTraverse.java | 4 +- .../linkedin/data/schema/DataSchemaUtil.java | 10 +- .../linkedin/data/schema/EnumDataSchema.java | 4 +- .../com/linkedin/data/schema/PathSpec.java | 6 +- .../data/schema/RecordDataSchema.java | 6 +- .../linkedin/data/schema/SchemaParser.java | 10 +- .../data/schema/SchemaToJsonEncoder.java | 2 +- .../annotation/SchemaAnnotationHandler.java | 2 +- .../compatibility/CompatibilityChecker.java | 36 +- .../schema/generator/AbstractGenerator.java | 2 +- .../generator/DefaultSampleDataCallback.java | 4 +- .../generator/SchemaSampleDataGenerator.java | 2 +- .../data/schema/grammar/PdlSchemaParser.java | 2 +- .../resolver/AbstractDataSchemaResolver.java | 6 +- .../resolver/FileDataSchemaResolver.java | 2 +- .../validation/ValidateDataAgainstSchema.java | 4 +- .../schema/validation/ValidationOptions.java | 2 +- .../DataSchemaAnnotationValidator.java | 8 +- .../template/DataObjectToObjectCache.java | 4 +- .../data/template/DataTemplateUtil.java | 4 +- .../data/template/DirectMapTemplate.java | 2 +- .../data/template/DynamicRecordMetadata.java | 4 +- .../template/JacksonDataTemplateCodec.java | 8 +- .../data/template/WrappingArrayTemplate.java | 3 +- .../data/template/WrappingMapTemplate.java | 6 +- .../linkedin/data/transforms/Transforms.java | 10 +- .../main/java/com/linkedin/util/FileUtil.java | 4 +- .../com/linkedin/data/TestByteString.java | 10 +- .../test/java/com/linkedin/data/TestData.java | 22 +- .../test/java/com/linkedin/data/TestUtil.java | 14 +- .../data/codec/CodecDataProviders.java | 2 +- .../linkedin/data/codec/TestBufferChain.java | 4 +- .../data/collections/TestCheckedUtil.java | 10 +- .../data/collections/TestCommonList.java | 24 +- .../data/collections/TestCommonMap.java | 34 +- .../data/collections/TestCowList.java | 6 +- .../linkedin/data/collections/TestCowMap.java | 2 +- .../linkedin/data/collections/TestCowSet.java | 10 +- .../data/collections/TestCowUtil.java | 12 +- .../data/element/TestDataElement.java | 2 +- .../linkedin/data/it/TestDataIterator.java | 48 +- .../com/linkedin/data/it/TestTransformer.java | 42 +- .../data/it/TestValueAccumulator.java | 10 +- .../performance/TestCloudPerformance.java | 2 +- .../TestCompatibilityChecker.java | 10 +- .../generator/TestAbstractGenerator.java | 8 +- .../resolver/TestDataSchemaResolver.java | 4 +- .../data/schema/validator/TestValidator.java | 9 +- .../validator/VisitedTrackingValidator.java | 8 +- .../data/template/TestArrayTemplate.java | 24 +- .../data/template/TestConvertArray.java | 4 +- .../linkedin/data/template/TestCustom.java | 2 +- .../template/TestDataObjectToObjectCache.java | 12 +- .../template/TestDynamicRecordTemplate.java | 34 +- .../data/template/TestMapTemplate.java | 28 +- .../template/TestRecordAndUnionTemplate.java | 4 +- .../util/degrader/CallTrackerImpl.java | 18 +- .../util/degrader/TestCallTracker.java | 4 +- .../linkedin/entitystream/EntityStreams.java | 2 +- .../com/example/d2/server/EchoServer.java | 2 +- .../example/d2/server/ExampleD2Server.java | 2 +- .../example/d2/server/ExampleD2Server.java | 2 +- .../com/example/fortune/impl/FortunesDB.java | 2 +- .../fortune/impl/FortunesResource.java | 2 +- .../example/fortune/impl/FortunesBean.java | 6 +- .../TestSchemaSampleDataGenerator.java | 8 +- .../pegasus/generator/override/TestArray.java | 12 +- .../generator/override/TestCustomPoint.java | 4 +- .../generator/override/TestDeprecated.java | 2 +- .../pegasus/generator/override/TestEnum.java | 2 +- .../pegasus/generator/override/TestMap.java | 13 +- .../pegasus/generator/test/TestArray.java | 12 +- .../generator/test/TestCustomPoint.java | 4 +- .../generator/test/TestDeprecated.java | 2 +- .../pegasus/generator/test/TestEnum.java | 2 +- .../pegasus/generator/test/TestMap.java | 13 +- .../CaseSensitiveFileCodeWriter.java | 2 +- .../pegasus/generator/JavaCodeUtil.java | 4 +- .../generator/JavaDataTemplateGenerator.java | 6 +- .../generator/TemplateSpecGenerator.java | 14 +- .../generator/spec/ClassTemplateSpec.java | 2 +- .../generator/spec/PrimitiveTemplateSpec.java | 2 +- .../generator/spec/RecordTemplateSpec.java | 2 +- .../generator/spec/UnionTemplateSpec.java | 4 +- .../pegasus/gradle/PegasusOptions.java | 6 +- .../pegasus/gradle/PegasusPlugin.java | 2 +- .../linkedin/jersey/api/uri/UriComponent.java | 4 +- .../linkedin/jersey/api/uri/UriTemplate.java | 6 +- .../jersey/api/uri/UriTemplateParser.java | 10 +- .../jersey/core/util/MultivaluedMap.java | 4 +- .../multipart/MultiPartMIMEInputStream.java | 2 +- .../multipart/MultiPartMIMEReader.java | 6 +- .../multipart/MultiPartMIMEUtils.java | 4 +- .../multipart/MultiPartMIMEWriter.java | 4 +- .../multipart/AbstractMIMEUnitTest.java | 4 +- .../multipart/TestMIMEChainingAlternate.java | 4 +- .../multipart/TestMIMEChainingReader.java | 5 +- .../multipart/TestMIMEChainingSinglePart.java | 5 +- .../linkedin/multipart/TestMIMEReader.java | 14 +- ...estMIMEReaderClientCallbackExceptions.java | 6 +- .../multipart/TestMIMEReaderDrain.java | 20 +- .../multipart/TestMIMEReaderExceptions.java | 10 +- .../multipart/TestMIMEReaderR2Error.java | 4 +- .../linkedin/multipart/TestMIMEWriter.java | 22 +- .../AbstractMIMEIntegrationStreamTest.java | 6 +- .../TestMIMEChainingMultipleSources.java | 16 +- .../integ/TestMIMEIntegrationReader.java | 18 +- .../integ/TestMIMEIntegrationReaderDrain.java | 22 +- .../TestMIMEIntegrationReaderWriter.java | 14 +- .../multipart/utils/MIMETestUtils.java | 8 +- .../linkedin/common/callback/Callbacks.java | 2 +- .../common/callback/FutureCallback.java | 6 +- .../common/callback/MultiCallback.java | 2 +- .../com/linkedin/common/util/TestMapUtil.java | 4 +- .../com/linkedin/r2/caprep/ReplayFilter.java | 2 +- .../r2/caprep/db/DirectoryDbSource.java | 2 +- .../linkedin/r2/caprep/db/TransientDb.java | 2 +- .../linkedin/r2/filter/FilterChainImpl.java | 12 +- .../r2/filter/transport/ResponseFilter.java | 2 +- .../r2/message/BaseMessageBuilder.java | 8 +- .../linkedin/r2/message/QueryTunnelUtil.java | 2 +- .../linkedin/r2/message/rest/RestUtil.java | 2 +- .../r2/transport/common/AbstractClient.java | 2 +- .../transport/common/WireAttributeHelper.java | 4 +- .../bridge/client/TransportClientAdapter.java | 8 +- .../bridge/common/TransportResponseImpl.java | 8 +- .../bridge/server/ContextDispatcher.java | 8 +- .../server/TransportCallbackAdapter.java | 4 +- .../server/TransportDispatcherBuilder.java | 10 +- .../server/TransportDispatcherImpl.java | 8 +- .../transport/http/client/AsyncPoolImpl.java | 10 +- .../client/ExponentialBackOffRateLimiter.java | 4 +- .../http/client/TimeoutTransportCallback.java | 2 +- .../http/server/AbstractR2Servlet.java | 2 +- .../transport/http/server/HttpDispatcher.java | 4 +- .../com/linkedin/r2/util/ClosableQueue.java | 4 +- .../r2/util/ConfigValueExtractor.java | 2 +- .../com/linkedin/r2/util/LinkedDeque.java | 2 +- .../java/com/linkedin/r2/util/Timeout.java | 2 +- .../com/linkedin/r2/util/TimeoutRunnable.java | 2 +- .../r2/util/TestConfigValueExtractor.java | 4 +- .../com/linkedin/r2/util/TestLinkedDeque.java | 114 ++-- .../java/test/r2/filter/StreamFilterTest.java | 2 +- .../test/r2/filter/TestFilterChainImpl.java | 8 +- .../test/r2/filter/TestServerRetryFilter.java | 8 +- .../test/r2/message/TestRestBuilders.java | 6 +- .../message/streaming/TestEntityStream.java | 2 +- .../common/TestWireAttributeHelper.java | 12 +- .../transport/http/client/TestAsyncPool.java | 104 ++-- .../transport/http/common/TestHttpBridge.java | 16 +- .../r2/filter/compression/AcceptEncoding.java | 4 +- .../compression/ClientCompressionHelper.java | 4 +- .../r2/filter/compression/EncodingType.java | 2 +- .../compression/ServerCompressionFilter.java | 4 +- .../ServerStreamCompressionFilter.java | 4 +- .../compression/streaming/AcceptEncoding.java | 4 +- .../streaming/BufferedReaderInputStream.java | 2 +- .../compression/streaming/PartialReader.java | 2 +- .../streaming/StreamEncodingType.java | 2 +- .../streaming/StreamingDeflater.java | 2 +- .../TestClientStreamCompressionFilter.java | 2 +- .../stream/TestStreamingCompression.java | 6 +- .../streaming/TestStreamingCompression.java | 6 +- .../r2/integ/TestChannelPoolBehavior.java | 8 +- .../test/java/test/r2/integ/TestJetty404.java | 6 +- .../clientserver/TestCompressionEcho.java | 10 +- .../TestGeneralEchoServiceTest.java | 14 +- .../r2/integ/clientserver/TestHttpServer.java | 4 +- .../r2/integ/clientserver/TestHttpsEcho.java | 4 +- .../integ/clientserver/TestQueryTunnel.java | 4 +- .../clientserver/TestRequestCompression.java | 8 +- .../clientserver/TestRestCompressionEcho.java | 6 +- .../integ/clientserver/TestServerTimeout.java | 6 +- .../TestServerTimeoutAsyncEvent.java | 6 +- .../integ/clientserver/TestSslTimingKey.java | 2 +- .../clientserver/TestStreamClientTimeout.java | 4 +- .../r2/integ/clientserver/TestStreamEcho.java | 6 +- .../integ/clientserver/TestStreamRequest.java | 4 +- .../clientserver/TestStreamResponse.java | 10 +- .../TestStreamResponseCompression.java | 6 +- .../helper/CaptureWireAttributesFilter.java | 12 +- .../callback/StreamExecutionCallback.java | 4 +- .../r2/netty/common/SslHandlerUtil.java | 4 +- .../http/client/HttpClientFactory.java | 4 +- .../client/common/ChannelPoolManagerImpl.java | 2 +- .../stream/http/RAPStreamResponseDecoder.java | 2 +- .../http/client/TestChannelPoolManager.java | 6 +- .../http/client/TestHttpClientFactory.java | 34 +- .../http/client/TestHttpNettyClient.java | 90 ++- .../client/TestHttpNettyStreamClient.java | 80 ++- .../http/TestChannelPoolStreamHandler.java | 2 +- .../perf/client/AbstractClientRunnable.java | 2 +- .../java/test/r2/perf/client/PerfClient.java | 4 +- .../client/RestClientRunnableFactory.java | 2 +- .../r2/perf/client/StreamClientRunnable.java | 2 +- .../client/StreamClientRunnableFactory.java | 2 +- .../server/AbstractPerfServerFactory.java | 12 +- .../r2/testutils/filter/FilterUtil.java | 2 +- .../testutils/server/HttpServerBuilder.java | 4 +- .../MockBatchCreateIdResponseFactory.java | 2 +- .../MockBatchEntityResponseFactory.java | 24 +- .../testutils/MockBatchKVResponseFactory.java | 28 +- .../testutils/MockBatchResponseFactory.java | 2 +- .../MockCollectionResponseFactory.java | 4 +- .../MockFailedResponseFutureBuilder.java | 4 +- .../client/testutils/MockResponseBuilder.java | 4 +- .../MockRestliResponseExceptionBuilder.java | 2 +- .../MockSuccessfulResponseFutureBuilder.java | 4 +- .../TestMockBatchCreateIdResponseFactory.java | 14 +- .../test/TestMockBatchKVResponseFactory.java | 76 +-- .../test/TestMockBatchResponseFactory.java | 2 +- .../TestMockFailedResponseFutureBuilder.java | 8 +- .../test/TestMockResponseBuilder.java | 12 +- ...stMockSuccessfulResponseFutureBuilder.java | 10 +- .../util/GeneratePatchMethodInterceptor.java | 4 +- .../client/util/TestPatchRequestRecorder.java | 2 +- .../client/util/TestPatchTreeRecorder.java | 4 +- .../restli/client/AbstractRequestBuilder.java | 30 +- .../restli/client/ActionRequestBuilder.java | 34 +- .../BatchCreateIdEntityRequestBuilder.java | 38 +- .../client/BatchCreateIdRequestBuilder.java | 34 +- .../client/BatchCreateRequestBuilder.java | 34 +- .../restli/client/BatchDeleteRequest.java | 6 +- .../client/BatchDeleteRequestBuilder.java | 16 +- .../restli/client/BatchFindRequest.java | 2 +- .../client/BatchFindRequestBuilder.java | 22 +- .../client/BatchGetEntityRequestBuilder.java | 48 +- .../restli/client/BatchGetRequestBuilder.java | 160 ++--- .../restli/client/BatchGetRequestUtil.java | 12 +- .../client/BatchPartialUpdateRequest.java | 6 +- .../linkedin/restli/client/BatchRequest.java | 2 +- .../restli/client/BatchUpdateRequest.java | 6 +- .../client/BatchUpdateRequestBuilder.java | 26 +- .../client/CreateIdEntityRequestBuilder.java | 30 +- .../restli/client/CreateIdRequestBuilder.java | 28 +- .../restli/client/CreateRequestBuilder.java | 28 +- .../client/DefaultScatterGatherStrategy.java | 2 +- .../restli/client/DeleteRequestBuilder.java | 18 +- .../restli/client/ExecutionGroup.java | 2 +- .../linkedin/restli/client/FindRequest.java | 2 +- .../restli/client/FindRequestBuilder.java | 22 +- .../linkedin/restli/client/GetAllRequest.java | 2 +- .../restli/client/GetAllRequestBuilder.java | 20 +- .../linkedin/restli/client/GetRequest.java | 2 +- .../restli/client/GetRequestBuilder.java | 20 +- .../client/ParSeqBasedCompletionStage.java | 2 +- .../ParSeqBasedCompletionStageFactory.java | 40 +- .../client/PartialUpdateRequestBuilder.java | 22 +- .../linkedin/restli/client/RestClient.java | 6 +- .../restli/client/UpdateRequestBuilder.java | 22 +- .../base/BatchGetRequestBuilderBase.java | 2 +- .../multiplexer/MultiplexedCallback.java | 4 +- .../MultiplexedRequestBuilder.java | 8 +- .../multiplexer/MultiplexedResponse.java | 2 +- .../client/response/BatchKVResponse.java | 8 +- .../util/RestliRequestUriSignature.java | 4 +- .../client/ActionResponseDecoder.java | 2 +- .../internal/client/BatchCreateDecoder.java | 4 +- .../internal/client/BatchCreateIdDecoder.java | 4 +- .../client/BatchCreateIdEntityDecoder.java | 6 +- .../client/BatchKVResponseDecoder.java | 12 +- .../internal/client/BatchResponseDecoder.java | 2 +- .../client/CollectionRequestUtil.java | 2 +- .../client/CollectionResponseDecoder.java | 2 +- .../client/CreateResponseDecoder.java | 6 +- .../restli/internal/client/ExceptionUtil.java | 2 +- .../client/IdEntityResponseDecoder.java | 6 +- .../internal/client/IdResponseDecoder.java | 6 +- .../client/OptionsResponseDecoder.java | 4 +- .../internal/client/QueryParamsUtil.java | 2 +- .../client/RequestBodyTransformer.java | 2 +- .../internal/client/ResponseFutureImpl.java | 8 +- .../restli/internal/client/ResponseImpl.java | 4 +- .../internal/client/RestResponseDecoder.java | 4 +- .../client/BatchGetRequestBuilderTest.java | 572 +++++++++--------- .../linkedin/restli/client/MockClient.java | 2 +- .../restli/client/RestClientTest.java | 32 +- .../client/TestAbstractRequestBuilder.java | 48 +- .../restli/client/TestClientBuilders.java | 546 ++++++++--------- .../client/TestCollectionRequestUtil.java | 60 +- .../TestDefaultScatterGatherStrategy.java | 3 +- .../TestParSeqBasedCompletionStage.java | 2 +- .../linkedin/restli/client/TestRequest.java | 20 +- .../TestSingleEntityRequestBuilder.java | 2 +- .../restli/client/TestVersionNegotiation.java | 4 +- .../multiplexer/MultiplexerTestBase.java | 6 +- .../multiplexer/TestMultiplexedCallback.java | 18 +- .../TestMultiplexedRequestBuilder.java | 6 +- .../client/response/TestBatchKVResponse.java | 18 +- .../util/TestRestliRequestUriSignature.java | 16 +- .../TestBatchEntityResponseDecoder.java | 18 +- .../TestBatchUpdateResponseDecoder.java | 2 +- .../restli/internal/client/TestResponse.java | 8 +- .../restli/common/testutils/DataAssert.java | 7 +- .../testutils/MockActionResponseFactory.java | 4 +- .../common/testutils/TestDataAssert.java | 2 +- .../TestMockActionResponseFactory.java | 2 +- .../common/BatchCreateIdEntityResponse.java | 4 +- .../restli/common/BatchCreateIdResponse.java | 2 +- .../restli/common/BatchCreateResponse.java | 4 +- .../common/BatchFinderCriteriaResult.java | 2 +- .../linkedin/restli/common/BatchRequest.java | 6 +- .../linkedin/restli/common/BatchResponse.java | 6 +- .../restli/common/CollectionRequest.java | 2 +- .../restli/common/CollectionResponse.java | 2 +- .../restli/common/ComplexKeySpec.java | 2 +- .../restli/common/ComplexResourceKey.java | 4 +- .../linkedin/restli/common/CompoundKey.java | 2 +- .../linkedin/restli/common/HttpStatus.java | 2 +- .../restli/common/KeyValueRecord.java | 4 +- .../restli/common/KeyValueRecordFactory.java | 2 +- .../linkedin/restli/common/PatchRequest.java | 2 +- .../linkedin/restli/common/RestConstants.java | 16 +- .../com/linkedin/restli/common/TypeSpec.java | 2 +- .../common/util/ProjectionMaskApplier.java | 2 +- ...esourceSchemaToResourceSpecTranslator.java | 16 +- .../common/util/RichResourceSchema.java | 14 +- .../internal/common/AsciiHexEncoding.java | 2 +- .../internal/common/AttachmentUtils.java | 6 +- .../BatchFinderCriteriaResultDecoder.java | 2 +- .../restli/internal/common/CookieUtil.java | 8 +- .../common/CreateIdEntityStatusDecoder.java | 4 +- .../common/CreateIdStatusDecoder.java | 2 +- .../restli/internal/common/HeaderUtil.java | 6 +- .../internal/common/QueryParamsDataMap.java | 14 +- .../internal/common/ReflectionUtils.java | 6 +- .../common/ResourcePropertiesImpl.java | 2 +- .../restli/internal/common/URIConstants.java | 2 +- .../restli/internal/common/URIParamUtils.java | 8 +- .../common/TestBatchCreateIdResponse.java | 12 +- .../restli/common/TestComplexResourceKey.java | 20 +- .../restli/common/TestIdEntityResponse.java | 22 +- .../restli/common/TestIdResponse.java | 22 +- .../restli/common/TestKeyValueRecord.java | 50 +- .../internal/common/TestHeaderUtil.java | 6 +- .../common/TestQueryParamsDataMap.java | 10 +- .../internal/common/TestURIElementParser.java | 2 +- .../internal/common/TestURIMaskUtil.java | 2 +- .../internal/common/TestUriParamUtils.java | 2 +- .../com/linkedin/restli/docgen/Graph.java | 4 +- .../MethodGatheringResourceSchemaVisitor.java | 22 +- .../java/com/linkedin/restli/docgen/Node.java | 2 +- .../docgen/ResourceSchemaCollection.java | 20 +- .../RestLiJSONDocumentationRenderer.java | 8 +- .../ExampleRequestResponseGenerator.java | 118 ++-- .../example/RestLiExampleBasicClient.java | 5 +- .../restli/example/RestLiExampleD2Client.java | 2 +- .../example/impl/AlbumDatabaseImpl.java | 2 +- .../example/impl/AlbumEntryDatabaseImpl.java | 4 +- .../example/impl/AlbumEntryResource.java | 4 +- .../example/impl/PhotoDatabaseImpl.java | 2 +- .../restli/example/impl/PhotoResource.java | 10 +- .../example/impl/TestAlbumEntryResource.java | 10 +- .../example/impl/TestPhotoResource.java | 4 +- .../client/AllPartitionsRequestBuilder.java | 2 +- .../restli/client/ScatterGatherBuilder.java | 78 +-- .../TestCustomTypesRequestBuilders.java | 2 +- .../groups/TestGroupsRequestBuilders.java | 50 +- .../examples/groups/TestPatchGeneration.java | 10 +- .../examples/AssociationResourceHelpers.java | 2 +- .../server/AssociationsResource.java | 6 +- .../server/AssociationsSubResource.java | 2 +- .../AutomaticValidationDemoResource.java | 32 +- ...maticValidationWithProjectionResource.java | 16 +- .../greetings/server/BatchFinderResource.java | 6 +- .../server/BatchGreetingResource.java | 12 +- .../server/ChainedTyperefResource.java | 6 +- .../server/ComplexArrayResource.java | 4 +- .../server/ComplexKeysDataProvider.java | 28 +- .../greetings/server/ComplexKeysResource.java | 4 +- .../greetings/server/CompressionResource.java | 4 +- .../greetings/server/CookieResource.java | 2 +- .../CustomMetadataProjectionResource.java | 16 +- .../server/CustomTypesResource2.java | 18 +- .../server/CustomTypesResource3.java | 6 +- .../greetings/server/ExceptionsResource.java | 4 +- .../greetings/server/ExceptionsResource2.java | 6 +- .../greetings/server/FindersResource.java | 11 +- .../GreetingsResourceCodeGenerator.java | 8 +- .../server/GreetingsResourceImpl.java | 40 +- .../server/NullGreetingsResourceImpl.java | 64 +- .../server/PagingProjectionResource.java | 20 +- ...SimpleResourceUnderCollectionResource.java | 2 +- .../greetings/server/StringKeysResource.java | 26 +- .../server/StringKeysSubResource.java | 2 +- .../greetings/server/TyperefKeysResource.java | 2 +- .../server/ValidationDemoResource.java | 26 +- .../greetings/server/WithContextResource.java | 2 +- .../altkey/AssociationAltKeyResource.java | 14 +- .../altkey/CollectionAltKeyResource.java | 12 +- .../altkey/ComplexKeyAltKeyResource.java | 6 +- .../altkey/StringComplexKeyCoercer.java | 4 +- .../defaults/FieldFillInDefaultResources.java | 7 +- .../server/impl/HashGroupMembershipMgr.java | 10 +- .../groups/server/impl/HashMapGroupMgr.java | 8 +- .../rest/impl/GroupMembershipsResource2.java | 18 +- .../rest/impl/GroupMembershipsResource3.java | 34 +- .../restli/docgen/TestExamplesGenerator.java | 12 +- .../docgen/TestResourceSchemaCollection.java | 4 +- .../restspec/TestAnnotationResource.java | 2 +- .../TestDeprecationAnnotationResource.java | 2 +- .../restli/test/util/BatchCreateHelper.java | 2 +- .../restli/test/util/RootBuilderWrapper.java | 4 +- .../linkedin/restli/client/MockLBFactory.java | 18 +- .../com/linkedin/restli/client/MockStore.java | 2 +- .../restli/client/TestResponseDecoder.java | 2 +- .../restli/client/TestScatterGather.java | 92 +-- .../client/TestUnstructuredDataClient.java | 6 +- .../multiplexer/TestMultiplexerDelays.java | 2 +- .../TestMultiplexerIntegration.java | 42 +- .../examples/RestLiIntegrationTest.java | 6 +- .../restli/examples/TestActionsResource.java | 24 +- .../TestAllPartitionsRequestBuilder.java | 26 +- .../restli/examples/TestAltKeyResource.java | 4 +- .../examples/TestAssociationsResource.java | 6 +- .../examples/TestComplexArrayResource.java | 10 +- .../examples/TestComplexByteKeyResource.java | 4 +- .../examples/TestComplexKeysResource.java | 32 +- .../examples/TestCompressionServer.java | 12 +- .../examples/TestCustomContextData.java | 2 +- .../examples/TestCustomTypesClient.java | 10 +- .../examples/TestEscapeCharsInStringKeys.java | 16 +- .../linkedin/restli/examples/TestFilters.java | 10 +- .../restli/examples/TestGreetingsClient.java | 18 +- .../restli/examples/TestGroupsClient.java | 14 +- .../TestHttp11With204AndException.java | 2 +- .../examples/TestNullGreetingsClient.java | 8 +- .../TestParseqBasedFluentClientApi.java | 20 +- .../examples/TestRequestCompression.java | 10 +- .../examples/TestResponseCompression.java | 6 +- .../restli/examples/TestRestLiValidation.java | 12 +- .../TestRestLiValidationFromClient.java | 2 +- .../TestRestLiValidationWithProjection.java | 6 +- .../examples/TestReturnEntityWithCreate.java | 4 +- .../examples/TestSimpleResourceHierarchy.java | 4 +- .../examples/TestStreamingGreetings.java | 4 +- ...refCustomDoubleAssociationKeyResource.java | 18 +- .../test/util/TestRootBuilderWrapper.java | 10 +- .../restli/internal/testutils/URIDetails.java | 6 +- .../TestParseqTraceDebugRequestHandler.java | 4 +- .../testutils/MockHttpServerFactory.java | 2 +- .../test/TestMockHttpServerFactory.java | 4 +- .../restli/internal/server/PathKeysImpl.java | 2 +- .../restli/internal/server/RestLiRouter.java | 4 +- .../methods/arguments/ArgumentBuilder.java | 2 +- .../internal/server/model/AnnotationSet.java | 2 +- .../model/ResourceMethodDescriptor.java | 2 +- .../server/model/ResourceMethodLookup.java | 2 +- .../internal/server/model/ResourceModel.java | 6 +- .../server/model/ResourceModelAnnotation.java | 4 +- .../server/model/ResourceModelEncoder.java | 4 +- .../server/model/RestLiAnnotationReader.java | 34 +- .../server/model/RestLiApiBuilder.java | 4 +- .../server/model/RestLiClasspathScanner.java | 6 +- .../internal/server/util/MIMEParse.java | 10 +- .../restli/server/BatchFinderResult.java | 2 +- .../linkedin/restli/server/BatchResult.java | 6 +- .../server/DelegatingTransportDispatcher.java | 4 +- .../linkedin/restli/server/RestLiConfig.java | 2 +- .../restli/server/RestLiRequestDataImpl.java | 6 +- .../linkedin/restli/server/RestliServlet.java | 2 +- .../restli/server/annotations/RestMethod.java | 2 +- .../linkedin/restli/server/filter/Filter.java | 2 +- .../mock/InjectMockResourceFactory.java | 2 +- .../server/mock/SimpleBeanProvider.java | 4 +- .../resources/InjectResourceFactory.java | 2 +- .../server/resources/Jsr330Adapter.java | 16 +- .../restli/server/util/ChainedIterator.java | 2 +- .../server/util/FileClassNameScanner.java | 2 +- .../restli/server/util/PatchHelper.java | 4 +- .../TestFilterRequestContextInternalImpl.java | 4 +- .../filter/testfilters/CountFilter.java | 2 +- .../arguments/TestArgumentBuilder.java | 4 +- .../arguments/TestGetArgumentBuilder.java | 6 +- .../model/TestParameterDefaultValue.java | 22 +- .../server/model/TestRestLiApiBuilder.java | 4 +- .../server/response/ResponseBuilderUtil.java | 2 +- .../TestBatchCreateResponseBuilder.java | 54 +- .../TestBatchFinderResponseBuilder.java | 12 +- .../response/TestCreateResponseBuilder.java | 8 +- .../server/response/TestRestLiCallback.java | 4 +- .../server/response/TestRestLiResponse.java | 2 +- .../response/TestRestLiResponseEnvelope.java | 4 +- .../internal/server/util/TestRestUtils.java | 4 +- .../restli/server/RestLiTestHelper.java | 2 +- .../server/TestRestLiRequestDataImpl.java | 4 +- .../restli/server/TestRestLiServer.java | 2 +- .../server/combined/CombinedResources.java | 2 +- .../TestMultiplexedRequestHandlerImpl.java | 46 +- .../resources/TestInjectResourceFactory.java | 10 +- .../server/test/EasyMockResourceFactory.java | 2 +- .../restli/server/test/EasyMockUtils.java | 8 +- .../restli/server/test/RestLiTestHelper.java | 2 +- .../server/test/TestResourceContext.java | 16 +- .../test/TestRestLiMethodInvocation.java | 18 +- .../server/twitter/ExceptionsResource.java | 4 +- .../JavaRequestBuilderGenerator.java | 12 +- .../RequestBuilderSpecGenerator.java | 36 +- .../tools/clientgen/RestSpecParser.java | 6 +- .../builderspec/ActionBuilderSpec.java | 2 +- .../builderspec/ActionSetRootBuilderSpec.java | 2 +- .../CollectionRootBuilderSpec.java | 2 +- .../builderspec/RequestBuilderSpec.java | 4 +- .../builderspec/SimpleRootBuilderSpec.java | 2 +- .../tools/clientgen/fluentspec/SpecUtils.java | 4 +- .../compatibility/CompatibilityInfoMap.java | 18 +- .../ResourceCompatibilityChecker.java | 18 +- .../tools/data/PredicateExpressionParser.java | 8 +- ...stLiResourceModelCompatibilityChecker.java | 2 +- .../tools/idlgen/DocletDocsProvider.java | 8 +- .../idlgen/MultiLanguageDocsProvider.java | 6 +- .../restli/tools/idlgen/RestLiDoclet.java | 8 +- .../idlgen/RestLiResourceModelExporter.java | 10 +- .../snapshot/check/AbstractSnapshot.java | 2 +- .../RestLiSnapshotCompatibilityChecker.java | 2 +- .../restli/tools/snapshot/check/RestSpec.java | 2 +- .../snapshot/gen/RestLiSnapshotExporter.java | 10 +- .../tools/snapshot/gen/SnapshotGenerator.java | 4 +- .../TestRequestBuilderSpecGenerator.java | 26 +- .../TestResourceCompatibilityChecker.java | 84 +-- ...stLiResourceModelCompatibilityChecker.java | 8 +- .../sample/CustomKeyAssociationResource.java | 2 +- ...susSchemaSnapshotCompatibilityChecker.java | 6 +- ...estRestliSnapshotCompatibilityChecker.java | 20 +- .../tools/snapshot/check/TestSnapshot.java | 2 +- 687 files changed, 4568 insertions(+), 4634 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc3e1fa57e..2e776a3741 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ When updating the changelog, remember to be very clear about what behavior has c and what APIs have changed, if applicable. ## [Unreleased] +- Use the Java 7 diamond operator everywhere. ## [29.19.4] - 2021-06-23 - Do not apply Idea and Eclipse plugins. diff --git a/d2-benchmark/src/jmh/java/com/linkedin/d2/util/hashing/ConsistentHashRingBenchmark.java b/d2-benchmark/src/jmh/java/com/linkedin/d2/util/hashing/ConsistentHashRingBenchmark.java index 7ff5df9294..dbed70628c 100644 --- a/d2-benchmark/src/jmh/java/com/linkedin/d2/util/hashing/ConsistentHashRingBenchmark.java +++ b/d2-benchmark/src/jmh/java/com/linkedin/d2/util/hashing/ConsistentHashRingBenchmark.java @@ -208,7 +208,7 @@ public URI measureBoundedLoad_firstFull_MPCHash_100Hosts_21Probes(BoundedLoad_MP @State(Scope.Benchmark) public static class ConsistentHashRing_10Hosts_100PointsPerHost_State { - Ring _ring = new ConsistentHashRing(buildPointsMap(10, 100)); + Ring _ring = new ConsistentHashRing<>(buildPointsMap(10, 100)); Random _random = new Random(); } @@ -247,7 +247,7 @@ public URI measureBoundedLoad_firstFull_ConsistentHashRing_10Hosts_100PointsPerH @State(Scope.Benchmark) public static class ConsistentHashRing_100Hosts_100PointsPerHost_State { - Ring _ring = new ConsistentHashRing(buildPointsMap(100, 100)); + Ring _ring = new ConsistentHashRing<>(buildPointsMap(100, 100)); Random _random = new Random(); } diff --git a/d2-contrib/src/main/java/com/linkedin/d2/contrib/RouteLookupClient.java b/d2-contrib/src/main/java/com/linkedin/d2/contrib/RouteLookupClient.java index 6a2c15ba58..4a4d5b49bb 100644 --- a/d2-contrib/src/main/java/com/linkedin/d2/contrib/RouteLookupClient.java +++ b/d2-contrib/src/main/java/com/linkedin/d2/contrib/RouteLookupClient.java @@ -103,7 +103,7 @@ public Future restRequest(RestRequest request, String routeKey) public Future restRequest(final RestRequest request, final RequestContext requestContext, String routekey) { - final FutureCallback futureCallback = new FutureCallback(); + final FutureCallback futureCallback = new FutureCallback<>(); String originalServiceName = LoadBalancerUtil.getServiceNameFromUri(request.getURI()); String resultServiceName; _routeLookup.run(originalServiceName, _routingGroup, routekey, futureCallback); diff --git a/d2-contrib/src/test/java/com/linkedin/d2/contrib/TestRouteLookupClient.java b/d2-contrib/src/test/java/com/linkedin/d2/contrib/TestRouteLookupClient.java index 7de003add7..d1b949c7a1 100644 --- a/d2-contrib/src/test/java/com/linkedin/d2/contrib/TestRouteLookupClient.java +++ b/d2-contrib/src/test/java/com/linkedin/d2/contrib/TestRouteLookupClient.java @@ -21,7 +21,6 @@ package com.linkedin.d2.contrib; import com.linkedin.common.callback.FutureCallback; -import com.linkedin.common.util.None; import com.linkedin.d2.balancer.D2Client; import com.linkedin.d2.balancer.D2ClientBuilder; import com.linkedin.r2.message.rest.RestRequest; @@ -49,14 +48,14 @@ public void testSimpleRouteLookup() throws ExecutionException, InterruptedExcept { RouteLookup routeLookup = new SimpleTestRouteLookup(); - FutureCallback futureCallback = new FutureCallback(); + FutureCallback futureCallback = new FutureCallback<>(); String serviceName = "BarBar"; routeLookup.run(serviceName, null, "1",futureCallback); String resultString = futureCallback.get(); Assert.assertEquals(resultString, serviceName + "1" + "Foo"); - futureCallback = new FutureCallback(); + futureCallback = new FutureCallback<>(); routeLookup.run(serviceName, "blah", "2",futureCallback); resultString = futureCallback.get(); Assert.assertEquals(resultString, serviceName + "blah" + "2" + "Foo"); @@ -68,7 +67,7 @@ public void testRouteLookupClientFuture() throws ExecutionException, Interrupted RouteLookup routeLookup = new SimpleTestRouteLookup(); final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build(); - d2Client.start(new FutureCallback()); + d2Client.start(new FutureCallback<>()); RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast"); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("d2://simple_uri")).build(); Future future = routeLookupClient.restRequest(dummyRestRequest, "5436"); @@ -97,10 +96,10 @@ public void testRouteLookupClientCallback() RouteLookup routeLookup = new SimpleTestRouteLookup(); final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build(); - d2Client.start(new FutureCallback()); + d2Client.start(new FutureCallback<>()); RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast"); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("d2://simple_uri")).build(); - FutureCallback futureCallback = new FutureCallback(); + FutureCallback futureCallback = new FutureCallback<>(); routeLookupClient.restRequest(dummyRestRequest,futureCallback, "5555"); try @@ -124,7 +123,7 @@ public void testBadRequest() RouteLookup routeLookup = new SimpleTestRouteLookup(); final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build(); - d2Client.start(new FutureCallback()); + d2Client.start(new FutureCallback<>()); RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast"); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("http://simple_uri")).build(); try diff --git a/d2-int-test/src/test/java/com/linkedin/d2/D2BaseTest.java b/d2-int-test/src/test/java/com/linkedin/d2/D2BaseTest.java index c11b1c35b1..d6896b3ac6 100644 --- a/d2-int-test/src/test/java/com/linkedin/d2/D2BaseTest.java +++ b/d2-int-test/src/test/java/com/linkedin/d2/D2BaseTest.java @@ -265,7 +265,7 @@ public Map sendRequests(int num, public Map> generateClusterData(String[] clusters, int addOn) { - Map> clustersData = new HashMap> (); + Map> clustersData = new HashMap<>(); for (int i=0; i < clusters.length; i++) { @@ -276,8 +276,8 @@ public Map> generateClusterData(String[] clusters, int add public Map generatePartitionProperties(String regex, int keyRangeStart, int partitionCount, int partitionSize, String type) { - final Map partitionProperties = new HashMap(); - Map map = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map map = new HashMap<>(); map.put("partitionKeyRegex", regex); map.put("keyRangeStart", String.valueOf(keyRangeStart)); map.put("partitionCount", String.valueOf(partitionCount)); @@ -290,7 +290,7 @@ public Map generatePartitionProperties(String regex, int keyRang protected Map createLatencyDataHash(List servers, T[] latency) { - Map hash = new HashMap(); + Map hash = new HashMap<>(); int count = 0; for (LoadBalancerEchoServer server: servers) { @@ -308,13 +308,13 @@ protected Map createLatencyDataHash(List> createServerWeightDataMap(List servers, int partitionId, Double[] weight) { - Map> hash = new HashMap>(); + Map> hash = new HashMap<>(); int count = 0; for (LoadBalancerEchoServer server: servers) { if (count < weight.length) { - Map partitionWeight = new HashMap (); + Map partitionWeight = new HashMap<>(); partitionWeight.put(Integer.valueOf(partitionId), weight[count]); hash.put(server, partitionWeight); count++; @@ -344,7 +344,7 @@ protected void assertServersWeighSetup(Map generateHostResponseCountMap(Map responses) { - Map res = new HashMap(); + Map res = new HashMap<>(); res.put(Integer.valueOf(ECHO_SERVER_PORT1_1), new AtomicInteger(0)); res.put(Integer.valueOf(ECHO_SERVER_PORT1_2), new AtomicInteger(0)); diff --git a/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestD2ConfigWithSingleZKFailover.java b/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestD2ConfigWithSingleZKFailover.java index ce6c752c65..e3f3078e74 100644 --- a/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestD2ConfigWithSingleZKFailover.java +++ b/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestD2ConfigWithSingleZKFailover.java @@ -66,10 +66,10 @@ public void setup() throws IOException, Exception _zkPort = _zkServer.getPort(); _zkHosts = ZK_HOST+":" + _zkPort; _zkUriString = "zk://"+_zkHosts; - + // Register clusters/services (two services per cluster) LoadBalancerClientCli.runDiscovery(_zkHosts, "/d2", D2_CONFIG_DATA); - + // Get LoadBalancer Client _cli = new LoadBalancerClientCli(_zkHosts, "/d2"); @@ -235,7 +235,7 @@ public void testEchoServerMarkDownUp() throws IOException, InterruptedException, // Echo Server mark up _echoServers.get(1).markUp(); _echoServers.get(2).markUp(); - + msg = generateMessage(_zkUriString); expectedResponses = getExpectedResponses(0, msg); @@ -297,7 +297,7 @@ private String getExpectedResponse(int partitionId, String msg, String postfix) private void startAllEchoServers() throws Exception { - _echoServers = new ArrayList(); + _echoServers = new ArrayList<>(); _echoServers.add(startEchoServer(ZK_HOST, _zkPort, ECHO_SERVER_HOST, ECHO_SERVER_PORT1, "cluster-1", "service-1_1", "service-1_2", "service-1_3" )); _echoServers.add(startEchoServer(ZK_HOST, _zkPort, ECHO_SERVER_HOST, ECHO_SERVER_PORT2, "cluster-1", "service-1_1", "service-1_2", "service-1_3" )); _echoServers.add(startEchoServer(ZK_HOST, _zkPort, ECHO_SERVER_HOST, ECHO_SERVER_PORT3, "cluster-2", "service-2_1", "service-2_2", "service-2_3" )); diff --git a/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestPartitionsWithZKQuorum.java b/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestPartitionsWithZKQuorum.java index 8aaef74401..05f69dc9b0 100644 --- a/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestPartitionsWithZKQuorum.java +++ b/d2-int-test/src/test/java/com/linkedin/d2/discovery/TestPartitionsWithZKQuorum.java @@ -84,7 +84,7 @@ public void testRegisterUnregisterDefaultPartitionEchoServers() throws IOExcepti InterruptedException, Exception { - _echoServers = new ArrayList(); + _echoServers = new ArrayList<>(); setup(); assertEquals(LoadBalancerClientCli.runDiscovery(_quorum.getHosts(), "/d2", D2_CONFIG_DEFAULT_PARTITION_DATA), 0); _cli = new LoadBalancerClientCli(_quorum.getHosts(), "/d2"); @@ -109,13 +109,13 @@ public void testRegisterUnregisterCustomPartitionEchoServers() throws IOExceptio InterruptedException, Exception { - _echoServers = new ArrayList(); + _echoServers = new ArrayList<>(); setup(); assertEquals(LoadBalancerClientCli.runDiscovery(_quorum.getHosts(), "/d2", D2_CONFIG_CUSTOM_PARTITION_DATA), 0); _cli = new LoadBalancerClientCli(_quorum.getHosts(), "/d2"); _client = _cli.createZKFSTogglingLBClient(_quorum.getHosts(), "/d2", null); // Echo servers startup - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(Integer.valueOf(1), Double.valueOf(1.0d)); startCustomPartitionEchoServers(partitionWeight); assertAllEchoServersRegistered(_cli.getZKClient(), _zkUriString, _echoServers); @@ -135,13 +135,13 @@ public void testRegisterUnregisterAllEchoServers() throws IOException, InterruptedException, Exception { - _echoServers = new ArrayList(); + _echoServers = new ArrayList<>(); setup(); assertEquals(LoadBalancerClientCli.runDiscovery(_quorum.getHosts(), "/d2", D2_CONFIG_DATA), 0); _cli = new LoadBalancerClientCli(_quorum.getHosts(), "/d2"); _client = _cli.createZKFSTogglingLBClient(_quorum.getHosts(), "/d2", null); // Echo servers startup - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(Integer.valueOf(1), Double.valueOf(1.0d)); startAllEchoServers(partitionWeight); assertAllEchoServersRegistered(_cli.getZKClient(), _zkUriString, _echoServers); diff --git a/d2-int-test/src/test/java/com/linkedin/d2/loadbalancer/TestD2ZKQuorumFailover.java b/d2-int-test/src/test/java/com/linkedin/d2/loadbalancer/TestD2ZKQuorumFailover.java index 3247a58b6e..1d0db1348f 100644 --- a/d2-int-test/src/test/java/com/linkedin/d2/loadbalancer/TestD2ZKQuorumFailover.java +++ b/d2-int-test/src/test/java/com/linkedin/d2/loadbalancer/TestD2ZKQuorumFailover.java @@ -272,8 +272,8 @@ private void assertQuorumProcessAllRequests(String clustersData) throws Exceptio private void startAllEchoServers() throws Exception { - _echoServers = new ArrayList(); - Map partitionWeight = new HashMap(); + _echoServers = new ArrayList<>(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(Integer.valueOf(1), Double.valueOf(1.0d)); _echoServers.add(startEchoServer(getHost(_zkHosts[0]), getPort(_zkHosts[0]), ECHO_SERVER_HOST, ECHO_SERVER_PORT1_1, "cluster-1", "service-1_1", "service-1_2", "service-1_3" )); _echoServers.add(startEchoServer(getHost(_zkHosts[0]), getPort(_zkHosts[0]), ECHO_SERVER_HOST, ECHO_SERVER_PORT1_2, "cluster-1", "service-1_1", "service-1_2", "service-1_3" )); diff --git a/d2-int-test/src/test/java/com/linkedin/d2/quorum/ZKQuorum.java b/d2-int-test/src/test/java/com/linkedin/d2/quorum/ZKQuorum.java index 96f31a8c46..b14fee0974 100644 --- a/d2-int-test/src/test/java/com/linkedin/d2/quorum/ZKQuorum.java +++ b/d2-int-test/src/test/java/com/linkedin/d2/quorum/ZKQuorum.java @@ -16,8 +16,6 @@ package com.linkedin.d2.quorum; -import java.io.IOException; -import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -51,10 +49,10 @@ public class ZKQuorum * @param n - number of peers in the ensemble ( for test stability, set peer number in a quorum to 7+ (7, 9 or 11) ) */ - public ZKQuorum(int ttlPeersCount) throws IOException, Exception + public ZKQuorum(int ttlPeersCount) throws Exception { - _peers = new HashMap(); - _peersView = new HashMap(); + _peers = new HashMap<>(); + _peersView = new HashMap<>(); _peerCount = ttlPeersCount; _hosts = ""; @@ -225,7 +223,7 @@ private boolean isExists(int id) return false; } - public void restart(int id) throws IOException, Exception + public void restart(int id) throws Exception { _log.info("Restarting peer #" + getQuorumPeerPortsInfo(id)); _peers.get(id).shutdown(false); @@ -248,7 +246,7 @@ public void restartPeersInTerminatedState() throws Exception waitForAllPeersUp(); } - public void startAll() throws IOException, Exception + public void startAll() throws Exception { for (int id=1; id <= _peerCount; id++) { diff --git a/d2/src/main/java/com/linkedin/d2/backuprequests/LatencyMetric.java b/d2/src/main/java/com/linkedin/d2/backuprequests/LatencyMetric.java index 50cea81674..84d2413af7 100644 --- a/d2/src/main/java/com/linkedin/d2/backuprequests/LatencyMetric.java +++ b/d2/src/main/java/com/linkedin/d2/backuprequests/LatencyMetric.java @@ -53,10 +53,10 @@ public class LatencyMetric { * - read happens on previously put aside current, once read is completed, the histogram is reset * and put back as inactive */ - private AtomicReference _current = new AtomicReference( + private AtomicReference _current = new AtomicReference<>( new ShortCountsHistogram(LOWEST_DISCERNIBLE_VALUE, HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS)); - private AtomicReference _inactive = new AtomicReference( + private AtomicReference _inactive = new AtomicReference<>( new ShortCountsHistogram(LOWEST_DISCERNIBLE_VALUE, HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS)); /** diff --git a/d2/src/main/java/com/linkedin/d2/balancer/D2ClientBuilder.java b/d2/src/main/java/com/linkedin/d2/balancer/D2ClientBuilder.java index f15964e402..70106f8215 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/D2ClientBuilder.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/D2ClientBuilder.java @@ -540,7 +540,7 @@ public D2ClientBuilder setDeterministicSubsettingMetadataProvider(DeterministicS private Map createDefaultTransportClientFactories() { - final Map clientFactories = new HashMap(); + final Map clientFactories = new HashMap<>(); TransportClientFactory transportClientFactory = new HttpClientFactory.Builder().build(); clientFactories.put("http", transportClientFactory); clientFactories.put("https", transportClientFactory); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/clients/BackupRequestsClient.java b/d2/src/main/java/com/linkedin/d2/balancer/clients/BackupRequestsClient.java index 241bbd4d08..392481d1cf 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/clients/BackupRequestsClient.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/clients/BackupRequestsClient.java @@ -161,7 +161,7 @@ public Future restRequest(RestRequest request) @Override public Future restRequest(RestRequest request, RequestContext requestContext) { - final FutureCallback future = new FutureCallback(); + final FutureCallback future = new FutureCallback<>(); restRequest(request, requestContext, future); return future; } diff --git a/d2/src/main/java/com/linkedin/d2/balancer/clients/DegraderTrackerClientImpl.java b/d2/src/main/java/com/linkedin/d2/balancer/clients/DegraderTrackerClientImpl.java index 83ce2cff69..875780f8bb 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/clients/DegraderTrackerClientImpl.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/clients/DegraderTrackerClientImpl.java @@ -105,7 +105,7 @@ public DegraderTrackerClientImpl(URI uri, Map partitionD * However, now it becomes harder to have different configurations for different partitions. */ int mapSize = partitionDataMap.size(); - MappartitionStates = new HashMap(mapSize * 2); + MappartitionStates = new HashMap<>(mapSize * 2); config.setName("TrackerClient Degrader: " + uri); DegraderImpl degrader = new DegraderImpl(config); DegraderControl degraderControl = new DegraderControl(degrader); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/config/ConfigWriter.java b/d2/src/main/java/com/linkedin/d2/balancer/config/ConfigWriter.java index e8c276d9ac..1df27d4b15 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/config/ConfigWriter.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/config/ConfigWriter.java @@ -73,7 +73,7 @@ public void writeConfig() throws ExecutionException, TimeoutException, Interrupt { long startTime = System.currentTimeMillis(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _store.start(callback); callback.get(_timeout, _timeoutUnit); @@ -116,7 +116,7 @@ public void onError(Throwable e) throw new TimeoutException(); } - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); _store.shutdown(shutdownCallback); shutdownCallback.get(_timeout, _timeoutUnit); @@ -134,7 +134,7 @@ public static Map merge(Map source, Map result = new HashMap(defaultMap); + Map result = new HashMap<>(defaultMap); for (String key : source.keySet()) { Object sourceValue = source.get(key); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/config/PartitionDataFactory.java b/d2/src/main/java/com/linkedin/d2/balancer/config/PartitionDataFactory.java index 2dbb1babb3..164d5ecc9f 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/config/PartitionDataFactory.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/config/PartitionDataFactory.java @@ -31,7 +31,7 @@ public class PartitionDataFactory { public static Map createPartitionDataMap(Map sourceMap) { - Map map = new HashMap(); + Map map = new HashMap<>(); if (sourceMap != null) { for (Map.Entry entry : sourceMap.entrySet()) diff --git a/d2/src/main/java/com/linkedin/d2/balancer/properties/AllowedClientPropertyKeys.java b/d2/src/main/java/com/linkedin/d2/balancer/properties/AllowedClientPropertyKeys.java index 6834a658f7..d83296985c 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/properties/AllowedClientPropertyKeys.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/properties/AllowedClientPropertyKeys.java @@ -48,7 +48,7 @@ public enum AllowedClientPropertyKeys private static final Set _allowedKeys; static { - _allowedKeys = new HashSet(); + _allowedKeys = new HashSet<>(); for (AllowedClientPropertyKeys propertyKey: AllowedClientPropertyKeys.values()) { _allowedKeys.add(propertyKey._keyName); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/properties/ServicePropertiesJsonSerializer.java b/d2/src/main/java/com/linkedin/d2/balancer/properties/ServicePropertiesJsonSerializer.java index 59a31055a3..e0146e399d 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/properties/ServicePropertiesJsonSerializer.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/properties/ServicePropertiesJsonSerializer.java @@ -213,7 +213,7 @@ public ServiceProperties fromMap(Map map) Set banned = new HashSet<>(bannedList); List prioritizedSchemes = mapGetOrDefault(map, PropertyKeys.PRIORITIZED_SCHEMES, Collections.emptyList()); - Map metadataProperties = new HashMap(); + Map metadataProperties = new HashMap<>(); String isDefaultService = mapGetOrDefault(map, PropertyKeys.IS_DEFAULT_SERVICE, null); if ("true".equalsIgnoreCase(isDefaultService)) { diff --git a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriProperties.java b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriProperties.java index 3540359c4f..7881c99ab5 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriProperties.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriProperties.java @@ -46,23 +46,22 @@ public UriProperties(String clusterName, Map> uriSpecificProperties) { _clusterName = clusterName; - Map> partitionDescriptionsMap = new HashMap>(partitionDescriptions.size() * 2); + Map> partitionDescriptionsMap = new HashMap<>(partitionDescriptions.size() * 2); for (Map.Entry> entry : partitionDescriptions.entrySet()) { - partitionDescriptionsMap.put(entry.getKey(), Collections.unmodifiableMap( - new HashMap(entry.getValue()))); + partitionDescriptionsMap.put(entry.getKey(), Collections.unmodifiableMap(new HashMap<>(entry.getValue()))); } _partitionDesc = Collections.unmodifiableMap(partitionDescriptionsMap); // group uris by scheme and partition - HashMap>> urisBySchemeAndPartition = new HashMap>>(); + HashMap>> urisBySchemeAndPartition = new HashMap<>(); for (Map.Entry> entry : _partitionDesc.entrySet()) { final URI uri = entry.getKey(); Map> map= urisBySchemeAndPartition.get(uri.getScheme()); if (map == null) { - map = new HashMap>(); + map = new HashMap<>(); urisBySchemeAndPartition.put(uri.getScheme(), map); } @@ -72,7 +71,7 @@ public UriProperties(String clusterName, Set uriSet = map.get(partitionId); if (uriSet == null) { - uriSet = new HashSet(); + uriSet = new HashSet<>(); map.put(partitionId, uriSet); } uriSet.add(uri); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesJsonSerializer.java b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesJsonSerializer.java index a023e42723..7d7bb00970 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesJsonSerializer.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesJsonSerializer.java @@ -42,7 +42,7 @@ public byte[] toBytes(UriProperties property) { UriProperties propertyToSerialize; final Map> partitionDesc = property.getPartitionDesc(); - final Map weights = new HashMap(partitionDesc.size() * 2); + final Map weights = new HashMap<>(partitionDesc.size() * 2); boolean isPartitioned = false; for (Map.Entry> entry : partitionDesc.entrySet()) { @@ -112,7 +112,7 @@ public UriProperties fromMap(Map map) if (map.containsKey(applicationPropertiesKey)) { // the URI key gets serialized into a String, so we have to convert the String back into an URI - applicationProperties = new HashMap>(); + applicationProperties = new HashMap<>(); Map> storedApplicationProperties = (Map>)PropertyUtil.checkAndGetValue(map, applicationPropertiesKey, @@ -128,8 +128,7 @@ public UriProperties fromMap(Map map) applicationProperties = Collections.emptyMap(); } - Map> partitionDesc = - new HashMap>(); + Map> partitionDesc = new HashMap<>(); @SuppressWarnings("unchecked") Map> descMap = (Map>)map.get("partitionDesc"); @@ -140,7 +139,7 @@ public UriProperties fromMap(Map map) { URI uri = URI.create(entry.getKey()); Map partitionMap = entry.getValue(); - Map partitionDataMap = new HashMap(partitionMap.size()* 2); + Map partitionDataMap = new HashMap<>(partitionMap.size()* 2); for (Map.Entry partitionEntry : partitionMap.entrySet()) { @SuppressWarnings("unchecked") @@ -154,14 +153,14 @@ public UriProperties fromMap(Map map) @SuppressWarnings("unchecked") Map weights = (Map) map.get("weights"); - Map> partitionDescFromWeights = new HashMap>(); + Map> partitionDescFromWeights = new HashMap<>(); if (weights != null) { for(Map.Entry weightEntry: weights.entrySet()) { String uriStr = weightEntry.getKey(); URI uri = URI.create(uriStr); - Map partitionDataMap = new HashMap(2); + Map partitionDataMap = new HashMap<>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, // may be not a proper use of checkAndGetValue and uriStr is not the proper name for the value new PartitionData(PropertyUtil.checkAndGetValue(weights, uriStr, Number.class, clusterName).doubleValue())); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesMerger.java b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesMerger.java index ee5a08258d..5b98a28c02 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesMerger.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/properties/UriPropertiesMerger.java @@ -29,8 +29,8 @@ public class UriPropertiesMerger implements ZooKeeperPropertyMerger propertiesToMerge) { - Map> partitionData = new HashMap>(); - Map> uriSpecificProperties = new HashMap>(); + Map> partitionData = new HashMap<>(); + Map> uriSpecificProperties = new HashMap<>(); String clusterName = propertyName; diff --git a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZKUriStoreFactory.java b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZKUriStoreFactory.java index 25097beecb..f2f26a6e25 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZKUriStoreFactory.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZKUriStoreFactory.java @@ -40,7 +40,7 @@ public class ZKUriStoreFactory implements ZooKeeperConnectionManager.ZKStoreFact @Override public ZooKeeperEphemeralStore createStore(ZKConnection connection, String path) { - return new ZooKeeperEphemeralStore( - connection, new UriPropertiesJsonSerializer(), new UriPropertiesMerger(), path); + return new ZooKeeperEphemeralStore<>(connection, new UriPropertiesJsonSerializer(), + new UriPropertiesMerger(), path); } } diff --git a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperConnectionManager.java b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperConnectionManager.java index 432fa50a36..dc158199e0 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperConnectionManager.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperConnectionManager.java @@ -55,7 +55,7 @@ public class ZooKeeperConnectionManager private final String _zkBasePath; private final ZKStoreFactory> _factory; private final ZooKeeperAnnouncer[] _servers; - private final AtomicReference> _startupCallback = new AtomicReference>(); + private final AtomicReference> _startupCallback = new AtomicReference<>(); private final ZKPersistentConnection _zkConnection; @@ -159,7 +159,7 @@ public void shutdown(final Callback callback) { server.shutdown(); } - Callback zkCloseCallback = new CallbackAdapter(callback) + Callback zkCloseCallback = new CallbackAdapter(callback) { @Override protected None convertResponse(None none) throws Exception diff --git a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperServer.java b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperServer.java index 597e028c44..ea08f37280 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperServer.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/servers/ZooKeeperServer.java @@ -200,7 +200,7 @@ else if (!uris.Uris().contains(uri)) else { warn(_log, _store, " marked down for cluster ", clusterName, "with uri: ", uri); - Map> partitionData = new HashMap>(2); + Map> partitionData = new HashMap<>(2); partitionData.put(uri, Collections.emptyMap()); _store.removePartial(clusterName, new UriProperties(clusterName, partitionData), callback); } diff --git a/d2/src/main/java/com/linkedin/d2/balancer/simple/AbstractLoadBalancerSubscriber.java b/d2/src/main/java/com/linkedin/d2/balancer/simple/AbstractLoadBalancerSubscriber.java index fe95b92309..4df5ff0ecf 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/simple/AbstractLoadBalancerSubscriber.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/simple/AbstractLoadBalancerSubscriber.java @@ -38,7 +38,7 @@ public abstract class AbstractLoadBalancerSubscriber implements private final int _type; private final PropertyEventBus _eventBus; private final ConcurrentMap> _waiters = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); public AbstractLoadBalancerSubscriber(int type, PropertyEventBus eventBus) { @@ -67,7 +67,7 @@ public void ensureListening(String propertyName, boolean register = false; if (waiters == null) { - waiters = new ClosableQueue(); + waiters = new ClosableQueue<>(); ClosableQueue previous = _waiters.putIfAbsent(propertyName, waiters); if (previous == null) diff --git a/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancer.java b/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancer.java index 45c21a30c4..d8f128eee9 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancer.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancer.java @@ -270,7 +270,7 @@ public MapKeyResult, K> getRings(URI serviceUri, Iterable keys) } catch (PartitionAccessException e) { - unmappedKeys.add(new MapKeyResult.UnmappedKey(key, MapKeyResult.ErrorType.FAIL_TO_FIND_PARTITION)); + unmappedKeys.add(new MapKeyResult.UnmappedKey<>(key, MapKeyResult.ErrorType.FAIL_TO_FIND_PARTITION)); continue; } @@ -538,18 +538,18 @@ public HostToKeyMapper getPartitionInformation(URI serviceUri, Collection List orderedStrategies = _state.getStrategiesForService(serviceName, service.getPrioritizedSchemes()); - Map partitionWithoutEnoughHost = new HashMap(); + Map partitionWithoutEnoughHost = new HashMap<>(); if (! orderedStrategies.isEmpty()) { // get the partitionId -> keys mapping final PartitionAccessor accessor = getPartitionAccessor(serviceName, clusterName); int maxPartitionId = accessor.getMaxPartitionId(); - List unmappedKeys = new ArrayList(); + List unmappedKeys = new ArrayList<>(); Map> partitionSet = getPartitionSet(keys, accessor, unmappedKeys); // get the partitionId -> host URIs list - Map> partitionDataMap = new HashMap>(); + Map> partitionDataMap = new HashMap<>(); for (Integer partitionId : partitionSet.keySet()) { for (LoadBalancerState.SchemeStrategyPair pair : orderedStrategies) @@ -587,7 +587,7 @@ public HostToKeyMapper getPartitionInformation(URI serviceUri, Collection } } - return new HostToKeyMapper(unmappedKeys, partitionDataMap, limitHostPerPartition, maxPartitionId + 1, partitionWithoutEnoughHost); + return new HostToKeyMapper<>(unmappedKeys, partitionDataMap, limitHostPerPartition, maxPartitionId + 1, partitionWithoutEnoughHost); } else { @@ -598,12 +598,12 @@ public HostToKeyMapper getPartitionInformation(URI serviceUri, Collection private Map> getPartitionSet(Collection keys, PartitionAccessor accessor, Collection unmappedKeys) { - Map> partitionSet = new TreeMap>(); + Map> partitionSet = new TreeMap<>(); if (keys == null) { for (int i = 0; i <= accessor.getMaxPartitionId(); i++) { - partitionSet.put(i, new HashSet()); + partitionSet.put(i, new HashSet<>()); } } else @@ -624,7 +624,7 @@ private Map> getPartitionSet(Collection keys, PartitionAc Set set = partitionSet.get(partitionId); if (set == null) { - set = new HashSet(); + set = new HashSet<>(); partitionSet.put(partitionId, set); } set.add(key); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerState.java b/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerState.java index 696c63db10..b5fd17cfc4 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerState.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerState.java @@ -181,9 +181,9 @@ public SimpleLoadBalancerState(ScheduledExecutorService executorService, boolean isSSLEnabled) { this(executorService, - new PropertyEventBusImpl(executorService, uriPublisher), - new PropertyEventBusImpl(executorService, clusterPublisher), - new PropertyEventBusImpl(executorService, servicePublisher), + new PropertyEventBusImpl<>(executorService, uriPublisher), + new PropertyEventBusImpl<>(executorService, clusterPublisher), + new PropertyEventBusImpl<>(executorService, servicePublisher), clientFactories, loadBalancerStrategyFactories, sslContext, @@ -779,7 +779,7 @@ public List getStrategiesForService(String serviceName, else { - List orderedStrategies = new ArrayList(prioritizedSchemes.size()); + List orderedStrategies = new ArrayList<>(prioritizedSchemes.size()); for (String scheme : prioritizedSchemes) { // if this scheme is not supported (ie https not enabled) don't add it to the list diff --git a/d2/src/main/java/com/linkedin/d2/balancer/strategies/LoadBalancerStrategy.java b/d2/src/main/java/com/linkedin/d2/balancer/strategies/LoadBalancerStrategy.java index 0846c3d2a5..92b27cdcf4 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/strategies/LoadBalancerStrategy.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/strategies/LoadBalancerStrategy.java @@ -128,7 +128,7 @@ public static void addRequestContextExcludedHost(RequestContext context, URI exc Set excludedHosts = getRequestContextExcludedHosts(context); if (excludedHosts == null) { - excludedHosts = new HashSet(); + excludedHosts = new HashSet<>(); context.putLocalAttr(EXCLUDED_HOST_KEY_NAME, excludedHosts); } excludedHosts.add(excludedHost); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/strategies/PointBasedConsistentHashRingFactory.java b/d2/src/main/java/com/linkedin/d2/balancer/strategies/PointBasedConsistentHashRingFactory.java index 5b53cc0e66..e3f2967dcf 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/strategies/PointBasedConsistentHashRingFactory.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/strategies/PointBasedConsistentHashRingFactory.java @@ -193,7 +193,7 @@ else if (numDesiredPoints <= pointList.size()) } int hashInt = buf.getInt(); - pointList.add(new Point(t, hashInt)); + pointList.add(new Point<>(t, hashInt)); } return pointList; diff --git a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerState.java b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerState.java index de225dd055..e500ad1891 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerState.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerState.java @@ -58,8 +58,8 @@ public class DegraderLoadBalancerState DegraderLoadBalancerStrategyConfig config, List degraderStateListenerFactories) { - _degraderProperties = degraderProperties != null ? degraderProperties : Collections.emptyMap(); - _partitions = new ConcurrentHashMap(); + _degraderProperties = degraderProperties != null ? degraderProperties : Collections.emptyMap(); + _partitions = new ConcurrentHashMap<>(); _serviceName = serviceName; _config = config; _degraderStateListenerFactories = degraderStateListenerFactories; @@ -84,7 +84,7 @@ public Partition getPartition(int partitionId) new PartitionDegraderLoadBalancerState (-1, _config.getClock().currentTimeMillis(), false, new DelegatingRingFactory<>(_config), - new HashMap(), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy. LOAD_BALANCE, 0, 0, diff --git a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyV3.java b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyV3.java index 5897b598f0..14becd7669 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyV3.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyV3.java @@ -401,7 +401,7 @@ private void updatePartitionState(long clusterGenerationId, Partition partition, { PartitionDegraderLoadBalancerState partitionState = partition.getState(); - List clientUpdaters = new ArrayList(); + List clientUpdaters = new ArrayList<>(); for (DegraderTrackerClient client: trackerClients) { clientUpdaters.add(new DegraderTrackerClientUpdater(client, partition.getId())); @@ -723,7 +723,7 @@ private static PartitionDegraderLoadBalancerState doUpdatePartitionState(long cl debug(_log, "average cluster latency: ", newCurrentAvgClusterLatency); // This points map stores how many hash map points to allocate for each tracker client. - Map points = new HashMap(); + Map points = new HashMap<>(); Map oldPointsMap = oldState.getPointsMap(); for (DegraderTrackerClientUpdater clientUpdater : degraderTrackerClientUpdaters) @@ -1444,4 +1444,3 @@ public String toString() + ", _state=" + _state + "]"; } } - diff --git a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/PartitionDegraderLoadBalancerState.java b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/PartitionDegraderLoadBalancerState.java index e1b6faded2..f1448f55f3 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/PartitionDegraderLoadBalancerState.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/strategies/degrader/PartitionDegraderLoadBalancerState.java @@ -109,7 +109,7 @@ public enum Strategy _lastUpdated = lastUpdated; _serviceName = state._serviceName; _degraderProperties = state._degraderProperties; - _previousMaxDropRate = new HashMap(); + _previousMaxDropRate = new HashMap<>(); _currentClusterCallCount = 0; _quarantineMap = state._quarantineMap; _quarantineHistory = state._quarantineHistory; diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/HostToKeyMapper.java b/d2/src/main/java/com/linkedin/d2/balancer/util/HostToKeyMapper.java index 402dd23663..9928a01cce 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/HostToKeyMapper.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/HostToKeyMapper.java @@ -67,14 +67,14 @@ public HostToKeyMapper(Collection unmappedKeys, Map> { throw new IllegalArgumentException("MaxNumHost cannot be less than 1"); } - final Set> unmappedKeysSet = new HashSet>(); + final Set> unmappedKeysSet = new HashSet<>(); _partitionInfoMap = Collections.unmodifiableMap(partitionInfoMap); _limitHostPerPartition = limitHostPerPartition; _partitionsWithoutEnoughHosts = partitionsWithoutEnoughHosts; _partitionCount = partitionCount; for (K key : unmappedKeys) { - unmappedKeysSet.add(new UnmappedKey(key, ErrorType.FAIL_TO_FIND_PARTITION)); + unmappedKeysSet.add(new UnmappedKey<>(key, ErrorType.FAIL_TO_FIND_PARTITION)); } _unmappedKeys = Collections.unmodifiableSet(unmappedKeysSet); } @@ -91,7 +91,7 @@ public HostToKeyMapper(Collection unmappedKeys, Map> */ public HostToKeyResult getResult(int whichIteration) { - return doGetResult(whichIteration, _partitionInfoMap, new HashSet>(_unmappedKeys)); + return doGetResult(whichIteration, _partitionInfoMap, new HashSet<>(_unmappedKeys)); } /** @@ -106,11 +106,11 @@ public HostToKeyResult getResult(int whichIteration) */ public HostToKeyResult getResult(int whichIteration, Collection keys) { - Map> newPartitionInfoMap = new HashMap>(); + Map> newPartitionInfoMap = new HashMap<>(); for (Map.Entry> entry : _partitionInfoMap.entrySet()) { Collection keysForPartition = entry.getValue().getKeys(); - List newKeyList = new ArrayList(); + List newKeyList = new ArrayList<>(); for (Iterator iterator = keysForPartition.iterator(); iterator.hasNext();) { @@ -121,10 +121,10 @@ public HostToKeyResult getResult(int whichIteration, Collection keys) } } - newPartitionInfoMap.put(entry.getKey(), new KeysAndHosts(newKeyList, entry.getValue().getHosts())); + newPartitionInfoMap.put(entry.getKey(), new KeysAndHosts<>(newKeyList, entry.getValue().getHosts())); } - return doGetResult(whichIteration, newPartitionInfoMap, new HashSet>(_unmappedKeys)); + return doGetResult(whichIteration, newPartitionInfoMap, new HashSet<>(_unmappedKeys)); } private HostToKeyResult doGetResult(int whichIteration, Map> partitionInfoMap, Collection> unmappedKeys) @@ -134,7 +134,7 @@ private HostToKeyResult doGetResult(int whichIteration, Map> hostToKeysMerge = new HashMap>(); + Map> hostToKeysMerge = new HashMap<>(); for (Map.Entry> entry : partitionInfoMap.entrySet()) { Collection keysForThisPartition = entry.getValue().getKeys(); @@ -153,7 +153,7 @@ private HostToKeyResult doGetResult(int whichIteration, Map(hostToKeysMerge, unmappedKeys); + return new HostToKeyResult<>(hostToKeysMerge, unmappedKeys); } // utility method to merge keys that maps to the same host. This method does the merging in hostToKeysMerge that @@ -167,7 +167,7 @@ private void mergeKeys(List hosts, Collection keys, { for (K key : keys) { - unmappedKeys.add(new UnmappedKey(key, ErrorType.NO_HOST_AVAILABLE_IN_PARTITION)); + unmappedKeys.add(new UnmappedKey<>(key, ErrorType.NO_HOST_AVAILABLE_IN_PARTITION)); } } else @@ -176,7 +176,7 @@ private void mergeKeys(List hosts, Collection keys, Collection keysForCurrentHost = hostToKeysMerge.get(currentHost); if (keysForCurrentHost == null) { - keysForCurrentHost = new HashSet(); + keysForCurrentHost = new HashSet<>(); hostToKeysMerge.put(currentHost, keysForCurrentHost); } keysForCurrentHost.addAll(keys); @@ -185,12 +185,12 @@ private void mergeKeys(List hosts, Collection keys, public List getAllHosts() { - Set hosts = new HashSet(); + Set hosts = new HashSet<>(); for (Map.Entry> entry : _partitionInfoMap.entrySet()) { hosts.addAll(entry.getValue().getHosts()); } - return new ArrayList(hosts); + return new ArrayList<>(hosts); } public List getHosts(int partitionId) diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerClientCli.java b/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerClientCli.java index b176b085d9..6e361a2696 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerClientCli.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerClientCli.java @@ -440,7 +440,7 @@ public DynamicClient createZKFSTogglingLBClient(String zkHostsPortsConnectionStr Exception { _zkfsLoadBalancer = getZKFSLoadBalancer(zkHostsPortsConnectionString, d2path, servicePath); - FutureCallback startupCallback = new FutureCallback(); + FutureCallback startupCallback = new FutureCallback<>(); _zkfsLoadBalancer.start(startupCallback); startupCallback.get(5000, TimeUnit.MILLISECONDS); @@ -589,7 +589,7 @@ public static PropertyStore getStore(ZKConnection zkclient, if (storeUri.getScheme().equals("zk")) { - ZooKeeperPermanentStore zkStore = new ZooKeeperPermanentStore( + ZooKeeperPermanentStore zkStore = new ZooKeeperPermanentStore<>( zkclient, serializer, storeUri.getPath()); startStore(zkStore); return zkStore; @@ -602,14 +602,14 @@ public static PropertyStore getStore(ZKConnection zkclient, else { // assume it's a local file - return new FileStore(storeUri.getPath(), ".json", serializer); + return new FileStore<>(storeUri.getPath(), ".json", serializer); } } public static List getServicesGroups (ZKConnection zkclient, String basePath) throws Exception { - List servicesGroups = new ArrayList(); + List servicesGroups = new ArrayList<>(); ZooKeeper zook = zkclient.getZooKeeper(); List children = zook.getChildren(basePath,false); @@ -639,7 +639,7 @@ public static PropertyStore getEphemeralStore(ZKConnection zkclient, if (storeUri.getScheme().equals("zk")) { - ZooKeeperEphemeralStore zkStore = new ZooKeeperEphemeralStore( zkclient, serializer, merger, storeUri.getPath()); + ZooKeeperEphemeralStore zkStore = new ZooKeeperEphemeralStore<>( zkclient, serializer, merger, storeUri.getPath()); startStore(zkStore); return zkStore; } @@ -651,7 +651,7 @@ public static PropertyStore getEphemeralStore(ZKConnection zkclient, else { // assume it's a local file - return new FileStore(storeUri.getPath(), ".json", serializer); + return new FileStore<>(storeUri.getPath(), ".json", serializer); } } @@ -660,7 +660,7 @@ private static void startStore(PropertyStore store) throws PropertyStoreE { try { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); } @@ -703,14 +703,14 @@ public static SimpleLoadBalancer getLoadBalancer(ZKConnection zkclient, ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("D2 PropertyEventExecutor")); PropertyEventBus serviceBus = - new PropertyEventBusImpl(executor, zkServiceRegistry); + new PropertyEventBusImpl<>(executor, zkServiceRegistry); PropertyEventBus uriBus = - new PropertyEventBusImpl(executor, zkUriRegistry); + new PropertyEventBusImpl<>(executor, zkUriRegistry); PropertyEventBus clusterBus = - new PropertyEventBusImpl(executor, zkClusterRegistry); + new PropertyEventBusImpl<>(executor, zkClusterRegistry); Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); loadBalancerStrategyFactories.put("random", new RandomLoadBalancerStrategyFactory()); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); @@ -718,8 +718,7 @@ public static SimpleLoadBalancer getLoadBalancer(ZKConnection zkclient, loadBalancerStrategyFactories.put("degraderV3", new DegraderLoadBalancerStrategyFactoryV3()); loadBalancerStrategyFactories.put("degraderV2_1", new DegraderLoadBalancerStrategyFactoryV3()); - Map clientFactories = - new HashMap(); + Map clientFactories = new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); @@ -734,7 +733,7 @@ public static SimpleLoadBalancer getLoadBalancer(ZKConnection zkclient, null, null, false); SimpleLoadBalancer balancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, executor); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(5, TimeUnit.SECONDS); @@ -759,11 +758,11 @@ public ZKFSLoadBalancer getZKFSLoadBalancer(String zkConnectString, String d2pat d2ServicePath = "services"; } - Map clientFactories = new HashMap(); + Map clientFactories = new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); loadBalancerStrategyFactories.put("random", new RandomLoadBalancerStrategyFactory()); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); @@ -786,7 +785,7 @@ public Set< UriProperties> getServiceURIsProps(String zkserver, String d2path, URISyntaxException, PropertyStoreException { - Set uriprops = new HashSet(); + Set uriprops = new HashSet<>(); // zk stores String scstoreString = zkserver + ZKFSUtil.servicePath(d2path); String uristoreString = zkserver + ZKFSUtil.uriPath(d2path); @@ -812,7 +811,7 @@ public Map getServiceClustersURIsInfo(String zkserver, S URISyntaxException, PropertyStoreException { - Map map = new HashMap(); + Map map = new HashMap<>(); // zk stores String scstoreString = zkserver + ZKFSUtil.servicePath(d2path); String uristoreString = zkserver + ZKFSUtil.uriPath(d2path); @@ -985,9 +984,9 @@ public static String printStores(ZKConnection zkclient, String zkserver, String int serviceCount = 0; String zkstr = "\nZKServer:" + zkserver; StringBuilder sb = new StringBuilder(); - Set currentservices = new HashSet(); - Map> zkServiceRegistryMap = new HashMap>(); - Map> servicesGroupMap = new HashMap>(); + Set currentservices = new HashSet<>(); + Map> zkServiceRegistryMap = new HashMap<>(); + Map> servicesGroupMap = new HashMap<>(); // zk stores String clstoreString = zkserver + ZKFSUtil.clusterPath(d2path); @@ -1285,7 +1284,7 @@ private void shutdownZKRegistry(ZooKeeperStore zkregistry) throws Exception { if (zkregistry != null) { - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); zkregistry.shutdown(shutdownCallback); shutdownCallback.get(5000, TimeUnit.MILLISECONDS); } diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerUtil.java b/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerUtil.java index c4c033a5fb..c9a0bd118e 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerUtil.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/LoadBalancerUtil.java @@ -101,8 +101,7 @@ public static Map> getSubProperties(String prefix, String propertiesString) throws IOException { Properties fileProperties = new Properties(); - Map> utilServicePropertyMap = - new HashMap>(); + Map> utilServicePropertyMap = new HashMap<>(); fileProperties.load(new StringReader(propertiesString)); @@ -121,7 +120,7 @@ public static Map> getSubProperties(String prefix, if (serviceProperties == null) { - serviceProperties = new HashMap(); + serviceProperties = new HashMap<>(); utilServicePropertyMap.put(serviceName, serviceProperties); } @@ -150,7 +149,7 @@ public static List getOrElse(List list) { if (list == null) { - return new ArrayList(); + return new ArrayList<>(); } return list; diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/MapKeyResult.java b/d2/src/main/java/com/linkedin/d2/balancer/util/MapKeyResult.java index 7136cb9fad..cbaf92bfae 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/MapKeyResult.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/MapKeyResult.java @@ -88,7 +88,7 @@ public boolean equals(Object o) public MapKeyResult(Map> mapResult, Collection> unMappedKeys) { - Map> mapResultTmp = new HashMap>(mapResult.size() * 2); + Map> mapResultTmp = new HashMap<>(mapResult.size() * 2); for (Map.Entry> entry : mapResult.entrySet()) { mapResultTmp.put(entry.getKey(), Collections.unmodifiableCollection(entry.getValue())); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapper.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapper.java index 2334747ca1..5759e52cee 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapper.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapper.java @@ -117,8 +117,8 @@ public MapKeyResult mapKeysV2(URI serviceUri, Iterable keys) MapKeyResult, K> keyToPartitionResult = _ringProvider.getRings(serviceUri, keys); Map, Collection> ringToKeys = keyToPartitionResult.getMapResult(); - Map> result = new HashMap>(); - Collection> unmappedKeys = new ArrayList>(); + Map> result = new HashMap<>(); + Collection> unmappedKeys = new ArrayList<>(); // first collect unmappedkeys in ditributing keys to partitions unmappedKeys.addAll(keyToPartitionResult.getUnmappedKeys()); @@ -136,7 +136,7 @@ public MapKeyResult mapKeysV2(URI serviceUri, Iterable keys) Collection collection = result.get(uri); if (collection == null) { - collection = new ArrayList(); + collection = new ArrayList<>(); result.put(uri, collection); } collection.addAll(hostEntry.getValue()); @@ -146,15 +146,15 @@ public MapKeyResult mapKeysV2(URI serviceUri, Iterable keys) unmappedKeys.addAll(keyToHostResult.getUnmappedKeys()); } - return new MapKeyResult(result, unmappedKeys); + return new MapKeyResult<>(result, unmappedKeys); } private MapKeyResult doMapKeys(Ring ring, Iterable keys) throws ServiceUnavailableException { String[] keyTokens = new String[1]; - List> unmappedKeys = new ArrayList>(); - Map> result = new HashMap>(); + List> unmappedKeys = new ArrayList<>(); + Map> result = new HashMap<>(); for (K key : keys) { keyTokens[0] = key.toString(); @@ -163,18 +163,18 @@ private MapKeyResult doMapKeys(Ring ring, Iterable keys) URI uri = ring.get(hashCode); if (uri == null) { - unmappedKeys.add(new MapKeyResult.UnmappedKey(key, MapKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION)); + unmappedKeys.add(new MapKeyResult.UnmappedKey<>(key, MapKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION)); continue; } Collection collection = result.get(uri); if (collection == null) { - collection = new ArrayList(); + collection = new ArrayList<>(); result.put(uri, collection); } collection.add(key); } - return new MapKeyResult(result, unmappedKeys); + return new MapKeyResult<>(result, unmappedKeys); } } diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRing.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRing.java index 7090b63d90..61e56f70ad 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRing.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRing.java @@ -82,7 +82,7 @@ public ConsistentHashRing(List> points) // which are obsoleted already. When those strategies are removed, this three functions should be removed too. public ConsistentHashRing(Map pointMap) { - _points = new ArrayList>(); + _points = new ArrayList<>(); try { @@ -101,7 +101,7 @@ public ConsistentHashRing(Map pointMap) @Deprecated public ConsistentHashRing(Map pointMap, MessageDigest md) { - _points = new ArrayList>(); + _points = new ArrayList<>(); _md = md; add(pointMap); @@ -150,7 +150,7 @@ protected void add(Map pointMap) hash[iMod4TimesFour] + (hash[iMod4TimesFour + 1] << 8) + (hash[iMod4TimesFour + 2] << 16) + (hash[iMod4TimesFour + 3] << 24); - _points.add(new Point(t, hashInt)); + _points.add(new Point<>(t, hashInt)); } } Collections.sort(_points); @@ -162,7 +162,7 @@ private int getIndex(int key) { debug(_log, "searching for hash in ring of size ", _points.size(), " using hash: ", key); - int index = Collections.binarySearch(_points, new Point(null, key)); + int index = Collections.binarySearch(_points, new Point<>(null, key)); // if the index is negative, then no exact match was found, and the search function is // returning (-(insertionPoint) - 1). @@ -208,12 +208,12 @@ public Iterator getIterator(int key) { debug(_log, "get called on a hash ring with nothing in it"); - return new ConsistentHashRingIterator(_points, 0); + return new ConsistentHashRingIterator<>(_points, 0); } int from = getIndex(key); - return new ConsistentHashRingIterator(_points, from); + return new ConsistentHashRingIterator<>(_points, from); } public List> getPoints() @@ -256,7 +256,7 @@ Map getCoverageMap() return null; } - Map coverageMap = new HashMap(); + Map coverageMap = new HashMap<>(); Double curr = Double.valueOf(Integer.MIN_VALUE); T firstElement = null; //we know points are sortedSet and the iterator is iterating from low to high diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRing.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRing.java index 3d986c7565..e6a09c6b74 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRing.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRing.java @@ -96,7 +96,7 @@ public boolean isEmpty() private TreeMap calculateCDF(Map pointsMap) { int cumulativeSum = 0; - TreeMap cumulativePointsMap = new TreeMap(); + TreeMap cumulativePointsMap = new TreeMap<>(); for (Map.Entry entry : pointsMap.entrySet()) { diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/RingBasedUriMapper.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/RingBasedUriMapper.java index ec4f774dd9..da3d833eab 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/RingBasedUriMapper.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/RingBasedUriMapper.java @@ -115,7 +115,7 @@ public URIMappingResult mapUris(List> requestUriKeyPa Map hostToParitionId = new HashMap<>(); Map> hostToKeySet = distributeToHosts(requestsByPartition, rings, hashFunction, hostToParitionId, unmapped); - return new URIMappingResult(hostToKeySet, unmapped, hostToParitionId); + return new URIMappingResult<>(hostToKeySet, unmapped, hostToParitionId); } /** diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/StaticRingProvider.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/StaticRingProvider.java index 11031ea2b0..aafe8d441c 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/StaticRingProvider.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/StaticRingProvider.java @@ -44,7 +44,7 @@ public class StaticRingProvider implements HashRingProvider public StaticRingProvider(Ring ring) { - List> rings = new ArrayList>(); + List> rings = new ArrayList<>(); rings.add(ring); _rings = Collections.unmodifiableList(rings); _hashFunction = null; @@ -52,7 +52,7 @@ public StaticRingProvider(Ring ring) public StaticRingProvider(List> rings) { - _rings = Collections.unmodifiableList(new ArrayList>(rings)); + _rings = Collections.unmodifiableList(new ArrayList<>(rings)); _hashFunction = null; } @@ -65,8 +65,8 @@ public MapKeyResult, K> getRings(URI serviceUri, Iterable keys) throw new ServiceUnavailableException("PEGA_1030. Ring not configured:", serviceUri.toString()); } - Map, Collection> result = new HashMap, Collection>(); - List> unmappedKeys = new ArrayList>(); + Map, Collection> result = new HashMap<>(); + List> unmappedKeys = new ArrayList<>(); for (K key : keys) { // assume key could be parsed to int, just for simplicity, as this is only used in tests @@ -78,25 +78,25 @@ public MapKeyResult, K> getRings(URI serviceUri, Iterable keys) Collection set = result.get(ring); if (set == null) { - set = new HashSet(); + set = new HashSet<>(); result.put(ring, set); } set.add(key); } catch(NumberFormatException e) { - unmappedKeys.add(new MapKeyResult.UnmappedKey(key, MapKeyResult.ErrorType.FAIL_TO_FIND_PARTITION)); + unmappedKeys.add(new MapKeyResult.UnmappedKey<>(key, MapKeyResult.ErrorType.FAIL_TO_FIND_PARTITION)); } } - return new MapKeyResult, K>(result, unmappedKeys); + return new MapKeyResult<>(result, unmappedKeys); } @Override public Map> getRings(URI serviceUri) { int partitionCount = _rings.size(); - Map> ringMap = new HashMap>(partitionCount * 2); + Map> ringMap = new HashMap<>(partitionCount * 2); for (int partitionId = 0; partitionId < partitionCount; partitionId++) { ringMap.put(partitionId, _rings.get(partitionId)); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/URIRegexHash.java b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/URIRegexHash.java index ffcaa9dbdc..b747b8cc37 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/URIRegexHash.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/util/hashing/URIRegexHash.java @@ -86,7 +86,7 @@ public URIRegexHash(List patterns, boolean failOnNoMatch) public URIRegexHash(List patterns, boolean failOnNoMatch, boolean warnOnNoMatch) { - List compiledPatterns = new ArrayList(patterns.size()); + List compiledPatterns = new ArrayList<>(patterns.size()); for (String p : patterns) { compiledPatterns.add(Pattern.compile(p)); diff --git a/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSLoadBalancer.java b/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSLoadBalancer.java index ec12d5d5b0..f886fe9d12 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSLoadBalancer.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSLoadBalancer.java @@ -86,7 +86,7 @@ public class ZKFSLoadBalancer private final String _connectString; private final int _sessionTimeout; private final int _initialZKTimeout; - private final AtomicReference> _startupCallback = new AtomicReference>(); + private final AtomicReference> _startupCallback = new AtomicReference<>(); private final TogglingLoadBalancerFactory _loadBalancerFactory; private final File _zkFlagFile; private final ZKFSDirectory _directory; diff --git a/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSTogglingLoadBalancerFactoryImpl.java b/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSTogglingLoadBalancerFactoryImpl.java index 4eef81b9a5..15180e99de 100644 --- a/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSTogglingLoadBalancerFactoryImpl.java +++ b/d2/src/main/java/com/linkedin/d2/balancer/zkfs/ZKFSTogglingLoadBalancerFactoryImpl.java @@ -324,9 +324,8 @@ protected ZooKeeperPermanentStore createPermanentStore(ZKConnection zkCon ScheduledExecutorService executorService, int zookeeperReadWindowMs) { - ZooKeeperPermanentStore store = new ZooKeeperPermanentStore(zkConnection, serializer, nodePath, - executorService, zookeeperReadWindowMs); - return store; + return new ZooKeeperPermanentStore<>(zkConnection, serializer, nodePath, + executorService, zookeeperReadWindowMs); } protected ZooKeeperEphemeralStore createEphemeralStore(ZKConnection zkConnection, String nodePath, @@ -336,15 +335,13 @@ protected ZooKeeperEphemeralStore createEphemeralStore(ZKConnection zkCon ScheduledExecutorService executorService, int readWindow) { - ZooKeeperEphemeralStore store = new ZooKeeperEphemeralStore(zkConnection, serializer, merger, nodePath, + return new ZooKeeperEphemeralStore<>(zkConnection, serializer, merger, nodePath, false, useNewWatcher, backupStoreFilePath, executorService, readWindow); - return store; } protected FileStore createFileStore(String path, PropertySerializer serializer) { - FileStore store = new FileStore<>(path, FileSystemDirectory.FILE_STORE_EXTENSION, serializer); - return store; + return new FileStore<>(path, FileSystemDirectory.FILE_STORE_EXTENSION, serializer); } public interface ComponentFactory diff --git a/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventBusImpl.java b/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventBusImpl.java index 541d846b46..d75a24e41c 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventBusImpl.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventBusImpl.java @@ -43,9 +43,9 @@ public class PropertyEventBusImpl implements PropertyEventBus { private final PropertyEventThread _thread; private PropertyEventPublisher _publisher; - private final Map _properties = new HashMap(); - private final Map>> _subscribers = new HashMap>>(); - private final List> _allPropertySubscribers = new ArrayList>(); + private final Map _properties = new HashMap<>(); + private final Map>> _subscribers = new HashMap<>(); + private final List> _allPropertySubscribers = new ArrayList<>(); private static final Logger _log = LoggerFactory.getLogger(PropertyEventBusImpl.class); /* @@ -109,7 +109,7 @@ public void innerRun() List> listeners = _subscribers.get(prop); if (listeners == null) { - listeners = new ArrayList>(); + listeners = new ArrayList<>(); _subscribers.put(prop, listeners); } if (listeners.isEmpty()) @@ -269,9 +269,8 @@ private List> subscribers(String prop) { return subscribers; } - List> all = - new ArrayList>(subscribers.size() - + _allPropertySubscribers.size()); + List> all = new ArrayList<>(subscribers.size() + + _allPropertySubscribers.size()); all.addAll(_allPropertySubscribers); all.addAll(subscribers); return all; diff --git a/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventThread.java b/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventThread.java index 8db4ff4201..72ffe18d68 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventThread.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/event/PropertyEventThread.java @@ -47,7 +47,7 @@ public PropertyEventThread(String name, int size) public PropertyEventThread(String name, int size, boolean start) { - _messages = new LinkedBlockingQueue(size); + _messages = new LinkedBlockingQueue<>(size); setDaemon(true); setName("PropertyEventThread-" + getId() + "-" + name); diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/toggling/TogglingPublisher.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/toggling/TogglingPublisher.java index 6826670cd7..9e4ca25153 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/toggling/TogglingPublisher.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/toggling/TogglingPublisher.java @@ -40,14 +40,14 @@ public class TogglingPublisher private final PublisherWithStatus _primary; private final PublisherWithStatus _backup; private final PropertyEventBus _eventBus; - private final PropertyEventBus _nullBus = new NullEventBus(); + private final PropertyEventBus _nullBus = new NullEventBus<>(); public TogglingPublisher(PropertyEventPublisher primary, PropertyStore backup, PropertyEventBus eventBus) { - _primary = new PublisherWithStatus(primary); - _backup = new PublisherWithStatus(new StoreEventPublisher(backup)); + _primary = new PublisherWithStatus<>(primary); + _backup = new PublisherWithStatus<>(new StoreEventPublisher<>(backup)); _eventBus = eventBus; } diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/util/AbstractPropertyStoreAsync.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/util/AbstractPropertyStoreAsync.java index 283ecbdb17..a1ff9ce8bf 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/util/AbstractPropertyStoreAsync.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/util/AbstractPropertyStoreAsync.java @@ -35,7 +35,7 @@ public abstract class AbstractPropertyStoreAsync implements PropertyStoreAsyn @Override public final void put(String name, T value) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); put(name, value, callback); getUninterruptibly(callback); } @@ -43,7 +43,7 @@ public final void put(String name, T value) throws PropertyStoreException @Override public final void remove(String name) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); remove(name, callback); getUninterruptibly(callback); } @@ -51,7 +51,7 @@ public final void remove(String name) throws PropertyStoreException @Override public final T get(String name) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); get(name, callback); return getUninterruptibly(callback); } diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeper.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeper.java index 0137e02b7b..6e43c32ce0 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeper.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeper.java @@ -146,7 +146,7 @@ public void processResult(int ccRC, String ccPath, Object ccCtx, List cc switch(code) { case OK: - List ourChildren = new ArrayList(); + List ourChildren = new ArrayList<>(); for(final String child : ccChildren) { if(child.contains(_uuid.toString())) @@ -620,4 +620,4 @@ public void zkSetData(String path, byte[] data, int version, AsyncCallback.StatC _zk.setData(path, data, version, cb, ctx); } -} \ No newline at end of file +} diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZKConnection.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZKConnection.java index 30e69fc2a2..b608bece17 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZKConnection.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZKConnection.java @@ -78,11 +78,11 @@ public class ZKConnection // _countDownLatch signals when _zkRef is ready to be used private final CountDownLatch _zkRefLatch = new CountDownLatch(1); - private final AtomicReference _zkRef = new AtomicReference(); + private final AtomicReference _zkRef = new AtomicReference<>(); // _mutex protects the two fields below: _listeners and _currentState private final Object _mutex = new Object(); - private final Set _listeners = new HashSet(); + private final Set _listeners = new HashSet<>(); private Watcher.Event.KeeperState _currentState; public interface StateListener diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisher.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisher.java index 0306b02691..88b20e8d19 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisher.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisher.java @@ -128,12 +128,12 @@ private class ZKDataWatcher extends ZooKeeperStore.ZKStoreWatcher // See: // http://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#Java+Binding private volatile int _initialCount; - private volatile Map _childMap = new HashMap(); + private volatile Map _childMap = new HashMap<>(); private void initialize(String path, List children) { _initialCount = children.size(); - _childMap = new HashMap(); + _childMap = new HashMap<>(); for (String child : children) { String childPath = path + "/" + child; @@ -211,13 +211,13 @@ public void processResult(int rc, String path, Object ctx, byte[] bytes, Stat st { if (_initialCount == 0) { - _eventBus.publishInitialize(propToPublish, (T)new HashMap(_childMap)); + _eventBus.publishInitialize(propToPublish, (T) new HashMap<>(_childMap)); _log.debug("{}: published initialize", propToPublish); } } else { - _eventBus.publishAdd(propToPublish, (T)new HashMap(_childMap)); + _eventBus.publishAdd(propToPublish, (T) new HashMap<>(_childMap)); _log.debug("{}: published add", propToPublish); } } @@ -239,13 +239,13 @@ public void processResult(int rc, String path, Object ctx, byte[] bytes, Stat st { if (_initialCount == 0) { - _eventBus.publishInitialize(propToPublish,(T)new HashMap(_childMap)); + _eventBus.publishInitialize(propToPublish,(T) new HashMap<>(_childMap)); _log.debug("{}: published initialize", propToPublish); } } else { - _eventBus.publishAdd(propToPublish, (T)new HashMap(_childMap)); + _eventBus.publishAdd(propToPublish, (T) new HashMap<>(_childMap)); _log.debug("{}: published add", propToPublish); } break; diff --git a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStore.java b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStore.java index a6805cb3e8..02c9cc857e 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStore.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStore.java @@ -279,7 +279,7 @@ public void remove(String prop, Callback callback) public void removePartial(String listenTo, T discoveryProperties) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); removePartial(listenTo, discoveryProperties, callback); getUninterruptibly(callback); } @@ -290,10 +290,10 @@ public void removePartial(final String prop, final T value, final Callback trace(_log, "remove partial ", prop, ": ", value); - final Callback> childrenCallback = new Callback>() + final Callback> childrenCallback = new Callback>() { @Override - public void onSuccess(Map children) + public void onSuccess(Map children) { String delete = _merger.unmerge(prop, value, children); @@ -388,10 +388,10 @@ private void getMergedChildren(String path, List children, ZKStoreWatche if (children.size() > 0) { _log.debug("getMergedChildren: collecting {}", children); - ChildCollector collector = new ChildCollector(children.size(), new CallbackAdapter>(callback) + ChildCollector collector = new ChildCollector(children.size(), new CallbackAdapter>(callback) { @Override - protected T convertResponse(Map response) throws Exception + protected T convertResponse(Map response) throws Exception { return _merger.merge(propertyName, response.values()); } @@ -858,7 +858,7 @@ private class ChildCollector implements AsyncCallback.DataCallback private ChildCollector(int count, Callback> callback) { _count = count; - _properties = new HashMap(_count); + _properties = new HashMap<>(_count); _callback = callback; } diff --git a/d2/src/main/java/com/linkedin/d2/discovery/util/D2Config.java b/d2/src/main/java/com/linkedin/d2/discovery/util/D2Config.java index 0bfa654531..405a9afc86 100644 --- a/d2/src/main/java/com/linkedin/d2/discovery/util/D2Config.java +++ b/d2/src/main/java/com/linkedin/d2/discovery/util/D2Config.java @@ -155,22 +155,22 @@ public D2Config (String zkHosts, int sessionTimeout, String basePath, public int configure() throws Exception { // original map derived from properties file - Map clusterServiceConfiguration = merge(_clusterServiceConfigurations); + Map clusterServiceConfiguration = merge(_clusterServiceConfigurations); // map of clusterName -> cluster configuration - Map> clusters = new HashMap>(); + Map> clusters = new HashMap<>(); // map of serviceName -> service configuration - Map> services = new HashMap>(); + Map> services = new HashMap<>(); // Ugly. But this is a map of service groups, so it needs to reflect multiple services maps. - Map>> serviceVariants = new HashMap>>(); + Map>> serviceVariants = new HashMap<>(); // temporary mapping from cluster name to services map, to aid in create cluster variants and // service groups. - Map>> clusterToServiceMapping = new HashMap>>(); + Map>> clusterToServiceMapping = new HashMap<>(); int status; // temporary mapping from cluster name to the list of colo variants it has. - Map> variantToVariantsMapping = new HashMap>(); + Map> variantToVariantsMapping = new HashMap<>(); // temporary mapping from cluster name to coloVariant ClusterNames list. - Map> clusterToColoClustersMapping = new HashMap>(); + Map> clusterToColoClustersMapping = new HashMap<>(); // mapping from regular cluster name to the list of containing services // which will be added as children of the regular cluster znode. Map> regularClusterToServicesMapping = new HashMap<>(); @@ -313,7 +313,7 @@ public int configure() throws Exception // coloServicesConfigs are the set of d2 services in this cluster in this colo // for the regular cluster case I could avoid creation of a new HashMap for both coloServicesConfig // and coloServiceConfig, as an optimization at the expense of simplicity. - Map> coloServicesConfigs = new HashMap>(); + Map> coloServicesConfigs = new HashMap<>(); // Only create the default services once, and only when we have an empty colo string or the // colo matches the default colo. @@ -349,7 +349,7 @@ public int configure() throws Exception Map transportClientConfig = (Map) transportClientProperty; serviceConfig.put(PropertyKeys.TRANSPORT_CLIENT_PROPERTIES, transportClientConfig); - Map coloServiceConfig = new HashMap(serviceConfig); + Map coloServiceConfig = new HashMap<>(serviceConfig); // we will create the default services when this is a non-colo aware cluster or when the colo // matches the default colo. This, along with the defaultServicesCreated flag, ensures we @@ -365,7 +365,7 @@ public int configure() throws Exception // Cluster. Why not just use the original service name? We will point the original // service name at the local cluster, as well as to make it explicit that requests // sent to this service might cross colos, if the master is located in another colo. - Map masterServiceConfig = new HashMap(serviceConfig); + Map masterServiceConfig = new HashMap<>(serviceConfig); String masterServiceName = serviceName + PropertyKeys.MASTER_SUFFIX; String masterClusterName; if (enableSymlink) @@ -387,7 +387,7 @@ public int configure() throws Exception // the colo-agnostic service -> colo-agnostic cluster mapping (fooService -> FooCluster) // the latter only being done for regular clusters, the former only being done for clusters // that have coloVariants specified. - Map regularServiceConfig = new HashMap(serviceConfig); + Map regularServiceConfig = new HashMap<>(serviceConfig); if (createColoVariantsForService) { // we set isDefaultService flag only if it is a multi-colo aware service. @@ -432,7 +432,7 @@ public int configure() throws Exception Map coloClusterConfig = clusterConfig; if (!clusterName.equals(coloClusterName)) { - coloClusterConfig = new HashMap(clusterConfig); + coloClusterConfig = new HashMap<>(clusterConfig); coloClusterConfig.put(PropertyKeys.CLUSTER_NAME, coloClusterName); if (createDefaultServices) { @@ -447,7 +447,7 @@ public int configure() throws Exception // list before the cluster variants. if (clusterVariantConfig != null) { - Map> coloClusterVariantConfig = new HashMap>(clusterVariantConfig); + Map> coloClusterVariantConfig = new HashMap<>(clusterVariantConfig); status = handleClusterVariants(coloClusterVariantConfig, clusterConfig, clusters, coloServicesConfigs, clusterToServiceMapping, colo, variantToVariantsMapping, masterColo, enableSymlink); @@ -484,7 +484,7 @@ public int configure() throws Exception // listed clusters, and prep that for writing to a different znode than the default service // znode directory. Note that we had already pointed those services to the appropriate cluster // variant earlier. - Map> servicesGroupConfig = new HashMap>(); + Map> servicesGroupConfig = new HashMap<>(); @SuppressWarnings("unchecked") Map configGroupMap = (Map) _serviceVariants.get(serviceGroup); String type = (String)configGroupMap.get(PropertyKeys.TYPE); @@ -542,7 +542,7 @@ public int configure() throws Exception { // start from the full list of services, and then overwrite the services specified by the // cluster variants. - Map> fullServiceList = new HashMap>(services); + Map> fullServiceList = new HashMap<>(services); fullServiceList.putAll(servicesGroupConfig); serviceVariants.put(serviceGroup, fullServiceList); } @@ -655,9 +655,9 @@ private void writeConfig(String path, PropertySerializer serializer, Map propertyDefaults) throws Exception { ZooKeeperPermanentStore store = _useDeltaWrite ? - new DeltaWriteZooKeeperPermanentStore(_zkConnection, serializer, path) : - new ZooKeeperPermanentStore(_zkConnection, serializer, path); - ConfigWriter writer = new ConfigWriter(store, builder, properties, propertyDefaults, _timeout, + new DeltaWriteZooKeeperPermanentStore<>(_zkConnection, serializer, path) : + new ZooKeeperPermanentStore<>(_zkConnection, serializer, path); + ConfigWriter writer = new ConfigWriter<>(store, builder, properties, propertyDefaults, _timeout, TimeUnit.MILLISECONDS, _maxOutstandingWrites); writer.writeConfig(); } @@ -678,12 +678,12 @@ private void writeChildren(Map> clusterToServices) } } - private Map merge(List> maps) + private Map merge(List> maps) { - Map result = new HashMap(); - for (Map map : maps) + Map result = new HashMap<>(); + for (Map map : maps) { - for (Map.Entry e : map.entrySet()) + for (Map.Entry e : map.entrySet()) { if (result.put(e.getKey(), e.getValue()) != null) { @@ -846,7 +846,7 @@ private int handleClusterVariants(Map> clusterVariantC return EXCEPTION_EXIT_CODE; } - Map> varServicesConfig = new HashMap>(); + Map> varServicesConfig = new HashMap<>(); // now take a copy of the services for the default sibling cluster and point the // services to the cluster variant. We form this clusterToServiceMapping here so it is @@ -910,7 +910,7 @@ private void addNewVariantToVariantsList(Map> variantToVari } else { - variantsList = new ArrayList(); + variantsList = new ArrayList<>(); variantsList.add(variantName); variantToVariantsMapping.put(variant, variantsList); } diff --git a/d2/src/main/java/com/linkedin/d2/jmx/DegraderLoadBalancerStrategyV3Jmx.java b/d2/src/main/java/com/linkedin/d2/jmx/DegraderLoadBalancerStrategyV3Jmx.java index a34a991508..7a98bacb88 100644 --- a/d2/src/main/java/com/linkedin/d2/jmx/DegraderLoadBalancerStrategyV3Jmx.java +++ b/d2/src/main/java/com/linkedin/d2/jmx/DegraderLoadBalancerStrategyV3Jmx.java @@ -82,7 +82,7 @@ public String getPointsMap(int partitionId) public String getUnhealthyClientsPoints(int partitionId) { int pointsPerWeight = _strategy.getConfig().getPointsPerWeight(); - List result = new ArrayList(); + List result = new ArrayList<>(); for (Map.Entry entry : _strategy.getState().getPartitionState(partitionId).getPointsMap().entrySet()) { if (entry.getValue() < pointsPerWeight) diff --git a/d2/src/main/java/com/linkedin/d2/jmx/JmxManager.java b/d2/src/main/java/com/linkedin/d2/jmx/JmxManager.java index ef36772066..b965fdcc0a 100644 --- a/d2/src/main/java/com/linkedin/d2/jmx/JmxManager.java +++ b/d2/src/main/java/com/linkedin/d2/jmx/JmxManager.java @@ -71,7 +71,7 @@ public synchronized JmxManager registerFileStore(String name, FileStore s public synchronized JmxManager registerZooKeeperPermanentStore(String name, ZooKeeperPermanentStore store) { - checkReg(new ZooKeeperPermanentStoreJmx(store), name); + checkReg(new ZooKeeperPermanentStoreJmx<>(store), name); return this; } @@ -79,7 +79,7 @@ public synchronized JmxManager registerZooKeeperPermanentStore(String name, public synchronized JmxManager registerZooKeeperEphemeralStore(String name, ZooKeeperEphemeralStore store) { - checkReg(new ZooKeeperEphemeralStoreJmx(store), name); + checkReg(new ZooKeeperEphemeralStoreJmx<>(store), name); return this; } @@ -146,7 +146,7 @@ public synchronized JmxManager registerZooKeeperAnnouncer(String name, public synchronized JmxManager registerZooKeeperTogglingStore(String name, ZooKeeperTogglingStore store) { - checkReg(new ZooKeeperTogglingStoreJmx(store), name); + checkReg(new ZooKeeperTogglingStoreJmx<>(store), name); return this; } diff --git a/d2/src/main/java/com/linkedin/d2/jmx/SimpleLoadBalancerStateJmx.java b/d2/src/main/java/com/linkedin/d2/jmx/SimpleLoadBalancerStateJmx.java index 28113991ce..f02013f691 100644 --- a/d2/src/main/java/com/linkedin/d2/jmx/SimpleLoadBalancerStateJmx.java +++ b/d2/src/main/java/com/linkedin/d2/jmx/SimpleLoadBalancerStateJmx.java @@ -68,13 +68,13 @@ public int getServiceListenCount() @Override public List getSupportedSchemes() { - return new ArrayList(_state.getSupportedSchemes()); + return new ArrayList<>(_state.getSupportedSchemes()); } @Override public List getSupportedStrategies() { - return new ArrayList(_state.getSupportedStrategies()); + return new ArrayList<>(_state.getSupportedStrategies()); } @Override diff --git a/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperAnnouncerJmx.java b/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperAnnouncerJmx.java index 6756ca47a9..ce1d8c62b3 100644 --- a/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperAnnouncerJmx.java +++ b/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperAnnouncerJmx.java @@ -49,7 +49,7 @@ public ZooKeeperAnnouncerJmx(ZooKeeperAnnouncer announcer) @Override public void reset() throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _announcer.reset(callback); try { @@ -64,7 +64,7 @@ public void reset() throws PropertyStoreException @Override public void markUp() throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _announcer.markUp(callback); try { @@ -79,7 +79,7 @@ public void markUp() throws PropertyStoreException @Override public void markDown() throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _announcer.markDown(callback); try { @@ -142,7 +142,7 @@ public void setPartitionDataUsingJson(String partitionDataJson) { Map rawObject = JacksonUtil.getObjectMapper().readValue(partitionDataJson, new TypeReference>(){}); - Map partitionDataMap = new HashMap(); + Map partitionDataMap = new HashMap<>(); for (Map.Entry entry : rawObject.entrySet()) { PartitionData data = new PartitionData(entry.getValue()); diff --git a/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperServerJmx.java b/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperServerJmx.java index 7111137ffc..4fe336a926 100644 --- a/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperServerJmx.java +++ b/d2/src/main/java/com/linkedin/d2/jmx/ZooKeeperServerJmx.java @@ -41,7 +41,7 @@ public ZooKeeperServerJmx(ZooKeeperServer server) @Override public void setMarkDown(String clusterName, String uri) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _server.markDown(clusterName, URI.create(uri), callback); try { @@ -56,9 +56,9 @@ public void setMarkDown(String clusterName, String uri) throws PropertyStoreExce @Override public void setMarkUp(String clusterName, String uri, double weight) throws PropertyStoreException { - Map partitionDataMap = new HashMap(1); + Map partitionDataMap = new HashMap<>(1); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weight)); - setMarkup(clusterName, uri, partitionDataMap, Collections.emptyMap()); + setMarkup(clusterName, uri, partitionDataMap, Collections.emptyMap()); } @Override @@ -74,7 +74,7 @@ public void setMarkup(String clusterName, Map uriSpecificProperties) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _server.markUp(clusterName, URI.create(uri), partitionDataMap, uriSpecificProperties, callback); try { diff --git a/d2/src/test/java/com/linkedin/d2/balancer/LoadBalancerTestState.java b/d2/src/test/java/com/linkedin/d2/balancer/LoadBalancerTestState.java index 1b5cd2b1cd..9fd39acdb3 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/LoadBalancerTestState.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/LoadBalancerTestState.java @@ -59,7 +59,7 @@ public class LoadBalancerTestState implements LoadBalancerState @Override public TrackerClient getClient(String clusterName, URI uri) { - Map partitionDataMap = new HashMap(2); + Map partitionDataMap = new HashMap<>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1)); return (getClient) ? new DegraderTrackerClientImpl(uri, partitionDataMap, new TestClient(), SystemClock.instance(), null) : null; } @@ -74,37 +74,35 @@ public TransportClient getClient(String clusterName, String Scheme) public LoadBalancerStateItem getClusterProperties(String clusterName) { return (getClusterProperties) - ? new LoadBalancerStateItem(new ClusterProperties("cluster-1"), - 0, - 0) : null; + ? new LoadBalancerStateItem<>(new ClusterProperties("cluster-1"), 0, 0) : null; } @Override public LoadBalancerStateItem getPartitionAccessor(String clusterName) { return getPartitionAccessor - ? new LoadBalancerStateItem(DefaultPartitionAccessor.getInstance(), 0, 0) : null; + ? new LoadBalancerStateItem<>(DefaultPartitionAccessor.getInstance(), 0, 0) : null; } @Override public LoadBalancerStateItem getServiceProperties(String serviceName) { - List prioritizedSchemes = new ArrayList(); + List prioritizedSchemes = new ArrayList<>(); prioritizedSchemes.add("http"); return (getServiceProperties) - ? new LoadBalancerStateItem(new ServiceProperties("service-1", - "cluster-1", - "/foo", - Arrays.asList("rr"), - Collections.emptyMap(), - null, - null, - prioritizedSchemes, - null), - 0, - 0) : null; + ? new LoadBalancerStateItem<>(new ServiceProperties("service-1", + "cluster-1", + "/foo", + Arrays.asList("rr"), + Collections.emptyMap(), + null, + null, + prioritizedSchemes, + null), + 0, + 0) : null; } @Override @@ -116,16 +114,16 @@ public LoadBalancerStateItem getUriProperties(String clusterName) URI uri2 = URI.create("http://test.qa2.com:2345"); URI uri3 = URI.create("http://test.qa3.com:6789"); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(3); + Map> uriData = new HashMap<>(3); uriData.put(uri1, partitionData); uriData.put(uri2, partitionData); uriData.put(uri3, partitionData); return (getUriProperties) - ? new LoadBalancerStateItem(new UriProperties("cluster-1", uriData), - 0, - 0) : null; + ? new LoadBalancerStateItem<>(new UriProperties("cluster-1", uriData), + 0, + 0) : null; } catch (Exception e) { @@ -189,7 +187,7 @@ public void shutdown(PropertyEventShutdownCallback shutdown) public List getStrategiesForService(String serviceName, List prioritizedSchemes) { - List orderedStrategies = new ArrayList(prioritizedSchemes.size()); + List orderedStrategies = new ArrayList<>(prioritizedSchemes.size()); for (String scheme : prioritizedSchemes) { LoadBalancerStrategy strategy = getStrategy(serviceName, scheme); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/PartitionedLoadBalancerTestState.java b/d2/src/test/java/com/linkedin/d2/balancer/PartitionedLoadBalancerTestState.java index 3995ed6dae..f09b71689b 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/PartitionedLoadBalancerTestState.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/PartitionedLoadBalancerTestState.java @@ -67,7 +67,7 @@ public PartitionedLoadBalancerTestState(String cluster, String service, String p _partitionDescriptions = partitionDescriptions; _orderedStrategies = orderedStrategies; _partitionAccessor = partitionAccessor; - _trackerClients = new ConcurrentHashMap(); + _trackerClients = new ConcurrentHashMap<>(); _maxClientRequestRetryRatio = maxClientRequestRetryRatio; } @@ -113,33 +113,33 @@ public LoadBalancerStateItem getUriProperties(String clusterName) { //this is used to get partitionId -> host uris UriProperties uriProperties = new UriProperties(_cluster, _partitionDescriptions); - return new LoadBalancerStateItem(uriProperties, 1, 1); + return new LoadBalancerStateItem<>(uriProperties, 1, 1); } @Override public LoadBalancerStateItem getClusterProperties(String clusterName) { - List prioritizedSchemes = new ArrayList(); + List prioritizedSchemes = new ArrayList<>(); prioritizedSchemes.add("http"); ClusterProperties clusterProperties = new ClusterProperties(_cluster, prioritizedSchemes); - return new LoadBalancerStateItem(clusterProperties, 1, 1); + return new LoadBalancerStateItem<>(clusterProperties, 1, 1); } @Override public LoadBalancerStateItem getPartitionAccessor(String clusterName) { //this is used to get partitionId -> key mapping - return new LoadBalancerStateItem(_partitionAccessor,1,1); + return new LoadBalancerStateItem<>(_partitionAccessor,1,1); } @Override public LoadBalancerStateItem getServiceProperties(String serviceName) { ServiceProperties serviceProperties = new ServiceProperties(serviceName, _cluster, _path, - Collections.singletonList(_strategyName), Collections.emptyMap(), + Collections.singletonList(_strategyName), Collections.emptyMap(), Collections.singletonMap(PropertyKeys.HTTP_MAX_CLIENT_REQUEST_RETRY_RATIO, _maxClientRequestRetryRatio), - Collections.emptyMap(), Collections.emptyList(), Collections.emptySet()); - return new LoadBalancerStateItem(serviceProperties, 1, 1); + Collections.emptyMap(), Collections.emptyList(), Collections.emptySet()); + return new LoadBalancerStateItem<>(serviceProperties, 1, 1); } @Override diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/DynamicClientTest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/DynamicClientTest.java index e53fbe80ec..897c379fee 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/DynamicClientTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/DynamicClientTest.java @@ -60,7 +60,7 @@ public void testClient(boolean restOverStream) throws URISyntaxException DynamicClient client = new DynamicClient(balancer, facilities, restOverStream); URI uri = URI.create("d2://test"); RestRequest restRequest = new RestRequestBuilder(uri).build(); - TestCallback restCallback = new TestCallback(); + TestCallback restCallback = new TestCallback<>(); client.restRequest(restRequest, restCallback); @@ -78,7 +78,7 @@ public void testUnavailable(boolean restOverStream) throws URISyntaxException DynamicClient client = new DynamicClient(balancer, null, restOverStream); URI uri = URI.create("d2://test"); RestRequest restRequest = new RestRequestBuilder(uri).build(); - TestCallback restCallback = new TestCallback(); + TestCallback restCallback = new TestCallback<>(); client.restRequest(restRequest, restCallback); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/LazyClientTest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/LazyClientTest.java index 99b31ce3d0..d120f70ff4 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/LazyClientTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/LazyClientTest.java @@ -42,7 +42,7 @@ public class LazyClientTest public void testClientRest() { LazyClientTestFactory factory = new LazyClientTestFactory(); - Map properties = new HashMap(); + Map properties = new HashMap<>(); LazyClient client = new LazyClient(properties, factory); properties.put("test", "exists"); @@ -70,7 +70,7 @@ public void testClientRest() public void testClientStream() { LazyClientTestFactory factory = new LazyClientTestFactory(); - Map properties = new HashMap(); + Map properties = new HashMap<>(); LazyClient client = new LazyClient(properties, factory); properties.put("test", "exists"); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/RetryClientTest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/RetryClientTest.java index d1b5894e62..637b75f464 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/RetryClientTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/RetryClientTest.java @@ -104,7 +104,7 @@ public void testRestRetry() throws Exception false); URI uri = URI.create("d2://retryService?arg1arg2"); RestRequest restRequest = new RestRequestBuilder(uri).setEntity(CONTENT).build(); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest, restCallback); assertNull(restCallback.e); @@ -129,7 +129,7 @@ public void testStreamRetry() throws Exception true); URI uri = URI.create("d2://retryService?arg1arg2"); StreamRequest streamRequest = new StreamRequestBuilder(uri).build(EntityStreams.newEntityStream(new ByteStringWriter(CONTENT))); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.streamRequest(streamRequest, restCallback); assertNull(restCallback.e); @@ -154,7 +154,7 @@ public void testIgnoreStreamRetry() throws Exception false); URI uri = URI.create("d2://retryService?arg1arg2"); StreamRequest streamRequest = new StreamRequestBuilder(uri).build(EntityStreams.newEntityStream(new ByteStringWriter(CONTENT))); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.streamRequest(streamRequest, restCallback); assertNull(restCallback.t); @@ -180,7 +180,7 @@ public void testRestException() throws Exception false); URI uri = URI.create("d2://retryService?arg1=empty&arg2=empty"); RestRequest restRequest = new RestRequestBuilder(uri).build(); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); RequestContext context = new RequestContext(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, URI.create("http://test.linkedin.com/bad")); @@ -209,7 +209,7 @@ public void testStreamException() throws Exception true); URI uri = URI.create("d2://retryService?arg1=empty&arg2=empty"); StreamRequest streamRequest = new StreamRequestBuilder(uri).build(EntityStreams.emptyStream()); - TrackerClientTest.TestCallback streamCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback streamCallback = new TrackerClientTest.TestCallback<>(); RequestContext context = new RequestContext(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, URI.create("http://test.linkedin.com/bad")); @@ -238,7 +238,7 @@ public void testRestRetryOverLimit() throws Exception false); URI uri = URI.create("d2://retryService?arg1=empty&arg2=empty"); RestRequest restRequest = new RestRequestBuilder(uri).build(); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest, restCallback); assertNull(restCallback.t); @@ -264,7 +264,7 @@ public void testStreamRetryOverLimit() throws Exception true); URI uri = URI.create("d2://retryService?arg1=empty&arg2=empty"); StreamRequest streamRequest = new StreamRequestBuilder(uri).build(EntityStreams.emptyStream()); - TrackerClientTest.TestCallback streamCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback streamCallback = new TrackerClientTest.TestCallback<>(); client.streamRequest(streamRequest, streamCallback); assertNull(streamCallback.t); @@ -290,7 +290,7 @@ public void testRestRetryNoAvailableHosts() throws Exception false); URI uri = URI.create("d2://retryService?arg1=empty&arg2=empty"); RestRequest restRequest = new RestRequestBuilder(uri).build(); - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest, restCallback); assertNull(restCallback.t); @@ -352,7 +352,7 @@ public void testRestRetryExceedsClientRetryRatio() throws Exception RestRequest restRequest2 = new RestRequestBuilder(uri2).build(); // This request will be retried and route to the good host - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest1, restCallback); assertNull(restCallback.e); @@ -361,7 +361,7 @@ public void testRestRetryExceedsClientRetryRatio() throws Exception // This request will not be retried because the retry ratio is exceeded clock.addDuration(RetryClient.DEFAULT_UPDATE_INTERVAL_MS); - restCallback = new TrackerClientTest.TestCallback(); + restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest1, restCallback); assertNull(restCallback.t); @@ -369,7 +369,7 @@ public void testRestRetryExceedsClientRetryRatio() throws Exception assertTrue(restCallback.e.getMessage().contains("Data not available")); // If the client sends request to a different service endpoint, the retry ratio should not interfere - restCallback = new TrackerClientTest.TestCallback(); + restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest2, restCallback); assertNull(restCallback.e); @@ -378,7 +378,7 @@ public void testRestRetryExceedsClientRetryRatio() throws Exception // After 5s interval, retry counter is reset and this request will be retried again clock.addDuration(RetryClient.DEFAULT_UPDATE_INTERVAL_MS * RetryClient.DEFAULT_AGGREGATED_INTERVAL_NUM); - restCallback = new TrackerClientTest.TestCallback(); + restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest1, restCallback); assertNull(restCallback.e); @@ -406,7 +406,7 @@ public void testRestRetryUnlimitedClientRetryRatio() throws Exception clock.scheduleWithFixedDelay(() -> { - TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback(); + TrackerClientTest.TestCallback restCallback = new TrackerClientTest.TestCallback<>(); client.restRequest(restRequest, restCallback); // This request will be retried and route to the good host @@ -425,11 +425,11 @@ public SimpleLoadBalancer prepareLoadBalancer(List uris, double maxClien String strategyName = "degrader"; // setup partition - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); for (String uri : uris) { final URI foo = URI.create(uri); - Map foo1Data = new HashMap(); + Map foo1Data = new HashMap<>(); // ensure that we first route to the retry uris before the good uris double weight = uri.contains("good") ? 0.0001 : 1.0; foo1Data.put(0, new PartitionData(weight)); @@ -439,7 +439,7 @@ public SimpleLoadBalancer prepareLoadBalancer(List uris, double maxClien DegraderLoadBalancerStrategyV3 strategy = new DegraderLoadBalancerStrategyV3( new DegraderLoadBalancerStrategyConfig(5000), serviceName, null, Collections.emptyList()); - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair("http", strategy)); PartitionAccessor accessor = new TestRetryPartitionAccessor(); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTest.java index 40ac1ef60e..065b1a3a18 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTest.java @@ -47,9 +47,8 @@ public void testClient() throws URISyntaxException assertEquals(client.getServiceName(), serviceName); RestRequest restRequest = new RestRequestBuilder(URI.create("d2://HistoryService/getCube")).build(); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); @@ -76,9 +75,8 @@ public void testWithQueryAndFragment() assertEquals(client.getServiceName(), serviceName); RestRequest restRequest = new RestRequestBuilder(URI.create("d2://HistoryService/getCube?bar=baz#fragId")).build(); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); @@ -127,9 +125,8 @@ private void testEscapingHelper(String hostUri, String serviceName, String path) assertEquals(client.getServiceName(), serviceName); RestRequest restRequest = new RestRequestBuilder(URI.create("d2://" + serviceName + path)).build(); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); @@ -153,9 +150,8 @@ public void testWithEverything() assertEquals(client.getServiceName(), serviceName); RestRequest restRequest = new RestRequestBuilder(URI.create("d2://HistoryService/getCube?bar=baz#fragId")).build(); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); @@ -178,9 +174,8 @@ public void testPathAppend() assertEquals(client.getServiceName(), serviceName); RestRequest restRequest; - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); restRequest = new RestRequestBuilder(URI.create("d2://HistoryService")).build(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTestStreamRequest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTestStreamRequest.java index a42d43961f..31089ca31c 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTestStreamRequest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClientTestStreamRequest.java @@ -49,9 +49,8 @@ public void testClient() throws URISyntaxException assertEquals(client.getServiceName(), serviceName); StreamRequest streamRequest = new StreamRequestBuilder(URI.create("d2://HistoryService/getCube")).build(EntityStreams.emptyStream()); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); @@ -77,9 +76,8 @@ public void testWithQueryAndFragment() assertEquals(client.getServiceName(), serviceName); StreamRequest streamRequest = getRequest("d2://HistoryService/getCube?bar=baz#fragId"); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); @@ -127,9 +125,8 @@ private void testEscapingHelper(String hostUri, String serviceName, String path) assertEquals(client.getServiceName(), serviceName); StreamRequest streamRequest = getRequest("d2://" + serviceName + path); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); @@ -152,9 +149,8 @@ public void testWithEverything() assertEquals(client.getServiceName(), serviceName); StreamRequest streamRequest = getRequest("d2://HistoryService/getCube?bar=baz#fragId"); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); @@ -176,9 +172,8 @@ public void testPathAppend() assertEquals(client.getServiceName(), serviceName); StreamRequest streamRequest; - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); streamRequest = getRequest("d2://HistoryService"); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/TestBackupRequestsClient.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/TestBackupRequestsClient.java index da295b2cad..fa724d643c 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/TestBackupRequestsClient.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/TestBackupRequestsClient.java @@ -711,7 +711,7 @@ private BackupRequestsClient createAlwaysBackupClientWithHosts(List uris int responseDelayNano, int backupDelayNano, boolean isD2Async) throws IOException { - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); uris.forEach(uri -> partitionDescriptions.put(URI.create(uri), Collections.singletonMap(0, new PartitionData(1)))); StaticLoadBalancerState LbState = new StaticLoadBalancerState() diff --git a/d2/src/test/java/com/linkedin/d2/balancer/clients/TrackerClientTest.java b/d2/src/test/java/com/linkedin/d2/balancer/clients/TrackerClientTest.java index c110f2befd..00eea932b3 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/clients/TrackerClientTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/clients/TrackerClientTest.java @@ -79,9 +79,8 @@ public void testClientStreamRequest() throws URISyntaxException Assert.assertEquals(client.getTransportClient(), wrappedClient); StreamRequest streamRequest = new StreamRequestBuilder(uri).build(EntityStreams.emptyStream()); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.streamRequest(streamRequest, new RequestContext(), restWireAttrs, restCallback); @@ -106,9 +105,8 @@ public void testClientRestRequest() throws URISyntaxException Assert.assertEquals(client.getTransportClient(), wrappedClient); RestRequest restRequest = new RestRequestBuilder(uri).build(); - Map restWireAttrs = new HashMap(); - TestTransportCallback restCallback = - new TestTransportCallback(); + Map restWireAttrs = new HashMap<>(); + TestTransportCallback restCallback = new TestTransportCallback<>(); client.restRequest(restRequest, new RequestContext(), restWireAttrs, restCallback); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/properties/ClientServiceConfigValidatorTest.java b/d2/src/test/java/com/linkedin/d2/balancer/properties/ClientServiceConfigValidatorTest.java index bbbd310378..3a7c677525 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/properties/ClientServiceConfigValidatorTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/properties/ClientServiceConfigValidatorTest.java @@ -15,10 +15,10 @@ public class ClientServiceConfigValidatorTest @Test public void testValidHttpRequestTimeout() { - Map serviceSuppliedProperties = new HashMap(); + Map serviceSuppliedProperties = new HashMap<>(); serviceSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "1000"); - Map clientSuppliedProperties = new HashMap(); + Map clientSuppliedProperties = new HashMap<>(); clientSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "2000"); Assert.assertTrue(ClientServiceConfigValidator.isValidValue(serviceSuppliedProperties, @@ -29,10 +29,10 @@ public void testValidHttpRequestTimeout() @Test public void testInvalidHttpRequestTimeout() { - Map serviceSuppliedProperties = new HashMap(); + Map serviceSuppliedProperties = new HashMap<>(); serviceSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "1000"); - Map clientSuppliedProperties = new HashMap(); + Map clientSuppliedProperties = new HashMap<>(); clientSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "100"); Assert.assertFalse(ClientServiceConfigValidator.isValidValue(serviceSuppliedProperties, @@ -43,10 +43,10 @@ public void testInvalidHttpRequestTimeout() @Test public void testParseFailureHttpRequestTimeout() { - Map serviceSuppliedProperties = new HashMap(); + Map serviceSuppliedProperties = new HashMap<>(); serviceSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "1000"); - Map clientSuppliedProperties = new HashMap(); + Map clientSuppliedProperties = new HashMap<>(); clientSuppliedProperties.put(PropertyKeys.HTTP_REQUEST_TIMEOUT, "foo"); Assert.assertFalse(ClientServiceConfigValidator.isValidValue(serviceSuppliedProperties, @@ -57,10 +57,10 @@ public void testParseFailureHttpRequestTimeout() @Test public void testMaxResponse() { - Map serviceSuppliedProperties = new HashMap(); + Map serviceSuppliedProperties = new HashMap<>(); serviceSuppliedProperties.put(PropertyKeys.HTTP_MAX_RESPONSE_SIZE, "1000"); - Map clientSuppliedProperties = new HashMap(); + Map clientSuppliedProperties = new HashMap<>(); clientSuppliedProperties.put(PropertyKeys.HTTP_MAX_RESPONSE_SIZE, "10000"); Assert.assertTrue(ClientServiceConfigValidator.isValidValue(serviceSuppliedProperties, diff --git a/d2/src/test/java/com/linkedin/d2/balancer/properties/ClusterPropertiesSerializerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/properties/ClusterPropertiesSerializerTest.java index de317afb4d..4dcc5b7705 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/properties/ClusterPropertiesSerializerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/properties/ClusterPropertiesSerializerTest.java @@ -49,8 +49,8 @@ public static void main(String[] args) throws PropertySerializationException public void testClusterPropertiesSerializer() throws PropertySerializationException { ClusterPropertiesJsonSerializer jsonSerializer = new ClusterPropertiesJsonSerializer(); - List schemes = new ArrayList(); - Map supProperties = new HashMap(); + List schemes = new ArrayList<>(); + Map supProperties = new HashMap<>(); Set bannedSet = new HashSet<>(); bannedSet.add(URI.create("https://test1.linkedin.com:12345/test")); bannedSet.add(URI.create("https://test2.linkedin.com:56789/test")); @@ -78,7 +78,7 @@ public void testClusterPropertiesSerializer() throws PropertySerializationExcept property = new ClusterProperties("test", schemes, supProperties, bannedSet, hbp); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); - property = new ClusterProperties("test", schemes, supProperties, new HashSet(), NullPartitionProperties.getInstance(), + property = new ClusterProperties("test", schemes, supProperties, new HashSet<>(), NullPartitionProperties.getInstance(), Arrays.asList("principal1", "principal2"), (Map)null, false); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); @@ -102,7 +102,7 @@ public void testDarkClusterJsonSerializer() throws PropertySerializationExceptio .setDispatcherOutboundTargetRate(50); DarkClusterConfigMap darkClusterConfigMap = new DarkClusterConfigMap(); darkClusterConfigMap.put(DARK_CLUSTER1_KEY, darkCluster1); - ClusterProperties property = new ClusterProperties("test", new ArrayList(), Collections.emptyMap(), new HashSet(), NullPartitionProperties.getInstance(), + ClusterProperties property = new ClusterProperties("test", new ArrayList<>(), Collections.emptyMap(), new HashSet<>(), NullPartitionProperties.getInstance(), Arrays.asList("principal1", "principal2"), DarkClustersConverter.toProperties(darkClusterConfigMap), false); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); } @@ -150,7 +150,7 @@ public void testEmptyDarkClusterJsonSerializer() throws PropertySerializationExc public void testNullDarkClusterJsonSerializer() throws PropertySerializationException { ClusterPropertiesJsonSerializer jsonSerializer = new ClusterPropertiesJsonSerializer(); - ClusterProperties property = new ClusterProperties("test", new ArrayList<>(), new HashMap<>(), new HashSet(), NullPartitionProperties.getInstance(), + ClusterProperties property = new ClusterProperties("test", new ArrayList<>(), new HashMap<>(), new HashSet<>(), NullPartitionProperties.getInstance(), Arrays.asList("principal1", "principal2"), (Map) null, false); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/properties/ServicePropertiesSerializerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/properties/ServicePropertiesSerializerTest.java index 36907f234c..2f744dc345 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/properties/ServicePropertiesSerializerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/properties/ServicePropertiesSerializerTest.java @@ -62,7 +62,7 @@ public void testServicePropertiesSerializer() throws URISyntaxException, Collections.singletonMap("foo", "bar")); assertEquals(serializer.fromBytes(serializer.toBytes(property)), property); - Map arbitraryProperties = new HashMap(); + Map arbitraryProperties = new HashMap<>(); arbitraryProperties.put("foo", "bar"); property = new ServiceProperties(TEST_SERVICE_NAME, TEST_CLUSTER_NAME, @@ -96,7 +96,7 @@ public void testBadConfigInServiceProperties() throws PropertySerializationExcep ServicePropertiesJsonSerializer serializer = new ServicePropertiesJsonSerializer(); Map badDegraderConfig = Collections.singletonMap(PropertyKeys.DEGRADER_INITIAL_DROP_RATE, "0.1"); - Map arbitraryProperties = new HashMap(); + Map arbitraryProperties = new HashMap<>(); arbitraryProperties.put("foo", "bar"); ServiceProperties badServiceProp = new ServiceProperties(TEST_SERVICE_NAME, TEST_CLUSTER_NAME, diff --git a/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java index 6d22d7816d..3e1f44a1b3 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java @@ -37,10 +37,10 @@ public class UriPropertiesSerializerTest // However, it has the same signature as the new one after type erasure if it is still a constructor public static UriProperties getInstanceWithOldArguments(String clusterName, Map weights) { - Map> partitionData = new HashMap>(); + Map> partitionData = new HashMap<>(); for (URI uri : weights.keySet()) { - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weights.get(uri))); partitionData.put(uri,partitionWeight); } @@ -52,7 +52,7 @@ public void testUriPropertiesSerializer() throws URISyntaxException, PropertySerializationException { UriPropertiesJsonSerializer jsonSerializer = new UriPropertiesJsonSerializer(); - Map uriWeights = new HashMap(); + Map uriWeights = new HashMap<>(); UriProperties property = getInstanceWithOldArguments("test", uriWeights); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); @@ -67,10 +67,10 @@ public void testUriPropertiesSerializer() throws URISyntaxException, assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property2)), property2); // test new way of constructing uri property - final Map> partitionDesc = new HashMap>(); + final Map> partitionDesc = new HashMap<>(); property = new UriProperties("test 3", partitionDesc); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); - final Map partitions = new HashMap(); + final Map partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(700, new PartitionData(0.3d)); partitions.put(1200, new PartitionData(0.4d)); @@ -116,14 +116,14 @@ public UriProperties fromOldFormatBytes(byte[] bytes) throws PropertySerializati public UriProperties fromOldFormatMap(Map map) { String clusterName = (String)map.get("clusterName"); - Map> partitionDesc = new HashMap>(); + Map> partitionDesc = new HashMap<>(); Map weights = (Map) map.get("weights"); if (weights != null) { for(Map.Entry weight: weights.entrySet()) { URI uri = URI.create(weight.getKey()); - Map partitionDataMap = new HashMap(); + Map partitionDataMap = new HashMap<>(); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weight.getValue())); partitionDesc.put(uri, partitionDataMap); } @@ -141,13 +141,13 @@ public void testWithApplicationProperties() // new constructor - Map applicationProperties = new HashMap(); + Map applicationProperties = new HashMap<>(); applicationProperties.put("foo", "fooValue"); applicationProperties.put("bar", "barValue"); applicationProperties.put("baz", 1); - Map> partitionDesc = new HashMap>(); - Map partitions = new HashMap(); + Map> partitionDesc = new HashMap<>(); + Map partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(1000, new PartitionData(0.3d)); @@ -159,8 +159,8 @@ public void testWithApplicationProperties() // from bytes that were stored using an old constructor - partitionDesc = new HashMap>(); - partitions = new HashMap(); + partitionDesc = new HashMap<>(); + partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(1000, new PartitionData(0.3d)); partitionDesc.put(uri, partitions); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesTest.java b/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesTest.java index 11c7fcd530..593cc31c49 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesTest.java @@ -34,19 +34,19 @@ public void testUriProperties() URI uri2 = URI.create("http://linkedin.com"); URI uri3 = URI.create("https://linkedin.com"); - Map map1 = new HashMap(); + Map map1 = new HashMap<>(); map1.put(0, new PartitionData(1)); map1.put(1, new PartitionData(2)); - Map map2 = new HashMap(); + Map map2 = new HashMap<>(); map2.put(1, new PartitionData(0.5)); - Map map3 = new HashMap(); + Map map3 = new HashMap<>(); map3.put(1, new PartitionData(2)); map3.put(3, new PartitionData(3.5)); map3.put(4, new PartitionData(1)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri1, map1); uriData.put(uri2, map2); uriData.put(uri3, map3); @@ -63,7 +63,7 @@ public void testUriProperties() Assert.assertEquals(properties.getPartitionDataMap(uri3), map3); // test getUriBySchemeAndPartition - Set set = new HashSet(1); + Set set = new HashSet<>(1); set.add(uri1); Assert.assertEquals(properties.getUriBySchemeAndPartition("http", 0), set); set.add(uri2); @@ -73,7 +73,7 @@ public void testUriProperties() Assert.assertEquals(properties.getUriBySchemeAndPartition("https", 1), set); Assert.assertNull(properties.getUriBySchemeAndPartition("rtp", 0)); Assert.assertNull(properties.getUriBySchemeAndPartition("http", 2)); - + // test unmodifiability Map> partitionDesc = properties.getPartitionDesc(); Map partitionDataMap = properties.getPartitionDataMap(uri1); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/servers/ZooKeeperServerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/servers/ZooKeeperServerTest.java index 572a9fc3dd..50a35cbf33 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/servers/ZooKeeperServerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/servers/ZooKeeperServerTest.java @@ -66,11 +66,11 @@ public void testZkServer() throws InterruptedException, zkClient.start(); ZooKeeperEphemeralStore store = - new ZooKeeperEphemeralStore(zkClient, - new UriPropertiesJsonSerializer(), - new UriPropertiesMerger(), - "/echo/lb/uris"); - FutureCallback callback = new FutureCallback(); + new ZooKeeperEphemeralStore<>(zkClient, + new UriPropertiesJsonSerializer(), + new UriPropertiesMerger(), + "/echo/lb/uris"); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(); @@ -136,7 +136,7 @@ public void testZkServer() throws InterruptedException, // bring up uri1 - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(5, new PartitionData(0.3d)); partitionWeight.put(15, new PartitionData(0.7d)); markUp(server, cluster, uri1, partitionWeight, null); @@ -145,7 +145,7 @@ public void testZkServer() throws InterruptedException, assertEquals(properties.getPartitionDataMap(uri1), partitionWeight); - Map uri2SpecificProperties = new HashMap(); + Map uri2SpecificProperties = new HashMap<>(); uri2SpecificProperties.put("foo", "fooValue"); uri2SpecificProperties.put("bar", 1); @@ -168,12 +168,12 @@ public void testZkServer() throws InterruptedException, markDown(server, cluster, uri1); - Map uri1SpecificProperties = new HashMap(); + Map uri1SpecificProperties = new HashMap<>(); uri1SpecificProperties.put("baz", "bazValue"); // use new partition data so that we can test the mapping later on - Map newUri1PartitionWeights = new HashMap(partitionWeight); + Map newUri1PartitionWeights = new HashMap<>(partitionWeight); newUri1PartitionWeights.remove(10); markUp(server, cluster, uri1, newUri1PartitionWeights, uri1SpecificProperties); @@ -188,7 +188,7 @@ public void testZkServer() throws InterruptedException, assertEquals(properties.getUriSpecificProperties().get(uri1), uri1SpecificProperties); assertEquals(properties.getUriSpecificProperties().get(uri2), uri2SpecificProperties); - Set uriSet = new HashSet(); + Set uriSet = new HashSet<>(); uriSet.add(uri1); uriSet.add(uri2); @@ -264,7 +264,7 @@ public void testZkServer() throws InterruptedException, private void markUp(ZooKeeperServer server, String cluster, URI uri, double weight) { - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weight)); markUp(server, cluster, uri, partitionWeight, null); } @@ -275,7 +275,7 @@ private void markUp(ZooKeeperServer server, Map partitionDataMap, Map uriSpecificProperties) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); if (uriSpecificProperties == null) { server.markUp(cluster, uri, partitionDataMap, callback); @@ -296,7 +296,7 @@ private void markUp(ZooKeeperServer server, private void markDown(ZooKeeperServer server, String cluster, URI uri) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); server.markDown(cluster, uri, callback); try { @@ -314,7 +314,7 @@ private void changeWeight(ZooKeeperServer server, boolean doNotSlowStart, double weight) { - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weight)); changeWeight(server, cluster, uri, doNotSlowStart, partitionWeight); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/servers/ZookeeperConnectionManagerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/servers/ZookeeperConnectionManagerTest.java index e6cd3b11a5..ff8b1a7892 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/servers/ZookeeperConnectionManagerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/servers/ZookeeperConnectionManagerTest.java @@ -166,7 +166,7 @@ public void testDelayMarkUp() ZooKeeperAnnouncer announcer = new ZooKeeperAnnouncer(new ZooKeeperServer(), false); announcer.setCluster(_cluster); announcer.setUri(_uri); - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(ZookeeperConnectionManagerTest.WEIGHT)); announcer.setPartitionData(partitionWeight); @@ -176,7 +176,7 @@ public void testDelayMarkUp() UriProperties properties = store.get(_cluster); assertNull(properties); - FutureCallback markUpCallback = new FutureCallback(); + FutureCallback markUpCallback = new FutureCallback<>(); announcer.markUp(markUpCallback); markUpCallback.get(); @@ -203,7 +203,7 @@ public void testMarkUpAndMarkDown() assertEquals(properties.getPartitionDataMap(URI.create(_uri)).get(DefaultPartitionAccessor.DEFAULT_PARTITION_ID).getWeight(), WEIGHT); assertEquals(properties.Uris().size(), 1); - FutureCallback markDownCallback = new FutureCallback(); + FutureCallback markDownCallback = new FutureCallback<>(); announcer.markDown(markDownCallback); markDownCallback.get(); @@ -255,7 +255,7 @@ public void testMarkDownDuringDisconnection() _zkServer.shutdown(false); - FutureCallback markDownCallback = new FutureCallback(); + FutureCallback markDownCallback = new FutureCallback<>(); announcer.markDown(markDownCallback); // ugly, but we need to wait for a while just so that Disconnect event is propagated @@ -287,9 +287,9 @@ public void testMarkDownAndUpDuringDisconnection() _zkServer.shutdown(false); - FutureCallback markDownCallback = new FutureCallback(); + FutureCallback markDownCallback = new FutureCallback<>(); announcer.markDown(markDownCallback); - FutureCallback markUpCallback = new FutureCallback(); + FutureCallback markUpCallback = new FutureCallback<>(); announcer.markUp(markUpCallback); // ugly, but we need to wait for a while just so that Disconnect event is propagated @@ -445,7 +445,7 @@ public void testMarkUpAndDownMultipleTimesFinalUp() ZooKeeperAnnouncer announcer = getZooKeeperAnnouncer(_cluster, _uri, WEIGHT); ZooKeeperConnectionManager manager = createManager(true, announcer); - FutureCallback managerStartCallback = new FutureCallback(); + FutureCallback managerStartCallback = new FutureCallback<>(); manager.start(managerStartCallback); managerStartCallback.get(10, TimeUnit.SECONDS); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simple/LoadBalancerSimulator.java b/d2/src/test/java/com/linkedin/d2/balancer/simple/LoadBalancerSimulator.java index 9f0fe6f2bb..270bfa447a 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simple/LoadBalancerSimulator.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simple/LoadBalancerSimulator.java @@ -181,7 +181,7 @@ interface TimedValueGenerator _loadBalancer = new SimpleLoadBalancer(_loadBalancerState, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); _loadBalancer.start(balancerCallback); balancerCallback.get(); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerDelayTest.java b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerDelayTest.java index e412b3cc4d..a22487f259 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerDelayTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerDelayTest.java @@ -68,9 +68,9 @@ public void testLoadBalancerWithDelay() throws Exception URI uri3 = URI.create("http://test.qa3.com:6789"); List uris = Arrays.asList("test.qa1.com:1234", "test.qa2.com:2345", "test.qa3.com:6789"); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(3); + Map> uriData = new HashMap<>(3); uriData.put(uri1, partitionData); uriData.put(uri2, partitionData); uriData.put(uri3, partitionData); @@ -1642,9 +1642,9 @@ public static LoadBalancerSimulator build( throws InterruptedException, ExecutionException { // only support 1 partition for now - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(2); + Map> uriData = new HashMap<>(2); for (String uriString : uris) { diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStateTest.java b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStateTest.java index 67141883d6..a8d67044e6 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStateTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStateTest.java @@ -190,7 +190,7 @@ public void reset(boolean useSSL, boolean enableRelativeLoadBalancer) _loadBalancerStrategyFactories); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _state.start(callback); try { @@ -208,7 +208,7 @@ public void testRegister() reset(); TestListener listener = new TestListener(); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); schemes.add("http"); _state.register(listener); @@ -251,7 +251,7 @@ public void testRegister() _state.listenToCluster("partition-cluster-1", new NullStateListenerCallback()); _clusterRegistry.put("partition-cluster-1", new ClusterProperties("partition-cluster-1", null, - new HashMap(), new HashSet(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); + new HashMap<>(), new HashSet<>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); _state.listenToService("partition-service-1", new NullStateListenerCallback()); _serviceRegistry.put("partition-service-1", @@ -274,7 +274,7 @@ public void testUnregister() reset(); TestListener listener = new TestListener(); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); schemes.add("http"); _state.register(listener); @@ -321,10 +321,10 @@ public void testShutdown() throws URISyntaxException, URI uri = URI.create("http://cluster-1/test"); TestListener listener = new TestListener(); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); _state.register(listener); @@ -369,10 +369,10 @@ public void testShutdownWithListener() throws URISyntaxException, URI uri = URI.create("http://cluster-1/test"); TestListener listener = new TestListener(); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); _state.register(listener); @@ -464,7 +464,7 @@ public void testListenToCluster() throws URISyntaxException, { reset(); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); schemes.add("http"); @@ -507,10 +507,10 @@ public void testGetClient() throws URISyntaxException reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -547,7 +547,7 @@ public void testGetClientWithoutScheme() throws URISyntaxException reset(); URI uri = URI.create("cluster-1/test"); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); Map> uriData = new HashMap<>(); @@ -582,8 +582,8 @@ public void testGetStrategy() throws URISyntaxException reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map weights = new HashMap(); + List schemes = new ArrayList<>(); + Map weights = new HashMap<>(); weights.put(uri, 1d); schemes.add("http"); @@ -617,8 +617,8 @@ public void testRefreshServiceStrategies() throws URISyntaxException, Interrupte reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map weights = new HashMap(); + List schemes = new ArrayList<>(); + Map weights = new HashMap<>(); weights.put(uri, 1d); schemes.add("http"); @@ -689,10 +689,10 @@ public void testRefreshServiceStrategies() throws URISyntaxException, Interrupte public void testServiceStrategyList() throws URISyntaxException, InterruptedException { reset(); - LinkedList strategyList = new LinkedList(); + LinkedList strategyList = new LinkedList<>(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map weights = new HashMap(); + List schemes = new ArrayList<>(); + Map weights = new HashMap<>(); weights.put(uri, 1d); schemes.add("http"); @@ -840,9 +840,9 @@ public void testServiceStrategyListWithRelativeStrategyNotSupported() public void testRefreshWithConcurrentGetTC() throws URISyntaxException, InterruptedException { reset(); - LinkedList strategyList = new LinkedList(); + LinkedList strategyList = new LinkedList<>(); URI uri = URI.create("http://cluster-1/test"); - final List schemes = new ArrayList(); + final List schemes = new ArrayList<>(); schemes.add("http"); strategyList.add("degraderV3"); @@ -873,10 +873,10 @@ public void testRefreshWithConcurrentGetTC() throws URISyntaxException, Interrup assertNotNull(resultTC, "got null tracker client in non-concurrent env"); ExecutorService myExecutor = Executors.newCachedThreadPool(); - ArrayList cArray = new ArrayList(); + ArrayList cArray = new ArrayList<>(); - List clients = new ArrayList(); - Map partitionDataMap = new HashMap(2); + List clients = new ArrayList<>(); + Map partitionDataMap = new HashMap<>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); clients.add(new DegraderTrackerClientImpl(uri, partitionDataMap, new DegraderLoadBalancerTest.TestLoadBalancerClient(uri), SystemClock.instance(), null)); @@ -893,7 +893,7 @@ public void run() { while(true) { - List myStrategyList = new LinkedList(); + List myStrategyList = new LinkedList<>(); myStrategyList.add("degraderV3"); _state.refreshServiceStrategies(new ServiceProperties("service-1", "cluster-1", @@ -915,7 +915,7 @@ public void run() myExecutor.execute(refreshTask); Integer badResults = 0; - ArrayList> myList = new ArrayList>(); + ArrayList> myList = new ArrayList<>(); for (int i=0; i schemes = new ArrayList(); + List schemes = new ArrayList<>(); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -1033,7 +1033,7 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta _state.listenToCluster("partition-cluster-1", new NullStateListenerCallback()); _clusterRegistry.put("partition-cluster-1", new ClusterProperties("partition-cluster-1", null, - new HashMap(), new HashSet(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); + new HashMap<>(), new HashSet<>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); _state.listenToService("partition-service-1", new NullStateListenerCallback()); _serviceRegistry.put("partition-service-1", @@ -1044,12 +1044,12 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta schemes, Collections.emptySet())); - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(0, new PartitionData(1d)); partitionWeight.put(1, new PartitionData(2d)); Map> partitionDesc = - new HashMap>(); + new HashMap<>(); partitionDesc.put(uri1, partitionWeight); partitionWeight.remove(0); @@ -1069,8 +1069,8 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta TrackerClient client = _state.getClient("service-1", uri); client.restRequest(new RestRequestBuilder(URI.create("d2://service-1/foo")).build(), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); // now force a refresh by adding cluster _clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1")); @@ -1079,8 +1079,8 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta client = _state.getClient("service-1", uri); client.restRequest(new RestRequestBuilder(URI.create("d2://service-1/foo")).build(), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); // refresh by adding service _serviceRegistry.put("service-1", new ServiceProperties("service-1", @@ -1097,8 +1097,8 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta client = _state.getClient("service-1", uri); client.restRequest(new RestRequestBuilder(URI.create("d2://service-1/foo")).build(), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); _uriRegistry.put("cluster-1", new UriProperties("cluster-1", Collections.>emptyMap())); @@ -1108,8 +1108,8 @@ public void testClientsShutdownAfterPropertyUpdatesRestRequest() throws URISynta client = _state.getClient("service-1", uri); client.restRequest(new RestRequestBuilder(URI.create("d2://service-1/foo")).build(), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); @@ -1130,11 +1130,11 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -1162,23 +1162,23 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn _state.listenToCluster("partition-cluster-1", new NullStateListenerCallback()); _clusterRegistry.put("partition-cluster-1", new ClusterProperties("partition-cluster-1", null, - new HashMap(), new HashSet(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); + new HashMap<>(), new HashSet<>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 100, 2))); _state.listenToService("partition-service-1", new NullStateListenerCallback()); _serviceRegistry.put("partition-service-1", new ServiceProperties("partition-service-1", - "partition-cluster-1", "/partition-test", Arrays.asList("degraderV3"), Collections.emptyMap(), - Collections.emptyMap(), - Collections.emptyMap(), + "partition-cluster-1", "/partition-test", Arrays.asList("degraderV3"), Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), schemes, - Collections.emptySet())); + Collections.emptySet())); - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(0, new PartitionData(1d)); partitionWeight.put(1, new PartitionData(2d)); Map> partitionDesc = - new HashMap>(); + new HashMap<>(); partitionDesc.put(uri1, partitionWeight); partitionWeight.remove(0); @@ -1198,8 +1198,8 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn TrackerClient client = _state.getClient("service-1", uri); client.streamRequest(new StreamRequestBuilder(URI.create("d2://service-1/foo")).build(EntityStreams.emptyStream()), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); // now force a refresh by adding cluster _clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1")); @@ -1208,8 +1208,8 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn client = _state.getClient("service-1", uri); client.streamRequest(new StreamRequestBuilder(URI.create("d2://service-1/foo")).build(EntityStreams.emptyStream()), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); // refresh by adding service _serviceRegistry.put("service-1", new ServiceProperties("service-1", @@ -1226,8 +1226,8 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn client = _state.getClient("service-1", uri); client.streamRequest(new StreamRequestBuilder(URI.create("d2://service-1/foo")).build(EntityStreams.emptyStream()), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); _uriRegistry.put("cluster-1", new UriProperties("cluster-1", Collections.>emptyMap())); @@ -1237,8 +1237,8 @@ public void testClientsShutdownAfterPropertyUpdatesStreamRequest() throws URISyn client = _state.getClient("service-1", uri); client.streamRequest(new StreamRequestBuilder(URI.create("d2://service-1/foo")).build(EntityStreams.emptyStream()), new RequestContext(), - Collections.emptyMap(), - new TransportCallbackAdapter(Callbacks.empty())); + Collections.emptyMap(), + new TransportCallbackAdapter<>(Callbacks.empty())); @@ -1261,10 +1261,10 @@ public void testVersion() throws URISyntaxException int expectedVersion = 0; URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -1324,10 +1324,10 @@ public void testGetClientWithSSLValidation() throws URISyntaxException reset(true, true); URI uri = URI.create("https://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("https"); @@ -1336,7 +1336,7 @@ public void testGetClientWithSSLValidation() throws URISyntaxException _state.listenToCluster("cluster-1", new NullStateListenerCallback()); _state.listenToService("service-1", new NullStateListenerCallback()); - Map transportClientProperties = new HashMap(); + Map transportClientProperties = new HashMap<>(); transportClientProperties.put(HttpClientFactory.HTTP_SSL_CONTEXT, _sslContext); transportClientProperties.put(HttpClientFactory.HTTP_SSL_PARAMS, _sslParameters); transportClientProperties = Collections.unmodifiableMap(transportClientProperties); @@ -1369,10 +1369,10 @@ public void testGetSSLClient() throws URISyntaxException reset(true, true); URI uri = URI.create("https://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("https"); @@ -1388,7 +1388,7 @@ public void testGetSSLClient() throws URISyntaxException assertNull(_state.getClient("service-1", uri)); - Map transportClientProperties = new HashMap(); + Map transportClientProperties = new HashMap<>(); transportClientProperties.put(HttpClientFactory.HTTP_SSL_CONTEXT, _sslContext); transportClientProperties.put(HttpClientFactory.HTTP_SSL_PARAMS, _sslParameters); transportClientProperties = Collections.unmodifiableMap(transportClientProperties); @@ -1415,10 +1415,10 @@ public void testSSLDisabledWithHttpsInstances() throws URISyntaxException URI uri = URI.create("http://cluster-1/test"); URI httpsUri = URI.create("https://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); uriData.put(httpsUri, partitionData); @@ -1437,7 +1437,7 @@ public void testSSLDisabledWithHttpsInstances() throws URISyntaxException assertNull(_state.getClient("service-1", uri)); - Map transportClientProperties = new HashMap(); + Map transportClientProperties = new HashMap<>(); transportClientProperties.put(HttpClientFactory.HTTP_SSL_CONTEXT, _sslContext); transportClientProperties.put(HttpClientFactory.HTTP_SSL_PARAMS, _sslParameters); transportClientProperties = Collections.unmodifiableMap(transportClientProperties); @@ -1478,10 +1478,10 @@ public void testListValueInTransportClientProperties() throws URISyntaxException reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -1497,14 +1497,14 @@ public void testListValueInTransportClientProperties() throws URISyntaxException assertNull(_state.getClient("service-1", uri)); - Map transportClientProperties = new HashMap(); + Map transportClientProperties = new HashMap<>(); - List allowedClientOverrideKeys = new ArrayList(); + List allowedClientOverrideKeys = new ArrayList<>(); allowedClientOverrideKeys.add(PropertyKeys.HTTP_REQUEST_TIMEOUT); allowedClientOverrideKeys.add(PropertyKeys.HTTP_RESPONSE_COMPRESSION_OPERATIONS); transportClientProperties.put(PropertyKeys.ALLOWED_CLIENT_OVERRIDE_KEYS, allowedClientOverrideKeys); - List compressionOperations = new ArrayList(); + List compressionOperations = new ArrayList<>(); compressionOperations.add("get"); compressionOperations.add("batch_get"); compressionOperations.add("get_all"); @@ -1532,10 +1532,10 @@ public void testGetClientAfterServiceMetadataChange() { reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); @@ -1582,9 +1582,9 @@ public void testGetClientAfterServiceMetadataChange() _state.listenToCluster("cluster-2", new NullStateListenerCallback()); URI uri2 = URI.create("http://cluster-2/test"); - Map partitionData2 = new HashMap(1); + Map partitionData2 = new HashMap<>(1); partitionData2.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData2 = new HashMap>(); + Map> uriData2 = new HashMap<>(); uriData2.put(uri2, partitionData2); //if we start publishing new event to cluster-2 then we should get trackerClient @@ -1614,21 +1614,21 @@ public void testGetClientAfterBadProperties() throws URISyntaxException, Interru reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionData = new HashMap(1); + List schemes = new ArrayList<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionData); schemes.add("http"); assertNull(_state.getClient("service-1", uri)); - Map transportProperties = new HashMap(); + Map transportProperties = new HashMap<>(); transportProperties.put("foobar", "unsupportedValue"); _serviceRegistry.put("service-1", new ServiceProperties("service-1", "cluster-1", "/test", Arrays.asList("random"), - Collections.emptyMap(), + Collections.emptyMap(), transportProperties, null, schemes, null)); // we add the property first before listening to the service because the MockStore will @@ -1666,9 +1666,9 @@ public void testUpdatePartitionDataMap() { reset(); URI uri = URI.create("http://cluster-1/test"); - List schemes = new ArrayList(); - Map partitionDataMap = new HashMap(1); - Map> uriData = new HashMap>(); + List schemes = new ArrayList<>(); + Map partitionDataMap = new HashMap<>(1); + Map> uriData = new HashMap<>(); uriData.put(uri, partitionDataMap); schemes.add("http"); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStrawMan.java b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStrawMan.java index 81bfda2c7a..338ddb45f5 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStrawMan.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerStrawMan.java @@ -47,24 +47,23 @@ public static void main(String[] args) throws URISyntaxException, { // define the load balancing strategies that we support (round robin, etc) Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); loadBalancerStrategyFactories.put("rr", new RandomLoadBalancerStrategyFactory()); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); // define the clients that we support (http, etc) - Map clientFactories = - new HashMap(); + Map clientFactories = new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); // listen for service updates (could be a glu discovery client, zk discovery client, // config discovery client, etc) ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); SimpleLoadBalancerState state = new SimpleLoadBalancerState(executorService, diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerTest.java index 1be5daf6b9..a021dd0631 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simple/SimpleLoadBalancerTest.java @@ -155,7 +155,7 @@ public static void main(String[] args) throws ServiceUnavailableException, @BeforeSuite public void doOneTimeSetUp() { - _dirsToDelete = new ArrayList(); + _dirsToDelete = new ArrayList<>(); } @AfterSuite @@ -189,7 +189,7 @@ private SimpleLoadBalancer setupLoadBalancer(LoadBalancerState state, MockStore< SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(loadBalancerState, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); return loadBalancer; @@ -240,7 +240,7 @@ private void populateUriRegistry(int numHttp, int numHttps, int partitionIdForAd { Map partitionData = new HashMap<>(1); partitionData.put(partitionIdForAdd, new PartitionData(1d)); - Map> uriData = new HashMap>(numHttp); + Map> uriData = new HashMap<>(numHttp); Set schemeSet = new HashSet<>(); schemeSet.add(PropertyKeys.HTTP_SCHEME); schemeSet.add(PropertyKeys.HTTPS_SCHEME); @@ -363,7 +363,7 @@ public void testClusterInfoProviderRegisterClusterListener() MockStore clusterRegistry = new MockStore<>(); MockStore uriRegistry = new MockStore<>(); SimpleLoadBalancer loadBalancer = setupLoadBalancer(null, serviceRegistry, clusterRegistry, uriRegistry); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); MockClusterListener testClusterListener = new MockClusterListener(); @@ -394,7 +394,7 @@ public void testClusterInfoProviderUnregisterClusterListener() MockStore clusterRegistry = new MockStore<>(); MockStore uriRegistry = new MockStore<>(); SimpleLoadBalancer loadBalancer = setupLoadBalancer(null, serviceRegistry, clusterRegistry, uriRegistry); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); MockClusterListener testClusterListener = new MockClusterListener(); @@ -423,14 +423,13 @@ public void testLoadBalancerSmoke() throws URISyntaxException, for (int tryAgain = 0; tryAgain < 1000; ++tryAgain) { Map> loadBalancerStrategyFactories = - new HashMap>(); - Map clientFactories = - new HashMap(); - List prioritizedSchemes = new ArrayList(); + new HashMap<>(); + Map clientFactories = new HashMap<>(); + List prioritizedSchemes = new ArrayList<>(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); ScheduledExecutorService executorService = new SynchronousExecutorService(); @@ -451,7 +450,7 @@ public void testLoadBalancerSmoke() throws URISyntaxException, SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); @@ -459,9 +458,9 @@ public void testLoadBalancerSmoke() throws URISyntaxException, URI uri2 = URI.create("http://test.qa2.com:2345"); URI uri3 = URI.create("http://test.qa3.com:6789"); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(3); + Map> uriData = new HashMap<>(3); uriData.put(uri1, partitionData); uriData.put(uri2, partitionData); uriData.put(uri3, partitionData); @@ -485,7 +484,7 @@ public void testLoadBalancerSmoke() throws URISyntaxException, URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo"); URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo"); - Set expectedUris = new HashSet(); + Set expectedUris = new HashSet<>(); expectedUris.add(expectedUri1); expectedUris.add(expectedUri2); @@ -528,13 +527,13 @@ public void done() public void testGetClientWithBannedURI() throws Exception { Map> loadBalancerStrategyFactories = - new HashMap>(); - Map clientFactories = new HashMap(); - List prioritizedSchemes = new ArrayList(); + new HashMap<>(); + Map clientFactories = new HashMap<>(); + List prioritizedSchemes = new ArrayList<>(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); ScheduledExecutorService executorService = new SynchronousExecutorService(); @@ -552,15 +551,15 @@ public void testGetClientWithBannedURI() throws Exception SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); URI uri1Banned = URI.create("http://test.qd.com:1234"); URI uri2Usable = URI.create("http://test.qd.com:5678"); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(2); + Map> uriData = new HashMap<>(2); uriData.put(uri1Banned, partitionData); uriData.put(uri2Usable, partitionData); @@ -602,14 +601,13 @@ public void testGetClient() throws Exception { Map> loadBalancerStrategyFactories = - new HashMap>(); - Map clientFactories = - new HashMap(); - List prioritizedSchemes = new ArrayList(); + new HashMap<>(); + Map clientFactories = new HashMap<>(); + List prioritizedSchemes = new ArrayList<>(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); ScheduledExecutorService executorService = new SynchronousExecutorService(); @@ -630,13 +628,13 @@ public void testGetClient() throws Exception SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(5, TimeUnit.SECONDS); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(3); + Map> uriData = new HashMap<>(3); prioritizedSchemes.add(PropertyKeys.HTTPS_SCHEME); @@ -696,13 +694,13 @@ public void testGetClientHostOverrideList() throws Exception SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(2); + Map> uriData = new HashMap<>(2); uriData.put(URI.create("http://host1/path"), partitionData); prioritizedSchemes.add(PropertyKeys.HTTP_SCHEME); @@ -783,29 +781,29 @@ public void testGetPartitionInfoOrdering() String strategyName = "degrader"; // setup 3 partitions. Partition 1 and Partition 2 both have server1 - server3. Partition 3 only has server1. - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); final URI server1 = new URI("http://foo1.com"); - Map server1Data = new HashMap(); + Map server1Data = new HashMap<>(); server1Data.put(1, new PartitionData(1.0)); server1Data.put(2, new PartitionData(1.0)); server1Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server1, server1Data); final URI server2 = new URI("http://foo2.com"); - Map server2Data = new HashMap(); + Map server2Data = new HashMap<>(); server2Data.put(1, new PartitionData(1.0)); server2Data.put(2, new PartitionData(1.0)); partitionDescriptions.put(server2, server2Data); final URI server3 = new URI("http://foo3.com"); - Map server3Data = new HashMap(); + Map server3Data = new HashMap<>(); server3Data.put(1, new PartitionData(1.0)); server3Data.put(2, new PartitionData(1.0)); partitionDescriptions.put(server3, server3Data); //setup strategy which involves tweaking the hash ring to get partitionId -> URI host - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); LoadBalancerStrategy strategy = new TestLoadBalancerStrategy(partitionDescriptions); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair(PropertyKeys.HTTP_SCHEME, strategy)); @@ -819,7 +817,7 @@ public void testGetPartitionInfoOrdering() accessor ), _d2Executor); - List keys = new ArrayList(); + List keys = new ArrayList<>(); keys.add(1); keys.add(2); keys.add(3); @@ -972,31 +970,31 @@ public void testGetAllPartitionMultipleHostsOrdering() String strategyName = "degrader"; //setup partition - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); final URI server1 = new URI("http://foo1.com"); - Map server1Data = new HashMap(); + Map server1Data = new HashMap<>(); server1Data.put(1, new PartitionData(1.0)); server1Data.put(2, new PartitionData(1.0)); server1Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server1, server1Data); final URI server2 = new URI("http://foo2.com"); - Map server2Data = new HashMap(); + Map server2Data = new HashMap<>(); server2Data.put(1, new PartitionData(1.0)); server2Data.put(2, new PartitionData(1.0)); //server2Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server2, server2Data); final URI server3 = new URI("http://foo3.com"); - Map server3Data = new HashMap(); + Map server3Data = new HashMap<>(); server3Data.put(1, new PartitionData(1.0)); server3Data.put(2, new PartitionData(1.0)); //server3Data.put(3, new PartitionData(1.0)); partitionDescriptions.put(server3, server3Data); //setup strategy which involves tweaking the hash ring to get partitionId -> URI host - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); LoadBalancerStrategy strategy = new TestLoadBalancerStrategy(partitionDescriptions); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair(PropertyKeys.HTTP_SCHEME, strategy)); @@ -1050,14 +1048,13 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, for (int tryAgain = 0; tryAgain < 12; ++tryAgain) { Map> loadBalancerStrategyFactories = - new HashMap>(); - Map clientFactories = - new HashMap(); - List prioritizedSchemes = new ArrayList(); + new HashMap<>(); + Map clientFactories = new HashMap<>(); + List prioritizedSchemes = new ArrayList<>(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); @@ -1075,7 +1072,7 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, executorService); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); @@ -1083,23 +1080,23 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, URI uri2 = URI.create("http://test.qa2.com:2345"); URI uri3 = URI.create("http://test.qa3.com:6789"); - Map uris = new HashMap(); + Map uris = new HashMap<>(); uris.put(uri1, 1d); uris.put(uri2, 1d); uris.put(uri3, 1d); Map> partitionDesc = - new HashMap>(); + new HashMap<>(); - Map server1 = new HashMap(); + Map server1 = new HashMap<>(); server1.put(0, new PartitionData(1d)); server1.put(1, new PartitionData(1d)); - Map server2 = new HashMap(); + Map server2 = new HashMap<>(); server2.put(0, new PartitionData(1d)); - Map server3 = new HashMap(); + Map server3 = new HashMap<>(); server3.put(1, new PartitionData(1d)); partitionDesc.put(uri1, server1); partitionDesc.put(uri2, server2); @@ -1111,21 +1108,21 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, switch (partitionMethod) { case 0: - clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap(), - new HashSet(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 2))); + clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<>(), + new HashSet<>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 2))); break; case 1: - clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap(), - new HashSet(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MODULO")))); + clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<>(), + new HashSet<>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MODULO")))); break; case 2: - clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap(), - new HashSet(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MD5")))); + clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<>(), + new HashSet<>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MD5")))); break; case 3: // test getRings with gap. here, no server serves partition 2 - clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap(), - new HashSet(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 4))); + clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<>(), + new HashSet<>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 4))); server3.put(3, new PartitionData(1d)); partitionDesc.put(uri3, server3); break; @@ -1150,7 +1147,7 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, Map> ringMap = loadBalancer.getRings(URI.create("d2://foo")); assertEquals(ringMap.size(), 4); // the ring for partition 2 should be empty - assertEquals(ringMap.get(2).toString(), new ConsistentHashRing(Collections.emptyList()).toString()); + assertEquals(ringMap.get(2).toString(), new ConsistentHashRing<>(Collections.emptyList()).toString()); continue; } @@ -1158,7 +1155,7 @@ public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo"); URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo"); - Set expectedUris = new HashSet(); + Set expectedUris = new HashSet<>(); expectedUris.add(expectedUri1); expectedUris.add(expectedUri2); expectedUris.add(expectedUri3); @@ -1236,7 +1233,7 @@ else if (partitionMethod == 1) if (partitionMethod != 2) { - Set keys = new HashSet(); + Set keys = new HashSet<>(); for (int j = 0; j < 50; j++) { if (partitionMethod == 0) @@ -1540,12 +1537,12 @@ public void testLoadBalancerSimulationDegraderWithFileStore() throws URISyntaxEx SimpleLoadBalancerSimulation simulator = new SimpleLoadBalancerSimulation(new DegraderLoadBalancerStrategyFactoryV3(), - new FileStoreTestFactory("cluster", - new ClusterPropertiesJsonSerializer()), - new FileStoreTestFactory("service", - new ServicePropertiesJsonSerializer()), - new FileStoreTestFactory("uri", - new UriPropertiesJsonSerializer())); + new FileStoreTestFactory<>("cluster", + new ClusterPropertiesJsonSerializer()), + new FileStoreTestFactory<>("service", + new ServicePropertiesJsonSerializer()), + new FileStoreTestFactory<>("uri", + new UriPropertiesJsonSerializer())); simulator.simulateMultithreaded(1, 1000, 20); simulator.reset(); @@ -1562,12 +1559,12 @@ public void testLoadBalancerSimulationDegraderWithFileStoreLarge() throws URISyn { SimpleLoadBalancerSimulation simulator = new SimpleLoadBalancerSimulation(new DegraderLoadBalancerStrategyFactoryV3(), - new FileStoreTestFactory("cluster", - new ClusterPropertiesJsonSerializer()), - new FileStoreTestFactory("service", - new ServicePropertiesJsonSerializer()), - new FileStoreTestFactory("uri", - new UriPropertiesJsonSerializer())); + new FileStoreTestFactory<>("cluster", + new ClusterPropertiesJsonSerializer()), + new FileStoreTestFactory<>("service", + new ServicePropertiesJsonSerializer()), + new FileStoreTestFactory<>("uri", + new UriPropertiesJsonSerializer())); simulator.simulateMultithreaded(1, 1000, 20); simulator.reset(); @@ -1607,9 +1604,9 @@ public FileStoreTestFactory(String subfolder, PropertySerializer serializer) @Override public PropertyStore getStore() { - return new FileStore(_testDirectory + File.separator + _subfolder, - FileSystemDirectory.FILE_STORE_EXTENSION, - _serializer); + return new FileStore<>(_testDirectory + File.separator + _subfolder, + FileSystemDirectory.FILE_STORE_EXTENSION, + _serializer); } } @@ -1673,14 +1670,14 @@ private static class TestLoadBalancerStrategy implements LoadBalancerStrategy public TestLoadBalancerStrategy(Map> partitionDescriptions) { - _partitionData = new HashMap>(); + _partitionData = new HashMap<>(); for (Map.Entry> uriPartitionPair : partitionDescriptions.entrySet()) { for (Map.Entry partitionData : uriPartitionPair.getValue().entrySet()) { if (!_partitionData.containsKey(partitionData.getKey())) { - _partitionData.put(partitionData.getKey(), new HashMap()); + _partitionData.put(partitionData.getKey(), new HashMap<>()); } _partitionData.get(partitionData.getKey()).put(uriPartitionPair.getKey(), 100); } @@ -1709,11 +1706,11 @@ public Ring getRing(long clusterGenerationId, int partitionId, Map(_partitionData.get(partitionId)); + return new ConsistentHashRing<>(_partitionData.get(partitionId)); } else { - return new ConsistentHashRing(new HashMap()); + return new ConsistentHashRing<>(new HashMap<>()); } } @@ -1774,13 +1771,13 @@ public void testLoadBalancerDropRate() throws ServiceUnavailableException, for (int tryAgain = 0; tryAgain < RETRY; ++tryAgain) { Map> loadBalancerStrategyFactories = - new HashMap>(); - Map clientFactories = new HashMap(); - List prioritizedSchemes = new ArrayList(); + new HashMap<>(); + Map clientFactories = new HashMap<>(); + List prioritizedSchemes = new ArrayList<>(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); ScheduledExecutorService executorService = new SynchronousExecutorService(); @@ -1801,7 +1798,7 @@ public void testLoadBalancerDropRate() throws ServiceUnavailableException, SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS, _d2Executor); - FutureCallback balancerCallback = new FutureCallback(); + FutureCallback balancerCallback = new FutureCallback<>(); loadBalancer.start(balancerCallback); balancerCallback.get(); @@ -1809,9 +1806,9 @@ public void testLoadBalancerDropRate() throws ServiceUnavailableException, URI uri2 = URI.create("http://test.qa2.com:2345"); URI uri3 = URI.create("http://test.qa3.com:6789"); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(3); + Map> uriData = new HashMap<>(3); uriData.put(uri1, partitionData); uriData.put(uri2, partitionData); uriData.put(uri3, partitionData); @@ -1835,7 +1832,7 @@ public void testLoadBalancerDropRate() throws ServiceUnavailableException, URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo"); URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo"); - Set expectedUris = new HashSet(); + Set expectedUris = new HashSet<>(); expectedUris.add(expectedUri1); expectedUris.add(expectedUri2); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simulator/R2D2Server.java b/d2/src/test/java/com/linkedin/d2/balancer/simulator/R2D2Server.java index 4007a49f96..325e488c11 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simulator/R2D2Server.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simulator/R2D2Server.java @@ -59,12 +59,12 @@ public static void main(String[] args) throws Exception public R2D2Server() throws Exception { int port = 9876; - _clusters = new HashMap>(); + _clusters = new HashMap<>(); // create two clusters. ten servers each. three services per cluster. for (String clusterName : new String[] { "cluster-1", "cluster-2" }) { - List servers = new ArrayList(); + List servers = new ArrayList<>(); for (int i = 0; i < 10; ++i) { @@ -84,7 +84,7 @@ public void run() throws Exception // start everything for (Map.Entry> servers : _clusters.entrySet()) { - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); schemes.add("http"); @@ -114,9 +114,9 @@ private void putService(ServiceProperties serviceProperties) throws Exception ZKConnection client = new ZKConnection(_zookeeperHost+":"+_zookeeperPort, 30000); PropertyStore store = - new ZooKeeperPermanentStore(client, - new ServicePropertiesJsonSerializer(), - _basePath+"/services"); + new ZooKeeperPermanentStore<>(client, + new ServicePropertiesJsonSerializer(), + _basePath+"/services"); store.put(serviceProperties.getServiceName(), serviceProperties); client.getZooKeeper().close(); @@ -128,9 +128,9 @@ private void putCluster(ClusterProperties clusterProperties) throws Exception ZKConnection client = new ZKConnection(_zookeeperHost+":"+_zookeeperPort, 30000); PropertyStore store = - new ZooKeeperPermanentStore(client, - new ClusterPropertiesJsonSerializer(), - _basePath+"/clusters"); + new ZooKeeperPermanentStore<>(client, + new ClusterPropertiesJsonSerializer(), + _basePath + "/clusters"); store.put(clusterProperties.getClusterName(), clusterProperties); client.getZooKeeper().close(); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/simulator/SimpleLoadBalancerSimulation.java b/d2/src/test/java/com/linkedin/d2/balancer/simulator/SimpleLoadBalancerSimulation.java index 6959f499a1..7b829cf11a 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/simulator/SimpleLoadBalancerSimulation.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/simulator/SimpleLoadBalancerSimulation.java @@ -146,9 +146,9 @@ public static void main(String[] args) throws Exception public SimpleLoadBalancerSimulation(LoadBalancerStrategyFactory loadBalancerStrategyFactoryToTest) { this(loadBalancerStrategyFactoryToTest, - new MockStoreFactory(), - new MockStoreFactory(), - new MockStoreFactory()); + new MockStoreFactory<>(), + new MockStoreFactory<>(), + new MockStoreFactory<>()); } public SimpleLoadBalancerSimulation(LoadBalancerStrategyFactory loadBalancerStrategyFactoryToTest, @@ -172,25 +172,24 @@ public void reset() { // simulation state _random = new Random(); - _possibleServices = Collections.synchronizedList(new ArrayList()); - _possibleClusters = Collections.synchronizedList(new ArrayList()); - _possiblePaths = Collections.synchronizedList(new ArrayList()); - _possibleSchemes = Collections.synchronizedList(new ArrayList()); - _possibleStrategies = Collections.synchronizedList(new ArrayList()); - _possibleUris = Collections.synchronizedList(new ArrayList()); + _possibleServices = Collections.synchronizedList(new ArrayList<>()); + _possibleClusters = Collections.synchronizedList(new ArrayList<>()); + _possiblePaths = Collections.synchronizedList(new ArrayList<>()); + _possibleSchemes = Collections.synchronizedList(new ArrayList<>()); + _possibleStrategies = Collections.synchronizedList(new ArrayList<>()); + _possibleUris = Collections.synchronizedList(new ArrayList<>()); // load balancer state _executorService = Executors.newSingleThreadScheduledExecutor();; // pretend that these are zk stores - _serviceRegistry = new MockStore(); - _uriRegistry = new MockStore(); - _clusterRegistry = new MockStore(); + _serviceRegistry = new MockStore<>(); + _uriRegistry = new MockStore<>(); + _clusterRegistry = new MockStore<>(); - _loadBalancerStrategyFactories = - new HashMap>(); - _clientFactories = new HashMap(); + _loadBalancerStrategyFactories = new HashMap<>(); + _clientFactories = new HashMap<>(); _state = new SimpleLoadBalancerState(_executorService, _uriRegistry, @@ -200,7 +199,7 @@ public void reset() _loadBalancerStrategyFactories); _loadBalancer = new SimpleLoadBalancer(_state, 10, TimeUnit.SECONDS, _executorService); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _loadBalancer.start(callback); try { @@ -212,9 +211,9 @@ public void reset() } // verification state - _expectedServiceProperties = new ConcurrentHashMap(); - _expectedClusterProperties = new ConcurrentHashMap(); - _expectedUriProperties = new ConcurrentHashMap(); + _expectedServiceProperties = new ConcurrentHashMap<>(); + _expectedClusterProperties = new ConcurrentHashMap<>(); + _expectedUriProperties = new ConcurrentHashMap<>(); _totalMessages = 0; // state setup @@ -627,7 +626,7 @@ public void done() // schemes could find no available uris in the // cluster. let's see if we can find a URI that // matches a prioritized scheme in the cluster. - Set schemes = new HashSet(); + Set schemes = new HashSet<>(); for (URI uri : uriProperties.Uris()) { @@ -751,11 +750,11 @@ public void addCluster(String clusterName, new ClusterProperties(clusterName, prioritizedSchemes); // weight the uris randomly between 1 and 2 - Map> uriData = new HashMap>(); + Map> uriData = new HashMap<>(); for (URI uri : uris) { - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d + _random.nextDouble())); uriData.put(uri, partitionData); } @@ -779,7 +778,7 @@ public void removeCluster(String clusterName) // helpers public List stringToUris(String urisString) { - List uris = new ArrayList(); + List uris = new ArrayList<>(); if (urisString.length() > 0) { @@ -886,7 +885,7 @@ public void initQueues(int queues) for (int i = 0; i < queues; ++i) { - _queues[i] = new ConcurrentLinkedQueue(); + _queues[i] = new ConcurrentLinkedQueue<>(); } } @@ -915,7 +914,7 @@ public static class MockStoreFactory implements PropertyStoreFactory @Override public PropertyStore getStore() { - return new MockStore(); + return new MockStore<>(); } } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderConfigFactoryTest.java b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderConfigFactoryTest.java index 85c79a5989..a5780cf3a4 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderConfigFactoryTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderConfigFactoryTest.java @@ -37,7 +37,7 @@ public class DegraderConfigFactoryTest @Test public void testToDegraderConfig() { - Map properties = new HashMap();; + Map properties = new HashMap<>();; Boolean logEnabled = false; DegraderImpl.LatencyToUse latencyToUse = DegraderImpl.LatencyToUse.PCT95; Double maxDropRate = 0.33; diff --git a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStateTest.java b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStateTest.java index c3208b34c3..8330831565 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStateTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStateTest.java @@ -183,7 +183,7 @@ private static PartitionDegraderLoadBalancerState newPartitionState(long generat private static List newPartitionStates(int numberOfPartitions) { - List states = new ArrayList(); + List states = new ArrayList<>(); for (int p = 0; p < numberOfPartitions; ++p) states.add(newPartitionState(p, p)); return states; @@ -219,7 +219,7 @@ private static List concurrentGets(DegraderL { int getsPerPartition = 3; List> reads - = new ArrayList>(); + = new ArrayList<>(); for (int g = 0; g < getsPerPartition; ++g) for (int p = 0; p < numberOfPartitions; ++p) reads.add(new GetPartitionState(subject, p)); @@ -264,14 +264,14 @@ private static void testConcurrentGetsAndSets(int numberOfPartitions) { int numberOfPartitions = newStates.size(); int getsPerPartition = 3; - List> calls = new ArrayList>(); + List> calls = new ArrayList<>(); for (int p = 0; p < numberOfPartitions; ++p) calls.add(new GetAndSetPartitionState(subject, p, newStates.get(p))); for (int g = 0; g < getsPerPartition; ++g) for (int p = 0; p < numberOfPartitions; ++p) calls.add(new GetPartitionState(subject, p)); getAll(concurrently(calls)); - List actual = new ArrayList(); + List actual = new ArrayList<>(); for (int p = 0; p < numberOfPartitions; ++p) actual.add(subject.getPartitionState(p)); assertSameElements(actual, newStates); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyConfigTest.java b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyConfigTest.java index a4e2163015..fad338ee85 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyConfigTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerStrategyConfigTest.java @@ -25,7 +25,7 @@ public class DegraderLoadBalancerStrategyConfigTest @Test public void testCreateHttpConfigFromMap() { - Map properties = new HashMap(); + Map properties = new HashMap<>(); long httpUpdateIntervalMs = 5231; boolean updateOnlyAtInterval = false; @@ -42,8 +42,8 @@ public void testCreateHttpConfigFromMap() double hashRingPointCleanUpRate = 0.1; String consistentHashAlgo = "multiProbe"; int numProbes = 1024; - Map httpHashConfig = new HashMap(); - List httpRegexes = new LinkedList(); + Map httpHashConfig = new HashMap<>(); + List httpRegexes = new LinkedList<>(); httpRegexes.add("httphashToken=(\\d+)"); httpHashConfig.put("regexes", httpRegexes); @@ -110,7 +110,7 @@ public void testCreateHttpConfigFromMap() @Test public void testCreateHttpConfigFromMapWithExtraArguments() { - Map properties = new HashMap(); + Map properties = new HashMap<>(); long httpUpdateIntervalMs = 5231; boolean updateOnlyAtInterval = false; @@ -128,8 +128,8 @@ public void testCreateHttpConfigFromMapWithExtraArguments() String consistentHashAlgo = "multiProbe"; int numProbes = 1024; long quarantineLatency = 50; - Map httpHashConfig = new HashMap(); - List httpRegexes = new LinkedList(); + Map httpHashConfig = new HashMap<>(); + List httpRegexes = new LinkedList<>(); httpRegexes.add("httphashToken=(\\d+)"); httpHashConfig.put("regexes", httpRegexes); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerTest.java index 3e88577a9b..2a21fba947 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/strategies/degrader/DegraderLoadBalancerTest.java @@ -114,7 +114,7 @@ public static Map getDefaultPartitionData(double weight) public static Map getDefaultPartitionData(double weight, int numberOfPartitions) { PartitionData data = new PartitionData(weight); - Map partitionDataMap = new HashMap(numberOfPartitions + 1); + Map partitionDataMap = new HashMap<>(numberOfPartitions + 1); for (int p = 0; p < numberOfPartitions; ++p) partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID + p, data); return partitionDataMap; @@ -128,7 +128,7 @@ public void testDegraderLoadBalancerStateComparison() long clusterGenerationId = 1; long lastUpdated = 29999; long currentAverageClusterLatency = 3000; - Map configMap = new HashMap(); + Map configMap = new HashMap<>(); configMap.put(PropertyKeys.HTTP_LB_LOW_WATER_MARK, 500d); configMap.put(PropertyKeys.HTTP_LB_STRATEGY_PROPERTIES_POINTS_PER_WEIGHT, 120); DegraderLoadBalancerStrategyConfig config = DegraderLoadBalancerStrategyConfig.createHttpConfigFromMap(configMap); @@ -139,7 +139,7 @@ public void testDegraderLoadBalancerStateComparison() double currentOverrideDropRate = 0.4; boolean initialized = true; String name = "degraderV2"; - Map points = new HashMap(); + Map points = new HashMap<>(); Map recoveryMap = new HashMap<>(); URI uri1 = new URI("http://test.linkedin.com:10010/abc0"); URI uri2 = new URI("http://test.linkedin.com:10010/abc1"); @@ -151,7 +151,7 @@ public void testDegraderLoadBalancerStateComparison() TestClock clock = new TestClock(); List clients = createTrackerClient(3, clock, null); - List clientUpdaters = new ArrayList(); + List clientUpdaters = new ArrayList<>(); for (DegraderTrackerClient client : clients) { recoveryMap.put(client, 0.0); @@ -563,7 +563,7 @@ public void testDegraderLoadBalancerHandlingExceptionInUpdate() // test DegraderLoadBalancerStrategy when the strategy is CALL_DROPPING. We have to make some prepare the // environment by simulating lots of high latency calls to the tracker client int numberOfCallsPerClient = 10; - List callCompletions = new ArrayList(); + List callCompletions = new ArrayList<>(); for (DegraderTrackerClient client : clients) { for (int i = 0; i < numberOfCallsPerClient; i++) @@ -655,7 +655,7 @@ private void runMultiThreadedTest(final DegraderLoadBalancerStrategyAdapter stra final CountDownLatch exitLatch = new CountDownLatch(numberOfThread); final CountDownLatch startLatch = new CountDownLatch(numberOfThread); ExecutorService executorService = Executors.newFixedThreadPool(numberOfThread); - List> futures = new ArrayList>(); + List> futures = new ArrayList<>(); for (int i = 0; i < numberOfThread; i++) { @@ -874,7 +874,7 @@ public void testDropDueToDegrader() throws URISyntaxException { DegraderLoadBalancerStrategyV3 strategy = getStrategy(); List clients = new ArrayList<>(); - List clientUpdaters = new ArrayList(); + List clientUpdaters = new ArrayList<>(); clients.add(getClient(URI.create("http://test.linkedin.com:3242/fdsaf"), new TestClock())); clients.add(getClient(URI.create("http://test.linkedin.com:3243/fdsaf"), new TestClock())); @@ -1053,7 +1053,7 @@ public void testOneTrackerClientForPartition() throws URISyntaxException DegraderLoadBalancerStrategyV3 strategy = getStrategy(); Map clients = new HashMap<>(); URI uri1 = URI.create("http://test.linkedin.com:3242/fdsaf"); - Map weightMap = new HashMap(); + Map weightMap = new HashMap<>(); weightMap.put(0, new PartitionData(1d)); TrackerClient client = new DegraderTrackerClientImpl(uri1, weightMap, @@ -1459,7 +1459,7 @@ public void TestRandomIncreaseReduceTrackerClients(String consistentHashAlgorith String baseUri = "http://linkedin.com:9999"; int numberOfClients = 100; int loopNumber = 100; - Map degraderProperties = new HashMap(); + Map degraderProperties = new HashMap<>(); degraderProperties.put(PropertyKeys.DEGRADER_HIGH_ERROR_RATE, "0.5"); degraderProperties.put(PropertyKeys.DEGRADER_LOW_ERROR_RATE, "0.2"); DegraderImpl.Config degraderConfig = DegraderConfigFactory.toDegraderConfig(degraderProperties); @@ -1522,7 +1522,7 @@ public void TestGetTrackerClients() String baseUri = "http://linkedin.com:9999"; int numberOfClients = 100; int loopNumber = 100000; - Map degraderProperties = new HashMap(); + Map degraderProperties = new HashMap<>(); degraderProperties.put(PropertyKeys.DEGRADER_HIGH_ERROR_RATE, "0.5"); degraderProperties.put(PropertyKeys.DEGRADER_LOW_ERROR_RATE, "0.2"); DegraderImpl.Config degraderConfig = DegraderConfigFactory.toDegraderConfig(degraderProperties); @@ -1564,7 +1564,7 @@ public void TestGetTrackerClients() @Test(groups = { "small", "back-end" }) public void testshouldUpdatePartition() throws URISyntaxException { - Map myConfig = new HashMap(); + Map myConfig = new HashMap<>(); TestClock testClock = new TestClock(); myConfig.put(PropertyKeys.CLOCK, testClock); myConfig.put(PropertyKeys.HTTP_LB_STRATEGY_PROPERTIES_UPDATE_INTERVAL_MS, 5000L); @@ -1589,7 +1589,7 @@ public void testshouldUpdatePartition() throws URISyntaxException testClock._currentTimeMillis, true, ringFactory, - new HashMap(), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy.LOAD_BALANCE, 0.0, -1, @@ -1613,7 +1613,7 @@ public void testshouldUpdatePartition() throws URISyntaxException testClock._currentTimeMillis, true, ringFactory, - new HashMap(), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy.LOAD_BALANCE, 0.0, -1, @@ -1637,7 +1637,7 @@ public void testshouldUpdatePartition() throws URISyntaxException testClock._currentTimeMillis, true, ringFactory, - new HashMap(), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy.LOAD_BALANCE, 0.0, -1, @@ -1660,7 +1660,7 @@ public void testshouldUpdatePartition() throws URISyntaxException testClock._currentTimeMillis, true, ringFactory, - new HashMap(), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy.LOAD_BALANCE, 0.0, -1, @@ -1683,7 +1683,7 @@ public void testshouldUpdatePartition() throws URISyntaxException @Test(groups = { "small", "back-end" }) public void testshouldUpdatePartitionOnlyAtInterval() throws URISyntaxException { - Map myConfig = new HashMap(); + Map myConfig = new HashMap<>(); TestClock testClock = new TestClock(); myConfig.put(PropertyKeys.CLOCK, testClock); myConfig.put(PropertyKeys.HTTP_LB_STRATEGY_PROPERTIES_UPDATE_INTERVAL_MS, 5000L); @@ -1716,8 +1716,8 @@ public void testshouldUpdatePartitionOnlyAtInterval() throws URISyntaxException current = new PartitionDegraderLoadBalancerState(1, testClock._currentTimeMillis, true, - new DelegatingRingFactory(new DegraderLoadBalancerStrategyConfig(1L)), - new HashMap(), + new DelegatingRingFactory<>(new DegraderLoadBalancerStrategyConfig(1L)), + new HashMap<>(), PartitionDegraderLoadBalancerState.Strategy.LOAD_BALANCE, 0.0, -1, @@ -1737,7 +1737,7 @@ public void testOverrideClusterDropRate() throws URISyntaxException { DegraderLoadBalancerStrategyV3 strategy = getStrategy(); List clients = new ArrayList<>(); - List clientUpdaters = new ArrayList(); + List clientUpdaters = new ArrayList<>(); for (DegraderTrackerClient client : clients) { clientUpdaters.add(new DegraderTrackerClientUpdater(client, DEFAULT_PARTITION_ID)); @@ -1969,7 +1969,7 @@ public void stressTest() TestClock testClock = new TestClock(); String baseUri = "http://linkedin.com:9999"; int numberOfPartitions = 10; - Map degraderProperties = new HashMap(); + Map degraderProperties = new HashMap<>(); degraderProperties.put(PropertyKeys.DEGRADER_HIGH_ERROR_RATE, "0.5"); degraderProperties.put(PropertyKeys.DEGRADER_LOW_ERROR_RATE, "0.2"); DegraderImpl.Config degraderConfig = DegraderConfigFactory.toDegraderConfig(degraderProperties); @@ -2185,7 +2185,7 @@ public void run() } }; - List actions = new ArrayList(); + List actions = new ArrayList<>(); actions.add(update); actions.add(resize); return actions; @@ -2221,7 +2221,7 @@ public Ring call() final ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); try { - final List>> results = new ArrayList>>(); + final List>> results = new ArrayList<>(); for (int r = 0; r < numberOfThreads; ++r) results.add(executor.submit(getRing)); clock.addMs(timeInterval); @@ -2241,7 +2241,7 @@ public Object[][] clientGlitch() { long timeInterval = 10; // msec TestClock clock = new TestClock(); - Map props = new HashMap(); + Map props = new HashMap<>(); props.put(PropertyKeys.CLOCK, clock); // We want the degrader to re-enter the ring after one cooling off period: props.put(PropertyKeys.HTTP_LB_INITIAL_RECOVERY_LEVEL, 0.005); @@ -2453,7 +2453,7 @@ public void clusterTotalRecovery1TC(Map myMap, TestClock clock, dcClient1Default.setMaxDropRate(1d); dcClient1Default.setUpStep(1.0d); - List ccList = new ArrayList(); + List ccList = new ArrayList<>(); CallCompletion cc; for (int j = 0; j < NUM_CHECKS; j++) @@ -2483,7 +2483,7 @@ public void clusterTotalRecovery1TC(Map myMap, TestClock clock, // now we mimic the high latency and force the state to drop all calls so to make // the overrideClusterDropRate to 1.0 - ccList = new ArrayList(); + ccList = new ArrayList<>(); for (int j = 0; j < NUM_CHECKS; j++) { cc = client1.getCallTracker().startCall(); @@ -2576,7 +2576,7 @@ public void clusterRecovery1TC(Map myMap, TestClock clock, dcClient1Default.setMaxDropRate(1d); dcClient1Default.setUpStep(1.0d); - List ccList = new ArrayList(); + List ccList = new ArrayList<>(); CallCompletion cc; for (int j = 0; j < NUM_CHECKS; j++) @@ -2691,7 +2691,7 @@ private List createTrackerClient(int n, TestClock clock, private void callClients(long milliseconds, double qps, List clients, TestClock clock, long timeInterval, boolean withError, boolean withQualifiedDegraderError) { - LinkedList callCompletions = new LinkedList(); + LinkedList callCompletions = new LinkedList<>(); int callHowManyTimes = (int)((qps * timeInterval) / 1000); for (int i = 0; i < callHowManyTimes; i++) { @@ -3087,13 +3087,13 @@ private void testDegraderLoadBalancerSimulator(DegraderLoadBalancerStrategyAdapt //we'll simulate the client dying one by one until all the clients are gone int numberOfClients = clients.size(); - HashSet uris = new HashSet(); - HashSet removedUris = new HashSet(); + HashSet uris = new HashSet<>(); + HashSet removedUris = new HashSet<>(); for (TrackerClient client : clients) { uris.add(client.getUri()); } - LinkedList removedClients = new LinkedList(); + LinkedList removedClients = new LinkedList<>(); //loadBalancing strategy will always be picked because there is no hash ring changes boolean isLoadBalancingStrategyTurn = true; for(int i = numberOfClients; i > 0; i--) @@ -3255,7 +3255,7 @@ public void testHighLowWatermarks() dcClient1Default.setOverrideMinCallCount(5); dcClient1Default.setMinCallCount(5); - List ccList = new ArrayList(); + List ccList = new ArrayList<>(); CallCompletion cc; TrackerClient resultTC = getTrackerClient(strategy, request, new RequestContext(), 1, clients); @@ -3363,7 +3363,7 @@ public void testClusterRecovery2TC() URI uri2 = URI.create("http://test.linkedin.com:3243/fdsaf"); URIRequest request = new URIRequest(uri1); - List ccList = new ArrayList(); + List ccList = new ArrayList<>(); CallCompletion cc; DegraderTrackerClient client1 = @@ -3494,7 +3494,7 @@ public void testAdjustedMinCallCount() URI uri1 = URI.create("http://test.linkedin.com:3242/fdsaf"); URIRequest request = new URIRequest(uri1); - List ccList = new ArrayList(); + List ccList = new ArrayList<>(); CallCompletion cc; DegraderTrackerClient client1 = @@ -3746,7 +3746,7 @@ public static DegraderTrackerClient getClient(URI uri) public static DegraderTrackerClient getClient(URI uri, Clock clock) { - Map partitionDataMap = new HashMap(2); + Map partitionDataMap = new HashMap<>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1)); return new DegraderTrackerClientImpl(uri, partitionDataMap, new TestLoadBalancerClient(uri), clock, null); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/strategies/random/RandomLoadBalancerTest.java b/d2/src/test/java/com/linkedin/d2/balancer/strategies/random/RandomLoadBalancerTest.java index 0c73d20821..f44be3319f 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/strategies/random/RandomLoadBalancerTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/strategies/random/RandomLoadBalancerTest.java @@ -40,7 +40,7 @@ public void testRoundRobinBalancer() { RandomLoadBalancerStrategyFactory lbFactory = new RandomLoadBalancerStrategyFactory(); RandomLoadBalancerStrategy rrLoadBalancer = lbFactory.newLoadBalancer(null); - Map partitionDataMap = new HashMap(2); + Map partitionDataMap = new HashMap<>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); TrackerClient trackerClient1 = Mockito.mock(TrackerClient.class); TrackerClient trackerClient2 = Mockito.mock(TrackerClient.class); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/HostToKeyMapperTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/HostToKeyMapperTest.java index bbf8fc6c5e..f854703bb3 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/HostToKeyMapperTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/HostToKeyMapperTest.java @@ -27,24 +27,24 @@ public void verifyMapKeyResultWithHost() throws URISyntaxException final URI foo5 = new URI("http://foo5.com"); final URI foo6 = new URI("http://foo6.com"); - Map> partitionInfoMap = new HashMap>(); - KeysAndHosts keyAndHosts0 = new KeysAndHosts(new ArrayList(Arrays.asList(1, 2, 3)), - new ArrayList(Arrays.asList(foo1, foo3))); - KeysAndHosts keyAndHosts1 = new KeysAndHosts(new ArrayList(Arrays.asList(4)), - new ArrayList(Arrays.asList(foo4, foo5))); - KeysAndHosts keyAndHosts2 = new KeysAndHosts(new ArrayList(Arrays.asList(9)), - new ArrayList()); - KeysAndHosts keyAndHosts3 = new KeysAndHosts(new ArrayList(Arrays.asList(10)), - new ArrayList(Arrays.asList(foo2))); - KeysAndHosts keyAndHosts4 = new KeysAndHosts(new ArrayList(Arrays.asList(13, 15)), - new ArrayList(Arrays.asList(foo2))); + Map> partitionInfoMap = new HashMap<>(); + KeysAndHosts keyAndHosts0 = new KeysAndHosts<>(new ArrayList<>(Arrays.asList(1, 2, 3)), + new ArrayList<>(Arrays.asList(foo1, foo3))); + KeysAndHosts keyAndHosts1 = new KeysAndHosts<>(new ArrayList<>(Arrays.asList(4)), + new ArrayList<>(Arrays.asList(foo4, foo5))); + KeysAndHosts keyAndHosts2 = new KeysAndHosts<>(new ArrayList<>(Arrays.asList(9)), + new ArrayList<>()); + KeysAndHosts keyAndHosts3 = new KeysAndHosts<>(new ArrayList<>(Arrays.asList(10)), + new ArrayList<>(Arrays.asList(foo2))); + KeysAndHosts keyAndHosts4 = new KeysAndHosts<>(new ArrayList<>(Arrays.asList(13, 15)), + new ArrayList<>(Arrays.asList(foo2))); partitionInfoMap.put(0, keyAndHosts0); partitionInfoMap.put(1, keyAndHosts1); partitionInfoMap.put(2, keyAndHosts2); partitionInfoMap.put(3, keyAndHosts3); partitionInfoMap.put(4, keyAndHosts4); - HostToKeyMapper result = new HostToKeyMapper(new ArrayList(Arrays.asList(16)), partitionInfoMap, 2, 5, new HashMap()); + HostToKeyMapper result = new HostToKeyMapper<>(new ArrayList<>(Arrays.asList(16)), partitionInfoMap, 2, 5, new HashMap<>()); Assert.assertNotNull(result); @@ -53,21 +53,21 @@ public void verifyMapKeyResultWithHost() throws URISyntaxException HostToKeyResult firstIteration = result.getResult(0); Assert.assertEquals(firstIteration.getUnmappedKeys().size(), 2); - Assert.assertTrue(firstIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(9, + Assert.assertTrue(firstIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(9, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(firstIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(16, + Assert.assertTrue(firstIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(16, HostToKeyResult.ErrorType.FAIL_TO_FIND_PARTITION))); Map> mapResult = firstIteration.getMapResult(); Assert.assertNotNull(mapResult); Assert.assertTrue(mapResult.size() == 3); - Collection keys0 = new HashSet(); + Collection keys0 = new HashSet<>(); keys0.add(1); keys0.add(2); keys0.add(3); - Collection keys1 = new HashSet(); + Collection keys1 = new HashSet<>(); keys1.add(4); - Collection keys2 = new HashSet(); + Collection keys2 = new HashSet<>(); keys2.add(10); keys2.add(13); keys2.add(15); @@ -95,15 +95,15 @@ else if (entry.getKey().equals(foo2)) HostToKeyResult secondIteration = result.getResult(1); Assert.assertEquals(secondIteration.getUnmappedKeys().size(), 5); - Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(9, + Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(9, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(10, + Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(10, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(13, + Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(13, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(15, + Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(15, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(16, + Assert.assertTrue(secondIteration.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(16, HostToKeyResult.ErrorType.FAIL_TO_FIND_PARTITION))); mapResult = secondIteration.getMapResult(); @@ -128,7 +128,7 @@ else if (entry.getKey().equals(foo5)) Assert.assertNull(thirdIteration); //test getResult with subset of keys - Collection subsetKeys = new HashSet(); + Collection subsetKeys = new HashSet<>(); subsetKeys.add(10); subsetKeys.add(13); subsetKeys.add(9); @@ -136,9 +136,9 @@ else if (entry.getKey().equals(foo5)) HostToKeyResult subsetKeyResult = result.getResult(0, subsetKeys); Assert.assertNotNull(subsetKeyResult); Assert.assertEquals(subsetKeyResult.getUnmappedKeys().size(), 2); - Assert.assertTrue(subsetKeyResult.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(9, + Assert.assertTrue(subsetKeyResult.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(9, HostToKeyResult.ErrorType.NO_HOST_AVAILABLE_IN_PARTITION))); - Assert.assertTrue(subsetKeyResult.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey(16, + Assert.assertTrue(subsetKeyResult.getUnmappedKeys().contains(new HostToKeyResult.UnmappedKey<>(16, HostToKeyResult.ErrorType.FAIL_TO_FIND_PARTITION))); mapResult = subsetKeyResult.getMapResult(); Assert.assertEquals(mapResult.size(), 1); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoClient.java b/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoClient.java index 051ace2384..719909980b 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoClient.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoClient.java @@ -136,22 +136,22 @@ public static SimpleLoadBalancer getLoadBalancer(String hostPort) throws IOExcep ZKConnection zkClient = new ZKConnection(hostPort, 10000); zkClusterRegistry = - new ZooKeeperPermanentStore(zkClient, - new ClusterPropertiesJsonSerializer(), - _basePath+"/clusters"); + new ZooKeeperPermanentStore<>(zkClient, + new ClusterPropertiesJsonSerializer(), + _basePath + "/clusters"); zkServiceRegistry = - new ZooKeeperPermanentStore(zkClient, - new ServicePropertiesJsonSerializer(), - _basePath+"/services"); + new ZooKeeperPermanentStore<>(zkClient, + new ServicePropertiesJsonSerializer(), + _basePath + "/services"); zkUriRegistry = - new ZooKeeperEphemeralStore(zkClient, - new UriPropertiesJsonSerializer(), - new UriPropertiesMerger(), - _basePath+"/uris", - false, - true); + new ZooKeeperEphemeralStore<>(zkClient, + new UriPropertiesJsonSerializer(), + new UriPropertiesMerger(), + _basePath + "/uris", + false, + true); // fs stores File testDirectory = @@ -164,17 +164,17 @@ public static SimpleLoadBalancer getLoadBalancer(String hostPort) throws IOExcep new File(testDirectory + File.separator + "uri").mkdir(); FileStore fsClusterStore = - new FileStore(testDirectory + File.separator + "cluster", + new FileStore<>(testDirectory + File.separator + "cluster", FileSystemDirectory.FILE_STORE_EXTENSION, new ClusterPropertiesJsonSerializer()); FileStore fsServiceStore = - new FileStore(testDirectory + File.separator + "service", + new FileStore<>(testDirectory + File.separator + "service", FileSystemDirectory.FILE_STORE_EXTENSION, new ServicePropertiesJsonSerializer()); FileStore fsUriStore = - new FileStore(testDirectory + File.separator + "uri", + new FileStore<>(testDirectory + File.separator + "uri", FileSystemDirectory.FILE_STORE_EXTENSION, new UriPropertiesJsonSerializer()); @@ -187,35 +187,34 @@ public static SimpleLoadBalancer getLoadBalancer(String hostPort) throws IOExcep thread.start(); PropertyEventBus serviceBus = - new PropertyEventBusImpl(executorService, zkServiceRegistry); + new PropertyEventBusImpl<>(executorService, zkServiceRegistry); serviceBus.register(fsServiceStore); - new ZooKeeperTogglingStore(zkServiceRegistry, - fsServiceStore, - serviceBus, - true); + new ZooKeeperTogglingStore<>(zkServiceRegistry, + fsServiceStore, + serviceBus, + true); PropertyEventBus uriBus = - new PropertyEventBusImpl(executorService, zkUriRegistry); + new PropertyEventBusImpl<>(executorService, zkUriRegistry); uriBus.register(fsUriStore); - new ZooKeeperTogglingStore(zkUriRegistry, fsUriStore, uriBus, true); + new ZooKeeperTogglingStore<>(zkUriRegistry, fsUriStore, uriBus, true); PropertyEventBus clusterBus = - new PropertyEventBusImpl(executorService, zkClusterRegistry); + new PropertyEventBusImpl<>(executorService, zkClusterRegistry); clusterBus.register(fsClusterStore); - new ZooKeeperTogglingStore(zkClusterRegistry, - fsClusterStore, - clusterBus, - true); + new ZooKeeperTogglingStore<>(zkClusterRegistry, + fsClusterStore, + clusterBus, + true); Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); // strategy and scheme factories loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); - Map clientFactories = - new HashMap(); + Map clientFactories = new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoServer.java b/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoServer.java index e44fcd5f64..f174b3f08d 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoServer.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/LoadBalancerEchoServer.java @@ -183,7 +183,7 @@ public LoadBalancerEchoServer(String zookeeperHost, _log.info("Server Uri:"+_uri); - Set validPaths = new HashSet(); + Set validPaths = new HashSet<>(); for (String service : services) { @@ -198,10 +198,10 @@ public LoadBalancerEchoServer(String zookeeperHost, final ZKConnection zkClient = ZKTestUtil.getConnection(zookeeperHost+":"+zookeeperPort, _timeout); ZooKeeperEphemeralStore zk = - new ZooKeeperEphemeralStore(zkClient, - new UriPropertiesJsonSerializer(), - new UriPropertiesMerger(), - _basePath+"/uris"); + new ZooKeeperEphemeralStore<>(zkClient, + new UriPropertiesJsonSerializer(), + new UriPropertiesMerger(), + _basePath + "/uris"); final CountDownLatch wait = new CountDownLatch(1); @@ -305,8 +305,8 @@ public void markUp() throws PropertyStoreException public void markUp(Map partitionWeight) throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); - Map partitionDataMap = new HashMap(); + FutureCallback callback = new FutureCallback<>(); + Map partitionDataMap = new HashMap<>(); if (partitionWeight != null) { for (int partitionId : partitionWeight.keySet()) @@ -332,7 +332,7 @@ public void markUp(Map partitionWeight) throws PropertyStoreExc public void markDown() throws PropertyStoreException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _announcer.markDown(_cluster, _uri, callback); try { @@ -408,7 +408,7 @@ public String getResponsePostfixStringWithPort() private String printWeights() { StringBuilder sb = new StringBuilder(); - Map partitionDataMap = new HashMap(); + Map partitionDataMap = new HashMap<>(); if (_partitionWeight != null) { partitionDataMap = _partitionWeight; diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/TestHelper.java b/d2/src/test/java/com/linkedin/d2/balancer/util/TestHelper.java index c5fa7f21b9..a34a4ad72c 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/TestHelper.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/TestHelper.java @@ -44,7 +44,7 @@ public static void assertSameElements(Iterable actual, Iterable expect */ public static List> split(List from, int subListSize) { - List> into = new ArrayList>(); + List> into = new ArrayList<>(); for (int first = 0; first < from.size(); first += subListSize) { into.add(from.subList(first, Math.min(first + subListSize, from.size()))); @@ -59,7 +59,7 @@ public static List getAll(Collection> futures) public static List getAll(Iterable> futures, long timeout, TimeUnit unit) { - List all = new ArrayList(); + List all = new ArrayList<>(); final long deadline = System.nanoTime() + unit.toNanos(timeout); int f = 0; for (Future future : futures) @@ -82,11 +82,11 @@ public static List> concurrently(Collection> calls) final int numberOfCalls = calls.size(); CountDownLatch ready = new CountDownLatch(numberOfCalls); CountDownLatch start = new CountDownLatch(1); - List> futures = new ArrayList>(numberOfCalls); + List> futures = new ArrayList<>(numberOfCalls); { ExecutorService pool = newFixedDaemonPool(numberOfCalls); for (Callable call : calls) - futures.add(pool.submit(new PauseCallable(1, ready, start, call))); + futures.add(pool.submit(new PauseCallable<>(1, ready, start, call))); assertEquals(futures.size(), numberOfCalls); } try diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapperTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapperTest.java index 9c346b8562..37336d96e0 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapperTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashKeyMapperTest.java @@ -98,10 +98,10 @@ static Map> mapKeys(KeyMapper mapper, URI uri, Set ke { MapKeyResult mapKeyResult = mapper.mapKeysV2(uri, keys); Map> collectionResult = mapKeyResult.getMapResult(); - Map> result = new HashMap>(collectionResult.size() * 2); + Map> result = new HashMap<>(collectionResult.size() * 2); for (Map.Entry> entry : collectionResult.entrySet()) { - result.put(entry.getKey(), new HashSet(entry.getValue())); + result.put(entry.getKey(), new HashSet<>(entry.getValue())); } return result; } @@ -201,41 +201,41 @@ private ConsistentHashKeyMapper getConsistentHashKeyMapper(RingFactory ring String strategyName = "degrader"; //setup partition - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); final URI foo1 = new URI("http://foo1.com"); - Map foo1Data = new HashMap(); + Map foo1Data = new HashMap<>(); foo1Data.put(0, new PartitionData(1.0)); partitionDescriptions.put(foo1, foo1Data); final URI foo2 = new URI("http://foo2.com"); - Map foo2Data = new HashMap(); + Map foo2Data = new HashMap<>(); foo2Data.put(3, new PartitionData(1.0)); foo2Data.put(4, new PartitionData(1.0)); partitionDescriptions.put(foo2, foo2Data); final URI foo3 = new URI("http://foo3.com"); - Map foo3Data = new HashMap(); + Map foo3Data = new HashMap<>(); foo3Data.put(0, new PartitionData(1.0)); partitionDescriptions.put(foo3, foo3Data); final URI foo4 = new URI("http://foo4.com"); - Map foo4Data = new HashMap(); + Map foo4Data = new HashMap<>(); foo4Data.put(1, new PartitionData(1.0)); partitionDescriptions.put(foo4, foo4Data); final URI foo5 = new URI("http://foo5.com"); - Map foo5Data = new HashMap(); + Map foo5Data = new HashMap<>(); foo5Data.put(1, new PartitionData(1.0)); partitionDescriptions.put(foo5, foo5Data); final URI foo6 = new URI("http://foo6.com"); - Map foo6Data = new HashMap(); + Map foo6Data = new HashMap<>(); foo6Data.put(1, new PartitionData(1.0)); partitionDescriptions.put(foo6, foo6Data); //setup strategy which involves tweaking the hash ring to get partitionId -> URI host - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); LoadBalancerStrategy strategy = new TestLoadBalancerStrategy(partitionDescriptions, ringFactory); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair("http", strategy)); @@ -265,9 +265,9 @@ public void testMapKeysConcurrency() throws Exception int numPartitions = 500; // setup partition - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); final URI foo1 = new URI("http://foo1.com"); - Map foo1Data = new HashMap(); + Map foo1Data = new HashMap<>(); for (int i = 0; i < numPartitions; i++) { foo1Data.put(i, new PartitionData(1.0)); @@ -277,7 +277,7 @@ public void testMapKeysConcurrency() throws Exception DegraderLoadBalancerStrategyV3 strategy = new DegraderLoadBalancerStrategyV3( new DegraderLoadBalancerStrategyConfig(5000), serviceName, null, DEGRADER_STATE_LISTENER_FACTORIES); - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair("http", strategy)); PartitionAccessor accessor = new TestDeadlockPartitionAccessor(numPartitions); @@ -291,7 +291,7 @@ public void testMapKeysConcurrency() throws Exception CountDownLatch latch = new CountDownLatch(numPartitions); List runnables = createRunnables(numPartitions, mapper, serviceName, latch); final ExecutorService executor = Executors.newFixedThreadPool(numPartitions); - List futures = new ArrayList(); + List futures = new ArrayList<>(); for (int i = 0; i < numPartitions; i++) { futures.add(executor.submit(runnables.get(i))); @@ -309,7 +309,7 @@ private List createRunnables(int num, final ConsistentHashKeyMapper ma { final URI serviceURI = new URI("d2://" + serviceName); - List runnables = new ArrayList(); + List runnables = new ArrayList<>(); for (int i = 0; i < num; i++) { // since i < numPartitions, the keys will be distributed to different partitions @@ -344,7 +344,7 @@ public void run() private List generateKeys(int partition) { - List keys = new ArrayList(); + List keys = new ArrayList<>(); keys.add(String.valueOf(partition)); return keys; } @@ -380,7 +380,7 @@ private void verifyHostToMapperWithoutKeys(HostToKeyMapper result) @SuppressWarnings("unchecked") private Map> getOrderingOfHostsForEachKey(HostToKeyMapper result, int numHost) { - Map> keyToHosts = new HashMap>(); + Map> keyToHosts = new HashMap<>(); for (int i = 0; i < numHost; i++) { HostToKeyResult hostToKeyResult = result.getResult(i); @@ -392,7 +392,7 @@ private Map> getOrderingOfHostsForEachKey(HostToKeyMapper hosts = keyToHosts.get(key); if (hosts == null) { - hosts = new ArrayList(); + hosts = new ArrayList<>(); keyToHosts.put(key, hosts); } hosts.add(entry.getKey()); @@ -407,7 +407,7 @@ public void testOneBatch(RingFactory ringFactory) throws URISyntaxException { ConsistentHashKeyMapper batcher = getKeyToHostMapper(ringFactory); - Set keys = new HashSet(); + Set keys = new HashSet<>(); keys.add(1); Map> batchedKeys = mapKeys(batcher, URI.create("d2://fooservice/"), keys); @@ -429,7 +429,7 @@ public void testOneBatchManyKeys(RingFactory ringFactory) throws URISyntaxE private Set getRandomKeys(int n) { - Set keys = new HashSet(); + Set keys = new HashSet<>(); Random r = new Random(RANDOM_SEED); for (int ii=0; ii getRandomKeys(int n) @Test(dataProvider = "ringFactories") public void testTwoBatches(RingFactory ringFactory) throws URISyntaxException, ServiceUnavailableException { - Map endpoints = new HashMap(); + Map endpoints = new HashMap<>(); endpoints.put(new URI("test1"), 100); endpoints.put(new URI("test2"), 100); ConsistentHashKeyMapper batcher = getKeyToHostMapper(endpoints, ringFactory); @@ -459,7 +459,7 @@ public void testTwoBatches(RingFactory ringFactory) throws URISyntaxExcepti @Test(dataProvider = "ringFactories") public void testThreePartitionsTwoBatches(RingFactory ringFactory) throws URISyntaxException, ServiceUnavailableException { - Map endpoints = new HashMap(); + Map endpoints = new HashMap<>(); endpoints.put(new URI("test1"), 100); endpoints.put(new URI("test2"), 100); endpoints.put(new URI("test3"), 100); @@ -467,7 +467,7 @@ public void testThreePartitionsTwoBatches(RingFactory ringFactory) throws U ConsistentHashKeyMapper batcher = getKeyToHostMapper(endpoints, 3, ringFactory); Set rawkeys = getRandomKeys(3000); - Set keys = new HashSet(); + Set keys = new HashSet<>(); for (Integer key : rawkeys) { if (key % 3 != 0) @@ -510,7 +510,7 @@ public void testThreePartitionsManyBatches(RingFactory ringFactory) throws ConsistentHashKeyMapper batcher = getKeyToHostMapper(endpoints, 3, ringFactory); Set rawkeys = getRandomKeys(3000); - Set keys = new HashSet(); + Set keys = new HashSet<>(); for (Integer key : rawkeys) { if (key % 3 != 0) @@ -596,7 +596,7 @@ public void testConsistencyWithRepeatedHashing(RingFactory ringFactory) thr ConsistentHashKeyMapper getKeyToHostMapper(RingFactory ringFactory) throws URISyntaxException, ServiceUnavailableException { - Map one = new HashMap(); + Map one = new HashMap<>(); one.put(new URI("test"), 100); return getKeyToHostMapper(one, ringFactory); } @@ -604,7 +604,7 @@ ConsistentHashKeyMapper getKeyToHostMapper(RingFactory ringFactory) throws private Map invert(Map> batchedKeys1) { - Map keyMappings = new HashMap(); + Map keyMappings = new HashMap<>(); for (Map.Entry> entry : batchedKeys1.entrySet()) { for (Integer value : entry.getValue()) @@ -617,7 +617,7 @@ private Map invert(Map> batchedKeys1) private Map createEndpoints(int n) throws URISyntaxException, ServiceUnavailableException { - Map endpoints = new HashMap(); + Map endpoints = new HashMap<>(); for (int ii=0; ii createEndpoints(int n) throws URISyntaxException, Serv private void checkBatchCoverage(Set keys, Map> batchedKeys) { - Set mergedBatches = new HashSet(); + Set mergedBatches = new HashSet<>(); for (Iterable batch : batchedKeys.values()) { boolean batchEmpty = true; @@ -670,21 +670,21 @@ private ConsistentHashKeyMapper getKeyToHostMapper(Map endpoints, { final int partitionSize = endpoints.size() / partitionNum; - List> mapList = new ArrayList>(); + List> mapList = new ArrayList<>(); int count = 0; for(final URI uri : endpoints.keySet()) { final int index = count / partitionSize; if (index == mapList.size()) { - mapList.add(new HashMap()); + mapList.add(new HashMap<>()); } Map map = mapList.get(index); map.put(uri, endpoints.get(uri)); count++; } - List> rings = new ArrayList>(); + List> rings = new ArrayList<>(); for (final Map map : mapList) { final Ring ring = ringFactory.createRing(map); @@ -701,14 +701,14 @@ public static class TestLoadBalancerStrategy implements LoadBalancerStrategy public TestLoadBalancerStrategy(Map> partitionDescriptions, RingFactory ringFactory) { - _partitionData = new HashMap>(); + _partitionData = new HashMap<>(); for (Map.Entry> uriPartitionPair : partitionDescriptions.entrySet()) { for (Map.Entry partitionData : uriPartitionPair.getValue().entrySet()) { if (!_partitionData.containsKey(partitionData.getKey())) { - _partitionData.put(partitionData.getKey(), new HashMap()); + _partitionData.put(partitionData.getKey(), new HashMap<>()); } _partitionData.get(partitionData.getKey()).put(uriPartitionPair.getKey(), 100); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingIteratorTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingIteratorTest.java index ce7c34bcc1..e2c986accd 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingIteratorTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingIteratorTest.java @@ -28,7 +28,7 @@ public class ConsistentHashRingIteratorTest public List> generatePoints(int num) { final List> points = new ArrayList<>(); for (int i = 1; i <= num; ++i) { - points.add(new ConsistentHashRing.Point(i, i)); + points.add(new ConsistentHashRing.Point<>(i, i)); } return points; } @@ -37,7 +37,7 @@ public List> generatePoints(int num) { public void testIterationFromBeginning() { final List> objects = generatePoints(6); - ConsistentHashRingIterator iterator = new ConsistentHashRingIterator(objects, 0); + ConsistentHashRingIterator iterator = new ConsistentHashRingIterator<>(objects, 0); verifyIterator(iterator, objects, 0); } @@ -46,7 +46,7 @@ public void testIterationFromBeginning() public void testIterationFromMiddle() { final List> objects = generatePoints(6); - ConsistentHashRingIterator iterator = new ConsistentHashRingIterator(objects, 3); + ConsistentHashRingIterator iterator = new ConsistentHashRingIterator<>(objects, 3); verifyIterator(iterator, objects, 3); } @@ -55,7 +55,7 @@ public void testIterationFromMiddle() public void testIterationFromEnd() { final List> objects = generatePoints(6); - ConsistentHashRingIterator iterator = new ConsistentHashRingIterator(objects, 5); + ConsistentHashRingIterator iterator = new ConsistentHashRingIterator<>(objects, 5); verifyIterator(iterator, objects, 5); } @@ -64,7 +64,7 @@ public void testIterationFromEnd() public void testEmptyIterator() { final List> objects = new ArrayList<>(); - ConsistentHashRingIterator iterator = new ConsistentHashRingIterator(objects, 0); + ConsistentHashRingIterator iterator = new ConsistentHashRingIterator<>(objects, 0); verifyIterator(iterator, objects, 0); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingTest.java index 123e1bdd51..6fb8cc21ae 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/ConsistentHashRingTest.java @@ -43,13 +43,13 @@ public static void main(String[] args) @Test(groups = { "small", "back-end" }) public void testZeroItems() { - Map zero = new HashMap(); - ConsistentHashRing test = new ConsistentHashRing(zero); + Map zero = new HashMap<>(); + ConsistentHashRing test = new ConsistentHashRing<>(zero); assertNull(test.get(0)); zero.put("test", 0); - test = new ConsistentHashRing(zero); + test = new ConsistentHashRing<>(zero); assertNull(test.get(100)); } @@ -57,11 +57,11 @@ public void testZeroItems() @Test(groups = { "small", "back-end" }) public void testOneItem() { - Map one = new HashMap(); + Map one = new HashMap<>(); one.put("test", 100); - ConsistentHashRing test = new ConsistentHashRing(one); + ConsistentHashRing test = new ConsistentHashRing<>(one); // will generate ring: // [-2138377917, .., 2112547902] @@ -90,8 +90,8 @@ public void testOneItem() @Test(groups = { "small", "back-end" }) public void testManyItemsEqualWeight() { - Map many = new HashMap(); - Map counts = new HashMap(); + Map many = new HashMap<>(); + Map counts = new HashMap<>(); for (int i = 0; i < 100; ++i) { @@ -124,8 +124,8 @@ public void testManyItemsEqualWeight() @Test(groups = { "small", "back-end" }) public void testManyItemsUnequalWeight() { - Map many = new HashMap(); - Map counts = new HashMap(); + Map many = new HashMap<>(); + Map counts = new HashMap<>(); for (int i = 0; i < 100; ++i) { @@ -133,7 +133,7 @@ public void testManyItemsUnequalWeight() counts.put(i, new AtomicInteger()); } - ConsistentHashRing test = new ConsistentHashRing(many); + ConsistentHashRing test = new ConsistentHashRing<>(many); assertNotNull(test.get(0)); @@ -155,12 +155,12 @@ public void testManyItemsUnequalWeight() public void test2ItemsWithOnePoint() throws URISyntaxException { - Map pointsMap = new HashMap(); + Map pointsMap = new HashMap<>(); URI uri1 = new URI("http://ext23.corp.linkedin.com:231/ajdi"); URI uri2 = new URI("http://ext66.corp.linkedin.com:231/ajdi"); pointsMap.put(uri1, 1); pointsMap.put(uri2, 1); - ConsistentHashRing test = new ConsistentHashRing(pointsMap); + ConsistentHashRing test = new ConsistentHashRing<>(pointsMap); //we will produce 2 points with value -590810423 for uri1 and 742698789 for uri2 //test edge case URI lowEdgeUri = test.get(-600000000); diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRingTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRingTest.java index f097d6f6e2..a9b9a8c8f8 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRingTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/DistributionNonDiscreteRingTest.java @@ -62,7 +62,7 @@ public void testEvenDistribution() throws Exception { Ring ring = new DistributionNonDiscreteRingFactory().createRing(pointsMap); trial(trials, countsMap, ring); - double sd = calculateStandardDeviation(new ArrayList(countsMap.values())); + double sd = calculateStandardDeviation(new ArrayList<>(countsMap.values())); Assert.assertTrue(sd < 0.05 * trials / numHosts); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/MPConsistentHashRingIteratorTest.java b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/MPConsistentHashRingIteratorTest.java index 8fd21becb1..ca2463e814 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/MPConsistentHashRingIteratorTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/util/hashing/MPConsistentHashRingIteratorTest.java @@ -45,7 +45,7 @@ private static Map buildPointsMap(int numHosts, int numPointsPerHo @Test public void testFirstItem() { - Ring ring = new MPConsistentHashRing(buildPointsMap(100, 100), 21, 10); + Ring ring = new MPConsistentHashRing<>(buildPointsMap(100, 100), 21, 10); int key = _random.nextInt(); Iterator iter = ring.getIterator(key); Assert.assertTrue(iter.hasNext()); @@ -56,7 +56,7 @@ public void testFirstItem() public void testOtherItems() { Map pointsMap = buildPointsMap(100, 100); - Ring ring = new MPConsistentHashRing(pointsMap, 21, 10); + Ring ring = new MPConsistentHashRing<>(pointsMap, 21, 10); int key = _random.nextInt(); Iterator iter = ring.getIterator(key); int iterations = 0; @@ -80,7 +80,7 @@ public void testOtherItems() public void testAgainstOldIterator() { Map pointsMap = buildPointsMap(100, 100); - Ring ring = new MPConsistentHashRing(pointsMap, 21, 10); + Ring ring = new MPConsistentHashRing<>(pointsMap, 21, 10); int key = _random.nextInt(); Iterator oldIter = ((MPConsistentHashRing) ring).getOrderedIterator(key); @@ -97,10 +97,10 @@ public void testAgainstOldIterator() Map pointsMap = buildPointsMap(100, 100); int key = 123456; - Ring firstRing = new MPConsistentHashRing(pointsMap, 21, 10); + Ring firstRing = new MPConsistentHashRing<>(pointsMap, 21, 10); Iterator firstIter = firstRing.getIterator(key); - Ring secondRing = new MPConsistentHashRing(pointsMap, 21, 10); + Ring secondRing = new MPConsistentHashRing<>(pointsMap, 21, 10); Iterator secondIter = secondRing.getIterator(key); while (firstIter.hasNext() || secondIter.hasNext()) @@ -119,7 +119,7 @@ public void testAgainstOldIterator() { int numHosts = Math.abs(_random.nextInt()) % 100; Map pointsMap = buildPointsMap(numHosts, 100); - Ring ring = new MPConsistentHashRing(pointsMap, 21, 10); + Ring ring = new MPConsistentHashRing<>(pointsMap, 21, 10); Iterator iter = ring.getIterator(_random.nextInt()); int iteration = 0; @@ -137,7 +137,7 @@ public void testNewIterPerformance() { int repeat = 10; Map pointsMap = buildPointsMap(4, 100); - Ring ring = new MPConsistentHashRing(pointsMap, 21, 10); + Ring ring = new MPConsistentHashRing<>(pointsMap, 21, 10); long start = 0; long end = 0; diff --git a/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ConnectionLostTest.java b/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ConnectionLostTest.java index 2ac25a5920..050b8fe4ba 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ConnectionLostTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ConnectionLostTest.java @@ -48,7 +48,7 @@ public void testConnectionLost() throws Exception // org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO); final ZKFSLoadBalancer balancer = getBalancer(); - final FutureCallback cb = new FutureCallback(); + final FutureCallback cb = new FutureCallback<>(); new Thread(new FakeZKServer()).start(); balancer.start(cb); cb.get(5, TimeUnit.SECONDS); @@ -61,8 +61,8 @@ private ZKFSLoadBalancer getBalancer() 5, TimeUnit.SECONDS, BASE_PATH, System.getProperty("java.io.tmpdir"), - new HashMap(), - new HashMap>()); + new HashMap<>(), + new HashMap<>()); return new ZKFSLoadBalancer("localhost:" + PORT, 60000, 5000, f2, null, BASE_PATH); } diff --git a/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ZKFSTest.java b/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ZKFSTest.java index 319445e183..dd0a1acb03 100644 --- a/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ZKFSTest.java +++ b/d2/src/test/java/com/linkedin/d2/balancer/zkfs/ZKFSTest.java @@ -140,13 +140,12 @@ private ZKFSLoadBalancer getBalancer() { ZKFSComponentFactory f = new ZKFSComponentFactory(); Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); - Map clientFactories = - new HashMap(); + Map clientFactories = new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); @@ -171,7 +170,7 @@ public void testNormalStartup() try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); @@ -189,7 +188,7 @@ public void testServerDownStartup() throws ExecutionException, TimeoutException, InterruptedException { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(15, TimeUnit.SECONDS); @@ -203,7 +202,7 @@ public void testExpiration() try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(5, TimeUnit.SECONDS); @@ -228,7 +227,7 @@ public void testServiceDirectory() throws Exception try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -238,15 +237,15 @@ public void testServiceDirectory() throws Exception conn.start(); ZooKeeperPermanentStore store = - new ZooKeeperPermanentStore(conn, new ServicePropertiesJsonSerializer(), ZKFSUtil.servicePath(BASE_PATH)); - callback = new FutureCallback(); + new ZooKeeperPermanentStore<>(conn, new ServicePropertiesJsonSerializer(), ZKFSUtil.servicePath(BASE_PATH)); + callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); ServiceProperties props = new ServiceProperties(TEST_SERVICE_NAME, "someCluster", "/somePath", Arrays.asList("someStrategy")); store.put(TEST_SERVICE_NAME, props); - FutureCallback> serviceCallback = new FutureCallback>(); + FutureCallback> serviceCallback = new FutureCallback<>(); dir.getServiceNames(serviceCallback); Assert.assertEquals(serviceCallback.get(30, TimeUnit.SECONDS), Collections.singletonList(TEST_SERVICE_NAME)); @@ -265,7 +264,7 @@ public void testClusterDirectory() throws Exception try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -275,16 +274,16 @@ public void testClusterDirectory() throws Exception conn.start(); ZooKeeperPermanentStore store = - new ZooKeeperPermanentStore(conn, new ClusterPropertiesJsonSerializer(), - ZKFSUtil.clusterPath(BASE_PATH)); - callback = new FutureCallback(); + new ZooKeeperPermanentStore<>(conn, new ClusterPropertiesJsonSerializer(), + ZKFSUtil.clusterPath(BASE_PATH)); + callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); ClusterProperties props = new ClusterProperties(TEST_CLUSTER_NAME); store.put(TEST_CLUSTER_NAME, props); - FutureCallback> clusterCallback = new FutureCallback>(); + FutureCallback> clusterCallback = new FutureCallback<>(); dir.getClusterNames(clusterCallback); Assert.assertEquals(clusterCallback.get(30, TimeUnit.SECONDS), Collections.singletonList(TEST_CLUSTER_NAME)); @@ -308,16 +307,16 @@ public void testKeyMapper() throws Exception { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(30, TimeUnit.SECONDS); ZKConnection conn = balancer.zkConnection(); ZooKeeperPermanentStore serviceStore = - new ZooKeeperPermanentStore(conn, - new ServicePropertiesJsonSerializer(), - ZKFSUtil.servicePath(BASE_PATH)); + new ZooKeeperPermanentStore<>(conn, + new ServicePropertiesJsonSerializer(), + ZKFSUtil.servicePath(BASE_PATH)); ServiceProperties props = new ServiceProperties(TEST_SERVICE_NAME, TEST_CLUSTER_NAME, "/test", Arrays.asList("degrader"), @@ -330,32 +329,32 @@ Collections. emptyMap(), ClusterProperties clusterProperties = new ClusterProperties(TEST_CLUSTER_NAME); ZooKeeperPermanentStore clusterStore = - new ZooKeeperPermanentStore(conn, new ClusterPropertiesJsonSerializer(), ZKFSUtil.clusterPath(BASE_PATH)); + new ZooKeeperPermanentStore<>(conn, new ClusterPropertiesJsonSerializer(), ZKFSUtil.clusterPath(BASE_PATH)); clusterStore.put(TEST_CLUSTER_NAME, clusterProperties); ZooKeeperEphemeralStore uriStore = - new ZooKeeperEphemeralStore(conn, - new UriPropertiesJsonSerializer(), - new UriPropertiesMerger(), - ZKFSUtil.uriPath(BASE_PATH), - false, - true); - Map> uriData = new HashMap>(); - Map partitionData = new HashMap(1); + new ZooKeeperEphemeralStore<>(conn, + new UriPropertiesJsonSerializer(), + new UriPropertiesMerger(), + ZKFSUtil.uriPath(BASE_PATH), + false, + true); + Map> uriData = new HashMap<>(); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1.0d)); uriData.put(TEST_SERVER_URI1, partitionData); uriData.put(TEST_SERVER_URI2, partitionData); UriProperties uriProps = new UriProperties(TEST_CLUSTER_NAME, uriData); - callback = new FutureCallback(); + callback = new FutureCallback<>(); uriStore.start(callback); callback.get(30, TimeUnit.SECONDS); uriStore.put(TEST_CLUSTER_NAME, uriProps); - Set keys = new HashSet(); + Set keys = new HashSet<>(); for (int ii=0; ii<100; ++ii) { keys.add(ii); @@ -386,7 +385,7 @@ public void testClientFactoryProvider() throws Exception try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -410,7 +409,7 @@ public void testZKDown() throws Exception try { ZKFSLoadBalancer balancer = getBalancer(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); balancer.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -418,8 +417,8 @@ public void testZKDown() throws Exception conn.start(); ZooKeeperPermanentStore store = - new ZooKeeperPermanentStore(conn, new ServicePropertiesJsonSerializer(), ZKFSUtil.servicePath(BASE_PATH)); - callback = new FutureCallback(); + new ZooKeeperPermanentStore<>(conn, new ServicePropertiesJsonSerializer(), ZKFSUtil.servicePath(BASE_PATH)); + callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -434,8 +433,8 @@ public void testZKDown() throws Exception store.put(TEST_SERVICE_NAME, props); ZooKeeperPermanentStore clusterStore = - new ZooKeeperPermanentStore(conn, new ClusterPropertiesJsonSerializer(), ZKFSUtil.clusterPath(BASE_PATH)); - callback = new FutureCallback(); + new ZooKeeperPermanentStore<>(conn, new ClusterPropertiesJsonSerializer(), ZKFSUtil.clusterPath(BASE_PATH)); + callback = new FutureCallback<>(); clusterStore.start(callback); callback.get(30, TimeUnit.SECONDS); @@ -444,14 +443,14 @@ public void testZKDown() throws Exception ZKConnection serverConn = new ZKConnection("localhost:" + PORT, 30000); serverConn.start(); - ZooKeeperEphemeralStore uriStore = new ZooKeeperEphemeralStore(serverConn, new UriPropertiesJsonSerializer(), new UriPropertiesMerger(), ZKFSUtil.uriPath(BASE_PATH)); - callback = new FutureCallback(); + ZooKeeperEphemeralStore uriStore = new ZooKeeperEphemeralStore<>(serverConn, new UriPropertiesJsonSerializer(), new UriPropertiesMerger(), ZKFSUtil.uriPath(BASE_PATH)); + callback = new FutureCallback<>(); uriStore.start(callback); callback.get(30, TimeUnit.SECONDS); ZooKeeperServer server = new ZooKeeperServer(uriStore); - callback = new FutureCallback(); - Map partitionDataMap = new HashMap(); + callback = new FutureCallback<>(); + Map partitionDataMap = new HashMap<>(); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1.0)); server.markUp(TEST_CLUSTER_NAME, URI.create("http://test.uri"), partitionDataMap, callback); callback.get(30, TimeUnit.SECONDS); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusImplTest.java b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusImplTest.java index a9b02968d1..81616f79d0 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusImplTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusImplTest.java @@ -39,8 +39,8 @@ public PropertyEventBus getBus() // TODO rewrite tests in the parent class so they work with either sync or async, and // test both modes of operation. ScheduledExecutorService executorService = new SynchronousExecutorService(); - PropertyEventPublisher publisher = new MockStore(); - PropertyEventBus bus = new PropertyEventBusImpl(executorService, publisher); + PropertyEventPublisher publisher = new MockStore<>(); + PropertyEventBus bus = new PropertyEventBusImpl<>(executorService, publisher); return bus; } diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusTest.java b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusTest.java index 86b1661b44..6006005865 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventBusTest.java @@ -45,7 +45,7 @@ public void testRegister() throws InterruptedException { PropertyEventBus bus = getBus(); PropertyEventTestSubscriber listener = new PropertyEventTestSubscriber(); - Set listenTos = new HashSet(); + Set listenTos = new HashSet<>(); listenTos.add("test"); listenTos.add("test2"); @@ -88,7 +88,7 @@ public void testUnregister() throws InterruptedException { PropertyEventBus bus = getBus(); PropertyEventTestSubscriber listener = new PropertyEventTestSubscriber(); - Set listenTos = new HashSet(); + Set listenTos = new HashSet<>(); listenTos.add("test"); listenTos.add("test2"); @@ -124,7 +124,7 @@ public void testDoubleUnregister() throws InterruptedException PropertyEventBus bus = getBus(); PropertyEventTestSubscriber listener1 = new PropertyEventTestSubscriber(); PropertyEventTestSubscriber listener2 = new PropertyEventTestSubscriber(); - Set listenTos = new HashSet(); + Set listenTos = new HashSet<>(); listenTos.add("dtest"); listenTos.add("dtest2"); @@ -207,10 +207,10 @@ public void testMaintainRegistration() // Now, switch to a new publisher that does have a value for this property; the // subscription should be maintained, and clients should receive an update. - MockStore newStore = new MockStore(); + MockStore newStore = new MockStore<>(); newStore.put(TEST_PROP, TEST_VALUE); - bus.setPublisher(new StoreEventPublisher(newStore)); + bus.setPublisher(new StoreEventPublisher<>(newStore)); // Now, should have received an update with the new value. assertEquals(subscriber.properties.get("add-" + TEST_PROP), TEST_VALUE); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventTestSubscriber.java b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventTestSubscriber.java index 69724088f2..5b72bd21e7 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventTestSubscriber.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/PropertyEventTestSubscriber.java @@ -35,7 +35,7 @@ public class PropertyEventTestSubscriber implements PropertyEventSubscriber(); + properties = new HashMap<>(); } @Override diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/PublisherTest.java b/d2/src/test/java/com/linkedin/d2/discovery/event/PublisherTest.java index 5ff1ab821d..822fe7172c 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/PublisherTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/PublisherTest.java @@ -109,7 +109,7 @@ protected static class MockBusSink implements PropertyEventBus private final Condition _addCondition = _lock.newCondition(); private final Condition _removeCondition = _lock.newCondition(); - private Map _currentValues = new HashMap(); + private Map _currentValues = new HashMap<>(); public void awaitInit(String key, String value, long timeout, TimeUnit timeoutUnit) throws InterruptedException, TimeoutException diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/SynchronousExecutorService.java b/d2/src/test/java/com/linkedin/d2/discovery/event/SynchronousExecutorService.java index 31a7f33bb7..5cd47156c4 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/SynchronousExecutorService.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/SynchronousExecutorService.java @@ -156,7 +156,7 @@ public List shutdownNow() { _isShutDown = true; } - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperEphemeralStorePublisherTest.java b/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperEphemeralStorePublisherTest.java index 0f733655d1..aa9819d84b 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperEphemeralStorePublisherTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperEphemeralStorePublisherTest.java @@ -47,13 +47,13 @@ public class ZooKeeperEphemeralStorePublisherTest extends ZooKeeperStorePublishe @Override protected ZooKeeperStore getStore() { - ZooKeeperEphemeralStore store = new ZooKeeperEphemeralStore( + ZooKeeperEphemeralStore store = new ZooKeeperEphemeralStore<>( getConnection(), new PropertyStringSerializer(), _merger, "/testing/testPath", false, true); try { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); } diff --git a/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperPermanentStorePublisherTest.java b/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperPermanentStorePublisherTest.java index 240dfd98bc..0aec714c20 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperPermanentStorePublisherTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/event/ZooKeeperPermanentStorePublisherTest.java @@ -39,11 +39,11 @@ public class ZooKeeperPermanentStorePublisherTest extends ZooKeeperStorePublishe @Override protected ZooKeeperStore getStore() { - ZooKeeperPermanentStore store = new ZooKeeperPermanentStore( + ZooKeeperPermanentStore store = new ZooKeeperPermanentStore<>( getConnection(), new PropertyStringSerializer(), "/testing/testPath"); try { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(30, TimeUnit.SECONDS); } diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStore.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStore.java index 0c65c4197f..0e08cfa82c 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStore.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStore.java @@ -45,8 +45,8 @@ public class MockStore implements PropertyEventPublisher, PropertyStore public MockStore() { - _properties = new HashMap(); - _publishing = new HashSet(); + _properties = new HashMap<>(); + _publishing = new HashSet<>(); _shutdown = false; } diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStoreTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStoreTest.java index 27f01d2647..6b3731a003 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStoreTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/mock/MockStoreTest.java @@ -26,7 +26,7 @@ public class MockStoreTest extends PropertyStoreTest @Override public PropertyStore getStore() { - return new MockStore(); + return new MockStore<>(); } @Test(groups = { "small", "back-end" }) diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/toggling/TogglingStoreTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/toggling/TogglingStoreTest.java index 9ee58a6d66..ef3819482e 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/toggling/TogglingStoreTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/toggling/TogglingStoreTest.java @@ -33,7 +33,7 @@ public class TogglingStoreTest extends PropertyStoreTest @Override public TogglingStore getStore() { - return new TogglingStore(new MockStore()); + return new TogglingStore<>(new MockStore<>()); } @Test(groups = { "small", "back-end" }) diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeperTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeperTest.java index 2d681dba60..321d82b1a3 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeperTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/RetryZooKeeperTest.java @@ -44,8 +44,8 @@ public class RetryZooKeeperTest { private static final String _dummyPath = "/dummy/path"; private static final String _dummyParentPath = "/dummy"; private static final int _dummyVersion = 1; - private static final List _dummyList = new ArrayList(); - private static final List _dummyACL = new ArrayList(); + private static final List _dummyList = new ArrayList<>(); + private static final List _dummyACL = new ArrayList<>(); private static final Object _dummyCtx = new Object(); private static final Stat _dummyStat = new Stat(); @@ -408,7 +408,7 @@ public void testCreateSequential() throws NoSuchMethodException // connection loss in create expectCreateCallbackWithCode(_connectionLossRC); - List children = new ArrayList(); + List children = new ArrayList<>(); children.add("ephemeral-3.14159"); children.add("ephemeral-6.26"); rzkPartialMock.zkGetChildren( @@ -430,7 +430,7 @@ public void testCreateSequential() throws NoSuchMethodException // connection loss in create, again expectCreateCallbackWithCode(_connectionLossRC); - List childrenWithOurChild = new ArrayList(); + List childrenWithOurChild = new ArrayList<>(); childrenWithOurChild.add("ephemeral-3.14159"); childrenWithOurChild.add("ephemeral-6.26"); childrenWithOurChild.add("ephemeral" + rzkPartialMock.getUuid() + "1"); @@ -465,7 +465,7 @@ public void testCreateSequential() throws NoSuchMethodException // connection loss in create, again expectCreateCallbackWithCode(_connectionLossRC); - List childrenWithThatKid = new ArrayList(); + List childrenWithThatKid = new ArrayList<>(); childrenWithThatKid.add("ephemeral-3.14159"); childrenWithThatKid.add("ephemeral-6.26"); childrenWithThatKid.add("ephemeral" + rzkPartialMock.getUuid() + "1"); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SharedZkConnectionProviderTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SharedZkConnectionProviderTest.java index d52efa59a6..6a33d895bf 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SharedZkConnectionProviderTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SharedZkConnectionProviderTest.java @@ -106,13 +106,13 @@ public void setUp() throws Exception { ZKConnection clusterZkConn = new ZKConnectionBuilder("localhost:" + ZK_PORT).setTimeout(5000).setWaitForConnected(true).build(); _serviceRegistry = - new ZooKeeperPermanentStore(serviceZkConn, new ServicePropertiesJsonSerializer(), + new ZooKeeperPermanentStore<>(serviceZkConn, new ServicePropertiesJsonSerializer(), ZKFSUtil.servicePath(ZKBASE_PATH)); _clusterRegistry = - new ZooKeeperPermanentStore(clusterZkConn, new ClusterPropertiesJsonSerializer(), + new ZooKeeperPermanentStore<>(clusterZkConn, new ClusterPropertiesJsonSerializer(), ZKFSUtil.clusterPath(ZKBASE_PATH)); - FutureCallback storesStartupCallBack = new FutureCallback(); + FutureCallback storesStartupCallBack = new FutureCallback<>(); Callback multiStartupCallback = Callbacks.countDown(storesStartupCallBack, 2); serviceZkConn.start(); clusterZkConn.start(); @@ -120,7 +120,7 @@ public void setUp() throws Exception { _clusterRegistry.start(multiStartupCallback); storesStartupCallBack.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); - FutureCallback propertiesSetupCallback = new FutureCallback(); + FutureCallback propertiesSetupCallback = new FutureCallback<>(); Callback multiPropertiesCallback = Callbacks.countDown(propertiesSetupCallback, 2); ServiceProperties serviceProps = @@ -157,9 +157,9 @@ private ZooKeeperEphemeralStore createAndStartVerificationStore() zkClient.start(); ZooKeeperEphemeralStore store = - new ZooKeeperEphemeralStore(zkClient, new UriPropertiesJsonSerializer(), + new ZooKeeperEphemeralStore<>(zkClient, new UriPropertiesJsonSerializer(), new UriPropertiesMerger(), ZKFSUtil.uriPath(ZKBASE_PATH)); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); return store; @@ -187,7 +187,7 @@ private List prepareConnectionManagers(List hos ZooKeeperAnnouncer announcer = new ZooKeeperAnnouncer(server, true); announcer.setCluster(CLUSTER_NAME); announcer.setUri(uri.toString()); - Map partitionWeight = new HashMap(); + Map partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(0.5d)); announcer.setPartitionData(partitionWeight); @@ -203,7 +203,7 @@ private List prepareConnectionManagers(List hos } private void shutdownConnectionManagers(List managers) throws Exception { - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); Callback shutdownMulitCallback = Callbacks.countDown(shutdownCallback, managers.size()); for (ZooKeeperConnectionManager manager : managers) { _threadPoolExecutor.submit(() -> manager.shutdown(shutdownMulitCallback)); @@ -373,7 +373,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //start both announcers and client - FutureCallback startUpCallback = new FutureCallback(); + FutureCallback startUpCallback = new FutureCallback<>(); Callback startUpMultiCallback = Callbacks.countDown(startUpCallback, connectionManagers.size() + 1); _threadPoolExecutor.submit(() -> client.start(startUpMultiCallback)); @@ -389,7 +389,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //fire some requests to make sure announcement is successful and hosts properties can be retrieved successfully. int requestRepeat = 1000; - FutureCallback reqCallback = new FutureCallback(); + FutureCallback reqCallback = new FutureCallback<>(); fireTestRequests(client, requestRepeat, reqCallback); reqCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); @@ -400,7 +400,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //Markdown half of the hosts and test the results - FutureCallback hostsMarkdownCallback = new FutureCallback(); + FutureCallback hostsMarkdownCallback = new FutureCallback<>(); Callback hostsMarkdownMultiCallback = Callbacks.countDown(hostsMarkdownCallback,10); for (ZooKeeperConnectionManager manager : connectionManagers.subList(0,10)) { _threadPoolExecutor.submit(() -> manager.getAnnouncers()[0].markDown(hostsMarkdownMultiCallback)); @@ -413,7 +413,7 @@ public void testAnnouncerAndClientSharing() throws Exception { assertEquals(properties.Uris().size(), 10); //fire some requests to make sure announcement is successful and hosts properties can be retrieved successfully. - FutureCallback secondReqCallback = new FutureCallback(); + FutureCallback secondReqCallback = new FutureCallback<>(); fireTestRequests(client, requestRepeat, secondReqCallback); secondReqCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); @@ -423,7 +423,7 @@ public void testAnnouncerAndClientSharing() throws Exception { Assert.assertEquals(testClientFactory.requestCount.get(), 2000); //Mix announcements with request firing to test connection robustness. - FutureCallback thirdReqCallback = new FutureCallback(); + FutureCallback thirdReqCallback = new FutureCallback<>(); Callback thirdReqMultiCallback = Callbacks.countDown(thirdReqCallback, requestRepeat + 10); for (int i = 0; i < requestRepeat; i++) { _threadPoolExecutor.submit(() -> { @@ -452,7 +452,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //announcers can be shutdown after announcing, without affecting client. This should not happen though. - FutureCallback announcerShutdownCallback = new FutureCallback(); + FutureCallback announcerShutdownCallback = new FutureCallback<>(); Callback announcersShutdownCallback = Callbacks.countDown(announcerShutdownCallback, connectionManagers.size()); for (ZooKeeperConnectionManager manager : connectionManagers) { manager.shutdown(announcersShutdownCallback); @@ -461,7 +461,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //fire some requests to make sure d2client is still usable. - FutureCallback fourthReqCallback = new FutureCallback(); + FutureCallback fourthReqCallback = new FutureCallback<>(); fireTestRequests(client, requestRepeat, fourthReqCallback); thirdReqCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); @@ -471,7 +471,7 @@ public void testAnnouncerAndClientSharing() throws Exception { //test done! - FutureCallback clientShutdownCallback = new FutureCallback(); + FutureCallback clientShutdownCallback = new FutureCallback<>(); client.shutdown(clientShutdownCallback); clientShutdownCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); @@ -489,13 +489,13 @@ public void testZKPropertyUpdate() throws Exception { List hosts = prepareHostNames(5, "testZKPropertyUpdate"); List connectionManagers = prepareConnectionManagers(hosts); - Map transportClientMap = new HashMap(); + Map transportClientMap = new HashMap<>(); transportClientMap.put("http", new TestTransportClientFactory()); // connection shared to d2client D2Client client = getD2Client(transportClientMap); - FutureCallback startupCallback = new FutureCallback(); + FutureCallback startupCallback = new FutureCallback<>(); client.start(startupCallback); startupCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); @@ -509,12 +509,12 @@ public void testZKPropertyUpdate() throws Exception { Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Arrays.asList("http"), Collections.emptySet()); - FutureCallback propertyCallback = new FutureCallback(); + FutureCallback propertyCallback = new FutureCallback<>(); _serviceRegistry.put("newTestService", serviceProps, propertyCallback); propertyCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); - FutureCallback finishCallback = new FutureCallback(); + FutureCallback finishCallback = new FutureCallback<>(); d2Directory.getServiceNames(new Callback>() { @Override public void onError(Throwable e) { @@ -534,7 +534,7 @@ public void onSuccess(List result) { Assert.assertTrue(serviceList.contains("testService")); shutdownConnectionManagers(connectionManagers); - FutureCallback clientShutdownCallback = new FutureCallback(); + FutureCallback clientShutdownCallback = new FutureCallback<>(); client.shutdown(clientShutdownCallback); clientShutdownCallback.get(BLOCKING_CALL_TIMEOUT, TimeUnit.MILLISECONDS); } @@ -610,5 +610,3 @@ public void shutdown(Callback callback) { } } } - - diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SymlinkAwareZooKeeperTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SymlinkAwareZooKeeperTest.java index 3c54c59f9e..cabe53c1de 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SymlinkAwareZooKeeperTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/SymlinkAwareZooKeeperTest.java @@ -83,27 +83,27 @@ private void initTestData() throws ExecutionException, InterruptedException, Uns FutureCallback callback; for (int i = 1; i <= 10; i++) { - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/foo/bar/" + i, callback); callback.get(); - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.setDataUnsafe("/foo/bar/" + i, String.valueOf(i).getBytes("UTF-8"), callback); callback.get(); } for (int i=11; i <= 15; i++) { - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/bar/foo/" + i, callback); callback.get(); - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.setDataUnsafe("/bar/foo/" + i, String.valueOf(i).getBytes("UTF-8"), callback); callback.get(); } - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.createSymlink("/foo/$link", "/foo/bar", callback); callback.get(); - callback = new FutureCallback(); + callback = new FutureCallback<>(); _zkClient.createSymlink("/$bar", "/foo", callback); callback.get(); } @@ -348,9 +348,9 @@ public void processResult(int rc, String path, Object ctx, Stat stat) // symlink: /foo/$link/newNode -> /foo/bar/newNode _zkClient.getZooKeeper().exists("/foo/$link/newNode", existWatch, existCallback2, null); latch2.await(30, TimeUnit.SECONDS); - _zkClient.ensurePersistentNodeExists("/foo/bar/newNode", new FutureCallback()); + _zkClient.ensurePersistentNodeExists("/foo/bar/newNode", new FutureCallback<>()); latch.await(30, TimeUnit.SECONDS); - _zkClient.removeNodeUnsafe("/foo/bar/newNode", new FutureCallback()); + _zkClient.removeNodeUnsafe("/foo/bar/newNode", new FutureCallback<>()); } @Test @@ -391,10 +391,10 @@ public void processResult(int rc, String path, Object ctx, Stat stat) _zkClient.getZooKeeper().exists("/foo/$link/foo", existWatch, existCallback2, null); latch2.await(30, TimeUnit.SECONDS); // update symlink. now it points to /bar/foo, which does exist. - _zkClient.setSymlinkData("/foo/$link", "/bar", new FutureCallback()); + _zkClient.setSymlinkData("/foo/$link", "/bar", new FutureCallback<>()); latch.await(30, TimeUnit.SECONDS); // restore symlink - _zkClient.setSymlinkData("/foo/$link", "/foo/bar", new FutureCallback()); + _zkClient.setSymlinkData("/foo/$link", "/foo/bar", new FutureCallback<>()); } @Test @@ -435,10 +435,10 @@ public void processResult(int rc, String path, Object ctx, Stat stat) _zkClient.getZooKeeper().exists("/$link", existWatch, existCallback2, null); latch2.await(30, TimeUnit.SECONDS); // create symlink /$link -> /foo/bar. existWatch should be notified. - _zkClient.createSymlink("/$link", "/foo/bar", new FutureCallback()); + _zkClient.createSymlink("/$link", "/foo/bar", new FutureCallback<>()); latch.await(30, TimeUnit.SECONDS); // delete symlink /$link - _zkClient.removeNodeUnsafe("/$link", new FutureCallback()); + _zkClient.removeNodeUnsafe("/$link", new FutureCallback<>()); } @Test @@ -479,9 +479,9 @@ public void processResult(int rc, String path, Object ctx, List children // symlink: /foo/$link -> /foo/bar _zkClient.getZooKeeper().getChildren("/foo/$link", childrenWatch, childrenCallback2, null); latch2.await(30, TimeUnit.SECONDS); - _zkClient.ensurePersistentNodeExists("/foo/bar/newNode", new FutureCallback()); + _zkClient.ensurePersistentNodeExists("/foo/bar/newNode", new FutureCallback<>()); latch.await(30, TimeUnit.SECONDS); - _zkClient.removeNodeUnsafe("/foo/bar/newNode", new FutureCallback()); + _zkClient.removeNodeUnsafe("/foo/bar/newNode", new FutureCallback<>()); } @Test @@ -520,9 +520,9 @@ public void processResult(int rc, String path, Object ctx, List children _zkClient.getZooKeeper().getChildren("/foo/$link", watcher, callback, null); latch1.await(30, TimeUnit.SECONDS); // update symlink - _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback()); + _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback<>()); latch2.await(30, TimeUnit.SECONDS); - FutureCallback fcb = new FutureCallback(); + FutureCallback fcb = new FutureCallback<>(); // restore symlink _zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb); fcb.get(); @@ -571,9 +571,9 @@ public void processResult(int rc, String path, Object ctx, List children _zkClient.getZooKeeper().getChildren("/foo/$link", watcher, callback, null); latch1.await(30, TimeUnit.SECONDS); // update symlink - _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback()); + _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback<>()); latch2.await(30, TimeUnit.SECONDS); - FutureCallback fcb = new FutureCallback(); + FutureCallback fcb = new FutureCallback<>(); // restore symlink _zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb); fcb.get(); @@ -604,7 +604,7 @@ public void process(WatchedEvent event) latch2.countDown(); } }; - FutureCallback fcb = new FutureCallback(); + FutureCallback fcb = new FutureCallback<>(); _zkClient.setSymlinkData("/foo/$link", "INVALID", fcb); fcb.get(); _zkClient.getZooKeeper().exists("/foo/$link", watcher, callback, null); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/TestZKPersistentConnection.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/TestZKPersistentConnection.java index aa6d6d8a13..3ec462e8d3 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/TestZKPersistentConnection.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/TestZKPersistentConnection.java @@ -228,7 +228,7 @@ public void notifyEvent(ZKPersistentConnection.Event event) { c.incrementShareCount(); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); Callback multiCallback = Callbacks.countDown(callback, numUsers); for (int i = 0; i < numUsers; i++) { final int userIndex = i; diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisherTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisherTest.java index 2f3157cb2b..df81ff7f6a 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisherTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperChildrenDataPublisherTest.java @@ -72,7 +72,7 @@ public void tearDown() throws IOException, InterruptedException { private void generateTestData() { - _testData = new HashMap(); + _testData = new HashMap<>(); _testData.put("bucket/child-1", "1"); _testData.put("bucket/child-2", "2"); _testData.put("bucket/child-3", "3"); @@ -85,10 +85,10 @@ public void setupMethod() generateTestData(); for (Map.Entry entry : _testData.entrySet()) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/" + entry.getKey(), callback); callback.get(30, TimeUnit.SECONDS); - FutureCallback callback2 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback<>(); _zkClient.setDataUnsafe("/" + entry.getKey(), entry.getValue().getBytes(), callback2); callback2.get(30, TimeUnit.SECONDS); } @@ -96,7 +96,7 @@ public void setupMethod() @AfterMethod public void tearDownMethod() throws ExecutionException, InterruptedException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.removeNodeUnsafeRecursive("/bucket", callback); callback.get(); } @@ -109,7 +109,7 @@ public void testPublishInitialize() client.start(); final ZooKeeperChildrenDataPublisher, String> publisher = - new ZooKeeperChildrenDataPublisher, String>(client, new PropertyStringSerializer(), "/"); + new ZooKeeperChildrenDataPublisher<>(client, new PropertyStringSerializer(), "/"); final CountDownLatch initLatch = new CountDownLatch(1); final CountDownLatch startLatch = new CountDownLatch(1); @@ -137,7 +137,7 @@ public void onError(Throwable e) { @Override public void onSuccess(None result) { - _eventBus = new PropertyEventBusImpl>(_executor, publisher); + _eventBus = new PropertyEventBusImpl<>(_executor, publisher); _eventBus.register(Collections.singleton("bucket"), subscriber); startLatch.countDown(); } @@ -162,7 +162,7 @@ public void testChildDataChanged() throws IOException, InterruptedException, Exe client.start(); final ZooKeeperChildrenDataPublisher, String> publisher = - new ZooKeeperChildrenDataPublisher, String>(client, new PropertyStringSerializer(), "/"); + new ZooKeeperChildrenDataPublisher<>(client, new PropertyStringSerializer(), "/"); final CountDownLatch initLatch = new CountDownLatch(1); final CountDownLatch addLatch = new CountDownLatch(1); @@ -190,7 +190,7 @@ public void onError(Throwable e) { @Override public void onSuccess(None result) { - _eventBus = new PropertyEventBusImpl>(_executor, publisher); + _eventBus = new PropertyEventBusImpl<>(_executor, publisher); _eventBus.register(Collections.singleton("bucket"), subscriber); startLatch.countDown(); } @@ -205,7 +205,7 @@ public void onSuccess(None result) { Assert.fail("unable to publish initial property value"); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.setDataUnsafe("/bucket/child-1", "4".getBytes(), callback); callback.get(); @@ -224,7 +224,7 @@ public void testChildDeletion() throws IOException, InterruptedException, Execut client.start(); final ZooKeeperChildrenDataPublisher, String> publisher = - new ZooKeeperChildrenDataPublisher, String>(client, new PropertyStringSerializer(), "/"); + new ZooKeeperChildrenDataPublisher<>(client, new PropertyStringSerializer(), "/"); final CountDownLatch initLatch = new CountDownLatch(1); final CountDownLatch addLatch = new CountDownLatch(1); @@ -252,7 +252,7 @@ public void onError(Throwable e) { @Override public void onSuccess(None result) { - _eventBus = new PropertyEventBusImpl>(_executor, publisher); + _eventBus = new PropertyEventBusImpl<>(_executor, publisher); _eventBus.register(Collections.singleton("bucket"), subscriber); startLatch.countDown(); } @@ -267,7 +267,7 @@ public void onSuccess(None result) { Assert.fail("unable to publish initial property value"); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.removeNodeUnsafe("/bucket/child-1", callback); callback.get(); @@ -286,7 +286,7 @@ public void testChildCreation() throws IOException, InterruptedException, Execut client.start(); final ZooKeeperChildrenDataPublisher, String> publisher = - new ZooKeeperChildrenDataPublisher, String>(client, new PropertyStringSerializer(), "/"); + new ZooKeeperChildrenDataPublisher<>(client, new PropertyStringSerializer(), "/"); final CountDownLatch initLatch = new CountDownLatch(1); final CountDownLatch addLatch = new CountDownLatch(1); @@ -314,7 +314,7 @@ public void onError(Throwable e) { @Override public void onSuccess(None result) { - _eventBus = new PropertyEventBusImpl>(_executor, publisher); + _eventBus = new PropertyEventBusImpl<>(_executor, publisher); _eventBus.register(Collections.singleton("bucket"), subscriber); startLatch.countDown(); } @@ -329,7 +329,7 @@ public void onSuccess(None result) { Assert.fail("unable to publish initial property value"); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/bucket/child-4", callback); callback.get(); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherTest.java index e42eb0f176..839323d316 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherTest.java @@ -99,7 +99,7 @@ public void setupMethod() throws ExecutionException, InterruptedException, TimeoutException, KeeperException { generateTestData(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/bucket", callback); callback.get(5, TimeUnit.SECONDS); @@ -118,7 +118,7 @@ private void addNode(String key, String value) throws InterruptedException, Exec @AfterMethod public void tearDownMethod() throws ExecutionException, InterruptedException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.removeNodeUnsafeRecursive("/bucket", callback); callback.get(); } @@ -182,7 +182,7 @@ public void onSuccess(None result) Assert.fail("unable to publish initial property value"); } - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.setDataUnsafe("/bucket/child-1", "4".getBytes(), callback); callback.get(); diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherWithFIleStoreTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherWithFIleStoreTest.java index 7ece02b5a8..ab1e52cdee 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherWithFIleStoreTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreChildrenWatcherWithFIleStoreTest.java @@ -131,7 +131,7 @@ public void testRecreatingNodeListening() throws Exception removeNode("/bucket"); _testData.clear(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/bucket", callback); callback.get(5, TimeUnit.SECONDS); @@ -185,7 +185,7 @@ public void setupMethod() { generateTestData(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.ensurePersistentNodeExists("/bucket", callback); callback.get(5, TimeUnit.SECONDS); @@ -214,7 +214,7 @@ private void removeNode(String path) throws ExecutionException, InterruptedExcep @AfterMethod public void tearDownMethod() throws ExecutionException, InterruptedException { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _zkClient.removeNodeUnsafeRecursive("/bucket", callback); callback.get(); } diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreStrawMan.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreStrawMan.java index a4a8a59852..ca1ef248c4 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreStrawMan.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreStrawMan.java @@ -37,19 +37,19 @@ public static void main(String[] args) throws IOException, InterruptedException, { ZKConnection zkClient = new ZKConnection("localhost:2181", 30000); PropertyStringMerger merger = new PropertyStringMerger(); - Set listenTos = new HashSet(); + Set listenTos = new HashSet<>(); ZooKeeperEphemeralStore zk = - new ZooKeeperEphemeralStore(zkClient, - new PropertyStringSerializer(), - merger, - "/test/lb/test-property-ephemeral", - false, - true); + new ZooKeeperEphemeralStore<>(zkClient, + new PropertyStringSerializer(), + merger, + "/test/lb/test-property-ephemeral", + false, + true); listenTos.add("foo12"); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - PropertyEventBus bus = new PropertyEventBusImpl(executorService, zk); + PropertyEventBus bus = new PropertyEventBusImpl<>(executorService, zk); bus.register(listenTos, new PropertyEventSubscriber() { diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreTest.java index 8a5e6506f1..3c9b170fea 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperEphemeralStoreTest.java @@ -81,14 +81,14 @@ public ZooKeeperEphemeralStore getStore() client.start(); - ZooKeeperEphemeralStore store = new ZooKeeperEphemeralStore( + ZooKeeperEphemeralStore store = new ZooKeeperEphemeralStore<>( client, new PropertyStringSerializer(), new PropertyStringMerger(), "/test-path", false, true); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(); return store; diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreStrawMan.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreStrawMan.java index 408435d8f8..95fd3d0572 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreStrawMan.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreStrawMan.java @@ -36,15 +36,15 @@ public static void main(String[] args) throws IOException, InterruptedException, PropertyStoreException { ZKConnection zkClient = new ZKConnection("localhost:2181", 1000); - Set listenTos = new HashSet(); + Set listenTos = new HashSet<>(); ZooKeeperPermanentStore zk = - new ZooKeeperPermanentStore(zkClient, - new PropertyStringSerializer(), - "/test/lb/test-property"); + new ZooKeeperPermanentStore<>(zkClient, + new PropertyStringSerializer(), + "/test/lb/test-property"); listenTos.add("foo12"); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - PropertyEventBus bus = new PropertyEventBusImpl(executorService, zk); + PropertyEventBus bus = new PropertyEventBusImpl<>(executorService, zk); bus.register(listenTos, new PropertyEventSubscriber() { diff --git a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreTest.java b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreTest.java index 09dff730af..29fbfe885c 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreTest.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZooKeeperPermanentStoreTest.java @@ -56,11 +56,11 @@ public PropertyStore getStore() throws PropertyStoreException ZKConnection client = new ZKConnection("localhost:" + PORT, 30000); client.start(); - ZooKeeperPermanentStore store = new ZooKeeperPermanentStore( + ZooKeeperPermanentStore store = new ZooKeeperPermanentStore<>( client, new PropertyStringSerializer(), "/test-path"); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); store.start(callback); callback.get(); return store; diff --git a/d2/src/test/java/com/linkedin/d2/discovery/util/D2ConfigTestUtil.java b/d2/src/test/java/com/linkedin/d2/discovery/util/D2ConfigTestUtil.java index 72a8b32c11..84656f99d6 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/util/D2ConfigTestUtil.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/util/D2ConfigTestUtil.java @@ -45,15 +45,15 @@ public class D2ConfigTestUtil private static double _defaultSuccessfulTransmissionWeight = 1.0; private static int _pointsPerWeight = 100; private static String _prioritizedSchemes = "http"; - private static List _loadBalancerStrategyList = Arrays.asList(new String[]{"degrader","degraderV3"}); - private Map _clusterProperties = new HashMap(); - private Map _clusterDefaults = new HashMap(); - private Map _serviceDefaults = new HashMap(); - private Map _loadBalancerStrategyProperties = new HashMap(); + private static List _loadBalancerStrategyList = Arrays.asList("degrader", "degraderV3"); + private Map _clusterProperties = new HashMap<>(); + private Map _clusterDefaults = new HashMap<>(); + private Map _serviceDefaults = new HashMap<>(); + private Map _loadBalancerStrategyProperties = new HashMap<>(); - private Map _clusterServiceConfigurations = new HashMap(); - private Map _extraClusterServiceConfigurations = new HashMap(); - private Map _serviceVariants = new HashMap(); + private Map _clusterServiceConfigurations = new HashMap<>(); + private Map _extraClusterServiceConfigurations = new HashMap<>(); + private Map _serviceVariants = new HashMap<>(); private boolean _useDeltaWrite = false; private int _maxOutstandingWrites = 1; @@ -78,7 +78,7 @@ public D2ConfigTestUtil(Map> clustersData, String defaultCol Map> extraClusterProperties, Set servicesWithDefaultRoutingToMaster) { - this(clustersData, defaultColo, extraClusterProperties, new HashMap>(), + this(clustersData, defaultColo, extraClusterProperties, new HashMap<>(), servicesWithDefaultRoutingToMaster); } @@ -341,7 +341,7 @@ public void generateClusters(String clusterNamePrefix, String serviceNamePrefix, for (int i=1; i <= totalClusters+1; i++) { _log.info("Creating cluster data: cluster"+i); - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",generateServicesMap(servicesPerCluster, serviceNamePrefix+i, null)); _clusterServiceConfigurations.put(clusterNamePrefix+i, services); @@ -350,7 +350,7 @@ public void generateClusters(String clusterNamePrefix, String serviceNamePrefix, public void generateClusters(Map> clustersData) { - generateClusters(clustersData, null, new HashMap>()); + generateClusters(clustersData, null, new HashMap<>()); } public void generateClusters(Map> clustersData, Map> clustersProperties, @@ -368,12 +368,12 @@ public void generateClusters(Map> clustersData, Map services = new HashMap(); - Map tmps = new HashMap(); + Map services = new HashMap<>(); + Map tmps = new HashMap<>(); for (String serviceName : clustersData.get(clusterName)) { - Map service = new HashMap(); + Map service = new HashMap<>(); service.put("path","/"+serviceName); if (excludeServiceList != null && excludeServiceList.contains(serviceName)) { @@ -402,7 +402,7 @@ public void generateClusters(Map> clustersData, Map serviceGroup = new HashMap(); + Map serviceGroup = new HashMap<>(); serviceGroup.put("type", "clusterVariantsList"); serviceGroup.put("clusterList", serviceGroupsData.get(serviceGroupName)); _serviceVariants.put(serviceGroupName, serviceGroup); @@ -417,12 +417,12 @@ public void generateClusters(Map> clustersData, for (String clusterName : clustersData.keySet()) { _log.info("Creating cluster data:"+clusterName); - final Map services = new HashMap(); - final Map tmps = new HashMap(); + final Map services = new HashMap<>(); + final Map tmps = new HashMap<>(); for (String serviceName : clustersData.get(clusterName)) { - final Map service = new HashMap(); + final Map service = new HashMap<>(); service.put("path","/"+serviceName); tmps.put(serviceName, service); } @@ -440,12 +440,12 @@ public void generateClusters(String mainClusterName, { //Cluster Service Configurations // Services - Map services = new HashMap(); - Map sp = new HashMap(); + Map services = new HashMap<>(); + Map sp = new HashMap<>(); for (String serviceName : servicesData.keySet()) { - Map service = new HashMap(); + Map service = new HashMap<>(); service.put("path","/"+servicesData.get(serviceName)); if (servicesWithDefaultRoutingToMaster.contains(serviceName)) { @@ -456,11 +456,11 @@ public void generateClusters(String mainClusterName, services.put("services",sp); // Cluster Variants - Map clusterVariants = new HashMap(); + Map clusterVariants = new HashMap<>(); for (String clusterName : serviceGroupsData.values()) { - clusterVariants.put(clusterName, new HashMap()); + clusterVariants.put(clusterName, new HashMap<>()); } services.put("clusterVariants",clusterVariants); @@ -470,21 +470,21 @@ public void generateClusters(String mainClusterName, // Service variants for (String serviceGroupName : serviceGroupsData.keySet()) { - Map serviceGroup = new HashMap(); + Map serviceGroup = new HashMap<>(); serviceGroup.put("type", "clusterVariantsList"); - serviceGroup.put("clusterList", Arrays.asList(new String[]{serviceGroupsData.get(serviceGroupName)})); + serviceGroup.put("clusterList", Arrays.asList(serviceGroupsData.get(serviceGroupName))); _serviceVariants.put(serviceGroupName, serviceGroup); } } public static Map generateServicesMap(int totalServices, String serviceNamePrefix, String servicePath) { - Map services = new HashMap(); + Map services = new HashMap<>(); for (int j=1; j <= totalServices+1; j++) { String serviceName = serviceNamePrefix+"_"+j; - Map service = new HashMap(); + Map service = new HashMap<>(); if (servicePath == null) { servicePath = serviceName; diff --git a/d2/src/test/java/com/linkedin/d2/discovery/util/TestD2Config.java b/d2/src/test/java/com/linkedin/d2/discovery/util/TestD2Config.java index 97e2aec218..1f9ba61679 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/util/TestD2Config.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/util/TestD2Config.java @@ -83,7 +83,7 @@ public class TestD2Config private static final int ZK_PORT = 11712; private static final String ECHO_SERVER_HOST = "127.0.0.1"; - private static List _echoServerList = new ArrayList(); + private static List _echoServerList = new ArrayList<>(); { _zkHosts = ZK_HOST+":"+ZK_PORT; @@ -212,13 +212,13 @@ public static void testSingleCluster() throws IOException, InterruptedException, public static void testSingleClusterCustomizedPartitions() throws IOException, InterruptedException, URISyntaxException, Exception { @SuppressWarnings("serial") - final Map> clustersData = new HashMap>() + final Map> clustersData = new HashMap>() {{ - put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); + put("partitioned-cluster", Arrays.asList("partitioned-service-1", "partitioned-service-2")); }}; - final Map partitionProperties = new HashMap(); - Map customized = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map customized = new HashMap<>(); List classList = Collections.emptyList(); customized.put("partitionType", "CUSTOM"); customized.put("partitionCount", "10"); @@ -232,7 +232,7 @@ public static void testSingleClusterCustomizedPartitions() throws IOException, I @Override public void register(String clusterName, BasePartitionAccessor accessor) { - List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList()); + List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList<>()); accessors.add(accessor); } @@ -275,10 +275,10 @@ public int getPartitionId(URI uri) throws PartitionAccessException assertEquals(0, accessor.getPartitionId(URI.create(illegalUri))); // Start Echo server on cluster-1 - Map serverConfig1 = new HashMap(); + Map serverConfig1 = new HashMap<>(); serverConfig1.put(0, 0.5d); serverConfig1.put(3, 0.5d); - Map serverConfig2 = new HashMap(); + Map serverConfig2 = new HashMap<>(); serverConfig2.put(0, 0.25d); serverConfig2.put(1, 0.5d); serverConfig2.put(2, 0.5d); @@ -288,7 +288,7 @@ public int getPartitionId(URI uri) throws PartitionAccessException _echoServerList.add(startEchoServer(echoServerPort1, "partitioned-cluster", serverConfig1)); _echoServerList.add(startEchoServer(echoServerPort2, "partitioned-cluster", serverConfig2)); - Map> partitionWeights = new HashMap>(); + Map> partitionWeights = new HashMap<>(); partitionWeights.put(URI.create("http://127.0.0.1:"+echoServerPort1+"/partitioned-cluster"), serverConfig1); partitionWeights.put(URI.create("http://127.0.0.1:"+echoServerPort2+"/partitioned-cluster"), @@ -307,8 +307,8 @@ public static void testPartitionAccessorFactory() throws IOException, Interrupte put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); }}; - final Map partitionProperties = new HashMap(); - Map customized = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map customized = new HashMap<>(); List classList = Arrays.asList("TestPartitionAccessor1", "TestPartitionAccessor2"); customized.put("partitionType", "CUSTOM"); customized.put("partitionCount", "10"); @@ -322,7 +322,7 @@ public static void testPartitionAccessorFactory() throws IOException, Interrupte @Override public void register(String clusterName, BasePartitionAccessor accessor) { - List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList()); + List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList<>()); accessors.add(accessor); } @@ -402,8 +402,8 @@ public static void testPartitionAccessorFactoryWithEmptyClassList() throws IOExc put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); }}; - final Map partitionProperties = new HashMap(); - Map customized = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map customized = new HashMap<>(); List classList = Collections.emptyList(); customized.put("partitionType", "CUSTOM"); customized.put("partitionCount", "10"); @@ -417,7 +417,7 @@ public static void testPartitionAccessorFactoryWithEmptyClassList() throws IOExc @Override public void register(String clusterName, BasePartitionAccessor accessor) { - List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList()); + List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList<>()); accessors.add(accessor); } @@ -494,11 +494,11 @@ public static void testPartitionAccessorFactoryWithoutMatch() throws IOException @SuppressWarnings("serial") final Map> clustersData = new HashMap>() {{ - put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); + put("partitioned-cluster", Arrays.asList("partitioned-service-1", "partitioned-service-2")); }}; - final Map partitionProperties = new HashMap(); - Map customized = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map customized = new HashMap<>(); List classList = Arrays.asList("NoClass"); customized.put("partitionType", "CUSTOM"); customized.put("partitionCount", "10"); @@ -512,7 +512,7 @@ public static void testPartitionAccessorFactoryWithoutMatch() throws IOException @Override public void register(String clusterName, BasePartitionAccessor accessor) { - List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList()); + List accessors = _registry.computeIfAbsent(clusterName, k -> new ArrayList<>()); accessors.add(accessor); } @@ -590,11 +590,11 @@ public static void testSingleClusterRangePartitions() throws IOException, Interr @SuppressWarnings("serial") final Map> clustersData = new HashMap>() {{ - put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); + put("partitioned-cluster", Arrays.asList("partitioned-service-1", "partitioned-service-2")); }}; - final Map partitionProperties = new HashMap(); - Map rangeBased = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map rangeBased = new HashMap<>(); rangeBased.put("partitionKeyRegex", "\\bid\\b=(\\d+)"); rangeBased.put("keyRangeStart", "0"); rangeBased.put("partitionCount", "10"); @@ -655,10 +655,10 @@ public static void testSingleClusterRangePartitions() throws IOException, Interr // Start Echo server on cluster-1 - Map serverConfig1 = new HashMap(); + Map serverConfig1 = new HashMap<>(); serverConfig1.put(0, 0.5d); serverConfig1.put(3, 0.5d); - Map serverConfig2 = new HashMap(); + Map serverConfig2 = new HashMap<>(); serverConfig2.put(0, 0.25d); serverConfig2.put(1, 0.5d); serverConfig2.put(2, 0.5d); @@ -668,7 +668,7 @@ public static void testSingleClusterRangePartitions() throws IOException, Interr _echoServerList.add(startEchoServer(echoServerPort1, "partitioned-cluster", serverConfig1)); _echoServerList.add(startEchoServer(echoServerPort2, "partitioned-cluster", serverConfig2)); - Map> partitionWeights = new HashMap>(); + Map> partitionWeights = new HashMap<>(); partitionWeights.put(URI.create("http://127.0.0.1:"+echoServerPort1+"/partitioned-cluster"), serverConfig1); partitionWeights.put(URI.create("http://127.0.0.1:"+echoServerPort2+"/partitioned-cluster"), @@ -685,11 +685,11 @@ public static void testSingleClusterHashPartitions() throws IOException, Interru @SuppressWarnings("serial") final Map> clustersData = new HashMap>() {{ - put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); + put("partitioned-cluster", Arrays.asList("partitioned-service-1", "partitioned-service-2")); }}; - final Map partitionProperties = new HashMap(); - Map hashBased = new HashMap(); + final Map partitionProperties = new HashMap<>(); + Map hashBased = new HashMap<>(); hashBased.put("partitionKeyRegex", "\\bid\\b=(\\d+)"); hashBased.put("partitionCount", "10"); hashBased.put("hashAlgorithm", "modulo"); @@ -723,7 +723,7 @@ public static void testMultipleClustersWithServiceGroups() throws IOException, I final int echoServerPort3 = 2345; @SuppressWarnings("serial") - Map servicesData = new HashMap() + Map servicesData = new HashMap() {{ put("service1", "testService"); put("service2", "testService"); @@ -732,7 +732,7 @@ public static void testMultipleClustersWithServiceGroups() throws IOException, I }}; @SuppressWarnings("serial") - Map serviceGroupsData = new HashMap() + Map serviceGroupsData = new HashMap() {{ put("ServiceGroup1", "Cluster1"); put("ServiceGroup2", "Cluster2"); @@ -742,7 +742,7 @@ public static void testMultipleClustersWithServiceGroups() throws IOException, I @SuppressWarnings("serial") Map clusterProperties = new HashMap() {{ - put(PropertyKeys.CLUSTER_VARIANTS, Arrays.asList(new String[]{"Cluster1", "Cluster2", "Cluster3"})); + put(PropertyKeys.CLUSTER_VARIANTS, Arrays.asList("Cluster1", "Cluster2", "Cluster3")); }}; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil("TestServices", servicesData, serviceGroupsData); @@ -871,20 +871,20 @@ public static void testWithNonUniqueServiceGroupClusterVariants() throws IOExcep { // D2Config error : "Service group has variants of the same cluster" - Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map clusterServiceConfigurations = new HashMap<>(); + Map serviceVariants = new HashMap<>(); //Cluster Service Configurations // Services With Variants - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",D2ConfigTestUtil.generateServicesMap(2, "service", "testService")); // Service variants @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put("zCluster1",new HashMap()); - put("zCluster2",new HashMap()); + put("zCluster1", new HashMap<>()); + put("zCluster2", new HashMap<>()); }}; services.put("clusterVariants", clusterVariants); @@ -896,18 +896,18 @@ public static void testWithNonUniqueServiceGroupClusterVariants() throws IOExcep // Cluster variants // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"zCluster1"})); + put("clusterList", Arrays.asList("zCluster1")); }}; // serviceGroup2 @SuppressWarnings("serial") - Map serviceGroup2 = new HashMap() + Map serviceGroup2 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"zCluster2", "zCluster1"})); + put("clusterList", Arrays.asList("zCluster2", "zCluster1")); }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -930,19 +930,19 @@ public static void testWithUnknownCluster() throws IOException, InterruptedExcep { // D2Config error : "Unknown cluster specified" - Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map clusterServiceConfigurations = new HashMap<>(); + Map serviceVariants = new HashMap<>(); //Cluster Service Configurations // Services With Variants - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",D2ConfigTestUtil.generateServicesMap(1, "service", "testService")); // Service variants @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put("cluster1",new HashMap()); + put("cluster1",new HashMap<>()); }}; services.put("clusterVariants", clusterVariants); @@ -953,18 +953,18 @@ public static void testWithUnknownCluster() throws IOException, InterruptedExcep // Cluster variants // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"cluster1"})); + put("clusterList", Arrays.asList("cluster1")); }}; // serviceGroup2 @SuppressWarnings("serial") - Map serviceGroup2 = new HashMap() + Map serviceGroup2 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"zCluster2",})); + put("clusterList", Arrays.asList("zCluster2")); }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -987,20 +987,20 @@ public static void testUnknownServiceVariantType() throws IOException, Interrupt { // D2Config error : "unknown serviceVariant type" - Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map clusterServiceConfigurations = new HashMap<>(); + Map serviceVariants = new HashMap<>(); //Cluster Service Configurations // Services With Variants - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",D2ConfigTestUtil.generateServicesMap(1, "service", "testService")); // Service variants @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put("cluster1",new HashMap()); - put("cluster2",new HashMap()); + put("cluster1", new HashMap<>()); + put("cluster2", new HashMap<>()); }}; services.put("clusterVariants", clusterVariants); @@ -1012,18 +1012,18 @@ public static void testUnknownServiceVariantType() throws IOException, Interrupt // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"cluster1"})); + put("clusterList", Arrays.asList("cluster1")); }}; // serviceGroup2 @SuppressWarnings("serial") - Map serviceGroup2 = new HashMap() + Map serviceGroup2 = new HashMap() {{ put("type", "someVariantsList"); - put("clusterList", Arrays.asList(new String[]{"cluster2",})); + put("clusterList", Arrays.asList("cluster2")); }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -1046,20 +1046,20 @@ public static void testNonUniqueClusterVariantName() throws IOException, Interru { // D2Config error message: "Cluster variant name: ... is not unique!" - Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map clusterServiceConfigurations = new HashMap<>(); + Map serviceVariants = new HashMap<>(); //Cluster Service Configurations // Services With Variants - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",D2ConfigTestUtil.generateServicesMap(1, "service", "testService")); // Service variants @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put("Cluster#1",new HashMap()); - put("Cluster#2",new HashMap()); + put("Cluster#1",new HashMap<>()); + put("Cluster#2",new HashMap<>()); }}; services.put("clusterVariants",clusterVariants); @@ -1069,18 +1069,18 @@ public static void testNonUniqueClusterVariantName() throws IOException, Interru // Cluster variants // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"Cluster#1"})); + put("clusterList", Arrays.asList("Cluster#1")); }}; // serviceGroup2 @SuppressWarnings("serial") - Map serviceGroup2 = new HashMap() + Map serviceGroup2 = new HashMap() {{ put("type", "clusterVariantsList"); - put("clusterList", Arrays.asList(new String[]{"Cluster#2"})); + put("clusterList", Arrays.asList("Cluster#2")); }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -1140,7 +1140,7 @@ public static void testWriteConfigDelta() throws Exception assertEquals(d2Conf.runDiscovery(_zkHosts), 0); // Build map of path to expected version. - final HashMap expectedVersionMap = new HashMap(); + final HashMap expectedVersionMap = new HashMap<>(); expectedVersionMap.put("/d2/services/service-1_a", 2); expectedVersionMap.put("/d2/services/service-1_b", 1); expectedVersionMap.put("/d2/services/service-1_c", 1); @@ -1152,7 +1152,7 @@ public static void testWriteConfigDelta() throws Exception expectedVersionMap.put("/d2/clusters/cluster-c", 1); // Get actual version number for each path. - final HashMap actualVersionMap = new HashMap(); + final HashMap actualVersionMap = new HashMap<>(); final CountDownLatch latch = new CountDownLatch(expectedVersionMap.size()); final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() { @@ -1252,7 +1252,7 @@ public static void verifyClusterProperties(String cluster) throws IOException, U assertEquals(clusterprops.getClusterName(), cluster); assertEquals(clusterprops.getPrioritizedSchemes(), Arrays.asList(new String[] {"http"})); assertEquals(clusterprops.getProperties().get("requestTimeout"), String.valueOf(10000)); - assertEquals(clusterprops.getBannedUris(), new TreeSet()); + assertEquals(clusterprops.getBannedUris(), new TreeSet<>()); } @SuppressWarnings("unchecked") @@ -1391,7 +1391,7 @@ public static void verifyPartitionedUriProperties(String cluster, Map> partitionUris = new HashMap>(); + Map> partitionUris = new HashMap<>(); for (final URI uri : partitionWeights.keySet()) { for(final int partitionId : partitionWeights.get(uri).keySet()) @@ -1399,7 +1399,7 @@ public static void verifyPartitionedUriProperties(String cluster, Map uriSet = partitionUris.get(partitionId); if (uriSet == null) { - uriSet = new HashSet(); + uriSet = new HashSet<>(); partitionUris.put(partitionId, uriSet); } uriSet.add(uri); @@ -1441,20 +1441,20 @@ public void testSuffixAppender() @Test public static void testSingleClusterNoColo() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put("cluster-1", serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add("cluster-1"); - Map clusterProperties = new HashMap(); - Map> peerColoList = new HashMap>(); - Map masterColoList = new HashMap(); - Map> clustersProperties = new HashMap>(); + Map clusterProperties = new HashMap<>(); + Map> peerColoList = new HashMap<>(); + Map masterColoList = new HashMap<>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put("cluster-1", clusterProperties); String defaultColo = ""; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1467,29 +1467,29 @@ public static void testSingleClusterNoColo() throws IOException, InterruptedExce @Test public static void testSingleColoCluster() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1503,20 +1503,20 @@ public static void testSingleColoCluster() throws IOException, InterruptedExcept public static void testSingleClusterNoColoWithDefaultColo() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put("cluster-1", serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add("cluster-1"); - Map clusterProperties = new HashMap(); - Map> peerColoList = new HashMap>(); - Map masterColoList = new HashMap(); - Map> clustersProperties = new HashMap>(); + Map clusterProperties = new HashMap<>(); + Map> peerColoList = new HashMap<>(); + Map masterColoList = new HashMap<>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put("cluster-1", clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1531,22 +1531,22 @@ public static void testSingleClusterNoColoWithDefaultColo() @Test public static void testSingleClusterNoColoWithDefaultColoMasterColo() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put("cluster-1", serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add("cluster-1"); - Map clusterProperties = new HashMap(); - Map> peerColoList = new HashMap>(); + Map clusterProperties = new HashMap<>(); + Map> peerColoList = new HashMap<>(); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); - Map> clustersProperties = new HashMap>(); + Map masterColoList = new HashMap<>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put("cluster-1", clusterProperties); String defaultColo = "EastCoast"; @@ -1560,36 +1560,36 @@ public static void testSingleClusterNoColoWithDefaultColoMasterColo() throws IOE @Test public static void testOneColoClusterOneNoColoCluster() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List serviceList2 = new ArrayList(); + List serviceList2 = new ArrayList<>(); serviceList2.add("service-2_1"); serviceList2.add("service-2_2"); String cluster2Name = "cluster-2"; clustersData.put(cluster2Name, serviceList2); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); clusterList.add(cluster2Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1602,25 +1602,25 @@ public static void testOneColoClusterOneNoColoCluster() throws IOException, Inte @Test public static void testClusterWithEmptyColoVariants() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add(""); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); - Map masterColoList = new HashMap(); - Map> clustersProperties = new HashMap>(); + Map masterColoList = new HashMap<>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1634,48 +1634,48 @@ public static void testClusterWithEmptyColoVariants() throws IOException, Interr public static void testSingleColoClusterWithClusterVariants() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); final String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); String masterColo = "WestCoast"; clusterProperties.put(PropertyKeys.MASTER_COLO, masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); // add in clusterVariants - Map> clusterVariants = new HashMap>(); + Map> clusterVariants = new HashMap<>(); final String cluster1Variant1Name = "cluster1Foo"; final String cluster1Variant2Name = "cluster1Bar"; - clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); - clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); - List clusterVariantsList = new ArrayList(); + clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); + clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); + List clusterVariantsList = new ArrayList<>(); clusterVariantsList.add(cluster1Variant1Name); clusterVariantsList.add(cluster1Variant2Name); clusterProperties.put(PropertyKeys.CLUSTER_VARIANTS, clusterVariants); - Map> clusterVariantsMapping = new HashMap>(); + Map> clusterVariantsMapping = new HashMap<>(); clusterVariantsMapping.put(cluster1Name,clusterVariantsList); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; @SuppressWarnings("serial") - Map> serviceGroupsData = new HashMap>() + Map> serviceGroupsData = new HashMap>() {{ put("ServiceGroup1", Collections.singletonList(cluster1Variant1Name)); put("ServiceGroup2", Collections.singletonList(cluster1Variant2Name)); @@ -1718,48 +1718,48 @@ public static void testSingleColoClusterWithClusterVariants() public static void testSingleColoClusterWithClusterVariants2() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); final String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); String masterColo = "EastCoast"; clusterProperties.put(PropertyKeys.MASTER_COLO, masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); // add in clusterVariants - Map> clusterVariants = new HashMap>(); + Map> clusterVariants = new HashMap<>(); final String cluster1Variant1Name = "cluster1Foo"; final String cluster1Variant2Name = "cluster1Bar"; - clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); - clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); - List clusterVariantsList = new ArrayList(); + clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); + clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); + List clusterVariantsList = new ArrayList<>(); clusterVariantsList.add(cluster1Variant1Name); clusterVariantsList.add(cluster1Variant2Name); clusterProperties.put(PropertyKeys.CLUSTER_VARIANTS, clusterVariants); - Map> clusterVariantsMapping = new HashMap>(); + Map> clusterVariantsMapping = new HashMap<>(); clusterVariantsMapping.put(cluster1Name,clusterVariantsList); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; @SuppressWarnings("serial") - Map> serviceGroupsData = new HashMap>() + Map> serviceGroupsData = new HashMap>() {{ put("ServiceGroup1", Collections.singletonList(cluster1Variant1Name)); put("ServiceGroup2", Collections.singletonList(cluster1Variant2Name)); @@ -1803,48 +1803,48 @@ public static void testSingleColoClusterWithClusterVariants2() public static void testSingleColoClusterWithClusterVariants3() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); final String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("EastCoast"); peerColos.add("WestCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); String masterColo = "EastCoast"; clusterProperties.put(PropertyKeys.MASTER_COLO, masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); // add in clusterVariants - Map> clusterVariants = new HashMap>(); + Map> clusterVariants = new HashMap<>(); final String cluster1Variant1Name = "cluster1Foo"; final String cluster1Variant2Name = "cluster1Bar"; - clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); - clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); - List clusterVariantsList = new ArrayList(); + clusterVariants.put(cluster1Variant1Name, Collections.emptyMap()); + clusterVariants.put(cluster1Variant2Name, Collections.emptyMap()); + List clusterVariantsList = new ArrayList<>(); clusterVariantsList.add(cluster1Variant1Name); clusterVariantsList.add(cluster1Variant2Name); clusterProperties.put(PropertyKeys.CLUSTER_VARIANTS, clusterVariants); - Map> clusterVariantsMapping = new HashMap>(); + Map> clusterVariantsMapping = new HashMap<>(); clusterVariantsMapping.put(cluster1Name,clusterVariantsList); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; @SuppressWarnings("serial") - Map> serviceGroupsData = new HashMap>() + Map> serviceGroupsData = new HashMap>() {{ put("ServiceGroup1", Collections.singletonList(cluster1Variant1Name)); put("ServiceGroup2", Collections.singletonList(cluster1Variant2Name)); @@ -1886,36 +1886,36 @@ public static void testSingleColoClusterWithClusterVariants3() @Test public static void testSingleColoClusterWithOneExcludedService() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); String excludedService = "service-1_22346"; serviceList.add(excludedService); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); List excludeServiceList = Arrays.asList(excludedService); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties, - new HashMap>(), excludeServiceList); + new HashMap<>(), excludeServiceList); assertEquals(d2Conf.runDiscovery(_zkHosts), 0); @@ -1937,29 +1937,29 @@ public static void testSingleColoClusterWithOneExcludedService() throws IOExcept @Test public static void testDefaultColoIsOneOfPeerColo() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "MiddleKingdom"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -1978,29 +1978,29 @@ public static void testDefaultColoIsOneOfPeerColo() throws IOException, Interrup @Test public static void testMasterColoIsOneOfPeerColo() throws IOException, InterruptedException, URISyntaxException, Exception { - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service-1_1"); serviceList.add("service-1_2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster-1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); String masterColo = "MiddleKingdom"; clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); String defaultColo = "EastCoast"; D2ConfigTestUtil d2Conf = new D2ConfigTestUtil( clustersData, defaultColo, clustersProperties); @@ -2027,30 +2027,30 @@ public static void testDefaultRoutingToMaster() throws IOException, InterruptedE final String masterColo = "WestCoast"; final String defaultColo = "EastCoast"; - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add("service1"); serviceList.add("service2"); @SuppressWarnings("serial") - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); String cluster1Name = "cluster1"; clustersData.put(cluster1Name, serviceList); - List clusterList = new ArrayList(); + List clusterList = new ArrayList<>(); clusterList.add(cluster1Name); - Map clusterProperties = new HashMap(); + Map clusterProperties = new HashMap<>(); - List peerColos = new ArrayList(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); - Map> peerColoList = new HashMap>(); + Map> peerColoList = new HashMap<>(); peerColoList.put(cluster1Name, peerColos); clusterProperties.put("coloVariants", peerColos); clusterProperties.put("masterColo", masterColo); - Map masterColoList = new HashMap(); + Map masterColoList = new HashMap<>(); masterColoList.put(cluster1Name, masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); Set servicesWithDefaultRoutingToMaster = Collections.singleton("service2"); @@ -2085,35 +2085,35 @@ public static void testServiceVariantsWithDefaultRoutingToMaster() throws Except final String clusterVariantName = "clusterVariant1"; final String serviceGroupName = "serviceGroup1"; - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add(service1); serviceList.add(service2); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put(cluster1Name, serviceList); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add(masterColo); peerColos.add(defaultColo); @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put(clusterVariantName,new HashMap()); - }}; + put(clusterVariantName, new HashMap<>()); + }}; clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); clusterProperties.put(PropertyKeys.MASTER_COLO, masterColo); clusterProperties.put(PropertyKeys.CLUSTER_VARIANTS, clusterVariants); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(cluster1Name, clusterProperties); @SuppressWarnings("serial") - Map serviceGroup = new HashMap() + Map serviceGroup = new HashMap() {{ put(PropertyKeys.TYPE, PropertyKeys.CLUSTER_VARIANTS_LIST); - put(PropertyKeys.CLUSTER_LIST, Arrays.asList(new String[]{clusterVariantName})); + put(PropertyKeys.CLUSTER_LIST, Arrays.asList(clusterVariantName)); }}; - Map serviceVariants = new HashMap(); + Map serviceVariants = new HashMap<>(); serviceVariants.put(serviceGroupName, serviceGroup); Set servicesWithDefaultRoutingToMaster = Collections.singleton(service2); @@ -2137,22 +2137,22 @@ public static void testServiceWithDefaultRoutingToMasterAndSymlinkEnabled() thro final String service2 = "service2"; final String clusterName = "cluster"; - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add(service1); serviceList.add(service2); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put(clusterName, serviceList); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add(masterColo); peerColos.add(defaultColo); clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); clusterProperties.put(PropertyKeys.MASTER_COLO, "MASTER_MANAGED_EXTERNALLY"); clusterProperties.put(PropertyKeys.ENABLE_SYMLINK, "true"); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(clusterName, clusterProperties); Set servicesWithDefaultRoutingToMaster = Collections.singleton("service2"); @@ -2179,36 +2179,36 @@ public static void testServiceVariantsWithDefaultRoutingToMasterAndSymlinkEnable final String clusterVariantName = "clusterVariant"; final String serviceGroupName = "serviceGroup"; - List serviceList = new ArrayList(); + List serviceList = new ArrayList<>(); serviceList.add(service1); serviceList.add(service2); - Map> clustersData = new HashMap>(); + Map> clustersData = new HashMap<>(); clustersData.put(clusterName, serviceList); - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add(masterColo); peerColos.add(defaultColo); @SuppressWarnings("serial") - Map clusterVariants = new HashMap() + Map clusterVariants = new HashMap() {{ - put(clusterVariantName,new HashMap()); - }}; + put(clusterVariantName, new HashMap<>()); + }}; clusterProperties.put(PropertyKeys.COLO_VARIANTS, peerColos); clusterProperties.put(PropertyKeys.MASTER_COLO, "MASTER_MANAGED_EXTERNALLY"); clusterProperties.put(PropertyKeys.CLUSTER_VARIANTS, clusterVariants); clusterProperties.put(PropertyKeys.ENABLE_SYMLINK, "true"); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(clusterName, clusterProperties); @SuppressWarnings("serial") - Map serviceGroup = new HashMap() + Map serviceGroup = new HashMap() {{ put(PropertyKeys.TYPE, PropertyKeys.CLUSTER_VARIANTS_LIST); - put(PropertyKeys.CLUSTER_LIST, Arrays.asList(new String[]{clusterVariantName})); - }}; - Map serviceVariants = new HashMap(); + put(PropertyKeys.CLUSTER_LIST, Arrays.asList(clusterVariantName)); + }}; + Map serviceVariants = new HashMap<>(); serviceVariants.put(serviceGroupName, serviceGroup); Set servicesWithDefaultRoutingToMaster = Collections.singleton(service2); @@ -2229,12 +2229,12 @@ public static void testServiceVariantsWithDefaultRoutingToMasterAndSymlinkEnable @Test public static void testWithDefaultClusterInFullListMode() throws IOException, InterruptedException, URISyntaxException, Exception { - Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map clusterServiceConfigurations = new HashMap<>(); + Map serviceVariants = new HashMap<>(); //Cluster Service Configurations // Services With Variants - Map services = new HashMap(); + Map services = new HashMap<>(); services.put("services",D2ConfigTestUtil.generateServicesMap(1, "service", "testService")); // We omit adding cluster variants to the cluster. @@ -2245,10 +2245,10 @@ public static void testWithDefaultClusterInFullListMode() throws IOException, In // Cluster variants // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "fullClusterList"); - put("clusterList", Arrays.asList(new String[]{"zServices"})); + put("clusterList", Arrays.asList("zServices")); }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -2267,27 +2267,26 @@ public static void testWithDefaultClusterInFullListMode() throws IOException, In @Test public static void testDefaultClusterWithColoInFullListMode() throws IOException, InterruptedException, URISyntaxException, Exception { - // Map clusterServiceConfigurations = new HashMap(); - Map serviceVariants = new HashMap(); + Map serviceVariants = new HashMap<>(); final String clusterName = "zServices"; //Cluster Service Configurations // Services With Variants @SuppressWarnings("serial") - Map> clustersData = new HashMap>() + Map> clustersData = new HashMap>() {{ - put(clusterName, Arrays.asList(new String[]{"service-1"})); - }}; + put(clusterName, Arrays.asList("service-1")); + }}; // Colo configs - Map clusterProperties = new HashMap(); - List peerColos = new ArrayList(); + Map clusterProperties = new HashMap<>(); + List peerColos = new ArrayList<>(); peerColos.add("WestCoast"); peerColos.add("EastCoast"); clusterProperties.put("coloVariants", peerColos); String masterColo = "WestCoast"; clusterProperties.put("masterColo", masterColo); - Map> clustersProperties = new HashMap>(); + Map> clustersProperties = new HashMap<>(); clustersProperties.put(clusterName, clusterProperties); String defaultColo = "EastCoast"; // We omit adding cluster variants to the cluster. @@ -2296,11 +2295,11 @@ public static void testDefaultClusterWithColoInFullListMode() throws IOException // serviceGroup1 @SuppressWarnings("serial") - Map serviceGroup1 = new HashMap() + Map serviceGroup1 = new HashMap() {{ put("type", "fullClusterList"); - put("clusterList", Arrays.asList(new String[]{"zServices"})); - }}; + put("clusterList", Arrays.asList("zServices")); + }}; serviceVariants.put("ServiceGroup1", serviceGroup1); @@ -2412,7 +2411,7 @@ private static List getOrCreatePeerList(String clusterName, Map(); + peerColos = new ArrayList<>(); peerColos.add(""); } return peerColos; diff --git a/d2/src/test/java/com/linkedin/d2/discovery/util/TestHashFunctions.java b/d2/src/test/java/com/linkedin/d2/discovery/util/TestHashFunctions.java index 78c6011085..d6c764de00 100644 --- a/d2/src/test/java/com/linkedin/d2/discovery/util/TestHashFunctions.java +++ b/d2/src/test/java/com/linkedin/d2/discovery/util/TestHashFunctions.java @@ -82,13 +82,13 @@ public void testSetup() throws IOException, Exception { } //Setting up partitionAccessors based on different hash functions. - final Map> clustersData = new HashMap>(); + final Map> clustersData = new HashMap<>(); clustersData.put("partitioned-cluster", Arrays.asList(new String[]{"partitioned-service-1", "partitioned-service-2"})); @SuppressWarnings("serial") - final Map partitionPropertiesXXHASH = new HashMap(); - Map XXhashBased = new HashMap(); + final Map partitionPropertiesXXHASH = new HashMap<>(); + Map XXhashBased = new HashMap<>(); XXhashBased.put("partitionKeyRegex", "\\bid\\b=(\\d+)"); XXhashBased.put("partitionCount", "10"); XXhashBased.put("hashAlgorithm", "XXHash"); @@ -100,8 +100,8 @@ public void testSetup() throws IOException, Exception { _XXHashAccessor = PartitionAccessorFactory.getPartitionAccessor("partitioned-cluster", null, clusterprops.getPartitionProperties()); - final Map partitionPropertiesMD5 = new HashMap(); - Map MD5HashBased = new HashMap(); + final Map partitionPropertiesMD5 = new HashMap<>(); + Map MD5HashBased = new HashMap<>(); MD5HashBased.put("partitionKeyRegex", "\\bid\\b=(\\d+)"); MD5HashBased.put("partitionCount", "10"); MD5HashBased.put("hashAlgorithm", "MD5"); diff --git a/darkcluster/src/main/java/com/linkedin/darkcluster/impl/BaseDarkClusterDispatcherImpl.java b/darkcluster/src/main/java/com/linkedin/darkcluster/impl/BaseDarkClusterDispatcherImpl.java index 83e4e6bc45..11e8cb3344 100644 --- a/darkcluster/src/main/java/com/linkedin/darkcluster/impl/BaseDarkClusterDispatcherImpl.java +++ b/darkcluster/src/main/java/com/linkedin/darkcluster/impl/BaseDarkClusterDispatcherImpl.java @@ -46,7 +46,7 @@ public class BaseDarkClusterDispatcherImpl implements BaseDarkClusterDispatcher private final AtomicInteger _requestCount = new AtomicInteger(0); private final AtomicInteger _successCount = new AtomicInteger(0); private final AtomicInteger _exceptionCount = new AtomicInteger(0); - private final ConcurrentHashMap _exceptionCountMap = new ConcurrentHashMap(); + private final ConcurrentHashMap _exceptionCountMap = new ConcurrentHashMap<>(); private final DarkClusterVerifierManager _verifierManager; public BaseDarkClusterDispatcherImpl(@Nonnull String darkClusterName, diff --git a/data-avro-generator/src/main/java/com/linkedin/data/avro/generator/AvroSchemaGenerator.java b/data-avro-generator/src/main/java/com/linkedin/data/avro/generator/AvroSchemaGenerator.java index 6ec040a505..0d90e6efc7 100644 --- a/data-avro-generator/src/main/java/com/linkedin/data/avro/generator/AvroSchemaGenerator.java +++ b/data-avro-generator/src/main/java/com/linkedin/data/avro/generator/AvroSchemaGenerator.java @@ -71,17 +71,17 @@ public class AvroSchemaGenerator extends AbstractGenerator private static final Logger _log = LoggerFactory.getLogger(AvroSchemaGenerator.class); - private final Set _sourceLocations = new HashSet(); + private final Set _sourceLocations = new HashSet<>(); /** * Sources as set. */ - private final Set _sources = new HashSet(); + private final Set _sources = new HashSet<>(); /** * Map of output file and the schema that should be written in the output file. */ - private final Map _fileToAvroSchemaMap = new HashMap(); + private final Map _fileToAvroSchemaMap = new HashMap<>(); /** * Options that specify how Avro schema should be generated. @@ -244,7 +244,7 @@ protected void outputAvroSchemas(File targetDirectory) throws IOException protected List targetFiles(File targetDirectory) { - ArrayList generatedFiles = new ArrayList(); + ArrayList generatedFiles = new ArrayList<>(); DataSchemaResolver resolver = getSchemaResolver(); Map nameToLocations = resolver.nameToDataSchemaLocations(); diff --git a/data-avro/src/main/java/com/linkedin/data/avro/AvroOverrideMap.java b/data-avro/src/main/java/com/linkedin/data/avro/AvroOverrideMap.java index b2ef298e2c..5c63ff0cc0 100644 --- a/data-avro/src/main/java/com/linkedin/data/avro/AvroOverrideMap.java +++ b/data-avro/src/main/java/com/linkedin/data/avro/AvroOverrideMap.java @@ -29,7 +29,7 @@ class AvroOverrideMap { private static final AvroOverride NO_AVRO_OVERRIDE = new AvroOverride(null, null, null, null); - protected final IdentityHashMap _dataSchemaToAvroOverrideMap = new IdentityHashMap(); + protected final IdentityHashMap _dataSchemaToAvroOverrideMap = new IdentityHashMap<>(); protected final AvroOverrideFactory _avroOverrideFactory; AvroOverrideMap(AvroOverrideFactory avroOverrideFactory) diff --git a/data-avro/src/main/java/com/linkedin/data/avro/DataTranslator.java b/data-avro/src/main/java/com/linkedin/data/avro/DataTranslator.java index 76bb6771a7..577b1bb29a 100644 --- a/data-avro/src/main/java/com/linkedin/data/avro/DataTranslator.java +++ b/data-avro/src/main/java/com/linkedin/data/avro/DataTranslator.java @@ -171,8 +171,8 @@ public static DataMap genericRecordToDataMap(GenericRecord record, RecordDataSch private static final GenericData _genericData = GenericData.get(); - protected final Deque _path = new ArrayDeque(); - protected final MessageList _messageList = new MessageList(); + protected final Deque _path = new ArrayDeque<>(); + protected final MessageList _messageList = new MessageList<>(); protected final AvroOverrideFactory _avroOverrideFactory = new AvroOverrideFactory() { { @@ -448,7 +448,7 @@ private final Map.Entry findUnionMemberSchema(Object value, appendMessage("cannot find %1$s in union %2$s for value %3$s", key, unionDataSchema, value); return null; } - return new AbstractMap.SimpleEntry(memberDataSchema, memberAvroSchema); + return new AbstractMap.SimpleEntry<>(memberDataSchema, memberAvroSchema); } private Object translateAvroRecordToPegasusUnionWithAliases(Object value, UnionDataSchema unionDataSchema, Schema avroSchema) @@ -564,7 +564,7 @@ private Object translate(Object value, DataSchema dataSchema, Schema avroSchema) DataMap map = (DataMap) value; DataSchema valueDataSchema = ((MapDataSchema) dereferencedDataSchema).getValues(); Schema valueAvroSchema = avroSchema.getValueType(); - Map avroMap = new HashMap(map.size()); + Map avroMap = new HashMap<>(map.size()); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); @@ -579,7 +579,7 @@ private Object translate(Object value, DataSchema dataSchema, Schema avroSchema) DataList list = (DataList) value; DataSchema elementDataSchema = ((ArrayDataSchema) dereferencedDataSchema).getItems(); Schema elementAvroSchema = avroSchema.getElementType(); - GenericData.Array avroList = new GenericData.Array(list.size(), avroSchema); + GenericData.Array avroList = new GenericData.Array<>(list.size(), avroSchema); for (int i = 0; i < list.size(); i++) { _path.addLast(i); @@ -812,7 +812,7 @@ protected Map.Entry findUnionMember(DataSchema dataSchema, Schem name = member.getType().toString().toLowerCase(); } if (name.equals(key)) - return new AbstractMap.SimpleEntry(name, member); + return new AbstractMap.SimpleEntry<>(name, member); } appendMessage("cannot find %1$s in union %2$s", key, avroSchema); return null; diff --git a/data-avro/src/main/java/com/linkedin/data/avro/SchemaToAvroJsonEncoder.java b/data-avro/src/main/java/com/linkedin/data/avro/SchemaToAvroJsonEncoder.java index d4886bfff4..0d649c3a47 100644 --- a/data-avro/src/main/java/com/linkedin/data/avro/SchemaToAvroJsonEncoder.java +++ b/data-avro/src/main/java/com/linkedin/data/avro/SchemaToAvroJsonEncoder.java @@ -153,7 +153,7 @@ protected void encodeProperties(DataSchema schema) throws IOException } private static final Set RESERVED_DATA_PROPERTIES = - new HashSet(Arrays.asList( + new HashSet<>(Arrays.asList( SchemaTranslator.AVRO_PREFIX, SchemaTranslator.SCHEMA_PROPERTY, SchemaTranslator.OPTIONAL_DEFAULT_MODE_PROPERTY, @@ -264,7 +264,7 @@ protected void encodeFieldType(RecordDataSchema.Field field) throws IOException if (unionDataSchema == null) { addNullMemberType = true; - resultMemberTypes = new ArrayList(1); + resultMemberTypes = new ArrayList<>(1); resultMemberTypes.add(fieldSchema); defaultValueSchema = ( defaultValue != null diff --git a/data-avro/src/main/java/com/linkedin/data/avro/util/AvroUtil.java b/data-avro/src/main/java/com/linkedin/data/avro/util/AvroUtil.java index 5d78953dfb..655e871707 100644 --- a/data-avro/src/main/java/com/linkedin/data/avro/util/AvroUtil.java +++ b/data-avro/src/main/java/com/linkedin/data/avro/util/AvroUtil.java @@ -31,7 +31,7 @@ public class AvroUtil { public static String jsonFromGenericRecord(GenericRecord record) throws IOException { - GenericDatumWriter writer = new GenericDatumWriter(); + GenericDatumWriter writer = new GenericDatumWriter<>(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Encoder jsonEncoder = AvroCompatibilityHelper.newJsonEncoder(record.getSchema(), outputStream, true); writer.setSchema(record.getSchema()); @@ -42,7 +42,7 @@ public static String jsonFromGenericRecord(GenericRecord record) throws IOExcept public static byte[] bytesFromGenericRecord(GenericRecord record) throws IOException { - GenericDatumWriter writer = new GenericDatumWriter(); + GenericDatumWriter writer = new GenericDatumWriter<>(); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); Encoder binaryEncoder = AvroCompatibilityHelper.newBinaryEncoder(byteOutputStream, false, null); writer.setSchema(record.getSchema()); @@ -53,7 +53,7 @@ public static byte[] bytesFromGenericRecord(GenericRecord record) throws IOExcep public static GenericRecord genericRecordFromBytes(byte[] bytes, Schema schema) throws IOException { - GenericDatumReader reader = new GenericDatumReader(); + GenericDatumReader reader = new GenericDatumReader<>(); Decoder binaryDecoder = AvroCompatibilityHelper.newBinaryDecoder( new ByteArrayInputStream(bytes), false, null); reader.setSchema(schema); @@ -63,7 +63,7 @@ public static GenericRecord genericRecordFromBytes(byte[] bytes, Schema schema) public static GenericRecord genericRecordFromJson(String json, Schema schema) throws IOException { - GenericDatumReader reader = new GenericDatumReader(); + GenericDatumReader reader = new GenericDatumReader<>(); Decoder jsonDecoder = AvroCompatibilityHelper.newCompatibleJsonDecoder(schema, json); reader.setSchema(schema); GenericRecord record = reader.read(null, jsonDecoder); diff --git a/data-avro/src/test/java/com/linkedin/data/avro/TestAvroOverrideFactory.java b/data-avro/src/test/java/com/linkedin/data/avro/TestAvroOverrideFactory.java index fa0715879d..82a4f66e39 100644 --- a/data-avro/src/test/java/com/linkedin/data/avro/TestAvroOverrideFactory.java +++ b/data-avro/src/test/java/com/linkedin/data/avro/TestAvroOverrideFactory.java @@ -58,7 +58,7 @@ private PrivateConstructorMyCustomDataTranslator() private static class MyAvroOverrideFactory extends AvroOverrideFactory { - private MessageList _messageList = new MessageList(); + private MessageList _messageList = new MessageList<>(); private static final Object[] _path = new Object[0]; MyAvroOverrideFactory() diff --git a/data-transform/src/main/java/com/linkedin/data/transform/FILOScheduler.java b/data-transform/src/main/java/com/linkedin/data/transform/FILOScheduler.java index 079735fe8c..cb8c86fe30 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/FILOScheduler.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/FILOScheduler.java @@ -40,7 +40,7 @@ public class FILOScheduler implements InstructionScheduler */ public FILOScheduler() { - _stack = new ArrayDeque(); + _stack = new ArrayDeque<>(); } public void scheduleInstructions(List instructions) diff --git a/data-transform/src/main/java/com/linkedin/data/transform/ImmutableList.java b/data-transform/src/main/java/com/linkedin/data/transform/ImmutableList.java index f151ffc034..e765cf3432 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/ImmutableList.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/ImmutableList.java @@ -83,7 +83,7 @@ public ImmutableList(T element) public ImmutableList append(T element) { ArgumentUtil.notNull(element, "element"); - return new ImmutableList(element, this); + return new ImmutableList<>(element, this); } /** diff --git a/data-transform/src/main/java/com/linkedin/data/transform/InterpreterContext.java b/data-transform/src/main/java/com/linkedin/data/transform/InterpreterContext.java index a8a5480123..70d4093af4 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/InterpreterContext.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/InterpreterContext.java @@ -32,10 +32,10 @@ public class InterpreterContext { //stores error messages - private final MessageList _errorMessages = new MessageList(); + private final MessageList _errorMessages = new MessageList<>(); //stores informational messages - private final MessageList _infoMessages = new MessageList(); + private final MessageList _infoMessages = new MessageList<>(); //current instruction is in every method that needs to add error message, because //instruction stores path; instead of passing instruction as parameter, it is accessible diff --git a/data-transform/src/main/java/com/linkedin/data/transform/ProjectionUtil.java b/data-transform/src/main/java/com/linkedin/data/transform/ProjectionUtil.java index 2b45b33b58..af6e66df12 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/ProjectionUtil.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/ProjectionUtil.java @@ -150,7 +150,7 @@ else if (currentValue == null) private static Set validate(DataMap filteredPathSpecs, Set paths) { - final Set result = new HashSet(); + final Set result = new HashSet<>(); for (PathSpec p : paths) { diff --git a/data-transform/src/main/java/com/linkedin/data/transform/filter/AbstractFilter.java b/data-transform/src/main/java/com/linkedin/data/transform/filter/AbstractFilter.java index e655c92b02..5de0d947a8 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/filter/AbstractFilter.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/filter/AbstractFilter.java @@ -256,7 +256,7 @@ private Object filterDataMap(DataMap opNode, { assert opNode != null; - final Map result = new HashMap(); + final Map result = new HashMap<>(); for (Map.Entry entry : valueDataMap.entrySet()) { final String name = entry.getKey(); diff --git a/data-transform/src/main/java/com/linkedin/data/transform/filter/DefaultNodeModeCalculator.java b/data-transform/src/main/java/com/linkedin/data/transform/filter/DefaultNodeModeCalculator.java index 7a6d71101d..cd153d069b 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/filter/DefaultNodeModeCalculator.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/filter/DefaultNodeModeCalculator.java @@ -64,7 +64,7 @@ public class DefaultNodeModeCalculator { // used for memoization of default node modes - private IdentityHashMap _defaultNodeModes = new IdentityHashMap(); + private IdentityHashMap _defaultNodeModes = new IdentityHashMap<>(); /** * Reruns default NodeMode for given filter node. * @param opNode DataMap containing filter, for which default mode needs to be determined diff --git a/data-transform/src/main/java/com/linkedin/data/transform/filter/MaskComposition.java b/data-transform/src/main/java/com/linkedin/data/transform/filter/MaskComposition.java index f7e5f84213..9894172f99 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/filter/MaskComposition.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/filter/MaskComposition.java @@ -438,7 +438,7 @@ private Integer merge(Integer m1, Integer m2, InterpreterContext instrCtx) private void prunePositiveMask(final DataMap complex) { removeArrayRanges(complex); - final List toBeRemoved = new ArrayList(); + final List toBeRemoved = new ArrayList<>(); for (Entry entry : complex.entrySet()) { Object v = entry.getValue(); diff --git a/data-transform/src/main/java/com/linkedin/data/transform/filter/request/MaskTree.java b/data-transform/src/main/java/com/linkedin/data/transform/filter/request/MaskTree.java index 5cec56ca10..9b2146ce4e 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/filter/request/MaskTree.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/filter/request/MaskTree.java @@ -127,7 +127,7 @@ public void addOperation(PathSpec path, MaskOperation op) */ public Map getOperations() { - Map result = new HashMap(); + Map result = new HashMap<>(); getOperationsImpl(_representation, PathSpec.emptyPath(), result); return result; } diff --git a/data-transform/src/main/java/com/linkedin/data/transform/patch/Patch.java b/data-transform/src/main/java/com/linkedin/data/transform/patch/Patch.java index 2bd0cb19a1..ab65106829 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/patch/Patch.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/patch/Patch.java @@ -54,7 +54,7 @@ public class Patch implements Interpreter // that we know that each node is distinct object, they never repeat in a tree and we // want to avoid expensive hash calculations on maps and lists private IdentityHashMap _hasDeletesOnly = - new IdentityHashMap(); + new IdentityHashMap<>(); // On $set and $delete operations, log the path as an info message in the interpreter context private final boolean _logOperations; @@ -87,7 +87,7 @@ public void interpret(final InterpreterContext instrCtx) //at this nodes. The reason for it is that if field should not be used in more than //one operation e.g. $set and $delete, because such patch becomes ambiguous. //Each operation, upon being executed updates this variable. - final Map usedFields = new HashMap(); + final Map usedFields = new HashMap<>(); DataMap opNode = (DataMap) instruction.getOperation(); DataComplex dataComplex = instruction.getData(); diff --git a/data-transform/src/main/java/com/linkedin/data/transform/patch/validator/PatchFilterValidator.java b/data-transform/src/main/java/com/linkedin/data/transform/patch/validator/PatchFilterValidator.java index 0980bbb8ac..8de92c4e4b 100644 --- a/data-transform/src/main/java/com/linkedin/data/transform/patch/validator/PatchFilterValidator.java +++ b/data-transform/src/main/java/com/linkedin/data/transform/patch/validator/PatchFilterValidator.java @@ -143,7 +143,7 @@ public static enum Mode private final Object[] _patchedPath; private final DataMap _opMap; private final Mode _mode; - private final ArrayList _path = new ArrayList(); + private final ArrayList _path = new ArrayList<>(); private static final Object[] _emptyPath = {}; protected static enum Status diff --git a/data-transform/src/test/java/com/linkedin/data/transform/TestProjectionUtil.java b/data-transform/src/test/java/com/linkedin/data/transform/TestProjectionUtil.java index 02d867aa38..5e40a9c484 100644 --- a/data-transform/src/test/java/com/linkedin/data/transform/TestProjectionUtil.java +++ b/data-transform/src/test/java/com/linkedin/data/transform/TestProjectionUtil.java @@ -103,14 +103,14 @@ public void testPositiveMultiPaths() final MaskTree filter = new MaskTree(); filter.addOperation(new PathSpec("foo", "bar", "baz"), MaskOperation.POSITIVE_MASK_OP); - final Collection positivePaths = new HashSet(Arrays.asList( + final Collection positivePaths = new HashSet<>(Arrays.asList( new PathSpec("foo"), new PathSpec("foo", "bar"), new PathSpec("foo", "bar", "baz"), new PathSpec("foo", "bar", "baz", "xyz"), new PathSpec("foo", "bar", "baz", "abc", "xyz") )); - final Collection negativePaths = new HashSet(Arrays.asList( + final Collection negativePaths = new HashSet<>(Arrays.asList( new PathSpec("xyz"), new PathSpec("foo", "baz"), new PathSpec("foo", "xyz"), @@ -118,19 +118,19 @@ public void testPositiveMultiPaths() )); // test false positive - final Set positiveResult = ProjectionUtil.getPresentPaths(filter, new HashSet(positivePaths)); + final Set positiveResult = ProjectionUtil.getPresentPaths(filter, new HashSet<>(positivePaths)); Assert.assertEquals(positiveResult, positivePaths); // test false negative - final Set negativeResult = ProjectionUtil.getPresentPaths(filter, new HashSet(negativePaths)); + final Set negativeResult = ProjectionUtil.getPresentPaths(filter, new HashSet<>(negativePaths)); Assert.assertTrue(negativeResult.isEmpty()); - final Set combinedPaths = new HashSet(positivePaths); + final Set combinedPaths = new HashSet<>(positivePaths); combinedPaths.addAll(negativePaths); // combine both to test internal ordering, overwrites, etc. final Set combinedResult = ProjectionUtil.getPresentPaths(filter, combinedPaths); - Assert.assertEquals(combinedResult, new HashSet(positivePaths)); + Assert.assertEquals(combinedResult, new HashSet<>(positivePaths)); for (PathSpec p : negativePaths) { @@ -144,28 +144,28 @@ public void testPositiveWithWildcardMultiPaths() final MaskTree filter = new MaskTree(); filter.addOperation(new PathSpec("foo", PathSpec.WILDCARD, "baz"), MaskOperation.POSITIVE_MASK_OP); - final Collection positivePaths = new HashSet(Arrays.asList( + final Collection positivePaths = new HashSet<>(Arrays.asList( new PathSpec("foo"), new PathSpec("foo", "bar"), new PathSpec("foo", "bar", "baz"), new PathSpec("foo", "bar", "baz", "xyz"), new PathSpec("foo", "bar", "baz", "abc", "xyz") )); - final Collection negativePaths = new HashSet(Arrays.asList( + final Collection negativePaths = new HashSet<>(Arrays.asList( new PathSpec("foo", "bar", "xyz") )); - final Set positiveResult = ProjectionUtil.getPresentPaths(filter, new HashSet(positivePaths)); + final Set positiveResult = ProjectionUtil.getPresentPaths(filter, new HashSet<>(positivePaths)); Assert.assertEquals(positiveResult, positivePaths); - final Set negativeResult = ProjectionUtil.getPresentPaths(filter, new HashSet(negativePaths)); + final Set negativeResult = ProjectionUtil.getPresentPaths(filter, new HashSet<>(negativePaths)); Assert.assertTrue(negativeResult.isEmpty()); - final Set combinedPaths = new HashSet(positivePaths); + final Set combinedPaths = new HashSet<>(positivePaths); combinedPaths.addAll(negativePaths); final Set combinedResult = ProjectionUtil.getPresentPaths(filter, combinedPaths); - Assert.assertEquals(combinedResult, new HashSet(positivePaths)); + Assert.assertEquals(combinedResult, new HashSet<>(positivePaths)); for (PathSpec p : negativePaths) { diff --git a/data-transform/src/test/java/com/linkedin/data/transform/patch/validator/TestPatchFilterValidator.java b/data-transform/src/test/java/com/linkedin/data/transform/patch/validator/TestPatchFilterValidator.java index 7f0b2599b0..5749741c86 100644 --- a/data-transform/src/test/java/com/linkedin/data/transform/patch/validator/TestPatchFilterValidator.java +++ b/data-transform/src/test/java/com/linkedin/data/transform/patch/validator/TestPatchFilterValidator.java @@ -48,7 +48,7 @@ public class TestPatchFilterValidator public class VisitedValidator implements Validator { - public List _visitedPaths = new ArrayList(); + public List _visitedPaths = new ArrayList<>(); public void validate(ValidatorContext ctx) { @@ -593,4 +593,3 @@ public void testPatchFilterValidator() throws IOException } } } - diff --git a/data/src/main/antlr/com/linkedin/data/grammar/Pdl.g4 b/data/src/main/antlr/com/linkedin/data/grammar/Pdl.g4 index a46b3f673c..286b312228 100644 --- a/data/src/main/antlr/com/linkedin/data/grammar/Pdl.g4 +++ b/data/src/main/antlr/com/linkedin/data/grammar/Pdl.g4 @@ -141,7 +141,7 @@ identifier returns [String value]: ID { // A full property name, made of property segments separated by dots. // Returns the list of property segments. propName returns [List path] -@init{$path = new ArrayList();} +@init{$path = new ArrayList<>();} : propSegment {$path.add($propSegment.value);} (DOT propSegment {$path.add($propSegment.value);})* ; diff --git a/data/src/main/java/com/linkedin/data/ByteString.java b/data/src/main/java/com/linkedin/data/ByteString.java index cdc0e25ea8..c28765308e 100644 --- a/data/src/main/java/com/linkedin/data/ByteString.java +++ b/data/src/main/java/com/linkedin/data/ByteString.java @@ -566,7 +566,7 @@ public void write(ProtoWriter writer) throws IOException */ public List decompose() { - final List decomposedList = new ArrayList(); + final List decomposedList = new ArrayList<>(); //Note that if this is the empty ByteString, there is still one byte array that exists. for (int i = 0; i < _byteArrays.getArraySize(); i++) @@ -898,7 +898,7 @@ public static class Builder public Builder() { - _chunks = new ArrayList(); + _chunks = new ArrayList<>(); } public Builder append(ByteString dataChunk) @@ -1749,4 +1749,4 @@ private void updateState() _bufferSize = array.getLength(); } } -} \ No newline at end of file +} diff --git a/data/src/main/java/com/linkedin/data/DataList.java b/data/src/main/java/com/linkedin/data/DataList.java index dd942ab3bd..9fe46bbf74 100644 --- a/data/src/main/java/com/linkedin/data/DataList.java +++ b/data/src/main/java/com/linkedin/data/DataList.java @@ -179,7 +179,7 @@ public void startInstrumentingAccess() _instrumented = true; if (_accessList == null) { - _accessList = new ArrayList(size()); + _accessList = new ArrayList<>(size()); } } diff --git a/data/src/main/java/com/linkedin/data/DataMap.java b/data/src/main/java/com/linkedin/data/DataMap.java index cf888deea9..4a70753336 100644 --- a/data/src/main/java/com/linkedin/data/DataMap.java +++ b/data/src/main/java/com/linkedin/data/DataMap.java @@ -345,7 +345,7 @@ public void startInstrumentingAccess() _instrumented = true; if (_accessMap == null) { - _accessMap = new HashMap(); + _accessMap = new HashMap<>(); } } diff --git a/data/src/main/java/com/linkedin/data/InstrumentationUtil.java b/data/src/main/java/com/linkedin/data/InstrumentationUtil.java index e97e158b8a..cd33c1e5b5 100644 --- a/data/src/main/java/com/linkedin/data/InstrumentationUtil.java +++ b/data/src/main/java/com/linkedin/data/InstrumentationUtil.java @@ -35,7 +35,7 @@ public static void emitInstrumentationData(StringBuilder key, Integer timesAccessed, Map> instrumentedData) { - Map attributeMap = new HashMap(2); + Map attributeMap = new HashMap<>(2); attributeMap.put(Instrumentable.VALUE, String.valueOf(object)); attributeMap.put(Instrumentable.TIMES_ACCESSED, timesAccessed); instrumentedData.put(key.toString(), attributeMap); diff --git a/data/src/main/java/com/linkedin/data/codec/AbstractJacksonDataCodec.java b/data/src/main/java/com/linkedin/data/codec/AbstractJacksonDataCodec.java index 94f99e151b..f746cfca20 100644 --- a/data/src/main/java/com/linkedin/data/codec/AbstractJacksonDataCodec.java +++ b/data/src/main/java/com/linkedin/data/codec/AbstractJacksonDataCodec.java @@ -425,7 +425,7 @@ private Map sortedLocationsMap() return null; } - TreeMap sortedMap = new TreeMap(); + TreeMap sortedMap = new TreeMap<>(); for (Map.Entry e : _locationMap.entrySet()) { sortedMap.put(e.getValue(), e.getKey()); diff --git a/data/src/main/java/com/linkedin/data/codec/BsonDataCodec.java b/data/src/main/java/com/linkedin/data/codec/BsonDataCodec.java index f6e37dc2d7..ab2ad1ade7 100644 --- a/data/src/main/java/com/linkedin/data/codec/BsonDataCodec.java +++ b/data/src/main/java/com/linkedin/data/codec/BsonDataCodec.java @@ -219,7 +219,7 @@ public DataList readList(InputStream in) throws IOException protected static class BsonTraverseCallback implements Data.TraverseCallback { private final BufferChain _buffer; - private final Deque _positionStack = new ArrayDeque(); + private final Deque _positionStack = new ArrayDeque<>(); private String _currentName = null; BsonTraverseCallback() diff --git a/data/src/main/java/com/linkedin/data/codec/BufferChain.java b/data/src/main/java/com/linkedin/data/codec/BufferChain.java index 0caf0d3231..3c0dfb985b 100644 --- a/data/src/main/java/com/linkedin/data/codec/BufferChain.java +++ b/data/src/main/java/com/linkedin/data/codec/BufferChain.java @@ -70,7 +70,7 @@ public class BufferChain private int _currentIndex; private ByteBuffer _currentBuffer; - private ArrayList _bufferList = new ArrayList(); + private ArrayList _bufferList = new ArrayList<>(); private int _bufferSize; private ByteOrder _order; private CharsetDecoder _decoder; @@ -636,7 +636,7 @@ private ArrayList accummulateByteBuffers(ArrayList buffe byteBuffer.order(_order); _currentBuffer.position(newPosition); if (bufferList == null) - bufferList = new ArrayList(); + bufferList = new ArrayList<>(); bufferList.add(byteBuffer); return bufferList; } diff --git a/data/src/main/java/com/linkedin/data/codec/PsonDataCodec.java b/data/src/main/java/com/linkedin/data/codec/PsonDataCodec.java index 87cea0d55e..fe3765a710 100644 --- a/data/src/main/java/com/linkedin/data/codec/PsonDataCodec.java +++ b/data/src/main/java/com/linkedin/data/codec/PsonDataCodec.java @@ -320,7 +320,7 @@ public String toString() protected class PsonSerializer implements Data.TraverseCallback { private final BufferChain _buffer; - private final HashMap _keyMap = new HashMap(200); + private final HashMap _keyMap = new HashMap<>(200); private int _keyIndex = 1; private final boolean _encodeStringLength = _options.getEncodeStringLength(); private final boolean _encodeCollectionCount = _options.getEncodeCollectionCount(); @@ -736,4 +736,3 @@ private String getStringWithLength(int length) throws IOException private int _expectedKeyIndex = 1; } } - diff --git a/data/src/main/java/com/linkedin/data/collections/CheckedList.java b/data/src/main/java/com/linkedin/data/collections/CheckedList.java index b9d97fc38c..39f9326705 100644 --- a/data/src/main/java/com/linkedin/data/collections/CheckedList.java +++ b/data/src/main/java/com/linkedin/data/collections/CheckedList.java @@ -52,7 +52,7 @@ public class CheckedList extends AbstractList implements CommonList, Cl public CheckedList() { _checker = null; - _list = new InternalList(); + _list = new InternalList<>(); } /** @@ -64,7 +64,7 @@ public CheckedList(List list) { _checker = null; checkAll(list); - _list = new InternalList(list); + _list = new InternalList<>(list); } /** @@ -75,7 +75,7 @@ public CheckedList(List list) public CheckedList(int initialCapacity) { _checker = null; - _list = new InternalList(initialCapacity); + _list = new InternalList<>(initialCapacity); } /** @@ -86,7 +86,7 @@ public CheckedList(int initialCapacity) public CheckedList(ListChecker checker) { _checker = checker; - _list = new InternalList(); + _list = new InternalList<>(); } /** @@ -100,7 +100,7 @@ public CheckedList(List list, ListChecker checker) { _checker = checker; checkAll(list); - _list = new InternalList(list); + _list = new InternalList<>(list); } /** @@ -113,7 +113,7 @@ public CheckedList(List list, ListChecker checker) public CheckedList(int initialCapacity, ListChecker checker) { _checker = checker; - _list = new InternalList(initialCapacity); + _list = new InternalList<>(initialCapacity); } @Override diff --git a/data/src/main/java/com/linkedin/data/collections/CowList.java b/data/src/main/java/com/linkedin/data/collections/CowList.java index 06f44a8b38..88951d7737 100644 --- a/data/src/main/java/com/linkedin/data/collections/CowList.java +++ b/data/src/main/java/com/linkedin/data/collections/CowList.java @@ -63,7 +63,7 @@ public class CowList extends AbstractList implements CommonList, Clonea public CowList() { _checker = null; - _refCounted = new RefCounted>(new InternalList()); + _refCounted = new RefCounted<>(new InternalList<>()); } /** @@ -75,7 +75,7 @@ public CowList(List list) { _checker = null; checkAll(list); - _refCounted = new RefCounted>(new InternalList(list)); + _refCounted = new RefCounted<>(new InternalList<>(list)); } /** @@ -86,7 +86,7 @@ public CowList(List list) public CowList(int initialCapacity) { _checker = null; - _refCounted = new RefCounted>(new InternalList(initialCapacity)); + _refCounted = new RefCounted<>(new InternalList<>(initialCapacity)); } /** @@ -97,7 +97,7 @@ public CowList(int initialCapacity) public CowList(ListChecker checker) { _checker = checker; - _refCounted = new RefCounted>(new InternalList()); + _refCounted = new RefCounted<>(new InternalList<>()); } /** @@ -111,7 +111,7 @@ public CowList(List list, ListChecker checker) { _checker = checker; checkAll(list); - _refCounted = new RefCounted>(new InternalList(list)); + _refCounted = new RefCounted<>(new InternalList<>(list)); } /** @@ -123,7 +123,7 @@ public CowList(List list, ListChecker checker) public CowList(int initialCapacity, ListChecker checker) { _checker = checker; - _refCounted = new RefCounted>(new InternalList(initialCapacity)); + _refCounted = new RefCounted<>(new InternalList<>(initialCapacity)); } @Override @@ -417,4 +417,4 @@ public void removeRange(int fromIndex, int toIndex) protected ListChecker _checker; private boolean _readOnly = false; private RefCounted> _refCounted; -} \ No newline at end of file +} diff --git a/data/src/main/java/com/linkedin/data/collections/CowMap.java b/data/src/main/java/com/linkedin/data/collections/CowMap.java index fe6fa1baa2..bcf9e1b86b 100644 --- a/data/src/main/java/com/linkedin/data/collections/CowMap.java +++ b/data/src/main/java/com/linkedin/data/collections/CowMap.java @@ -76,7 +76,7 @@ public class CowMap implements CommonMap, Cloneable public CowMap() { _checker = null; - _refCounted = new RefCounted>(new HashMap()); + _refCounted = new RefCounted<>(new HashMap<>()); } /** @@ -88,7 +88,7 @@ public CowMap(Map map) { _checker = null; checkAll(map); - _refCounted = new RefCounted>(new HashMap(map)); + _refCounted = new RefCounted<>(new HashMap<>(map)); } /** @@ -101,7 +101,7 @@ public CowMap(Map map) public CowMap(int initialCapacity) { _checker = null; - _refCounted = new RefCounted>(new HashMap(initialCapacity)); + _refCounted = new RefCounted<>(new HashMap<>(initialCapacity)); } /** @@ -115,7 +115,7 @@ public CowMap(int initialCapacity) public CowMap(int initialCapacity, float loadFactor) { _checker = null; - _refCounted = new RefCounted>(new HashMap(initialCapacity, loadFactor)); + _refCounted = new RefCounted<>(new HashMap<>(initialCapacity, loadFactor)); } /** @@ -126,7 +126,7 @@ public CowMap(int initialCapacity, float loadFactor) public CowMap(MapChecker checker) { _checker = checker; - _refCounted = new RefCounted>(new HashMap()); + _refCounted = new RefCounted<>(new HashMap<>()); } /** @@ -142,7 +142,7 @@ public CowMap(Map map, MapChecker checker) { _checker = checker; checkAll(map); - _refCounted = new RefCounted>(new HashMap(map)); + _refCounted = new RefCounted<>(new HashMap<>(map)); } /** @@ -157,7 +157,7 @@ public CowMap(Map map, MapChecker checker) public CowMap(int initialCapacity, MapChecker checker) { _checker = checker; - _refCounted = new RefCounted>(new HashMap(initialCapacity)); + _refCounted = new RefCounted<>(new HashMap<>(initialCapacity)); } /** @@ -172,7 +172,7 @@ public CowMap(int initialCapacity, MapChecker checker) public CowMap(int initialCapacity, float loadFactor, MapChecker checker) { _checker = checker; - _refCounted = new RefCounted>(new HashMap(initialCapacity, loadFactor)); + _refCounted = new RefCounted<>(new HashMap<>(initialCapacity, loadFactor)); } @Override diff --git a/data/src/main/java/com/linkedin/data/collections/CowSet.java b/data/src/main/java/com/linkedin/data/collections/CowSet.java index 0947901c1f..8252186e83 100644 --- a/data/src/main/java/com/linkedin/data/collections/CowSet.java +++ b/data/src/main/java/com/linkedin/data/collections/CowSet.java @@ -50,7 +50,7 @@ public class CowSet extends AbstractSet implements CommonSet */ public CowSet() { - _map = new CowMap(); + _map = new CowMap<>(); } private CowSet(CowMap map) @@ -61,7 +61,7 @@ private CowSet(CowMap map) @Override public Object clone() throws CloneNotSupportedException { - return new CowSet(_map.clone()); + return new CowSet<>(_map.clone()); } @Override diff --git a/data/src/main/java/com/linkedin/data/collections/CowUtil.java b/data/src/main/java/com/linkedin/data/collections/CowUtil.java index 6def97989f..6695462286 100644 --- a/data/src/main/java/com/linkedin/data/collections/CowUtil.java +++ b/data/src/main/java/com/linkedin/data/collections/CowUtil.java @@ -24,9 +24,9 @@ */ public class CowUtil { - private static final CowMap EMPTY_MAP = new CowMap(); - private static final CowSet EMPTY_SET = new CowSet(); - private static final CowList EMPTY_LIST = new CowList(); + private static final CowMap EMPTY_MAP = new CowMap<>(); + private static final CowSet EMPTY_SET = new CowSet<>(); + private static final CowList EMPTY_LIST = new CowList<>(); static { diff --git a/data/src/main/java/com/linkedin/data/element/DataElementUtil.java b/data/src/main/java/com/linkedin/data/element/DataElementUtil.java index e4267e0579..82448e6993 100644 --- a/data/src/main/java/com/linkedin/data/element/DataElementUtil.java +++ b/data/src/main/java/com/linkedin/data/element/DataElementUtil.java @@ -231,7 +231,7 @@ static List pathToList(String path, char separator) throws IllegalArgume return Collections.emptyList(); } - List list = new ArrayList(path.length() / 4); + List list = new ArrayList<>(path.length() / 4); int len = path.length(); int index = 0; if (path.charAt(index) != separator) @@ -255,4 +255,4 @@ static List pathToList(String path, char separator) throws IllegalArgume } return list; } -} \ No newline at end of file +} diff --git a/data/src/main/java/com/linkedin/data/it/Builder.java b/data/src/main/java/com/linkedin/data/it/Builder.java index 694edf7cc3..772a615c91 100644 --- a/data/src/main/java/com/linkedin/data/it/Builder.java +++ b/data/src/main/java/com/linkedin/data/it/Builder.java @@ -134,7 +134,7 @@ public static Builder create(DataTemplate template, IterationO { return create(template.data(), template.schema(), order); } - + protected Builder(DataElement element, IterationOrder order) { @@ -147,11 +147,11 @@ public Builder filterBy(Predicate predicate) _predicates.add(predicate); return this; } - + /** * Obtains a {@link DataIterator} from the {@link Builder} and accumulates Data objects returned by the iterator into the provided collection. * This method mutates the provided collection. - * + * * @param accumulator provides the collection that the accumulated data objects are added to. * @return the passed in collection, with the Data objects returned by the iterator added into it. * @see ValueAccumulator @@ -160,10 +160,10 @@ public Collection accumulateValues(Collection accumulator) { return ValueAccumulator.accumulateValues(dataIterator(), accumulator); } - + /** * Obtains a {@link DataIterator} from the {@link Builder} and accumulates Data objects returned by the iterator as a collection. - * + * * @return the Data objects accumulated from the {@link DataIterator}. * @see ValueAccumulator */ @@ -174,7 +174,7 @@ public Collection accumulateValues() /** * Obtains a {@link DataIterator} from the {@link Builder} and counts the number of {Link DataElement}s returned by the iterator. - * + * * @return the count of Data objects. * @see Counter */ @@ -200,7 +200,7 @@ public Object remove() * Obtains a {@link DataIterator} from the {@link Builder} and transforms the Data objects returned by the iterator. * This method mutates the Data object and it's descendants. * This method does not change the start Data object referenced by the Builder. - * + * * @param transform provides the transformation that will be used to replace Data objects. * @return the replacement if the root object was replaced by a transformation, else the root object with the transformations applied. * @see Transformer @@ -209,12 +209,12 @@ public Object transform(Transform transform) { return Transformer.transform(_element.getValue(), dataIterator(), transform); } - + /** * Obtains a {@link DataIterator} from the {@link Builder} and replaces the Data objects returned by the iterator. * This method mutates the Data object and it's descendants. * This method does not change the start Data object referenced by the Builder. - * + * * @param value provides the object that Data objects are replaced with. * @return the replacement if the root object was replaced, else the root object with the replacements applied. * @see Transformer @@ -240,7 +240,7 @@ public void iterate(Callback callback) } } - private List _predicates = new ArrayList(); + private List _predicates = new ArrayList<>(); private DataElement _element; private IterationOrder _order; } diff --git a/data/src/main/java/com/linkedin/data/it/ObjectIterator.java b/data/src/main/java/com/linkedin/data/it/ObjectIterator.java index 52950df32d..a6047ab6b1 100644 --- a/data/src/main/java/com/linkedin/data/it/ObjectIterator.java +++ b/data/src/main/java/com/linkedin/data/it/ObjectIterator.java @@ -334,7 +334,7 @@ private DataSchema currentSchema() } private final DataElement _startElement; - private final Deque _stack = new ArrayDeque(); + private final Deque _stack = new ArrayDeque<>(); private boolean _first = true; private DataElement _current = null; diff --git a/data/src/main/java/com/linkedin/data/it/PathMatchesPatternPredicate.java b/data/src/main/java/com/linkedin/data/it/PathMatchesPatternPredicate.java index ab4ba7ecc1..b7f98824fe 100644 --- a/data/src/main/java/com/linkedin/data/it/PathMatchesPatternPredicate.java +++ b/data/src/main/java/com/linkedin/data/it/PathMatchesPatternPredicate.java @@ -97,12 +97,12 @@ public PathMatchesPatternPredicate(Object... patterns) throws IllegalArgumentExc _patterns = patterns; generateComponentMatches(); } - + public PathMatchesPatternPredicate(PathSpec pathSpec) throws IllegalArgumentException { this(pathSpecToPathMatchPattern(pathSpec)); } - + private static Object[] pathSpecToPathMatchPattern(PathSpec pathSpec) { List pathComponents = pathSpec.getPathComponents(); @@ -314,7 +314,7 @@ private void dump(PrintStream out) */ private final Object[] _patterns; - private final List _matches = new ArrayList(); + private final List _matches = new ArrayList<>(); /** * A {@link Match} holds either a name that represents an exact match of a path component or diff --git a/data/src/main/java/com/linkedin/data/it/Remover.java b/data/src/main/java/com/linkedin/data/it/Remover.java index 9349f2cc75..8cc1849124 100644 --- a/data/src/main/java/com/linkedin/data/it/Remover.java +++ b/data/src/main/java/com/linkedin/data/it/Remover.java @@ -90,7 +90,7 @@ public static Object remove(Object root, DataIterator it) // construct the list of Data objects to remove // don't remove in place because iterator behavior with removals while iterating is undefined - ArrayList removeList = new ArrayList(); + ArrayList removeList = new ArrayList<>(); while ((element = it.next()) != null) { ToRemove toRemove = new ToRemove(element); diff --git a/data/src/main/java/com/linkedin/data/it/Transformer.java b/data/src/main/java/com/linkedin/data/it/Transformer.java index e93b9a026f..47b98f652b 100644 --- a/data/src/main/java/com/linkedin/data/it/Transformer.java +++ b/data/src/main/java/com/linkedin/data/it/Transformer.java @@ -26,7 +26,7 @@ /** * Transforms Data objects returned by a {@link DataIterator}. - * + * * @author "Joe Betz" */ public class Transformer @@ -54,7 +54,7 @@ private boolean isRoot() private void transform(Transform transform) { Object replacementValue = transform.apply(_value); - + Class nameClass = _name.getClass(); Class parentClass = _parent.getClass(); if (nameClass == String.class) @@ -85,7 +85,7 @@ else if (nameClass == Integer.class) /** * Transforms the Data objects returned by the {@link DataIterator}. * This method mutates the Data object and it's descendants. - * + * * @param root provides the root of the Data objects that will be transformed. * @param it provides the iterator of Data objects to be transformed. * @param transform used to provide a replacement value. @@ -94,9 +94,9 @@ else if (nameClass == Integer.class) public static Object transform(Object root, DataIterator it, Transform transform) { DataElement element; - + // don't transform in place because iterator behavior with replacements (which behave like a remove and an add) while iterating is undefined - ArrayList transformList = new ArrayList(); + ArrayList transformList = new ArrayList<>(); while ((element = it.next()) != null) { transformList.add(new ToTransform(element)); @@ -115,11 +115,11 @@ public static Object transform(Object root, DataIterator it, Transform" */ public class ValueAccumulator @@ -31,7 +31,7 @@ public class ValueAccumulator /** * Accumulates the Data objects returned by the {@link DataIterator} into the provided collection. * This method mutates the provided collection. - * + * * @param it provides the iterator of Data objects to be accumulated. * @param accumulator provides the collection that the accumulated Data objects are added to. * @return the passed in collection, mutated to include Data objects. @@ -44,15 +44,15 @@ public static Collection accumulateValues(DataIterator it, Collection accumulateValues(DataIterator it) { - return accumulateValues(it, new ArrayList()); + return accumulateValues(it, new ArrayList<>()); } } diff --git a/data/src/main/java/com/linkedin/data/schema/AbstractSchemaParser.java b/data/src/main/java/com/linkedin/data/schema/AbstractSchemaParser.java index 6f6fffab30..eae3a45452 100644 --- a/data/src/main/java/com/linkedin/data/schema/AbstractSchemaParser.java +++ b/data/src/main/java/com/linkedin/data/schema/AbstractSchemaParser.java @@ -722,7 +722,7 @@ protected List getStringList(DataMap map, String key, boolean required) List list = null; if (dataList != null) { - list = new ArrayList(); + list = new ArrayList<>(); for (Object o : dataList) { if (o instanceof String) @@ -748,7 +748,7 @@ protected List getStringList(DataMap map, String key, boolean required) protected Map extractProperties(DataMap map, Set reserved) { // Use TreeMap to keep properties in sorted order. - Map props = new TreeMap(); + Map props = new TreeMap<>(); for (Map.Entry e : map.entrySet()) { String key = e.getKey(); @@ -978,8 +978,8 @@ protected void addTopLevelSchema(DataSchema schema) { */ private String _currentPackage = ""; - private final Map _dataLocationMap = new IdentityHashMap(); - private final List _topLevelDataSchemas = new ArrayList(); + private final Map _dataLocationMap = new IdentityHashMap<>(); + private final List _topLevelDataSchemas = new ArrayList<>(); private final DataSchemaResolver _resolver; public static final ValidationOptions getDefaultSchemaParserValidationOptions() diff --git a/data/src/main/java/com/linkedin/data/schema/DataSchemaConstants.java b/data/src/main/java/com/linkedin/data/schema/DataSchemaConstants.java index 8166aa8983..f61796cf48 100644 --- a/data/src/main/java/com/linkedin/data/schema/DataSchemaConstants.java +++ b/data/src/main/java/com/linkedin/data/schema/DataSchemaConstants.java @@ -98,15 +98,15 @@ public class DataSchemaConstants DataSchema.Type.TYPEREF); NAMED_DATA_SCHEMA_TYPE_SET = Collections.unmodifiableSet(namedSet); - Set schemaKeys = new HashSet(Arrays.asList(ALIASES_KEY, DOC_KEY, FIELDS_KEY, INCLUDE_KEY, ITEMS_KEY, NAME_KEY, + Set schemaKeys = new HashSet<>(Arrays.asList(ALIASES_KEY, DOC_KEY, FIELDS_KEY, INCLUDE_KEY, ITEMS_KEY, NAME_KEY, NAMESPACE_KEY, PACKAGE_KEY, REF_KEY, SIZE_KEY, SYMBOLS_KEY, SYMBOL_DOCS_KEY, TYPE_KEY, VALUES_KEY)); SCHEMA_KEYS = Collections.unmodifiableSet(schemaKeys); - Set fieldKeys = new HashSet(Arrays.asList(ALIASES_KEY, DEFAULT_KEY, DOC_KEY, NAME_KEY, OPTIONAL_KEY, ORDER_KEY, TYPE_KEY)); + Set fieldKeys = new HashSet<>(Arrays.asList(ALIASES_KEY, DEFAULT_KEY, DOC_KEY, NAME_KEY, OPTIONAL_KEY, ORDER_KEY, TYPE_KEY)); FIELD_KEYS = Collections.unmodifiableSet(fieldKeys); - Set memberKeys = new HashSet(Arrays.asList(DOC_KEY, ALIAS_KEY, TYPE_KEY)); + Set memberKeys = new HashSet<>(Arrays.asList(DOC_KEY, ALIAS_KEY, TYPE_KEY)); MEMBER_KEYS = Collections.unmodifiableSet(memberKeys); Set restrictedUnionAliases = new HashSet<>(Arrays.asList(DISCRIMINATOR_FIELD)); diff --git a/data/src/main/java/com/linkedin/data/schema/DataSchemaTraverse.java b/data/src/main/java/com/linkedin/data/schema/DataSchemaTraverse.java index 1a51188cc9..a30babf2d3 100644 --- a/data/src/main/java/com/linkedin/data/schema/DataSchemaTraverse.java +++ b/data/src/main/java/com/linkedin/data/schema/DataSchemaTraverse.java @@ -44,8 +44,8 @@ public static interface Callback void callback(List path, DataSchema schema); } - private final IdentityHashMap _seen = new IdentityHashMap(); - private final ArrayList _path = new ArrayList(); + private final IdentityHashMap _seen = new IdentityHashMap<>(); + private final ArrayList _path = new ArrayList<>(); private final Order _order; private Map _callbacks = new HashMap<>(); diff --git a/data/src/main/java/com/linkedin/data/schema/DataSchemaUtil.java b/data/src/main/java/com/linkedin/data/schema/DataSchemaUtil.java index d8f62dba83..df65a791eb 100644 --- a/data/src/main/java/com/linkedin/data/schema/DataSchemaUtil.java +++ b/data/src/main/java/com/linkedin/data/schema/DataSchemaUtil.java @@ -138,7 +138,7 @@ private DataSchemaUtil() {} static { - _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP = new HashMap(); + _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP = new HashMap<>(); _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchemaConstants.NULL_TYPE, DataSchemaConstants.NULL_DATA_SCHEMA); _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchemaConstants.BOOLEAN_TYPE, DataSchemaConstants.BOOLEAN_DATA_SCHEMA); _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchemaConstants.INTEGER_TYPE, DataSchemaConstants.INTEGER_DATA_SCHEMA); @@ -148,7 +148,7 @@ private DataSchemaUtil() {} _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchemaConstants.BYTES_TYPE, DataSchemaConstants.BYTES_DATA_SCHEMA); _TYPE_STRING_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchemaConstants.STRING_TYPE, DataSchemaConstants.STRING_DATA_SCHEMA); - _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE = new HashMap, PrimitiveDataSchema>(32); + _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE = new HashMap<>(32); _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE.put(Integer.class, DataSchemaConstants.INTEGER_DATA_SCHEMA); _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE.put(int.class, DataSchemaConstants.INTEGER_DATA_SCHEMA); _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE.put(Long.class, DataSchemaConstants.LONG_DATA_SCHEMA); @@ -164,7 +164,7 @@ private DataSchemaUtil() {} _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE.put(String.class, DataSchemaConstants.STRING_DATA_SCHEMA); _JAVA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_TYPE.put(ByteString.class, DataSchemaConstants.BYTES_DATA_SCHEMA); - _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP = new IdentityHashMap(); + _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP = new IdentityHashMap<>(); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchema.Type.NULL, DataSchemaConstants.NULL_DATA_SCHEMA); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchema.Type.BOOLEAN, DataSchemaConstants.BOOLEAN_DATA_SCHEMA); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchema.Type.INT, DataSchemaConstants.INTEGER_DATA_SCHEMA); @@ -174,7 +174,7 @@ private DataSchemaUtil() {} _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchema.Type.BYTES, DataSchemaConstants.BYTES_DATA_SCHEMA); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_DATA_SCHEMA_MAP.put(DataSchema.Type.STRING, DataSchemaConstants.STRING_DATA_SCHEMA); - _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP = new IdentityHashMap>(); + _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP = new IdentityHashMap<>(); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP.put(DataSchema.Type.INT, Integer.class); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP.put(DataSchema.Type.LONG, Long.class); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP.put(DataSchema.Type.FLOAT, Float.class); @@ -183,7 +183,7 @@ private DataSchemaUtil() {} _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP.put(DataSchema.Type.STRING, String.class); _DATA_SCHEMA_TYPE_TO_PRIMITIVE_JAVA_TYPE_MAP.put(DataSchema.Type.BYTES, ByteString.class); - _TYPE_STRING_TO_COMPLEX_DATA_SCHEMA_TYPE_MAP = new HashMap(); + _TYPE_STRING_TO_COMPLEX_DATA_SCHEMA_TYPE_MAP = new HashMap<>(); _TYPE_STRING_TO_COMPLEX_DATA_SCHEMA_TYPE_MAP.put(DataSchemaConstants.ARRAY_TYPE, DataSchema.Type.ARRAY); _TYPE_STRING_TO_COMPLEX_DATA_SCHEMA_TYPE_MAP.put(DataSchemaConstants.ENUM_TYPE, DataSchema.Type.ENUM); _TYPE_STRING_TO_COMPLEX_DATA_SCHEMA_TYPE_MAP.put(DataSchemaConstants.ERROR_TYPE, DataSchema.Type.RECORD); diff --git a/data/src/main/java/com/linkedin/data/schema/EnumDataSchema.java b/data/src/main/java/com/linkedin/data/schema/EnumDataSchema.java index 2bd1cc6823..9f873b0719 100644 --- a/data/src/main/java/com/linkedin/data/schema/EnumDataSchema.java +++ b/data/src/main/java/com/linkedin/data/schema/EnumDataSchema.java @@ -52,7 +52,7 @@ public boolean setSymbols(List symbols, StringBuilder errorMessageBuilde boolean ok = true; if (symbols != null) { - Map map = new HashMap(); + Map map = new HashMap<>(); int index = 0; for (String symbol : symbols) { @@ -88,7 +88,7 @@ public boolean setSymbolDocs(Map symbolDocs, StringBuilder error boolean ok = true; if (symbolDocs != null) { - Map symbolDocsMap = new LinkedHashMap(); + Map symbolDocsMap = new LinkedHashMap<>(); for (String symbol : _symbols) { if (symbolDocs.containsKey(symbol)) diff --git a/data/src/main/java/com/linkedin/data/schema/PathSpec.java b/data/src/main/java/com/linkedin/data/schema/PathSpec.java index cf2c77b839..d3d33f34aa 100644 --- a/data/src/main/java/com/linkedin/data/schema/PathSpec.java +++ b/data/src/main/java/com/linkedin/data/schema/PathSpec.java @@ -59,7 +59,7 @@ public class PathSpec */ public PathSpec(List parentPath, String segment) { - _path = new ArrayList(parentPath.size()+1); + _path = new ArrayList<>(parentPath.size()+1); _path.addAll(parentPath); _path.add(segment); } @@ -71,7 +71,7 @@ public PathSpec(List parentPath, String segment) */ public PathSpec(String segment) { - _path = new ArrayList(1); + _path = new ArrayList<>(1); _path.add(segment); } @@ -82,7 +82,7 @@ public PathSpec(String segment) */ public PathSpec(String... segments) { - _path = new ArrayList(Arrays.asList(segments)); + _path = new ArrayList<>(Arrays.asList(segments)); } /** diff --git a/data/src/main/java/com/linkedin/data/schema/RecordDataSchema.java b/data/src/main/java/com/linkedin/data/schema/RecordDataSchema.java index 15e46b3904..ce1f540989 100644 --- a/data/src/main/java/com/linkedin/data/schema/RecordDataSchema.java +++ b/data/src/main/java/com/linkedin/data/schema/RecordDataSchema.java @@ -510,7 +510,7 @@ public boolean setFields(List fields, StringBuilder errorMessageBuilder) { boolean ok = true; _fields = Collections.unmodifiableList(fields); - Map map = new HashMap(); + Map map = new HashMap<>(); int index = 0; for (Field field : _fields) { @@ -622,7 +622,7 @@ public boolean equals(Object object) { if (startTracking) { - trackingMap = new IdentityHashMap(); + trackingMap = new IdentityHashMap<>(); _equalsTracking.set(trackingMap); } else @@ -662,7 +662,7 @@ public int hashCode() { if (startTracking) { - trackingMap = new IdentityHashMap(); + trackingMap = new IdentityHashMap<>(); _hashCodeTracking.set(trackingMap); } if (trackingMap.containsKey(this)) diff --git a/data/src/main/java/com/linkedin/data/schema/SchemaParser.java b/data/src/main/java/com/linkedin/data/schema/SchemaParser.java index 04c3e2cafc..b2f4918ee2 100644 --- a/data/src/main/java/com/linkedin/data/schema/SchemaParser.java +++ b/data/src/main/java/com/linkedin/data/schema/SchemaParser.java @@ -198,7 +198,7 @@ else if (object instanceof DataMap) */ public List parseFields(RecordDataSchema recordSchema, DataList list) { - List fields = new ArrayList(); + List fields = new ArrayList<>(); for (Object o : list) { boolean ok = true; @@ -404,7 +404,7 @@ protected DataSchema dataMapToDataSchema(DataMap map) try { bindNameToSchema(name, aliasNames, recordSchema); - List fields = new ArrayList(); + List fields = new ArrayList<>(); DataList includeList = getDataList(map, INCLUDE_KEY, false); DataList fieldsList = getDataList(map, FIELDS_KEY, true); @@ -725,8 +725,8 @@ private boolean fieldsBeforeIncludeWithoutLocation(DataList includeList, DataLis private class DefinedAndReferencedNames { private final StringBuilder _stringBuilder = new StringBuilder(); - private final Set _defines = new HashSet(); - private final Set _references = new HashSet(); + private final Set _defines = new HashSet<>(); + private final Set _references = new HashSet<>(); /** * Parse list of schemas for defined and referenced names. @@ -921,7 +921,7 @@ protected List getAliases(DataMap map) List aliasNames = null; if (aliases != null) { - aliasNames = new ArrayList(aliases.size()); + aliasNames = new ArrayList<>(aliases.size()); for (String alias : aliases) { Name name = null; diff --git a/data/src/main/java/com/linkedin/data/schema/SchemaToJsonEncoder.java b/data/src/main/java/com/linkedin/data/schema/SchemaToJsonEncoder.java index 83aa777294..aa205a6f56 100644 --- a/data/src/main/java/com/linkedin/data/schema/SchemaToJsonEncoder.java +++ b/data/src/main/java/com/linkedin/data/schema/SchemaToJsonEncoder.java @@ -284,7 +284,7 @@ protected void encodeNamed(NamedDataSchema schema, TypeRepresentation representa } encodeProperties(schema); - List aliases = new ArrayList(); + List aliases = new ArrayList<>(); for (Name name : schema.getAliases()) { aliases.add(name.getFullName()); diff --git a/data/src/main/java/com/linkedin/data/schema/annotation/SchemaAnnotationHandler.java b/data/src/main/java/com/linkedin/data/schema/annotation/SchemaAnnotationHandler.java index 2ed32c2c1f..b363da2676 100644 --- a/data/src/main/java/com/linkedin/data/schema/annotation/SchemaAnnotationHandler.java +++ b/data/src/main/java/com/linkedin/data/schema/annotation/SchemaAnnotationHandler.java @@ -245,7 +245,7 @@ class AnnotationCompatibilityResult implements CompatibilityResult public AnnotationCompatibilityResult() { - _messages = new MessageList(); + _messages = new MessageList<>(); } public void addMessage(CompatibilityMessage message) diff --git a/data/src/main/java/com/linkedin/data/schema/compatibility/CompatibilityChecker.java b/data/src/main/java/com/linkedin/data/schema/compatibility/CompatibilityChecker.java index ac1d990679..8e2f0356c2 100644 --- a/data/src/main/java/com/linkedin/data/schema/compatibility/CompatibilityChecker.java +++ b/data/src/main/java/com/linkedin/data/schema/compatibility/CompatibilityChecker.java @@ -77,8 +77,8 @@ public int hashCode() private final DataSchema _newer; } - private final ArrayDeque _path = new ArrayDeque(); - private final HashSet _checked = new HashSet(); + private final ArrayDeque _path = new ArrayDeque<>(); + private final HashSet _checked = new HashSet<>(); private Result _result; private CompatibilityOptions _options; @@ -293,18 +293,18 @@ private void checkRecord(RecordDataSchema older, RecordDataSchema newer) { checkName(older, newer); - List commonFields = new ArrayList(newer.getFields().size()); - List newerRequiredAdded = new CheckerArrayList(); + List commonFields = new ArrayList<>(newer.getFields().size()); + List newerRequiredAdded = new CheckerArrayList<>(); List newerRequiredWithDefaultAdded = new CheckerArrayList<>(); - List newerOptionalAdded = new CheckerArrayList(); - List requiredToOptional = new CheckerArrayList(); - List requiredWithDefaultToOptional = new CheckerArrayList(); - List optionalToRequired = new CheckerArrayList(); - List optionalToRequiredWithDefault = new CheckerArrayList(); - List newerRequiredRemoved = new CheckerArrayList(); - List newerOptionalRemoved = new CheckerArrayList(); - List requiredWithDefaultToRequired = new CheckerArrayList(); - List requiredToRequiredWithDefault = new CheckerArrayList(); + List newerOptionalAdded = new CheckerArrayList<>(); + List requiredToOptional = new CheckerArrayList<>(); + List requiredWithDefaultToOptional = new CheckerArrayList<>(); + List optionalToRequired = new CheckerArrayList<>(); + List optionalToRequiredWithDefault = new CheckerArrayList<>(); + List newerRequiredRemoved = new CheckerArrayList<>(); + List newerOptionalRemoved = new CheckerArrayList<>(); + List requiredWithDefaultToRequired = new CheckerArrayList<>(); + List requiredToRequiredWithDefault = new CheckerArrayList<>(); for (RecordDataSchema.Field newerField : newer.getFields()) { @@ -497,8 +497,8 @@ private void checkUnion(UnionDataSchema older, UnionDataSchema newer) // using list to preserve union member order List commonMembers = new CheckerArrayList<>(newer.getMembers().size()); - List newerAdded = new CheckerArrayList(); - List olderAdded = new CheckerArrayList(); + List newerAdded = new CheckerArrayList<>(); + List olderAdded = new CheckerArrayList<>(); computeAddedUnionMembers(older, newer, newerAdded, commonMembers); computeAddedUnionMembers(newer, older, olderAdded, null); @@ -545,10 +545,10 @@ private void checkEnum(EnumDataSchema older, EnumDataSchema newer) _path.addLast(DataSchemaConstants.SYMBOLS_KEY); // using list to preserve symbol order - List newerOnlySymbols = new CheckerArrayList(newer.getSymbols()); + List newerOnlySymbols = new CheckerArrayList<>(newer.getSymbols()); newerOnlySymbols.removeAll(older.getSymbols()); - List olderOnlySymbols = new CheckerArrayList(older.getSymbols()); + List olderOnlySymbols = new CheckerArrayList<>(older.getSymbols()); olderOnlySymbols.removeAll(newer.getSymbols()); if (newerOnlySymbols.isEmpty() == false) @@ -660,7 +660,7 @@ private static class Result implements CompatibilityResult { private Result() { - _messages = new MessageList(); + _messages = new MessageList<>(); } @Override diff --git a/data/src/main/java/com/linkedin/data/schema/generator/AbstractGenerator.java b/data/src/main/java/com/linkedin/data/schema/generator/AbstractGenerator.java index 1239cbdc0e..5b22dec7ef 100644 --- a/data/src/main/java/com/linkedin/data/schema/generator/AbstractGenerator.java +++ b/data/src/main/java/com/linkedin/data/schema/generator/AbstractGenerator.java @@ -110,7 +110,7 @@ protected List parseSources(String sources[]) throws IOException { try { - List sourceFiles = new ArrayList(); + List sourceFiles = new ArrayList<>(); for (String source : sources) { diff --git a/data/src/main/java/com/linkedin/data/schema/generator/DefaultSampleDataCallback.java b/data/src/main/java/com/linkedin/data/schema/generator/DefaultSampleDataCallback.java index d807501aee..592e21b05a 100644 --- a/data/src/main/java/com/linkedin/data/schema/generator/DefaultSampleDataCallback.java +++ b/data/src/main/java/com/linkedin/data/schema/generator/DefaultSampleDataCallback.java @@ -145,7 +145,7 @@ public String getEnum(String fieldName, EnumDataSchema enumDataSchema) private DefaultSampleDataCallback() { - _stringPool = new HashMap(); + _stringPool = new HashMap<>(); _stringPool.put("url|link", new String[] {"http://www.example.com", "http://rest.li"}); _stringPool.put("name", new String[] {"John", "Doe"}); _stringPool.put("email|emailAddress|email_address", new String[] {"foo@example.com", "bar@rest.li"}); @@ -174,7 +174,7 @@ private void compilePatterns(Set fieldNameRegexs) public static final SampleDataCallback INSTANCE = new DefaultSampleDataCallback(); private static final Random _random = new Random(); - private final Map _compiledPatterns = new HashMap(); + private final Map _compiledPatterns = new HashMap<>(); private final Map _stringPool; private final String[] _defaultStrings; } diff --git a/data/src/main/java/com/linkedin/data/schema/generator/SchemaSampleDataGenerator.java b/data/src/main/java/com/linkedin/data/schema/generator/SchemaSampleDataGenerator.java index fb039db2ea..64518cac3a 100644 --- a/data/src/main/java/com/linkedin/data/schema/generator/SchemaSampleDataGenerator.java +++ b/data/src/main/java/com/linkedin/data/schema/generator/SchemaSampleDataGenerator.java @@ -144,7 +144,7 @@ public void setCallback(SampleDataCallback pool) private static class ParentSchemas { - private final Map counts = new HashMap(); + private final Map counts = new HashMap<>(); public void incrementReferences(DataSchema schema) { Integer count = counts.get(schema); diff --git a/data/src/main/java/com/linkedin/data/schema/grammar/PdlSchemaParser.java b/data/src/main/java/com/linkedin/data/schema/grammar/PdlSchemaParser.java index 5c4356d994..5fb69a96ad 100644 --- a/data/src/main/java/com/linkedin/data/schema/grammar/PdlSchemaParser.java +++ b/data/src/main/java/com/linkedin/data/schema/grammar/PdlSchemaParser.java @@ -720,7 +720,7 @@ private MapDataSchema parseMap(MapDeclarationContext map) throws ParseException TypeAssignmentContext keyType = map.typeParams.key; TypeAssignmentContext valueType = map.typeParams.value; MapDataSchema schema = new MapDataSchema(toDataSchema(valueType)); - Map propsToAdd = new HashMap(); + Map propsToAdd = new HashMap<>(); if (keyType.typeReference() != null) { diff --git a/data/src/main/java/com/linkedin/data/schema/resolver/AbstractDataSchemaResolver.java b/data/src/main/java/com/linkedin/data/schema/resolver/AbstractDataSchemaResolver.java index 8abc5faa45..31c61981ee 100644 --- a/data/src/main/java/com/linkedin/data/schema/resolver/AbstractDataSchemaResolver.java +++ b/data/src/main/java/com/linkedin/data/schema/resolver/AbstractDataSchemaResolver.java @@ -363,11 +363,11 @@ public String toString() return schema; } - private final Map _nameToDataSchema = new HashMap(); - private final Map _nameToDataSchemaLocations = new HashMap(); + private final Map _nameToDataSchema = new HashMap<>(); + private final Map _nameToDataSchemaLocations = new HashMap<>(); private final DataSchemaParserFactory _parserFactory; private final Set _badLocations = new HashSet<>(); - private final Set _resolvedLocations = new HashSet(); + private final Set _resolvedLocations = new HashSet<>(); // Map of pending records with the boolean flag indicating if includes are being processed for that schema. private final LinkedHashMap _pendingSchemas = new LinkedHashMap<>(); diff --git a/data/src/main/java/com/linkedin/data/schema/resolver/FileDataSchemaResolver.java b/data/src/main/java/com/linkedin/data/schema/resolver/FileDataSchemaResolver.java index 8ba35d034e..c3ef181f40 100644 --- a/data/src/main/java/com/linkedin/data/schema/resolver/FileDataSchemaResolver.java +++ b/data/src/main/java/com/linkedin/data/schema/resolver/FileDataSchemaResolver.java @@ -294,7 +294,7 @@ protected InputStream locationToInputStream(DataSchemaLocation location, private List _paths = _emptyPaths; private String _extension = DEFAULT_EXTENSION; - private final Map _pathToJarFile = new HashMap(); + private final Map _pathToJarFile = new HashMap<>(); private static final List _emptyPaths = Collections.emptyList(); diff --git a/data/src/main/java/com/linkedin/data/schema/validation/ValidateDataAgainstSchema.java b/data/src/main/java/com/linkedin/data/schema/validation/ValidateDataAgainstSchema.java index fb350caccf..70ad4736f6 100644 --- a/data/src/main/java/com/linkedin/data/schema/validation/ValidateDataAgainstSchema.java +++ b/data/src/main/java/com/linkedin/data/schema/validation/ValidateDataAgainstSchema.java @@ -124,7 +124,7 @@ private static class State implements ValidationResult private Object _fixed = null; private boolean _valid = true; private final Context _context; - private List _toTrim = new ArrayList(0); + private List _toTrim = new ArrayList<>(0); private State(ValidationOptions options, Validator validator) { @@ -806,7 +806,7 @@ protected void addIsRequiredMessage(DataElement element, RecordDataSchema.Field _valid = false; } - private MessageList _messages = new MessageList(); + private MessageList _messages = new MessageList<>(); @Override public boolean hasFix() diff --git a/data/src/main/java/com/linkedin/data/schema/validation/ValidationOptions.java b/data/src/main/java/com/linkedin/data/schema/validation/ValidationOptions.java index b8e3695186..722625d8f8 100644 --- a/data/src/main/java/com/linkedin/data/schema/validation/ValidationOptions.java +++ b/data/src/main/java/com/linkedin/data/schema/validation/ValidationOptions.java @@ -178,7 +178,7 @@ public void setValidatorParameter(String key, Object parameter) { if (_validatorParameters == NO_VALIDATOR_PARAMETERS) { - _validatorParameters = new HashMap(); + _validatorParameters = new HashMap<>(); } _validatorParameters.put(key, parameter); } diff --git a/data/src/main/java/com/linkedin/data/schema/validator/DataSchemaAnnotationValidator.java b/data/src/main/java/com/linkedin/data/schema/validator/DataSchemaAnnotationValidator.java index efed6633bc..e4f361c8a1 100644 --- a/data/src/main/java/com/linkedin/data/schema/validator/DataSchemaAnnotationValidator.java +++ b/data/src/main/java/com/linkedin/data/schema/validator/DataSchemaAnnotationValidator.java @@ -204,7 +204,7 @@ public int compare(ValidatorInfo v1, ValidatorInfo v2) private DataSchema _schema = DataSchemaConstants.NULL_DATA_SCHEMA; private Map> _customValidatorClassMap = Collections.emptyMap(); private Map> _schemaValidators = Collections.emptyMap(); - private MessageList _initMessages = new MessageList(); + private MessageList _initMessages = new MessageList<>(); private static final List NO_VALIDATORS = Collections.emptyList(); @@ -334,7 +334,7 @@ public boolean isDebugMode() */ private IdentityHashMap> buildSchemaValidators(DataSchema schema) { - final IdentityHashMap> map = new IdentityHashMap>(); + final IdentityHashMap> map = new IdentityHashMap<>(); DataSchemaTraverse traverse = new DataSchemaTraverse(); traverse.traverse(schema, new DataSchemaTraverse.Callback() @@ -404,7 +404,7 @@ private List buildValidatorList(Object validateObject, List p else { DataMap validateMap = (DataMap) validateObject; - List validatorInfoList = new ArrayList(validateMap.size()); + List validatorInfoList = new ArrayList<>(validateMap.size()); for (Map.Entry entry : validateMap.entrySet()) { Object config = entry.getValue(); @@ -442,7 +442,7 @@ private List buildValidatorList(Object validateObject, List p } } Collections.sort(validatorInfoList, PRIORITY_COMPARATOR); - validatorList = new ArrayList(validatorInfoList.size()); + validatorList = new ArrayList<>(validatorInfoList.size()); for (ValidatorInfo validatorInfo : validatorInfoList) { validatorList.add(validatorInfo._validator); diff --git a/data/src/main/java/com/linkedin/data/template/DataObjectToObjectCache.java b/data/src/main/java/com/linkedin/data/template/DataObjectToObjectCache.java index cea00ce3cb..1fee96cf31 100644 --- a/data/src/main/java/com/linkedin/data/template/DataObjectToObjectCache.java +++ b/data/src/main/java/com/linkedin/data/template/DataObjectToObjectCache.java @@ -40,12 +40,12 @@ class DataObjectToObjectCache implements Cloneable DataObjectToObjectCache() { - _cache = new HashMap(); + _cache = new HashMap<>(); } DataObjectToObjectCache(int initialCapacity) { - _cache = new HashMap(initialCapacity); + _cache = new HashMap<>(initialCapacity); } @SuppressWarnings("unchecked") diff --git a/data/src/main/java/com/linkedin/data/template/DataTemplateUtil.java b/data/src/main/java/com/linkedin/data/template/DataTemplateUtil.java index 84c4ae10b0..7053830195 100644 --- a/data/src/main/java/com/linkedin/data/template/DataTemplateUtil.java +++ b/data/src/main/java/com/linkedin/data/template/DataTemplateUtil.java @@ -798,7 +798,7 @@ protected boolean isStringAllowed() static { - IdentityHashMap, DirectCoercer> map = new IdentityHashMap, DirectCoercer>(); + IdentityHashMap, DirectCoercer> map = new IdentityHashMap<>(); map.put(Integer.TYPE, INTEGER_COERCER); map.put(Integer.class, INTEGER_COERCER); map.put(Long.TYPE, LONG_COERCER); @@ -849,7 +849,7 @@ static void registerCoercer(Class targetClass, DirectCoercer coercer) throw new IllegalArgumentException(targetClass.getName() + " already has a coercer"); } } - Map, DirectCoercer> newMap = new IdentityHashMap, DirectCoercer>(_classToCoercerMap); + Map, DirectCoercer> newMap = new IdentityHashMap<>(_classToCoercerMap); newMap.put(targetClass, coercer); _classToCoercerMap = Collections.unmodifiableMap(newMap); } diff --git a/data/src/main/java/com/linkedin/data/template/DirectMapTemplate.java b/data/src/main/java/com/linkedin/data/template/DirectMapTemplate.java index 2c055c57d2..7941a4fcc1 100644 --- a/data/src/main/java/com/linkedin/data/template/DirectMapTemplate.java +++ b/data/src/main/java/com/linkedin/data/template/DirectMapTemplate.java @@ -138,7 +138,7 @@ public boolean contains(Object object) } if (valueClass.isEnum()) { - return _map.entrySet().contains(new AbstractMap.SimpleImmutableEntry((String) key, value.toString())); + return _map.entrySet().contains(new AbstractMap.SimpleImmutableEntry<>((String) key, value.toString())); } else { diff --git a/data/src/main/java/com/linkedin/data/template/DynamicRecordMetadata.java b/data/src/main/java/com/linkedin/data/template/DynamicRecordMetadata.java index 9902cf366f..9d34949a55 100644 --- a/data/src/main/java/com/linkedin/data/template/DynamicRecordMetadata.java +++ b/data/src/main/java/com/linkedin/data/template/DynamicRecordMetadata.java @@ -48,7 +48,7 @@ public class DynamicRecordMetadata */ public DynamicRecordMetadata(String name, Collection> fieldDefs) { - _fieldDefMap = new HashMap>(); + _fieldDefMap = new HashMap<>(); _recordDataSchema = buildSchema(name, fieldDefs); for (FieldDef fieldDef : fieldDefs) @@ -70,7 +70,7 @@ public static RecordDataSchema buildSchema(String name, Collection fields = new ArrayList(fieldDefs.size()); + List fields = new ArrayList<>(fieldDefs.size()); for (FieldDef fieldDef: fieldDefs) { RecordDataSchema.Field paramField = fieldDef.getField(); diff --git a/data/src/main/java/com/linkedin/data/template/JacksonDataTemplateCodec.java b/data/src/main/java/com/linkedin/data/template/JacksonDataTemplateCodec.java index 69b93627ff..ee12558287 100644 --- a/data/src/main/java/com/linkedin/data/template/JacksonDataTemplateCodec.java +++ b/data/src/main/java/com/linkedin/data/template/JacksonDataTemplateCodec.java @@ -528,7 +528,7 @@ public void endList() private static List> orderMapEntries(RecordDataSchema schema, DataMap map) { - List> output = new ArrayList>(map.size()); + List> output = new ArrayList<>(map.size()); List fields = schema.getFields(); // collect fields in the record schema in the order the fields are declared for (RecordDataSchema.Field field : fields) @@ -537,11 +537,11 @@ private static List> orderMapEntries(RecordDataSchema s Object found = map.get(fieldName); if (found != null) { - output.add(new AbstractMap.SimpleImmutableEntry(fieldName, found)); + output.add(new AbstractMap.SimpleImmutableEntry<>(fieldName, found)); } } // collect fields that are in the DataMap that is not in the record schema. - List> uncollected = new ArrayList>(map.size() - output.size()); + List> uncollected = new ArrayList<>(map.size() - output.size()); for (Map.Entry e : map.entrySet()) { if (schema.contains(e.getKey()) == false) @@ -581,6 +581,6 @@ private void pop() private DataSchema _currentSchema; private DataSchema _pendingSchema; - private final List _schemaStack = new ArrayList(); // use ArrayList because elements may be null + private final List _schemaStack = new ArrayList<>(); // use ArrayList because elements may be null } } diff --git a/data/src/main/java/com/linkedin/data/template/WrappingArrayTemplate.java b/data/src/main/java/com/linkedin/data/template/WrappingArrayTemplate.java index 999933b6ef..4d56ea4785 100644 --- a/data/src/main/java/com/linkedin/data/template/WrappingArrayTemplate.java +++ b/data/src/main/java/com/linkedin/data/template/WrappingArrayTemplate.java @@ -103,7 +103,7 @@ public WrappingArrayTemplate copy() throws CloneNotSupportedException { @SuppressWarnings("unchecked") WrappingArrayTemplate copy = (WrappingArrayTemplate) super.copy(); - copy._cache = new DataObjectToObjectCache(copy.data().size()); + copy._cache = new DataObjectToObjectCache<>(copy.data().size()); return copy; } @@ -170,4 +170,3 @@ protected E coerceOutput(Object value) throws TemplateOutputCastException private Constructor _constructor; protected DataObjectToObjectCache _cache; } - diff --git a/data/src/main/java/com/linkedin/data/template/WrappingMapTemplate.java b/data/src/main/java/com/linkedin/data/template/WrappingMapTemplate.java index 7eb0c7003b..87598097f7 100644 --- a/data/src/main/java/com/linkedin/data/template/WrappingMapTemplate.java +++ b/data/src/main/java/com/linkedin/data/template/WrappingMapTemplate.java @@ -129,7 +129,7 @@ public WrappingMapTemplate copy() throws CloneNotSupportedException private void initializeCopy() { - _cache = new DataObjectToObjectCache(data().size()); + _cache = new DataObjectToObjectCache<>(data().size()); _entrySet = new EntrySet(); } @@ -274,7 +274,7 @@ protected Map.Entry unwrapEntry(Object entry) } Object unwrapped = (_valueClass.cast(value)).data(); assert(unwrapped != value); - return new AbstractMap.SimpleImmutableEntry((String) key, unwrapped); + return new AbstractMap.SimpleImmutableEntry<>((String) key, unwrapped); } } return null; @@ -282,7 +282,7 @@ protected Map.Entry unwrapEntry(Object entry) protected Collection> unwrapCollection(Collection c) { - ArrayList> unwrappedList = new ArrayList>(c.size()); + ArrayList> unwrappedList = new ArrayList<>(c.size()); for (Object entry : c) { Map.Entry unwrappedEntry = unwrapEntry(entry); diff --git a/data/src/main/java/com/linkedin/data/transforms/Transforms.java b/data/src/main/java/com/linkedin/data/transforms/Transforms.java index 66543a2aff..1f73cebb1f 100644 --- a/data/src/main/java/com/linkedin/data/transforms/Transforms.java +++ b/data/src/main/java/com/linkedin/data/transforms/Transforms.java @@ -18,19 +18,19 @@ /** * Convenience methods for commonly used {@link Transform}s. - * + * * @author "Joe Betz" - * + * */ public class Transforms { public static Transform identity() { - return new IdentityTransform(); + return new IdentityTransform<>(); } public static Transform constantValue(T constant) { - return new ConstantValueTransform(constant); + return new ConstantValueTransform<>(constant); } -} \ No newline at end of file +} diff --git a/data/src/main/java/com/linkedin/util/FileUtil.java b/data/src/main/java/com/linkedin/util/FileUtil.java index f24a8ab507..6a87c655ac 100644 --- a/data/src/main/java/com/linkedin/util/FileUtil.java +++ b/data/src/main/java/com/linkedin/util/FileUtil.java @@ -62,8 +62,8 @@ public boolean accept(File file) */ public static List listFiles(File directory, FileFilter fileFilter) { - final List result = new ArrayList(); - final ArrayDeque deque = new ArrayDeque(); + final List result = new ArrayList<>(); + final ArrayDeque deque = new ArrayDeque<>(); deque.addFirst(directory); while (deque.isEmpty() == false) diff --git a/data/src/test/java/com/linkedin/data/TestByteString.java b/data/src/test/java/com/linkedin/data/TestByteString.java index fc8132d62a..9b29d01c00 100644 --- a/data/src/test/java/com/linkedin/data/TestByteString.java +++ b/data/src/test/java/com/linkedin/data/TestByteString.java @@ -723,11 +723,11 @@ public void testDecomposer(ByteString sourceString, List expectedRes public Object[][] variousCompoundByteStrings() { //hello - final List byteStringAList = new ArrayList(); + final List byteStringAList = new ArrayList<>(); byteStringAList.add(ByteString.copy("hello".getBytes())); final ByteString byteStringA = listToByteString(byteStringAList); - final List byteStringBList = new ArrayList(); + final List byteStringBList = new ArrayList<>(); byteStringBList.add(ByteString.copy("h".getBytes())); byteStringBList.add(ByteString.copy("e".getBytes())); byteStringBList.add(ByteString.copy("l".getBytes())); @@ -735,13 +735,13 @@ public Object[][] variousCompoundByteStrings() byteStringBList.add(ByteString.copy("o".getBytes())); final ByteString byteStringB= listToByteString(byteStringBList); - final List byteStringCList = new ArrayList(); + final List byteStringCList = new ArrayList<>(); byteStringCList.add(ByteString.copy("he".getBytes())); byteStringCList.add(ByteString.copy("ll".getBytes())); byteStringCList.add(ByteString.copy("o".getBytes())); final ByteString byteStringC = listToByteString(byteStringCList); - final List byteStringDList = new ArrayList(); + final List byteStringDList = new ArrayList<>(); byteStringDList.add(ByteString.copy("hel".getBytes())); byteStringDList.add(ByteString.copy("l".getBytes())); byteStringDList.add(ByteString.copy("o".getBytes())); @@ -772,4 +772,4 @@ private ByteString listToByteString(List byteStringList) return builder.build(); } -} \ No newline at end of file +} diff --git a/data/src/test/java/com/linkedin/data/TestData.java b/data/src/test/java/com/linkedin/data/TestData.java index 6d998c33b3..5f0e1efea5 100644 --- a/data/src/test/java/com/linkedin/data/TestData.java +++ b/data/src/test/java/com/linkedin/data/TestData.java @@ -38,7 +38,7 @@ public class TestData { - final static List referenceList1 = new ArrayList(); + final static List referenceList1 = new ArrayList<>(); final static int RL1_BOOLEAN_INDEX = 0; final static int RL1_INTEGER_INDEX = 1; final static int RL1_LONG_INDEX = 2; @@ -64,7 +64,7 @@ public class TestData referenceList1.add(RL1_BYTES_INDEX, RL1_BYTES_VALUE); } - final static Map referenceMap1 = new HashMap(); + final static Map referenceMap1 = new HashMap<>(); final static String RM1_BOOLEAN_KEY = "boolean_key"; final static String RM1_INTEGER_KEY = "integer_key"; final static String RM1_LONG_KEY = "long_key"; @@ -90,7 +90,7 @@ public class TestData referenceMap1.put(RM1_BYTES_KEY, RM1_BYTES_VALUE); } - final static List illegalObjects = new ArrayList(); + final static List illegalObjects = new ArrayList<>(); static { illegalObjects.add(new AtomicInteger(-13)); illegalObjects.add(new AtomicLong(-13)); @@ -99,12 +99,12 @@ public class TestData illegalObjects.add(new Byte("13")); illegalObjects.add(new Short("13")); - illegalObjects.add(new ArrayList()); - illegalObjects.add(new HashMap()); - illegalObjects.add(new HashSet()); + illegalObjects.add(new ArrayList<>()); + illegalObjects.add(new HashMap<>()); + illegalObjects.add(new HashSet<>()); } - final static Map illegalMap = new HashMap(); + final static Map illegalMap = new HashMap<>(); static { for (Object o : illegalObjects) @@ -1554,7 +1554,7 @@ public void testNoCyclesOnAddAndPut() Collection asCollection(Object... objects) { - ArrayList c = new ArrayList(); + ArrayList c = new ArrayList<>(); for (Object o : objects) { c.add(o); @@ -1610,7 +1610,7 @@ public void testDataMapInstrumentation() map.get("a"); StringBuilder prefix = new StringBuilder("prefix"); - Map> instrumentedData = new HashMap>(); + Map> instrumentedData = new HashMap<>(); map.collectInstrumentedData(prefix, instrumentedData, false); @@ -1670,7 +1670,7 @@ public void testDataListInstrumentation() list.get(1); StringBuilder prefix = new StringBuilder("prefix"); - Map> instrumentedData = new HashMap>(); + Map> instrumentedData = new HashMap<>(); list.collectInstrumentedData(prefix, instrumentedData, false); @@ -1746,7 +1746,7 @@ public void testNestedInstrumentation() containedMap.get("b"); StringBuilder prefix = new StringBuilder("prefix"); - Map> instrumentedData = new HashMap>(); + Map> instrumentedData = new HashMap<>(); map.collectInstrumentedData(prefix, instrumentedData, false); diff --git a/data/src/test/java/com/linkedin/data/TestUtil.java b/data/src/test/java/com/linkedin/data/TestUtil.java index bea41f52a4..2c4a4c5034 100644 --- a/data/src/test/java/com/linkedin/data/TestUtil.java +++ b/data/src/test/java/com/linkedin/data/TestUtil.java @@ -81,7 +81,7 @@ static public void dumpBytes(PrintStream printStream, byte bytes[]) static public List asList(Object... objects) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); for (Object object : objects) { list.add(object); @@ -94,7 +94,7 @@ static public Map asMap(Object... objects) { int index = 0; String key = null; - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); for (Object object : objects) { if (index % 2 == 0) @@ -276,7 +276,7 @@ public static File testDir(String testName, boolean debug) throws IOException public static Map> createSchemaFiles(File testDir, Map fileToSchemaMap, boolean debug) throws IOException { - Map> result = new HashMap>(); + Map> result = new HashMap<>(); ensureEmptyOutputDir(testDir, debug); @@ -317,7 +317,7 @@ public static void createSchemaJar(String jarFileName, Map fileT public static Collection computePathFromRelativePaths(File testDir, Collection relativePaths) throws IOException { - Collection paths = new ArrayList(); + Collection paths = new ArrayList<>(); // directory in path for (String testPath : relativePaths) @@ -334,14 +334,14 @@ public static Collection createJarsFromRelativePaths(File testDir, boolean debug) throws IOException { - Collection paths = new ArrayList(); + Collection paths = new ArrayList<>(); // jar files in path, create jar files paths.clear(); for (String testPath : relativePaths) { String jarFileName = (testDir.getCanonicalPath() + testPath + ".jar").replace('/', File.separatorChar); - Map jarFileContents = new HashMap(); + Map jarFileContents = new HashMap<>(); for (Map.Entry entry : fileToSchemaMap.entrySet()) { if (entry.getKey().startsWith(testPath)) @@ -547,7 +547,7 @@ public static boolean noCommonDataComplex(Object o1, Object o2) */ private static Set collectDataComplex(final Object object) { - IdentityHashMap identityHashMap = new IdentityHashMap(); + IdentityHashMap identityHashMap = new IdentityHashMap<>(); collectDataComplex(object, identityHashMap); return identityHashMap.keySet(); } diff --git a/data/src/test/java/com/linkedin/data/codec/CodecDataProviders.java b/data/src/test/java/com/linkedin/data/codec/CodecDataProviders.java index e3644a4f57..340bf54dbc 100644 --- a/data/src/test/java/com/linkedin/data/codec/CodecDataProviders.java +++ b/data/src/test/java/com/linkedin/data/codec/CodecDataProviders.java @@ -237,7 +237,7 @@ private static Map codecDataInputs() { DataMap mapOfStrings = new DataMap(); - ArrayList lengths = new ArrayList(); + ArrayList lengths = new ArrayList<>(); for (int stringLength = 0; stringLength < 1024; stringLength += 113) { diff --git a/data/src/test/java/com/linkedin/data/codec/TestBufferChain.java b/data/src/test/java/com/linkedin/data/codec/TestBufferChain.java index 0dbc993823..d988d4da53 100644 --- a/data/src/test/java/com/linkedin/data/codec/TestBufferChain.java +++ b/data/src/test/java/com/linkedin/data/codec/TestBufferChain.java @@ -31,14 +31,14 @@ public class TestBufferChain { - private final Map _strings = new LinkedHashMap(); + private final Map _strings = new LinkedHashMap<>(); private final int[] _bufferSizes = { 17, 19, 23, 29, 31, 37, 41, 43, 47, BufferChain.DEFAULT_BUFFER_SIZE }; @BeforeClass private void initStrings() { - ArrayList lengths = new ArrayList(); + ArrayList lengths = new ArrayList<>(); for (int stringLength = 0; stringLength < 1024; stringLength += 17) { lengths.add(stringLength); diff --git a/data/src/test/java/com/linkedin/data/collections/TestCheckedUtil.java b/data/src/test/java/com/linkedin/data/collections/TestCheckedUtil.java index 927cb2706b..65cadbf62f 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCheckedUtil.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCheckedUtil.java @@ -37,8 +37,8 @@ public class TestCheckedUtil @Test public void testUnsafeClone() { - final CheckedList list = new CheckedList(); - final CheckedMap map = new CheckedMap(); + final CheckedList list = new CheckedList<>(); + final CheckedMap map = new CheckedMap<>(); final CheckedList listClone = CommonUtil.unsafeClone(list); final CheckedMap mapClone = CommonUtil.unsafeClone(map); @@ -56,8 +56,8 @@ public void testUnsafeClone() @Test public void testUnsafeCloneSetReadOnly() { - final CheckedList list = new CheckedList(); - final CheckedMap map = new CheckedMap(); + final CheckedList list = new CheckedList<>(); + final CheckedMap map = new CheckedMap<>(); final CheckedList listClone = CommonUtil.unsafeCloneSetReadOnly(list); final CheckedMap mapClone = CommonUtil.unsafeCloneSetReadOnly(map); @@ -139,7 +139,7 @@ public void testPutCycleWithoutChecking() public void testPutAllCycleWithAssertChecking() { final DataMap map = new DataMap(); - final Map cycleMap = new HashMap(); + final Map cycleMap = new HashMap<>(); cycleMap.put("cycle", map); CheckedUtil.putAllWithoutChecking(map, cycleMap); diff --git a/data/src/test/java/com/linkedin/data/collections/TestCommonList.java b/data/src/test/java/com/linkedin/data/collections/TestCommonList.java index d105413880..623f4afd4d 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCommonList.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCommonList.java @@ -384,12 +384,12 @@ public void check(CommonList list, E value) @Test(dataProvider = "factories") public void testChecker(CommonListFactory factory) throws CloneNotSupportedException { - Checker checker1 = new Checker(); + Checker checker1 = new Checker<>(); CommonList list1 = factory.create(checker1); assertEquals(checker1.checkCount, 0); - Checker checker2 = new Checker(); + Checker checker2 = new Checker<>(); CommonList list2 = factory.create(referenceList1, checker2); int expected2 = referenceList1.size(); assertEquals(checker2.checkCount, expected2); @@ -515,23 +515,23 @@ public static class CowListFactory implements CommonListFactory { public CommonList create() { - return new CowList(); + return new CowList<>(); } public CommonList create(int initialCapacity) { - return new CowList(initialCapacity); + return new CowList<>(initialCapacity); } public CommonList create(List list) { - return new CowList(list); + return new CowList<>(list); } public CommonList create(ListChecker checker) { - return new CowList(checker); + return new CowList<>(checker); } public CommonList create(List list, ListChecker checker) { - return new CowList(list, checker); + return new CowList<>(list, checker); } public void addWithoutChecking(List list, E value) { @@ -543,23 +543,23 @@ public static class CheckedListFactory implements CommonListFactory { public CommonList create() { - return new CheckedList(); + return new CheckedList<>(); } public CommonList create(int initialCapacity) { - return new CheckedList(initialCapacity); + return new CheckedList<>(initialCapacity); } public CommonList create(List list) { - return new CheckedList(list); + return new CheckedList<>(list); } public CommonList create(ListChecker checker) { - return new CheckedList(checker); + return new CheckedList<>(checker); } public CommonList create(List list, ListChecker checker) { - return new CheckedList(list, checker); + return new CheckedList<>(list, checker); } public void addWithoutChecking(List list, E value) { diff --git a/data/src/test/java/com/linkedin/data/collections/TestCommonMap.java b/data/src/test/java/com/linkedin/data/collections/TestCommonMap.java index d1a1f6e36f..614dc581c3 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCommonMap.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCommonMap.java @@ -77,7 +77,7 @@ public static void testAgainstReferenceMap1(Map map) assertFalse(map.isEmpty()); assert(map.entrySet().equals(referenceMap1.entrySet())); assertEquals(map.keySet(), referenceMap1.keySet()); - assertEquals(new HashSet(map.values()), new HashSet(referenceMap1.values())); + assertEquals(new HashSet<>(map.values()), new HashSet<>(referenceMap1.values())); } public static void containsReferenceMap2(Map map) @@ -237,12 +237,12 @@ public void checkKeyValue(CommonMap map, K key, V value) @Test(dataProvider = "factories") public void testCheckKeyValue(CommonMapFactory factory) throws CloneNotSupportedException { - Checker checker1 = new Checker(); + Checker checker1 = new Checker<>(); CommonMap map1 = factory.create(checker1); assertEquals(checker1.checkCount, 0); - Checker checker2 = new Checker(); + Checker checker2 = new Checker<>(); CommonMap map2 = factory.create(referenceMap1, checker2); assertEquals(checker2.checkCount, referenceMap1.size()); @@ -286,7 +286,7 @@ public void testEntrySetKeySetValues(CommonMapFactory factory) } // keySet - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); for (Integer i = 0; i < count; i++) { String v = i.toString(); @@ -295,7 +295,7 @@ public void testEntrySetKeySetValues(CommonMapFactory factory) assertEquals(map.keySet(), expectedKeys); // values - Collection expectedValues = new ArrayList(); + Collection expectedValues = new ArrayList<>(); for (Integer i = 0; i < count; i++) { expectedValues.add("X" + i + "X"); @@ -327,27 +327,27 @@ public static class CowMapFactory implements CommonMapFactory { public CommonMap create() { - return new CowMap(); + return new CowMap<>(); } public CommonMap create(int initialCapacity) { - return new CowMap(initialCapacity); + return new CowMap<>(initialCapacity); } public CommonMap create(int initialCapacity, float factor) { - return new CowMap(initialCapacity, factor); + return new CowMap<>(initialCapacity, factor); } public CommonMap create(Map map) { - return new CowMap(map); + return new CowMap<>(map); } public CommonMap create(MapChecker checker) { - return new CowMap(checker); + return new CowMap<>(checker); } public CommonMap create(Map map, MapChecker checker) { - return new CowMap(map, checker); + return new CowMap<>(map, checker); } } @@ -355,27 +355,27 @@ public static class CheckedMapFactory implements CommonMapFactory { public CommonMap create() { - return new CheckedMap(); + return new CheckedMap<>(); } public CommonMap create(int initialCapacity) { - return new CheckedMap(initialCapacity); + return new CheckedMap<>(initialCapacity); } public CommonMap create(int initialCapacity, float factor) { - return new CheckedMap(initialCapacity, factor); + return new CheckedMap<>(initialCapacity, factor); } public CommonMap create(Map map) { - return new CheckedMap(map); + return new CheckedMap<>(map); } public CommonMap create(MapChecker checker) { - return new CheckedMap(checker); + return new CheckedMap<>(checker); } public CommonMap create(Map map, MapChecker checker) { - return new CheckedMap(map, checker); + return new CheckedMap<>(map, checker); } } } diff --git a/data/src/test/java/com/linkedin/data/collections/TestCowList.java b/data/src/test/java/com/linkedin/data/collections/TestCowList.java index 1df0f7c67c..c235125e24 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCowList.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCowList.java @@ -33,7 +33,7 @@ public class TestCowList @Test public void testCopyOnWrite() throws CloneNotSupportedException { - CowList list1 = new CowList(referenceList1); + CowList list1 = new CowList<>(referenceList1); testAgainstReferenceList1(list1); assertEquals(list1.getRefCounted().getRefCount(), 0); @@ -444,7 +444,7 @@ public void testCopyOnWrite() throws CloneNotSupportedException assertTrue(list3.getRefCounted() == list1.getRefCounted()); assertTrue(list28.getRefCounted() == list1.getRefCounted()); assertEquals(list1.getRefCounted().getRefCount(), 2); - List sublist28a = new ArrayList(referenceList1.subList(1, 4)); + List sublist28a = new ArrayList<>(referenceList1.subList(1, 4)); sublist28a.remove(1); sublist28.retainAll(sublist28a); assertEquals(sublist28.size(), 2); @@ -464,7 +464,7 @@ public void testCopyOnWrite() throws CloneNotSupportedException assertTrue(list3.getRefCounted() == list1.getRefCounted()); assertTrue(list29.getRefCounted() == list1.getRefCounted()); assertEquals(list1.getRefCounted().getRefCount(), 2); - List sublist29a = new ArrayList(referenceList1.subList(1, 4)); + List sublist29a = new ArrayList<>(referenceList1.subList(1, 4)); sublist29a.remove(1); sublist29.retainAll(sublist29a); assertEquals(sublist29.size(), 2); diff --git a/data/src/test/java/com/linkedin/data/collections/TestCowMap.java b/data/src/test/java/com/linkedin/data/collections/TestCowMap.java index fd6d97a696..f8616c2481 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCowMap.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCowMap.java @@ -36,7 +36,7 @@ public class TestCowMap @Test public void testCopyOnWrite() throws CloneNotSupportedException { - CowMap map1 = new CowMap(referenceMap1); + CowMap map1 = new CowMap<>(referenceMap1); testAgainstReferenceMap1(map1); assertEquals(map1.getRefCounted().getRefCount(), 0); diff --git a/data/src/test/java/com/linkedin/data/collections/TestCowSet.java b/data/src/test/java/com/linkedin/data/collections/TestCowSet.java index ccb6f1d83f..a3100ef1bc 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCowSet.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCowSet.java @@ -31,7 +31,7 @@ public class TestCowSet @Test public void testAdd() { - final CowSet set = new CowSet(); + final CowSet set = new CowSet<>(); Assert.assertEquals(set.size(), 0); Assert.assertFalse(set.contains("test")); @@ -48,7 +48,7 @@ public void testAdd() @Test public void testRemove() { - final CowSet set = new CowSet(); + final CowSet set = new CowSet<>(); set.add("test"); Assert.assertTrue(set.remove("test")); @@ -63,7 +63,7 @@ public void testRemove() @Test public void testReadOnly() { - final CowSet set = new CowSet(); + final CowSet set = new CowSet<>(); Assert.assertFalse(set.isReadOnly()); set.add("test"); @@ -101,7 +101,7 @@ public void testReadOnly() @Test public void testClone() throws CloneNotSupportedException { - final CowSet set1 = new CowSet(); + final CowSet set1 = new CowSet<>(); set1.add("test"); @SuppressWarnings("unchecked") @@ -137,7 +137,7 @@ public void testClone() throws CloneNotSupportedException @Test public void testModifyThroughIterator() { - final CowSet set = new CowSet(); + final CowSet set = new CowSet<>(); set.add("test"); set.setReadOnly(); diff --git a/data/src/test/java/com/linkedin/data/collections/TestCowUtil.java b/data/src/test/java/com/linkedin/data/collections/TestCowUtil.java index 3d6592c87b..d1dbab952f 100644 --- a/data/src/test/java/com/linkedin/data/collections/TestCowUtil.java +++ b/data/src/test/java/com/linkedin/data/collections/TestCowUtil.java @@ -30,9 +30,9 @@ public class TestCowUtil @Test public void testUnsafeClone() { - final CowList list = new CowList(); - final CowSet set = new CowSet(); - final CowMap map = new CowMap(); + final CowList list = new CowList<>(); + final CowSet set = new CowSet<>(); + final CowMap map = new CowMap<>(); final CowList listClone = CommonUtil.unsafeClone(list); final CowSet setClone = CommonUtil.unsafeClone(set); @@ -54,9 +54,9 @@ public void testUnsafeClone() @Test public void testUnsafeCloneSetReadOnly() { - final CowList list = new CowList(); - final CowSet set = new CowSet(); - final CowMap map = new CowMap(); + final CowList list = new CowList<>(); + final CowSet set = new CowSet<>(); + final CowMap map = new CowMap<>(); final CowList listClone = CommonUtil.unsafeCloneSetReadOnly(list); final CowSet setClone = CommonUtil.unsafeCloneSetReadOnly(set); diff --git a/data/src/test/java/com/linkedin/data/element/TestDataElement.java b/data/src/test/java/com/linkedin/data/element/TestDataElement.java index cba07ea4cf..b778118da0 100644 --- a/data/src/test/java/com/linkedin/data/element/TestDataElement.java +++ b/data/src/test/java/com/linkedin/data/element/TestDataElement.java @@ -336,7 +336,7 @@ public void testDataElement(DataElementFactory factory) throws IOException } }; - ArrayList pathAsList = new ArrayList(); + ArrayList pathAsList = new ArrayList<>(); for (Object[] row : testPathInput) { DataElement element = (DataElement) row[0]; diff --git a/data/src/test/java/com/linkedin/data/it/TestDataIterator.java b/data/src/test/java/com/linkedin/data/it/TestDataIterator.java index 9fc63fe521..884521a2c9 100644 --- a/data/src/test/java/com/linkedin/data/it/TestDataIterator.java +++ b/data/src/test/java/com/linkedin/data/it/TestDataIterator.java @@ -62,7 +62,7 @@ public Object jsonToObject(String s) throws IOException public List traverse(DataElement element, IterationOrder order, boolean usePath) { - List traversalList = new ArrayList(); + List traversalList = new ArrayList<>(); DataIterator it = Builder.create(element, order).dataIterator(); DataElement current; while ((current = it.next()) != null) @@ -122,7 +122,7 @@ public void testNoSchemaDataMapRoot() //using a Set. We want to make sure they are all visited. The only caveat is the position of root, as it should //appear first for preOrder and last for postOrder. - final Set commonValues = new HashSet(); + final Set commonValues = new HashSet<>(); commonValues.add("name=bytes, class=com.linkedin.data.ByteString, value=abc"); commonValues.add("name=int, class=java.lang.Integer, value=1"); commonValues.add("name=string, class=java.lang.String, value=foo"); @@ -132,12 +132,12 @@ public void testNoSchemaDataMapRoot() commonValues.add("name=float, class=java.lang.Float, value=3.0"); List preOrderTraversal = traverse(root, IterationOrder.PRE_ORDER); - Set preOrderTraversalWithoutRoot = new HashSet(preOrderTraversal.subList(1, preOrderTraversal.size())); + Set preOrderTraversalWithoutRoot = new HashSet<>(preOrderTraversal.subList(1, preOrderTraversal.size())); Assert.assertEquals(preOrderTraversal.get(0), "name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataMap", "The first node in the pre order traversal should be com.linkedin.data.DataMap"); List postOrderTraversal = traverse(root, IterationOrder.POST_ORDER); - Set postOrderTraversalWithoutRoot = new HashSet(postOrderTraversal.subList(0, postOrderTraversal.size() - 1)); + Set postOrderTraversalWithoutRoot = new HashSet<>(postOrderTraversal.subList(0, postOrderTraversal.size() - 1)); Assert.assertEquals(postOrderTraversal.get(postOrderTraversal.size() - 1), "name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataMap", "The last node in the post order traversal should be com.linkedin.data.DataMap"); @@ -157,7 +157,7 @@ public void testNoSchemaDataListRoot() root.add("foo"); root.add(ByteString.copyAvroString("abc", false)); - final List commonElements = new ArrayList(); + final List commonElements = new ArrayList<>(); commonElements.add("name=0, class=java.lang.Boolean, value=false"); commonElements.add("name=1, class=java.lang.Integer, value=1"); commonElements.add("name=2, class=java.lang.Long, value=2"); @@ -166,11 +166,11 @@ public void testNoSchemaDataListRoot() commonElements.add("name=5, class=java.lang.String, value=foo"); commonElements.add("name=6, class=com.linkedin.data.ByteString, value=abc"); - final List preOrderOutput = new ArrayList(); + final List preOrderOutput = new ArrayList<>(); preOrderOutput.add("name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataList"); preOrderOutput.addAll(commonElements); - final List postOrderOutput = new ArrayList(); + final List postOrderOutput = new ArrayList<>(); postOrderOutput.addAll(commonElements); postOrderOutput.add("name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataList"); @@ -211,11 +211,11 @@ public void testNoSchemaNestedMapOfArray() throws IOException Assert.assertEquals(preOrderTraversal.size(), 7, "We should have 7 elements in our pre order traversal"); Assert.assertEquals(preOrderTraversal.get(0), "name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataMap"); //The bKey and aKey traversal could be in any order - final List aKeyPreOrderList = new ArrayList(); + final List aKeyPreOrderList = new ArrayList<>(); aKeyPreOrderList.add("name=aKey, class=com.linkedin.data.DataList"); aKeyPreOrderList.add("name=0, class=java.lang.Integer, value=1"); aKeyPreOrderList.add("name=1, class=java.lang.Integer, value=2"); - final List bKeyPreOrderList = new ArrayList(); + final List bKeyPreOrderList = new ArrayList<>(); bKeyPreOrderList.add("name=bKey, class=com.linkedin.data.DataList"); bKeyPreOrderList.add("name=0, class=java.lang.Double, value=1.0"); bKeyPreOrderList.add("name=1, class=java.lang.Double, value=2.0"); @@ -231,11 +231,11 @@ public void testNoSchemaNestedMapOfArray() throws IOException Assert.assertEquals(postOrderTraversal.get(postOrderTraversal.size() - 1), "name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataMap"); //The bKey and aKey traversal could be in any order - final List aKeyPostOrderList = new ArrayList(); + final List aKeyPostOrderList = new ArrayList<>(); aKeyPostOrderList.add("name=0, class=java.lang.Integer, value=1"); aKeyPostOrderList.add("name=1, class=java.lang.Integer, value=2"); aKeyPostOrderList.add("name=aKey, class=com.linkedin.data.DataList"); - final List bKeyPostOrderList = new ArrayList(); + final List bKeyPostOrderList = new ArrayList<>(); bKeyPostOrderList.add("name=0, class=java.lang.Double, value=1.0"); bKeyPostOrderList.add("name=1, class=java.lang.Double, value=2.0"); bKeyPostOrderList.add("name=bKey, class=com.linkedin.data.DataList"); @@ -270,7 +270,7 @@ public void testNoSchemaNestedArrayOfMaps() throws IOException final Object arrayOfMapsObject = jsonToObject(arrayOfMapsString); final List preOrderTraversal = traverse(arrayOfMapsObject, IterationOrder.PRE_ORDER); - final List expectedPreOrder = new ArrayList(); + final List expectedPreOrder = new ArrayList<>(); expectedPreOrder.add("name=" + DataElement.ROOT_NAME + ", class=com.linkedin.data.DataList"); expectedPreOrder.add("name=0, class=com.linkedin.data.DataMap"); expectedPreOrder.add("name=aKey, class=java.lang.Integer, value=1"); @@ -279,7 +279,7 @@ public void testNoSchemaNestedArrayOfMaps() throws IOException Assert.assertEquals(preOrderTraversal, expectedPreOrder, "We should get the expected pre order traversal"); final List postOrderTraversal = traverse(arrayOfMapsObject, IterationOrder.POST_ORDER); - final List expectedPostOrder = new ArrayList(); + final List expectedPostOrder = new ArrayList<>(); expectedPostOrder.add("name=aKey, class=java.lang.Integer, value=1"); expectedPostOrder.add("name=0, class=com.linkedin.data.DataMap"); expectedPostOrder.add("name=bKey, class=java.lang.Double, value=2.0"); @@ -333,7 +333,7 @@ public void testNoSchemaWithParentDataElement() " path=/child/child, class=com.linkedin.data.DataMap\n"; */ - final Set commonValues = new HashSet(); + final Set commonValues = new HashSet<>(); commonValues.add("path=/child/child/bytes, class=com.linkedin.data.ByteString, value=abc"); commonValues.add("path=/child/child/int, class=java.lang.Integer, value=1"); commonValues.add("path=/child/child/string, class=java.lang.String, value=foo"); @@ -343,12 +343,12 @@ public void testNoSchemaWithParentDataElement() commonValues.add("path=/child/child/float, class=java.lang.Float, value=3.0"); List preOrderTraversal = traverseWithDataElement(element, IterationOrder.PRE_ORDER, true); - Set preOrderTraversalWithoutRoot = new HashSet(preOrderTraversal.subList(1, preOrderTraversal.size())); + Set preOrderTraversalWithoutRoot = new HashSet<>(preOrderTraversal.subList(1, preOrderTraversal.size())); Assert.assertEquals(preOrderTraversal.get(0), "path=/child/child, class=com.linkedin.data.DataMap", "The first node in the pre order traversal should be: com.linkedin.data.DataMap"); List postOrderTraversal = traverseWithDataElement(element, IterationOrder.POST_ORDER, true); - Set postOrderTraversalWithoutRoot = new HashSet(postOrderTraversal.subList(0, postOrderTraversal.size() - 1)); + Set postOrderTraversalWithoutRoot = new HashSet<>(postOrderTraversal.subList(0, postOrderTraversal.size() - 1)); Assert.assertEquals(postOrderTraversal.get(postOrderTraversal.size() - 1), "path=/child/child, class=com.linkedin.data.DataMap", "The last node in the post order traversal should be: com.linkedin.data.DataMap"); @@ -358,7 +358,7 @@ public void testNoSchemaWithParentDataElement() public void assertEqualsByName(Builder builder, List expectedNames) { - final List names = new ArrayList(); + final List names = new ArrayList<>(); builder.iterate(new Builder.Callback() { @Override @@ -374,7 +374,7 @@ public void callback(DataElement element) public void assertEqualsByValue(Builder builder, List expectedValues) { - final List values = new ArrayList(); + final List values = new ArrayList<>(); builder.iterate(new Builder.Callback() { @Override @@ -390,8 +390,8 @@ public void callback(DataElement element) public void assertEqualsByPath(Builder builder, List expectedPaths) { - final List paths = new ArrayList(); - final ArrayList pathAsList = new ArrayList(); + final List paths = new ArrayList<>(); + final ArrayList pathAsList = new ArrayList<>(); builder.iterate(new Builder.Callback() { @Override @@ -1299,7 +1299,7 @@ public void testSkipToSibling() throws IOException Object o = jsonToObject(input); DataElement e; DataIterator it = Builder.create(o, null, IterationOrder.POST_ORDER).dataIterator(); - List pathsWithSkip = new ArrayList(); + List pathsWithSkip = new ArrayList<>(); while ((e = it.next()) != null) { pathsWithSkip.add(e.pathAsString()); @@ -1307,7 +1307,7 @@ public void testSkipToSibling() throws IOException } it = Builder.create(o, null, IterationOrder.POST_ORDER).dataIterator(); - List pathsWithoutSkip = new ArrayList(); + List pathsWithoutSkip = new ArrayList<>(); while ((e = it.next()) != null) { pathsWithoutSkip.add(e.pathAsString()); @@ -1336,7 +1336,7 @@ public void testPredicates() assertFalse(and(alwaysTrue(), alwaysTrue(), alwaysFalse()).evaluate(null)); assertFalse(and(alwaysFalse(), alwaysFalse(), alwaysFalse()).evaluate(null)); - assertTrue(and(new ArrayList()).evaluate(null)); + assertTrue(and(new ArrayList<>()).evaluate(null)); assertTrue(and(Arrays.asList(alwaysTrue())).evaluate(null)); assertFalse(and(Arrays.asList(alwaysFalse())).evaluate(null)); assertTrue(and(Arrays.asList(alwaysTrue(), alwaysTrue())).evaluate(null)); @@ -1362,7 +1362,7 @@ public void testPredicates() assertTrue(or(alwaysFalse(), alwaysFalse(), alwaysTrue()).evaluate(null)); assertFalse(or(alwaysFalse(), alwaysFalse(), alwaysFalse()).evaluate(null)); - assertFalse(or(new ArrayList()).evaluate(null)); + assertFalse(or(new ArrayList<>()).evaluate(null)); assertFalse(or(Arrays.asList(alwaysFalse())).evaluate(null)); assertTrue(or(Arrays.asList(alwaysTrue(), alwaysTrue())).evaluate(null)); assertTrue(or(Arrays.asList(alwaysFalse(), alwaysTrue())).evaluate(null)); diff --git a/data/src/test/java/com/linkedin/data/it/TestTransformer.java b/data/src/test/java/com/linkedin/data/it/TestTransformer.java index 6a1ba4e525..6f99732933 100644 --- a/data/src/test/java/com/linkedin/data/it/TestTransformer.java +++ b/data/src/test/java/com/linkedin/data/it/TestTransformer.java @@ -48,11 +48,11 @@ public Object apply(Object element) public void testTransformByPredicateAtPath() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPattern("foo", Wildcard.ANY_ONE, "id")) .transform(plusTenTransform); - + assertEquals(data.getValue().getDataList("foo").getDataMap(0).getInteger("id").intValue(), 11); assertEquals(data.getValue().getDataList("foo").getDataMap(1).getInteger("id").intValue(), 12); assertEquals(data.getValue().getDataList("foo").getDataMap(2).getInteger("id").intValue(), 13); @@ -62,11 +62,11 @@ public void testTransformByPredicateAtPath() throws Exception public void testReplaceByPredicateAtPath() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.and(Predicates.pathMatchesPathSpec(IteratorTestData.PATH_TO_ID), IteratorTestData.LESS_THAN_3_CONDITION)) .replace(50); - + assertEquals(data.getValue().getDataList("foo").getDataMap(0).getInteger("id").intValue(), 50); assertEquals(data.getValue().getDataList("foo").getDataMap(1).getInteger("id").intValue(), 50); } @@ -75,16 +75,16 @@ public void testReplaceByPredicateAtPath() throws Exception public void testReplaceByPredicate() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(IteratorTestData.PATH_TO_ID)) .replace(100); - + assertEquals(data.getValue().getDataList("foo").getDataMap(0).getInteger("id").intValue(), 100); assertEquals(data.getValue().getDataList("foo").getDataMap(1).getInteger("id").intValue(), 100); assertEquals(data.getValue().getDataList("foo").getDataMap(2).getInteger("id").intValue(), 100); } - + @Test public void testReplaceAtPathNested() throws Exception { @@ -100,7 +100,7 @@ public void testReplaceAtPathNested() throws Exception assertEquals(count, 0); } - + /** * Removes multiple nodes in a complex type, including non-leaf nodes. */ @@ -108,56 +108,56 @@ public void testReplaceAtPathNested() throws Exception public void testReplaceByNameNested() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.nameEquals("foo")) .replace(new DataList()); - + assertEquals(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(new PathSpec("nested", "nested", "foo", PathSpec.WILDCARD))) .count(), 0); - + assertEquals(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(new PathSpec("foo", PathSpec.WILDCARD))) .count(), 0); } - + @Test public void testReplaceBySchemaNameNested() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.dataSchemaNameEquals("Bar")) .replace(500); - - List accumulate = new ArrayList(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) + + List accumulate = new ArrayList<>(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(new PathSpec("nested", "nested", "foo", PathSpec.WILDCARD))) .accumulateValues()); assertEquals(accumulate.size(), 2); assertEquals(accumulate.get(0), 500); assertEquals(accumulate.get(1), 500); - - accumulate = new ArrayList(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) + + accumulate = new ArrayList<>(Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPathSpec(new PathSpec("foo", PathSpec.WILDCARD))) .accumulateValues()); - + assertEquals(accumulate.size(), 3); assertEquals(accumulate.get(0), 500); assertEquals(accumulate.get(1), 500); assertEquals(accumulate.get(2), 500); } - + @Test public void testReplaceRoot() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - + Object result = Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.dataSchemaNameEquals("Foo")) .replace(new DataMap()); - + assertTrue(result instanceof DataMap); assertEquals(((DataMap)result).size(), 0); } diff --git a/data/src/test/java/com/linkedin/data/it/TestValueAccumulator.java b/data/src/test/java/com/linkedin/data/it/TestValueAccumulator.java index f83cd271d6..f2083ec627 100644 --- a/data/src/test/java/com/linkedin/data/it/TestValueAccumulator.java +++ b/data/src/test/java/com/linkedin/data/it/TestValueAccumulator.java @@ -35,9 +35,9 @@ public class TestValueAccumulator public void testAccumulateByPath() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - - List ids = new LinkedList(); - + + List ids = new LinkedList<>(); + Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.and(Predicates.pathMatchesPattern("foo", Wildcard.ANY_ONE, "id"))) .accumulateValues(ids); @@ -52,8 +52,8 @@ public void testAccumulateByPath() throws Exception public void testAccumulateByPathAndFilter() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); - - List ids = new ArrayList( + + List ids = new ArrayList<>( Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.and(Predicates.pathMatchesPathSpec(IteratorTestData.PATH_TO_ID), IteratorTestData.LESS_THAN_3_CONDITION)) .accumulateValues()); diff --git a/data/src/test/java/com/linkedin/data/performance/TestCloudPerformance.java b/data/src/test/java/com/linkedin/data/performance/TestCloudPerformance.java index ab55ab16b2..2308cd6c0a 100644 --- a/data/src/test/java/com/linkedin/data/performance/TestCloudPerformance.java +++ b/data/src/test/java/com/linkedin/data/performance/TestCloudPerformance.java @@ -251,7 +251,7 @@ private DataMap cloudEdgeDataMap() private List cloudEdgesList(int numElements) { - List edgeList = new ArrayList(numElements); + List edgeList = new ArrayList<>(numElements); for (int i = 0; i < numElements; i++) { edgeList.add(cloudEdge()); diff --git a/data/src/test/java/com/linkedin/data/schema/compatibility/TestCompatibilityChecker.java b/data/src/test/java/com/linkedin/data/schema/compatibility/TestCompatibilityChecker.java index abd5dd4b1d..1117165ba0 100644 --- a/data/src/test/java/com/linkedin/data/schema/compatibility/TestCompatibilityChecker.java +++ b/data/src/test/java/com/linkedin/data/schema/compatibility/TestCompatibilityChecker.java @@ -141,12 +141,12 @@ public class TestCompatibilityChecker @SuppressWarnings("unchecked") private static final List list(T...args) { - return new ArrayList(Arrays.asList(args)); + return new ArrayList<>(Arrays.asList(args)); } private static final List union(List arg1, List arg2) { - ArrayList result = new ArrayList(arg1); + ArrayList result = new ArrayList<>(arg1); result.addAll(arg2); return result; } @@ -155,7 +155,7 @@ private static final List union(List arg1, List arg2) @SuppressWarnings("unchecked") private static final List add(List arg, T... args) { - ArrayList result = new ArrayList(arg); + ArrayList result = new ArrayList<>(arg); result.addAll(Arrays.asList(args)); return result; } @@ -164,7 +164,7 @@ private static final List add(List arg, T... args) @SuppressWarnings("unchecked") private static final List subtract(List arg, T... args) { - ArrayList result = new ArrayList(arg); + ArrayList result = new ArrayList<>(arg); result.removeAll(Arrays.asList(args)); return result; } @@ -964,7 +964,7 @@ private void testCompatibility(Object[][] inputs) throws IOException @SuppressWarnings("unchecked") List compatibilityOptions = row[i] instanceof CompatibilityOptions ? - new ArrayList(Arrays.asList((CompatibilityOptions) row[i++])) : + new ArrayList<>(Arrays.asList((CompatibilityOptions) row[i++])) : (List) row[i++]; boolean hasError = i < row.length ? (Boolean) row[i++] : false; diff --git a/data/src/test/java/com/linkedin/data/schema/generator/TestAbstractGenerator.java b/data/src/test/java/com/linkedin/data/schema/generator/TestAbstractGenerator.java index a444f971ce..5372c1a19a 100644 --- a/data/src/test/java/com/linkedin/data/schema/generator/TestAbstractGenerator.java +++ b/data/src/test/java/com/linkedin/data/schema/generator/TestAbstractGenerator.java @@ -117,7 +117,7 @@ private void generate(String targetDirectoryPath, String sources[]) throws IOExc protected List targetFiles(File targetDirectory) { Collection schemas = getSchemaResolver().bindings().values(); - ArrayList generatedFiles = new ArrayList(schemas.size()); + ArrayList generatedFiles = new ArrayList<>(schemas.size()); for (DataSchema schema : schemas) { if (schema instanceof NamedDataSchema) @@ -179,7 +179,7 @@ protected void outputSchemas(File targetDirectory) throws IOException "/error/b/c" ); - Set _expectedSchemas = new HashSet(Arrays.asList( + Set _expectedSchemas = new HashSet<>(Arrays.asList( "/a1/foo.pdsc", "/a1/x/y/z.pdsc", "/a3/b/c/baz.pdsc", @@ -373,7 +373,7 @@ public void testAbstractGenerator() throws IOException // test sources are directories targetDir = setup(testPaths, debug); - List argList = new ArrayList(); + List argList = new ArrayList<>(); argList.add(targetDir.getCanonicalPath()); for (File f : testDir.listFiles()) { @@ -382,7 +382,7 @@ public void testAbstractGenerator() throws IOException argList.add(f.getCanonicalPath()); } } - Map> a1A2Files = new HashMap>(); + Map> a1A2Files = new HashMap<>(); for (Map.Entry> e : files.entrySet()) { String pdscFileName = e.getValue().getKey(); diff --git a/data/src/test/java/com/linkedin/data/schema/resolver/TestDataSchemaResolver.java b/data/src/test/java/com/linkedin/data/schema/resolver/TestDataSchemaResolver.java index 235f704d0c..4321eaaea3 100644 --- a/data/src/test/java/com/linkedin/data/schema/resolver/TestDataSchemaResolver.java +++ b/data/src/test/java/com/linkedin/data/schema/resolver/TestDataSchemaResolver.java @@ -765,7 +765,7 @@ public void testFileDataSchemaResolver() throws IOException File testDir = TestUtil.testDir("testFileDataSchemaResolver", debug); Map> files = TestUtil.createSchemaFiles(testDir, _testSchemas, debug); - List testPaths = new ArrayList(); + List testPaths = new ArrayList<>(); for (String testPath : _testPaths) { String dirname = (testDir.getCanonicalPath() + "/" + testPath).replace('/', File.separatorChar); @@ -783,7 +783,7 @@ public void testFileDataSchemaResolver() throws IOException for (String testPath : _testPaths) { String jarFileName = (testDir.getCanonicalPath() + testPath + ".jar").replace('/', File.separatorChar); - Map jarFileContents = new HashMap(); + Map jarFileContents = new HashMap<>(); for (Map.Entry entry : _testSchemas.entrySet()) { if (entry.getKey().startsWith(testPath)) diff --git a/data/src/test/java/com/linkedin/data/schema/validator/TestValidator.java b/data/src/test/java/com/linkedin/data/schema/validator/TestValidator.java index acf46d14d7..134874aeb1 100644 --- a/data/src/test/java/com/linkedin/data/schema/validator/TestValidator.java +++ b/data/src/test/java/com/linkedin/data/schema/validator/TestValidator.java @@ -254,7 +254,7 @@ public void testBadInitializationOfDataSchemaAnnotationValidator() throws IOExce final boolean debug = false; - Map> validatorClassMap = new HashMap>(); + Map> validatorClassMap = new HashMap<>(); validatorClassMap.put("bad", BadValidator.class); for (Object[] row : input) @@ -274,7 +274,7 @@ public void testBadInitializationOfDataSchemaAnnotationValidator() throws IOExce } } - static Map> _validatorClassMap = new HashMap>(); + static Map> _validatorClassMap = new HashMap<>(); static { _validatorClassMap.put("fooValidator", FooValidator.class); @@ -793,7 +793,7 @@ private boolean isSatisfied(List list) public static class OrderValidator extends AbstractValidator { private final String _name; - private static final List _orderList = new ArrayList(); + private static final List _orderList = new ArrayList<>(); public OrderValidator(DataMap dataMap) { @@ -813,7 +813,7 @@ public void validate(ValidatorContext ctx) @Test public void testValidatorPriority() throws IOException { - Map> validatorClassMap = new HashMap>(); + Map> validatorClassMap = new HashMap<>(); validatorClassMap.put("v1", OrderValidator.class); validatorClassMap.put("v2", OrderValidator.class); validatorClassMap.put("v3", OrderValidator.class); @@ -1116,4 +1116,3 @@ public void testValidatorPriority() throws IOException } } } - diff --git a/data/src/test/java/com/linkedin/data/schema/validator/VisitedTrackingValidator.java b/data/src/test/java/com/linkedin/data/schema/validator/VisitedTrackingValidator.java index 0073618c0d..67b56d0702 100644 --- a/data/src/test/java/com/linkedin/data/schema/validator/VisitedTrackingValidator.java +++ b/data/src/test/java/com/linkedin/data/schema/validator/VisitedTrackingValidator.java @@ -23,7 +23,7 @@ public class VisitedTrackingValidator implements Validator { - private final List _visited = new ArrayList(); + private final List _visited = new ArrayList<>(); private final Validator _nextValidator; public VisitedTrackingValidator(Validator nextValidator) @@ -48,8 +48,8 @@ public List getVisited() public Set getVisitedMoreThanOnce() { - Set visitedMoreThanOnce = new HashSet(); - Set visitedSet = new HashSet(); + Set visitedMoreThanOnce = new HashSet<>(); + Set visitedSet = new HashSet<>(); for (String path : _visited) { boolean added = visitedSet.add(path); @@ -58,4 +58,4 @@ public Set getVisitedMoreThanOnce() } return visitedMoreThanOnce; } -} \ No newline at end of file +} diff --git a/data/src/test/java/com/linkedin/data/template/TestArrayTemplate.java b/data/src/test/java/com/linkedin/data/template/TestArrayTemplate.java index 8dfb313732..37fc445d24 100644 --- a/data/src/test/java/com/linkedin/data/template/TestArrayTemplate.java +++ b/data/src/test/java/com/linkedin/data/template/TestArrayTemplate.java @@ -236,7 +236,7 @@ else if (e instanceof Enum) { ArrayTemplate arrayRemove = templateClass.newInstance(); arrayRemove.addAll(input); - InternalList reference = new InternalList(input); + InternalList reference = new InternalList<>(input); arrayRemove.removeRange(from, to); reference.removeRange(from, to); assertEquals(reference, arrayRemove); @@ -246,7 +246,7 @@ else if (e instanceof Enum) // set(int index, E element) ArrayTemplate array9 = templateClass.newInstance(); array9.addAll(input); - InternalList reference9 = new InternalList(input); + InternalList reference9 = new InternalList<>(input); for (int i = 0; i < input.size() / 2; ++i) { int k = input.size() - i - 1; @@ -356,7 +356,7 @@ else if (e instanceof Enum) ArrayTemplate arrayContainsAll = templateClass.newInstance(); arrayContainsAll.addAll(input); arrayContainsAll.addAll(adds); - InternalList referenceContainsAll = new InternalList(input); + InternalList referenceContainsAll = new InternalList<>(input); referenceContainsAll.addAll(adds); for (int from = 0; from < arrayContainsAll.size(); ++from) { @@ -375,7 +375,7 @@ else if (e instanceof Enum) } // removeAll - InternalList referenceListRemoveAll = new InternalList(input); + InternalList referenceListRemoveAll = new InternalList<>(input); referenceListRemoveAll.addAll(adds); for (int from = 0; from < referenceListRemoveAll.size(); ++from) { @@ -383,7 +383,7 @@ else if (e instanceof Enum) { ArrayTemplate arrayRemoveAll = templateClass.newInstance(); arrayRemoveAll.addAll(referenceListRemoveAll); - InternalList referenceRemoveAll = new InternalList(referenceListRemoveAll); + InternalList referenceRemoveAll = new InternalList<>(referenceListRemoveAll); boolean testResult = arrayRemoveAll.removeAll(referenceListRemoveAll.subList(from, to)); boolean referenceResult = referenceRemoveAll.removeAll(referenceListRemoveAll.subList(from, to)); @@ -396,7 +396,7 @@ else if (e instanceof Enum) } // retainAll - InternalList referenceListRetainAll = new InternalList(input); + InternalList referenceListRetainAll = new InternalList<>(input); referenceListRetainAll.addAll(adds); for (int from = 0; from < referenceListRetainAll.size(); ++from) { @@ -404,7 +404,7 @@ else if (e instanceof Enum) { ArrayTemplate arrayRetainAll = templateClass.newInstance(); arrayRetainAll.addAll(referenceListRetainAll); - InternalList referenceRetainAll = new InternalList(referenceListRetainAll); + InternalList referenceRetainAll = new InternalList<>(referenceListRetainAll); boolean testResult = arrayRetainAll.removeAll(referenceListRetainAll.subList(from, to)); boolean referenceResult = referenceRetainAll.removeAll(referenceListRetainAll.subList(from, to)); @@ -984,12 +984,12 @@ public ArrayOfStringArrayTemplate copy() throws CloneNotSupportedException @Test public void testArrayOfStringArray() { - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new StringArray("input" + i)); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new StringArray("add" + i)); @@ -1078,13 +1078,13 @@ public FooRecordArray copy() throws CloneNotSupportedException @Test public void testFooRecordArray() { - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new FooRecord()); input.get(i).setBar("input " + i); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new FooRecord()); @@ -1130,7 +1130,7 @@ public void testLegacyConstructor() { ArrayDataSchema schema = (ArrayDataSchema) DataTemplateUtil.parseSchema("{ \"type\" : \"array\", \"items\" : \"" + e.getKey() + "\" }"); @SuppressWarnings("unchecked") - PrimitiveLegacyArray array = new PrimitiveLegacyArray(new DataList(), schema, (Class)e.getValue()); + PrimitiveLegacyArray array = new PrimitiveLegacyArray<>(new DataList(), schema, (Class) e.getValue()); } EnumLegacyArray enumArray = new EnumLegacyArray(new DataList()); } diff --git a/data/src/test/java/com/linkedin/data/template/TestConvertArray.java b/data/src/test/java/com/linkedin/data/template/TestConvertArray.java index 04a9668753..87416422bc 100644 --- a/data/src/test/java/com/linkedin/data/template/TestConvertArray.java +++ b/data/src/test/java/com/linkedin/data/template/TestConvertArray.java @@ -108,8 +108,8 @@ public void testComplexArray() throws IOException Assert.assertSame(result.getClass(), TestFixedTemplate.Fixed5[].class); result = convert("[{\"A\": 3}, {\"B\": 4}]", IntegerMap[].class); - final Map integerFixture1 = new HashMap(); - final Map integerFixture2 = new HashMap(); + final Map integerFixture1 = new HashMap<>(); + final Map integerFixture2 = new HashMap<>(); integerFixture1.put("A", 3); integerFixture2.put("B", 4); Assert.assertEquals(result, new IntegerMap[] { new IntegerMap(integerFixture1), new IntegerMap(integerFixture2) }); diff --git a/data/src/test/java/com/linkedin/data/template/TestCustom.java b/data/src/test/java/com/linkedin/data/template/TestCustom.java index a9358a99d4..96b623e419 100644 --- a/data/src/test/java/com/linkedin/data/template/TestCustom.java +++ b/data/src/test/java/com/linkedin/data/template/TestCustom.java @@ -193,7 +193,7 @@ public void testInitialization() @Test public void testCustomPointArray() { - final List input = new ArrayList(Arrays.asList("1,1", "2,2", "3,3")); + final List input = new ArrayList<>(Arrays.asList("1,1", "2,2", "3,3")); final DataList inputDataList = new DataList(input); CustomPointArray a1 = new CustomPointArray(); diff --git a/data/src/test/java/com/linkedin/data/template/TestDataObjectToObjectCache.java b/data/src/test/java/com/linkedin/data/template/TestDataObjectToObjectCache.java index edc3bc2635..70e27c9807 100644 --- a/data/src/test/java/com/linkedin/data/template/TestDataObjectToObjectCache.java +++ b/data/src/test/java/com/linkedin/data/template/TestDataObjectToObjectCache.java @@ -31,8 +31,8 @@ public class TestDataObjectToObjectCache @Test public void testPutAndGet() { - IdentityHashMap> controlCache = new IdentityHashMap>(); - DataObjectToObjectCache> testCache = new DataObjectToObjectCache>(); + IdentityHashMap> controlCache = new IdentityHashMap<>(); + DataObjectToObjectCache> testCache = new DataObjectToObjectCache<>(); populateTestData(controlCache, testCache); crossCheckTestData(controlCache, testCache); @@ -41,8 +41,8 @@ public void testPutAndGet() @Test public void testClone() throws CloneNotSupportedException { - IdentityHashMap> controlCache = new IdentityHashMap>(); - DataObjectToObjectCache> testCache = new DataObjectToObjectCache>(); + IdentityHashMap> controlCache = new IdentityHashMap<>(); + DataObjectToObjectCache> testCache = new DataObjectToObjectCache<>(); populateTestData(controlCache, testCache); testCache = testCache.clone(); @@ -52,7 +52,7 @@ public void testClone() throws CloneNotSupportedException @Test public void testKeyNotFound() { - DataObjectToObjectCache> testCache = new DataObjectToObjectCache>(); + DataObjectToObjectCache> testCache = new DataObjectToObjectCache<>(); Assert.assertNull(testCache.get(new Object())); Assert.assertNull(testCache.get(new DataMap())); @@ -62,7 +62,7 @@ public void testKeyNotFound() @Test public void testValueOverwrite() { - DataObjectToObjectCache> testCache = new DataObjectToObjectCache>(); + DataObjectToObjectCache> testCache = new DataObjectToObjectCache<>(); DataMap mapKey = new DataMap(); DataList listKey = new DataList(); Object objKey = new Object(); diff --git a/data/src/test/java/com/linkedin/data/template/TestDynamicRecordTemplate.java b/data/src/test/java/com/linkedin/data/template/TestDynamicRecordTemplate.java index 16a2589586..b43dd05af0 100644 --- a/data/src/test/java/com/linkedin/data/template/TestDynamicRecordTemplate.java +++ b/data/src/test/java/com/linkedin/data/template/TestDynamicRecordTemplate.java @@ -55,43 +55,43 @@ public class TestDynamicRecordTemplate ); public static final FieldDef FIELD_boolean = - new FieldDef("boolean", Boolean.class, SCHEMA.getField("boolean").getType()); + new FieldDef<>("boolean", Boolean.class, SCHEMA.getField("boolean").getType()); public static final FieldDef FIELD_int = - new FieldDef("int", Integer.class, SCHEMA.getField("int").getType()); + new FieldDef<>("int", Integer.class, SCHEMA.getField("int").getType()); public static final FieldDef FIELD_long = - new FieldDef("long", Long.class, SCHEMA.getField("long").getType()); + new FieldDef<>("long", Long.class, SCHEMA.getField("long").getType()); public static final FieldDef FIELD_float = - new FieldDef("float", Float.class, SCHEMA.getField("float").getType()); + new FieldDef<>("float", Float.class, SCHEMA.getField("float").getType()); public static final FieldDef FIELD_double = - new FieldDef("double", Double.class, SCHEMA.getField("double").getType()); + new FieldDef<>("double", Double.class, SCHEMA.getField("double").getType()); public static final FieldDef FIELD_string = - new FieldDef("string", String.class, SCHEMA.getField("string").getType()); + new FieldDef<>("string", String.class, SCHEMA.getField("string").getType()); public static final FieldDef FIELD_bytes = - new FieldDef("bytes", ByteString.class, SCHEMA.getField("bytes").getType()); + new FieldDef<>("bytes", ByteString.class, SCHEMA.getField("bytes").getType()); public static final FieldDef FIELD_enum = - new FieldDef("enum", TestRecordAndUnionTemplate.EnumType.class, SCHEMA.getField("enum").getType()); + new FieldDef<>("enum", TestRecordAndUnionTemplate.EnumType.class, SCHEMA.getField("enum").getType()); public static final FieldDef FIELD_fixed = - new FieldDef("fixed", TestRecordAndUnionTemplate.FixedType.class, SCHEMA.getField("fixed").getType()); + new FieldDef<>("fixed", TestRecordAndUnionTemplate.FixedType.class, SCHEMA.getField("fixed").getType()); public static final FieldDef FIELD_record = - new FieldDef("record", TestRecordAndUnionTemplate.Bar.class, SCHEMA.getField("record").getType()); + new FieldDef<>("record", TestRecordAndUnionTemplate.Bar.class, SCHEMA.getField("record").getType()); public static final FieldDef FIELD_fixedArray = - new FieldDef("fixedArray", TestRecordAndUnionTemplate.FixedType[].class, SCHEMA.getField("fixedArray").getType()); + new FieldDef<>("fixedArray", TestRecordAndUnionTemplate.FixedType[].class, SCHEMA.getField("fixedArray").getType()); public static final FieldDef FIELD_intArray = - new FieldDef("intArray", Integer[].class, SCHEMA.getField("intArray").getType()); + new FieldDef<>("intArray", Integer[].class, SCHEMA.getField("intArray").getType()); public static final FieldDef FIELD_recordArray = - new FieldDef("recordArray", TestRecordAndUnionTemplate.Bar[].class, SCHEMA.getField("recordArray").getType()); + new FieldDef<>("recordArray", TestRecordAndUnionTemplate.Bar[].class, SCHEMA.getField("recordArray").getType()); public static final FieldDef FIELD_enumArray = - new FieldDef("enumArray", TestRecordAndUnionTemplate.EnumType[].class, SCHEMA.getField("enumArray").getType()); + new FieldDef<>("enumArray", TestRecordAndUnionTemplate.EnumType[].class, SCHEMA.getField("enumArray").getType()); public static final FieldDef FIELD_intArrayTemplate = - new FieldDef("intArrayTemplate", IntegerArray.class, SCHEMA.getField("intArray").getType()); + new FieldDef<>("intArrayTemplate", IntegerArray.class, SCHEMA.getField("intArray").getType()); public static final FieldDef FIELD_typeRef = - new FieldDef("typeRef", CustomNumber.class, SCHEMA.getField("typeRef").getType()); + new FieldDef<>("typeRef", CustomNumber.class, SCHEMA.getField("typeRef").getType()); public static DynamicRecordMetadata METADATA; static { - ArrayList> fieldDefs = new ArrayList>(); + ArrayList> fieldDefs = new ArrayList<>(); fieldDefs.add(FIELD_boolean); fieldDefs.add(FIELD_bytes); fieldDefs.add(FIELD_double); diff --git a/data/src/test/java/com/linkedin/data/template/TestMapTemplate.java b/data/src/test/java/com/linkedin/data/template/TestMapTemplate.java index ed94c3c2e1..b753442a22 100644 --- a/data/src/test/java/com/linkedin/data/template/TestMapTemplate.java +++ b/data/src/test/java/com/linkedin/data/template/TestMapTemplate.java @@ -158,10 +158,10 @@ else if (v instanceof Enum) assertTrue(map1.equals(input)); assertFalse(map1.equals(null)); assertFalse(map1.equals(adds)); - assertFalse(map1.equals(new HashMap())); + assertFalse(map1.equals(new HashMap<>())); map2.clear(); - Map hashMap2 = new HashMap(); - List> inputList = new ArrayList>(input.entrySet()); + Map hashMap2 = new HashMap<>(); + List> inputList = new ArrayList<>(input.entrySet()); int lastHash = 0; for (int i = 0; i < inputList.size(); ++i) { @@ -401,10 +401,10 @@ else if (v instanceof Enum) assertFalse(entrySet6.contains(null)); assertFalse(entrySet6.contains(1)); assertFalse(entrySet6.contains(new Object())); - assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry(null, null))); - assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry("xxxx", null))); - assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry("xxxx", "xxxx"))); - assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry("xxxx", new Object()))); + assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry<>(null, null))); + assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry<>("xxxx", null))); + assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry<>("xxxx", "xxxx"))); + assertFalse(entrySet6.contains(new AbstractMap.SimpleEntry<>("xxxx", new Object()))); // entrySet iterator for (Map.Entry e : map6.entrySet()) @@ -538,7 +538,7 @@ else if (v instanceof Enum) map8.putAll(input); Set> entrySet7 = map7.entrySet(); assertTrue(entrySet7.isEmpty()); - Map hashMap7 = new HashMap(); + Map hashMap7 = new HashMap<>(); lastHash = 0; for (int i = 0; i < inputList.size(); ++i) { @@ -782,7 +782,7 @@ void testNumberMap(Class templateClass, String key = e.getKey(); E castToValue = castTo.get(key); assertEquals(e.getValue(), castToValue); - assertTrue(e.equals(new AbstractMap.SimpleEntry(key, castToValue))); + assertTrue(e.equals(new AbstractMap.SimpleEntry<>(key, castToValue))); assertFalse(e.equals(null)); assertFalse(e.equals(new Object())); @@ -1076,14 +1076,14 @@ public MapOfStringMapTemplate copy() throws CloneNotSupportedException @Test public void testMapOfStringMap() { - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new StringMap()); input.get(key).put("subinput" + i, "subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -1185,14 +1185,14 @@ public FooRecordMap copy() throws CloneNotSupportedException @Test public void testFooRecordMap() { - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new FooRecord()); input.get(key).setBar("subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -1255,7 +1255,7 @@ public void testLegacyConstructor() { MapDataSchema schema = (MapDataSchema) DataTemplateUtil.parseSchema("{ \"type\" : \"map\", \"values\" : \"" + e.getKey() + "\" }"); @SuppressWarnings("unchecked") - PrimitiveLegacyMap map = new PrimitiveLegacyMap(new DataMap(), schema, (Class)e.getValue()); + PrimitiveLegacyMap map = new PrimitiveLegacyMap<>(new DataMap(), schema, (Class)e.getValue()); } EnumLegacyMap enumMap = new EnumLegacyMap(new DataMap()); } diff --git a/data/src/test/java/com/linkedin/data/template/TestRecordAndUnionTemplate.java b/data/src/test/java/com/linkedin/data/template/TestRecordAndUnionTemplate.java index cd77164fdf..56988461e4 100644 --- a/data/src/test/java/com/linkedin/data/template/TestRecordAndUnionTemplate.java +++ b/data/src/test/java/com/linkedin/data/template/TestRecordAndUnionTemplate.java @@ -2585,7 +2585,7 @@ public void testUnionField() throws CloneNotSupportedException } // test memberType - List badOutputMap = new ArrayList(); + List badOutputMap = new ArrayList<>(); badOutputMap.add(Data.NULL); badOutputMap.add(new DataMap()); badOutputMap.add(new DataMap(TestUtil.asMap("int", 1, "invalid", 2))); @@ -2979,7 +2979,7 @@ public void testInvalidDataOnUnionWithAliases() throws Exception } // Test with invalid data maps for the union field - List invalidData = new ArrayList(); + List invalidData = new ArrayList<>(); invalidData.add(Data.NULL); invalidData.add(new DataMap()); invalidData.add(new DataMap(TestUtil.asMap("int", 1, "invalid", 2))); diff --git a/degrader/src/main/java/com/linkedin/util/degrader/CallTrackerImpl.java b/degrader/src/main/java/com/linkedin/util/degrader/CallTrackerImpl.java index a991b4979c..a7db427803 100644 --- a/degrader/src/main/java/com/linkedin/util/degrader/CallTrackerImpl.java +++ b/degrader/src/main/java/com/linkedin/util/degrader/CallTrackerImpl.java @@ -76,7 +76,7 @@ public class CallTrackerImpl implements CallTracker private Pending _pending = null; // This CallTrackerListener list is immutable and copy-on-write. - private volatile List _listeners = new ArrayList(); + private volatile List _listeners = new ArrayList<>(); public CallTrackerImpl(long interval) { @@ -93,7 +93,7 @@ public CallTrackerImpl(long interval, Clock clock, boolean percentileTrackingEna _interval = interval; _lastStartTime = -1; _lastResetTime = _clock.currentTimeMillis(); - _errorTypeCountsTotal = new HashMap(); + _errorTypeCountsTotal = new HashMap<>(); /* create trackers for each resolution */ _tracker = new Tracker(percentileTrackingEnabled); } @@ -167,7 +167,7 @@ public void addStatsRolloverEventListener(StatsRolloverEventListener listener) // compared to read access to deliver events // which cannot be be done while holding _lock, // copy-on-write is implemented for _listeners. - List copy = new ArrayList(_listeners); + List copy = new ArrayList<>(_listeners); copy.add(listener); _listeners = Collections.unmodifiableList(copy); } @@ -185,7 +185,7 @@ public boolean removeStatsRolloverEventListener(StatsRolloverEventListener liste // copy-on-write is implemented for _listeners. if (_listeners.contains(listener)) { - List copy = new ArrayList(_listeners); + List copy = new ArrayList<>(_listeners); removed = copy.remove(listener); _listeners = Collections.unmodifiableList(copy); } @@ -214,7 +214,7 @@ public long getCurrentErrorCountTotal() @Override public Map getCurrentErrorTypeCountsTotal() { - return Collections.unmodifiableMap(new HashMap(_errorTypeCountsTotal)); + return Collections.unmodifiableMap(new HashMap<>(_errorTypeCountsTotal)); } @Override @@ -458,7 +458,7 @@ private Tracker(boolean percentileTrackingEnabled) { _callTimeTracking = new SimpleLongTracking(); } - _errorTypeCounts = new HashMap(); + _errorTypeCounts = new HashMap<>(); reset(); } @@ -591,7 +591,7 @@ public boolean isReset() private Pending(List listeners) { - _pendingEvents = new ArrayList(4); + _pendingEvents = new ArrayList<>(4); _listeners = listeners; } @@ -691,8 +691,8 @@ public CallTrackerStats( _outstandingCount = outstandingCount; _callTimeStats = callTimeStats; - _errorTypeCounts = Collections.unmodifiableMap(new HashMap(errorTypeCounts)); - _errorTypeCountsTotal = Collections.unmodifiableMap(new HashMap(errorTypeCountsTotal)); + _errorTypeCounts = Collections.unmodifiableMap(new HashMap<>(errorTypeCounts)); + _errorTypeCountsTotal = Collections.unmodifiableMap(new HashMap<>(errorTypeCountsTotal)); } public Map getErrorTypeCounts() diff --git a/degrader/src/test/java/com/linkedin/util/degrader/TestCallTracker.java b/degrader/src/test/java/com/linkedin/util/degrader/TestCallTracker.java index 08c88e75e9..77ad5f0cb8 100644 --- a/degrader/src/test/java/com/linkedin/util/degrader/TestCallTracker.java +++ b/degrader/src/test/java/com/linkedin/util/degrader/TestCallTracker.java @@ -1277,7 +1277,7 @@ public void testRecord() private List startCall(CallTracker callTracker, int count) { - List dones = new ArrayList(); + List dones = new ArrayList<>(); for (int x = 0; x < count; x++) { dones.add(callTracker.startCall()); @@ -1300,7 +1300,7 @@ private class Listener implements CallTracker.StatsRolloverEventListener private Listener() { - _intervalRecords = new ArrayList(); + _intervalRecords = new ArrayList<>(); } private List getRecords() diff --git a/entity-stream/src/main/java/com/linkedin/entitystream/EntityStreams.java b/entity-stream/src/main/java/com/linkedin/entitystream/EntityStreams.java index 49fe7b83fb..1bb387d304 100644 --- a/entity-stream/src/main/java/com/linkedin/entitystream/EntityStreams.java +++ b/entity-stream/src/main/java/com/linkedin/entitystream/EntityStreams.java @@ -59,6 +59,6 @@ public void onAbort(Throwable e) */ public static EntityStream newEntityStream(Writer writer) { - return new EntityStreamImpl(writer); + return new EntityStreamImpl<>(writer); } } diff --git a/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/EchoServer.java b/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/EchoServer.java index 1c5449c8d6..e0a26daeba 100644 --- a/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/EchoServer.java +++ b/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/EchoServer.java @@ -54,7 +54,7 @@ public EchoServer (int port, final String name, List contextPaths, { _port = port; _server = HttpServer.create(new InetSocketAddress(_port), 0); - _sensors = new ConcurrentHashMap(); + _sensors = new ConcurrentHashMap<>(); _name = name; for (String contextPath : contextPaths) { diff --git a/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/ExampleD2Server.java b/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/ExampleD2Server.java index 741b844317..5f138bf19a 100644 --- a/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/ExampleD2Server.java +++ b/examples/d2-advanced-example/server/src/main/java/com/example/d2/server/ExampleD2Server.java @@ -97,7 +97,7 @@ private static List createAndStartEchoServers(List echoServers = new ArrayList(); + List echoServers = new ArrayList<>(); for (Map echoServerConfig : echoServerConfigs) { int port = ((Long)echoServerConfig.get("port")).intValue(); diff --git a/examples/d2-quickstart/server/src/main/java/com/example/d2/server/ExampleD2Server.java b/examples/d2-quickstart/server/src/main/java/com/example/d2/server/ExampleD2Server.java index 5af2358b21..d16281e48b 100644 --- a/examples/d2-quickstart/server/src/main/java/com/example/d2/server/ExampleD2Server.java +++ b/examples/d2-quickstart/server/src/main/java/com/example/d2/server/ExampleD2Server.java @@ -97,7 +97,7 @@ private static List createAndStartEchoServers(List echoServers = new ArrayList(); + List echoServers = new ArrayList<>(); for (Map echoServerConfig : echoServerConfigs) { int port = ((Long)echoServerConfig.get("port")).intValue(); diff --git a/examples/guice-server/server/src/main/java/com/example/fortune/impl/FortunesDB.java b/examples/guice-server/server/src/main/java/com/example/fortune/impl/FortunesDB.java index 139126400e..a7f2221cec 100644 --- a/examples/guice-server/server/src/main/java/com/example/fortune/impl/FortunesDB.java +++ b/examples/guice-server/server/src/main/java/com/example/fortune/impl/FortunesDB.java @@ -13,7 +13,7 @@ public class FortunesDB { // Create trivial db for fortunes - static Map fortunes = new HashMap(); + static Map fortunes = new HashMap<>(); static { fortunes.put(1L, "Today is your lucky day."); fortunes.put(2L, "There's no time like the present."); diff --git a/examples/quickstart/server/src/main/java/com/example/fortune/impl/FortunesResource.java b/examples/quickstart/server/src/main/java/com/example/fortune/impl/FortunesResource.java index 007516e3be..3876f14704 100644 --- a/examples/quickstart/server/src/main/java/com/example/fortune/impl/FortunesResource.java +++ b/examples/quickstart/server/src/main/java/com/example/fortune/impl/FortunesResource.java @@ -32,7 +32,7 @@ public class FortunesResource extends CollectionResourceTemplate { // Create trivial db for fortunes - static Map fortunes = new HashMap(); + static Map fortunes = new HashMap<>(); static { fortunes.put(1L, "Today is your lucky day."); fortunes.put(2L, "There's no time like the present."); diff --git a/examples/spring-server/server/src/main/java/com/example/fortune/impl/FortunesBean.java b/examples/spring-server/server/src/main/java/com/example/fortune/impl/FortunesBean.java index 5387e11c6e..411cfef11c 100644 --- a/examples/spring-server/server/src/main/java/com/example/fortune/impl/FortunesBean.java +++ b/examples/spring-server/server/src/main/java/com/example/fortune/impl/FortunesBean.java @@ -7,15 +7,15 @@ @Component("fortunesBean") public class FortunesBean { - static Map fortunes = new HashMap(); + static Map fortunes = new HashMap<>(); static { fortunes.put(1L, "Today is your lucky day."); fortunes.put(2L, "There's no time like the present. There's no time like the present. There's no time like the present. There's no time like the present."); fortunes.put(3L, "Don't worry, be happy."); } - + public String getFortune(Long id) { return fortunes.get(id); } -} \ No newline at end of file +} diff --git a/generator-test/src/test/java/com/linkedin/data/schema/generator/TestSchemaSampleDataGenerator.java b/generator-test/src/test/java/com/linkedin/data/schema/generator/TestSchemaSampleDataGenerator.java index 15aadfd0e5..0a1ce4367d 100644 --- a/generator-test/src/test/java/com/linkedin/data/schema/generator/TestSchemaSampleDataGenerator.java +++ b/generator-test/src/test/java/com/linkedin/data/schema/generator/TestSchemaSampleDataGenerator.java @@ -154,7 +154,7 @@ public void testRecordSchema() public void testUnionSchema() { final UnionDataSchema schema = (UnionDataSchema) DataTemplateUtil.getSchema(UnionTest.UnionWithNull.class); - final Set memberKeys = new HashSet(); + final Set memberKeys = new HashSet<>(); for (UnionDataSchema.Member member: schema.getMembers()) { memberKeys.add(member.getUnionMemberKey()); @@ -231,11 +231,11 @@ public void testRecursivelyReferencedSchema() } private static final Map> _dataSchemaTypeToPrimitiveJavaTypeMap = - new IdentityHashMap>(); + new IdentityHashMap<>(); private static final Map>> _dataSchemaTypeToprimitiveArrayMap = - new IdentityHashMap>>(); + new IdentityHashMap<>(); private static final Map>> _dataSchemaTypeToprimitiveMapMap = - new IdentityHashMap>>(); + new IdentityHashMap<>(); private static final SchemaSampleDataGenerator.DataGenerationOptions _spec = new SchemaSampleDataGenerator.DataGenerationOptions(); static diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestArray.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestArray.java index aa0ed5a9ae..17ff8452dc 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestArray.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestArray.java @@ -52,13 +52,13 @@ public void testStringMapArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new StringMap()); input.get(i).put("input key " + i, "value " + i); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new StringMap()); @@ -76,12 +76,12 @@ public void testStringArrayArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new StringArray("input" + i)); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new StringArray("add" + i)); @@ -112,13 +112,13 @@ public void testRecordArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new RecordBar()); input.get(i).setLocation("input " + i); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new RecordBar()); diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestCustomPoint.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestCustomPoint.java index 6ce107bdb4..02a88fca69 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestCustomPoint.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestCustomPoint.java @@ -113,7 +113,7 @@ public void testCustomPointRecordUnion() throws CloneNotSupportedException @Test public void testCustomPointRecordArray() throws CloneNotSupportedException { - final List input = new ArrayList(Arrays.asList("1,1", "2,2", "3,3")); + final List input = new ArrayList<>(Arrays.asList("1,1", "2,2", "3,3")); final DataList inputDataList = new DataList(input); CustomPointRecord record = new CustomPointRecord(); @@ -147,7 +147,7 @@ public void testCustomPointRecordMap() throws CloneNotSupportedException @Test public void testCustomPointArray() throws IOException { - final List input = new ArrayList(Arrays.asList("1,1", "2,2", "3,3")); + final List input = new ArrayList<>(Arrays.asList("1,1", "2,2", "3,3")); final DataList inputDataList = new DataList(input); final String customPointArraySchemaText = "{\"type\":\"array\",\"items\":{\"type\":\"typeref\",\"name\":\"CustomPoint\",\"namespace\":\"com.linkedin.pegasus.generator.test\",\"ref\":\"string\",\"java\":{\"class\":\"com.linkedin.data.template.TestCustom.CustomPoint\"}}}"; diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestDeprecated.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestDeprecated.java index d20e400a34..d2fe28ad94 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestDeprecated.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestDeprecated.java @@ -46,7 +46,7 @@ public void testDeprecatedTypes() @Test public void testDeprecatedMethods() throws Exception { - Map> fields = new HashMap>(); + Map> fields = new HashMap<>(); fields.put("DeprecatedInt", int.class); fields.put("Sample", int.class); fields.put("SampleTyperef", Double.class); diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestEnum.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestEnum.java index c117e16ef7..674671ba03 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestEnum.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestEnum.java @@ -46,7 +46,7 @@ private static > void testEnum(Class enumClass) // get symbols EnumDataSchema enumSchema = (EnumDataSchema) schema; - Set schemaSymbols = new HashSet(enumSchema.getSymbols()); + Set schemaSymbols = new HashSet<>(enumSchema.getSymbols()); assertNotNull(schemaSymbols); for (String symbol : schemaSymbols) diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestMap.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestMap.java index 25cff408b4..58c4575d21 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestMap.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/override/TestMap.java @@ -53,13 +53,13 @@ public void testStringArrayMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new StringArray("subinput" + i)); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -77,14 +77,14 @@ public void testStringMapMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new StringMap()); input.get(key).put("subinput" + i, "subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -103,14 +103,14 @@ public void testRecordMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new RecordBar()); input.get(key).setLocation("subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -121,4 +121,3 @@ public void testRecordMap() TestMapTemplate.testMap(templateClass, schema, input, adds); } } - diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestArray.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestArray.java index 53d37b86db..437b6e4d18 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestArray.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestArray.java @@ -53,13 +53,13 @@ public void testStringMapArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new StringMap()); input.get(i).put("input key " + i, "value " + i); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new StringMap()); @@ -77,12 +77,12 @@ public void testStringArrayArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new StringArray("input" + i)); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new StringArray("add" + i)); @@ -113,13 +113,13 @@ public void testRecordArray() Class templateClass = (Class) fieldInfo.getFieldClass(); ArrayDataSchema schema = (ArrayDataSchema) fieldInfo.getField().getType(); - List input = new ArrayList(); + List input = new ArrayList<>(); for (int i = 0; i < 5; ++i) { input.add(new RecordBar()); input.get(i).setLocation("input " + i); } - List adds = new ArrayList(); + List adds = new ArrayList<>(); for (int i = 0; i < 5; ++i) { adds.add(new RecordBar()); diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestCustomPoint.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestCustomPoint.java index 4ff73c85b6..1a4c0de151 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestCustomPoint.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestCustomPoint.java @@ -111,7 +111,7 @@ public void testCustomPointRecordUnion() throws CloneNotSupportedException @Test public void testCustomPointRecordArray() throws CloneNotSupportedException { - final List input = new ArrayList(Arrays.asList("1,1", "2,2", "3,3")); + final List input = new ArrayList<>(Arrays.asList("1,1", "2,2", "3,3")); final DataList inputDataList = new DataList(input); CustomPointRecord record = new CustomPointRecord(); @@ -145,7 +145,7 @@ public void testCustomPointRecordMap() throws CloneNotSupportedException @Test public void testCustomPointArray() throws IOException { - final List input = new ArrayList(Arrays.asList("1,1", "2,2", "3,3")); + final List input = new ArrayList<>(Arrays.asList("1,1", "2,2", "3,3")); final DataList inputDataList = new DataList(input); final String customPointArraySchemaText = "{\"type\":\"array\",\"items\":{\"type\":\"typeref\",\"name\":\"CustomPoint\",\"namespace\":\"com.linkedin.pegasus.generator.test\",\"ref\":\"string\",\"java\":{\"class\":\"com.linkedin.data.template.TestCustom.CustomPoint\"}}}"; diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestDeprecated.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestDeprecated.java index 2655266acd..5614f01e9c 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestDeprecated.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestDeprecated.java @@ -43,7 +43,7 @@ public void testDeprecatedTypes() @Test public void testDeprecatedMethods() throws Exception { - Map> fields = new HashMap>(); + Map> fields = new HashMap<>(); fields.put("DeprecatedInt", int.class); fields.put("Sample", int.class); fields.put("SampleTyperef", Double.class); diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestEnum.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestEnum.java index 4cd2ed1f2a..8f5583bdcf 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestEnum.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestEnum.java @@ -48,7 +48,7 @@ private static > void testEnum(Class enumClass) // get symbols EnumDataSchema enumSchema = (EnumDataSchema) schema; - Set schemaSymbols = new HashSet(enumSchema.getSymbols()); + Set schemaSymbols = new HashSet<>(enumSchema.getSymbols()); assertNotNull(schemaSymbols); for (String symbol : schemaSymbols) diff --git a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestMap.java b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestMap.java index df231543df..d94abf6bc6 100644 --- a/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestMap.java +++ b/generator-test/src/test/java/com/linkedin/pegasus/generator/test/TestMap.java @@ -55,13 +55,13 @@ public void testStringArrayMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new StringArray("subinput" + i)); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -79,14 +79,14 @@ public void testStringMapMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new StringMap()); input.get(key).put("subinput" + i, "subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -105,14 +105,14 @@ public void testRecordMap() Class templateClass = (Class) fieldInfo.getFieldClass(); MapDataSchema schema = (MapDataSchema) fieldInfo.getField().getType(); - Map input = new HashMap(); + Map input = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "input" + i; input.put(key, new RecordBar()); input.get(key).setLocation("subinputvalue" + i); } - Map adds = new HashMap(); + Map adds = new HashMap<>(); for (int i = 0; i < 5; ++i) { String key = "add" + i; @@ -123,4 +123,3 @@ public void testRecordMap() TestMapTemplate.testMap(templateClass, schema, input, adds); } } - diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/CaseSensitiveFileCodeWriter.java b/generator/src/main/java/com/linkedin/pegasus/generator/CaseSensitiveFileCodeWriter.java index 7fd1c16370..155e7a4321 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/CaseSensitiveFileCodeWriter.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/CaseSensitiveFileCodeWriter.java @@ -21,7 +21,7 @@ public class CaseSensitiveFileCodeWriter extends CodeWriter { private final boolean readOnly; /** Files that shall be marked as read only. */ - private final Set readonlyFiles = new HashSet(); + private final Set readonlyFiles = new HashSet<>(); /** True, generated directories to be created in lower case; False, otherwise. */ private boolean generateLowercasePath; diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/JavaCodeUtil.java b/generator/src/main/java/com/linkedin/pegasus/generator/JavaCodeUtil.java index c0de7f3812..b2803ebb3e 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/JavaCodeUtil.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/JavaCodeUtil.java @@ -133,7 +133,7 @@ public static List targetFiles(File targetDirectory, JCodeModel codeModel, */ public static List targetFiles(File targetDirectory, JCodeModel codeModel, ClassLoader classLoader, PersistentClassChecker checker, boolean generateLowercasePath) { - final List generatedFiles = new ArrayList(); + final List generatedFiles = new ArrayList<>(); for (Iterator packageIterator = codeModel.packages(); packageIterator.hasNext(); ) { @@ -192,7 +192,7 @@ public static ClassLoader classLoaderFromResolverPath(String resolverPath) } else { - final List list = new ArrayList(); + final List list = new ArrayList<>(); final StringTokenizer tokenizer = new StringTokenizer(resolverPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/JavaDataTemplateGenerator.java b/generator/src/main/java/com/linkedin/pegasus/generator/JavaDataTemplateGenerator.java index 9dd7fd81e9..06da1c66a2 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/JavaDataTemplateGenerator.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/JavaDataTemplateGenerator.java @@ -143,7 +143,7 @@ public class JavaDataTemplateGenerator extends JavaCodeGeneratorBase StringMap.class }; - PredefinedJavaClasses = new HashMap>(); + PredefinedJavaClasses = new HashMap<>(); for (Class clazz : predefinedClass) { @@ -168,8 +168,8 @@ public class JavaDataTemplateGenerator extends JavaCodeGeneratorBase private static final String DEPRECATED_KEY = "deprecated"; static final String PROJECTION_MASK_CLASSNAME = "ProjectionMask"; - private final Map _definedClasses = new HashMap(); - private final Map _generatedClasses = new HashMap(); + private final Map _definedClasses = new HashMap<>(); + private final Map _generatedClasses = new HashMap<>(); private final JClass _recordBaseClass; private final JClass _unionBaseClass; diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/TemplateSpecGenerator.java b/generator/src/main/java/com/linkedin/pegasus/generator/TemplateSpecGenerator.java index dde281d49d..bdf5c49e7d 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/TemplateSpecGenerator.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/TemplateSpecGenerator.java @@ -79,20 +79,20 @@ public class TemplateSpecGenerator /** * Map of {@link ClassTemplateSpec} to {@link DataSchemaLocation}. */ - private final Map _classToDataSchemaLocationMap = new HashMap(); + private final Map _classToDataSchemaLocationMap = new HashMap<>(); /** * Map of Java class name to a {@link DataSchema}. */ - private final Map _classNameToSchemaMap = new HashMap(100); + private final Map _classNameToSchemaMap = new HashMap<>(100); /** * Map of {@link DataSchema} to {@link ClassTemplateSpec}. */ - private final IdentityHashMap _schemaToClassMap = new IdentityHashMap(100); + private final IdentityHashMap _schemaToClassMap = new IdentityHashMap<>(100); /** * Map of {@link DataSchema} to the information about the immediate dereferenced {@link DataSchema} with custom Java class binding. */ - private final Deque _locationStack = new ArrayDeque(); - private final Map _immediateCustomMap = new IdentityHashMap(); + private final Deque _locationStack = new ArrayDeque<>(); + private final Map _immediateCustomMap = new IdentityHashMap<>(); private final DataSchemaResolver _schemaResolver; private final String _customTypeLanguage; @@ -658,7 +658,7 @@ private ClassTemplateSpec generateUnion(UnionDataSchema schema, TyperefDataSchem private UnionTemplateSpec generateUnion(UnionDataSchema schema, UnionTemplateSpec unionClass) { - final Map customInfoMap = new IdentityHashMap(schema.getMembers().size() * 2); + final Map customInfoMap = new IdentityHashMap<>(schema.getMembers().size() * 2); for (UnionDataSchema.Member member: schema.getMembers()) { @@ -747,7 +747,7 @@ private RecordTemplateSpec generateRecord(RecordDataSchema schema) processSchema(includedSchema, null, null); } - final Map customInfoMap = new IdentityHashMap(schema.getFields().size() * 2); + final Map customInfoMap = new IdentityHashMap<>(schema.getFields().size() * 2); for (RecordDataSchema.Field field : schema.getFields()) { diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/spec/ClassTemplateSpec.java b/generator/src/main/java/com/linkedin/pegasus/generator/spec/ClassTemplateSpec.java index dc9a9ff125..1b841be1c2 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/spec/ClassTemplateSpec.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/spec/ClassTemplateSpec.java @@ -156,7 +156,7 @@ public Set getModifiers() public void setModifiers(ModifierSpec... modifiers) { - _modifiers = new HashSet(Arrays.asList(modifiers)); + _modifiers = new HashSet<>(Arrays.asList(modifiers)); } public String getLocation() diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/spec/PrimitiveTemplateSpec.java b/generator/src/main/java/com/linkedin/pegasus/generator/spec/PrimitiveTemplateSpec.java index d772dbcf80..b68a69e9ff 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/spec/PrimitiveTemplateSpec.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/spec/PrimitiveTemplateSpec.java @@ -30,7 +30,7 @@ */ public class PrimitiveTemplateSpec extends ClassTemplateSpec { - private static Map _schemaTypeToAst = new HashMap(); + private static Map _schemaTypeToAst = new HashMap<>(); static { diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/spec/RecordTemplateSpec.java b/generator/src/main/java/com/linkedin/pegasus/generator/spec/RecordTemplateSpec.java index 149cffec81..44561b3a82 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/spec/RecordTemplateSpec.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/spec/RecordTemplateSpec.java @@ -35,7 +35,7 @@ public class RecordTemplateSpec extends ClassTemplateSpec public RecordTemplateSpec(RecordDataSchema schema) { setSchema(schema); - _fields = new ArrayList(); + _fields = new ArrayList<>(); } @Override diff --git a/generator/src/main/java/com/linkedin/pegasus/generator/spec/UnionTemplateSpec.java b/generator/src/main/java/com/linkedin/pegasus/generator/spec/UnionTemplateSpec.java index 4d32c10e56..9364ef7c02 100644 --- a/generator/src/main/java/com/linkedin/pegasus/generator/spec/UnionTemplateSpec.java +++ b/generator/src/main/java/com/linkedin/pegasus/generator/spec/UnionTemplateSpec.java @@ -35,7 +35,7 @@ public class UnionTemplateSpec extends ClassTemplateSpec public UnionTemplateSpec(UnionDataSchema schema) { setSchema(schema); - _members = new ArrayList(); + _members = new ArrayList<>(); } @Override @@ -122,4 +122,4 @@ public String getUnionMemberKey() return (_alias != null) ? _alias : _schema.getUnionMemberKey(); } } -} \ No newline at end of file +} diff --git a/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusOptions.java b/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusOptions.java index c730ee6c8a..7cd612401c 100644 --- a/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusOptions.java +++ b/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusOptions.java @@ -32,7 +32,7 @@ public class PegasusOptions { - public Set generationModes = new HashSet(Arrays.asList(GenerationMode.PEGASUS)); + public Set generationModes = new HashSet<>(Arrays.asList(GenerationMode.PEGASUS)); public IdlOptions idlOptions = new IdlOptions(); public ClientOptions clientOptions = new ClientOptions(); public RestModelOptions restModelOptions = new RestModelOptions(); @@ -82,7 +82,7 @@ public IdlItem(String inApiName, List inPackageNames) public static class IdlOptions { - private List _idlOptionsList = new ArrayList(); + private List _idlOptionsList = new ArrayList<>(); public void addIdlItem(String inApiName, List inPackageNames) { @@ -121,7 +121,7 @@ public ClientItem(String inRestModelFileName, String inDefaultPackage, boolean i public static class ClientOptions { - private List clientOptionsList = new ArrayList(); + private List clientOptionsList = new ArrayList<>(); public void addClientItem(String inRestModelFileName, String inDefaultPackage, boolean inKeepDataTemplates) { diff --git a/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusPlugin.java b/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusPlugin.java index 4180cc9c6e..03ec8c7f7b 100644 --- a/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusPlugin.java +++ b/gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/PegasusPlugin.java @@ -649,7 +649,7 @@ public void apply(Project project) project.getPlugins().apply(JavaPlugin.class); // this HashMap will have a PegasusOptions per sourceSet - project.getExtensions().getExtraProperties().set("pegasus", new HashMap()); + project.getExtensions().getExtraProperties().set("pegasus", new HashMap<>()); // this map will extract PegasusOptions.GenerationMode to project property project.getExtensions().getExtraProperties().set("PegasusGenerationMode", Arrays.stream(PegasusOptions.GenerationMode.values()) diff --git a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriComponent.java b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriComponent.java index bb91705dc4..1c55897570 100644 --- a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriComponent.java +++ b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriComponent.java @@ -384,7 +384,7 @@ private static void appendUTF8EncodedCharacter(final StringBuilder sb, final int private static boolean[][] creatingEncodingTables() { boolean[][] tables = new boolean[Type.values().length][]; - List l = new ArrayList(); + List l = new ArrayList<>(); l.addAll(Arrays.asList(SCHEME)); tables[Type.SCHEME.ordinal()] = creatingEncodingTable(l); @@ -666,7 +666,7 @@ public static List decodePath(URI u, boolean decode) { * @return the list of path segments. */ public static List decodePath(String path, boolean decode) { - List segments = new LinkedList(); + List segments = new LinkedList<>(); if (path == null) { return segments; diff --git a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplate.java b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplate.java index 7e0b7ebbcf..6b4fd12206 100644 --- a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplate.java +++ b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplate.java @@ -431,7 +431,7 @@ public final String createURI(String... values) { * @return the URI. */ public final String createURI(String[] values, int offset, int length) { - Map mapValues = new HashMap(); + Map mapValues = new HashMap<>(); StringBuilder b = new StringBuilder(); // Find all template variables Matcher m = TEMPLATE_NAMES_PATTERN.matcher(normalizedTemplate); @@ -547,7 +547,7 @@ public final static String createURI( final String userInfo, final String host, final String port, final String path, final String query, final String fragment, final Map values, final boolean encode) { - Map stringValues = new HashMap(); + Map stringValues = new HashMap<>(); for (Map.Entry e : values.entrySet()) { if (e.getValue() != null) stringValues.put(e.getKey(), e.getValue().toString()); @@ -811,7 +811,7 @@ public final static String createURIWithStringValues( final String path, final String query, final String fragment, final String[] values, final boolean encode) { - final Map mapValues = new HashMap(); + final Map mapValues = new HashMap<>(); final StringBuilder sb = new StringBuilder(); int offset = 0; diff --git a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplateParser.java b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplateParser.java index 62f7d02aee..3a44504745 100644 --- a/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplateParser.java +++ b/li-jersey-uri/src/main/java/com/linkedin/jersey/api/uri/UriTemplateParser.java @@ -93,7 +93,7 @@ private static Set createReserved() { '(', ')'}; - Set s = new HashSet(reserved.length); + Set s = new HashSet<>(reserved.length); for (char c : reserved) s.add(c); return s; } @@ -153,11 +153,11 @@ public int pos() { private final Pattern pattern; - private final List names = new ArrayList(); + private final List names = new ArrayList<>(); - private final List groupCounts = new ArrayList(); + private final List groupCounts = new ArrayList<>(); - private final Map nameToPattern = new HashMap(); + private final Map nameToPattern = new HashMap<>(); /** * Parse a template. @@ -435,4 +435,4 @@ private char consumeWhiteSpace(CharacterIterator ci) { return c; } -} \ No newline at end of file +} diff --git a/li-jersey-uri/src/main/java/com/linkedin/jersey/core/util/MultivaluedMap.java b/li-jersey-uri/src/main/java/com/linkedin/jersey/core/util/MultivaluedMap.java index 13317c75e5..68002667ee 100644 --- a/li-jersey-uri/src/main/java/com/linkedin/jersey/core/util/MultivaluedMap.java +++ b/li-jersey-uri/src/main/java/com/linkedin/jersey/core/util/MultivaluedMap.java @@ -183,7 +183,7 @@ public final List get(String key, Class type) { ArrayList l = null; List values = get(key); if (values != null) { - l = new ArrayList(); + l = new ArrayList<>(); for (String value: values) { try { l.add(c.newInstance(value)); @@ -238,7 +238,7 @@ public final void add(String key, Object value) { private List getList(String key) { List l = get(key); if (l == null) { - l = new LinkedList(); + l = new LinkedList<>(); put(key, l); } return l; diff --git a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEInputStream.java b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEInputStream.java index 2977b18ac3..7a8351406e 100644 --- a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEInputStream.java +++ b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEInputStream.java @@ -408,7 +408,7 @@ private MultiPartMIMEInputStream(final InputStream inputStream, final ExecutorSe { _inputStream = inputStream; _executorService = executorService; - _headers = new HashMap(headers); //defensive copy + _headers = new HashMap<>(headers); //defensive copy _maximumBlockingTime = maximumBlockingTime; _writeChunkSize = writeChunkSize; _abortTimeout = abortTimeout; diff --git a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEReader.java b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEReader.java index ca45c2e98c..feff918d7f 100644 --- a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEReader.java +++ b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEReader.java @@ -95,7 +95,7 @@ class R2MultiPartMIMEReader implements Reader //These two fields are needed to support our iterative invocation of callbacks so that we don't end up with a recursive loop //which would lead to a stack overflow. - private final Queue> _callbackQueue = new LinkedDeque>(); + private final Queue> _callbackQueue = new LinkedDeque<>(); private volatile boolean _callbackInProgress = false; /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -889,7 +889,7 @@ private Map parseHeaders(final ByteString headerBytes) } else { - headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); //We have headers, lets read them in - we search using a sliding window. @@ -1663,4 +1663,4 @@ enum SingleReaderState REQUESTED_DRAIN, //Waiting for a drain to finish. FINISHED //This reader is done. } -} \ No newline at end of file +} diff --git a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEUtils.java b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEUtils.java index a5b09892a9..e0a9d18998 100644 --- a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEUtils.java +++ b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEUtils.java @@ -127,7 +127,7 @@ static String extractBoundary(final String contentTypeHeader) throws MultiPartIl final String[] contentTypeParameters = contentTypeHeader.split(";"); //In case someone used something like bOuNdArY - final Map parameterMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map parameterMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (final String parameter : contentTypeParameters) { //We don't need the first bit here. @@ -204,4 +204,4 @@ static ByteString serializeBoundaryAndHeaders(final byte[] normalEncapsulationBo return ByteString.unsafeWrap(byteArrayOutputStream.toByteArray()); } -} \ No newline at end of file +} diff --git a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEWriter.java b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEWriter.java index 5811b7a87d..9052873181 100644 --- a/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEWriter.java +++ b/multipart-mime/src/main/java/com/linkedin/multipart/MultiPartMIMEWriter.java @@ -49,7 +49,7 @@ public final class MultiPartMIMEWriter */ public static class Builder { - private List _allDataSources = new ArrayList(); + private List _allDataSources = new ArrayList<>(); private final String _preamble; private final String _epilogue; private int _dataSourceCount = 0; @@ -303,4 +303,4 @@ public String getBoundary() { return _rawBoundary; } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/AbstractMIMEUnitTest.java b/multipart-mime/src/test/java/com/linkedin/multipart/AbstractMIMEUnitTest.java index 591c5fe118..662f57bb16 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/AbstractMIMEUnitTest.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/AbstractMIMEUnitTest.java @@ -88,7 +88,7 @@ protected void mockR2AndWrite(final ByteString payload, final int chunkSize, fin //We have to use the AtomicReference holder technique to modify the current remaining buffer since the inner class //in doAnswer() can only access final variables. - final AtomicReference r2Reader = new AtomicReference(); + final AtomicReference r2Reader = new AtomicReference<>(); //This takes the place of VariableByteStringWriter if we were to use R2 directly. final VariableByteStringViewer variableByteStringViewer = new VariableByteStringViewer(payload, chunkSize); @@ -154,4 +154,4 @@ public Object answer(InvocationOnMock invocation) throws Throwable contentType + ";somecustomparameter=somecustomvalue" + ";anothercustomparameter=anothercustomvalue"; when(_streamRequest.getHeader(MultiPartMIMEUtils.CONTENT_TYPE_HEADER)).thenReturn(contentTypeHeader); } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingAlternate.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingAlternate.java index 89474ef9a5..e49f6e5b3c 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingAlternate.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingAlternate.java @@ -121,7 +121,7 @@ private static class ServerMultiPartMIMEAlternatorCallback implements MultiPartM final CountDownLatch _latch; final Callback _callbackA; final Callback _callbackB; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); int _currentPart = 0; ServerMultiPartMIMEAlternatorCallback(final CountDownLatch latch, final Callback callbackA, @@ -191,4 +191,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingReader.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingReader.java index 64649d0af5..3eead4b964 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingReader.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingReader.java @@ -108,8 +108,7 @@ public void onSuccess(StreamResponse result) //Client callbacks: private static class ClientMultiPartMIMEReaderReceiverCallback implements MultiPartMIMEReaderCallback { - final List _singlePartMIMEReaderCallbacks = - new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); final CountDownLatch _latch; ClientMultiPartMIMEReaderReceiverCallback(final CountDownLatch latch) @@ -193,4 +192,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingSinglePart.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingSinglePart.java index 5cb53e9d7e..5a8f41c553 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingSinglePart.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEChainingSinglePart.java @@ -118,8 +118,7 @@ private static class ServerMultiPartMIMEReaderSinglePartSenderCallback implement final CountDownLatch _latch; boolean _firstPartEchoed = false; final Callback _callback; - final List _singlePartMIMEReaderCallbacks = - new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); ServerMultiPartMIMEReaderSinglePartSenderCallback(final CountDownLatch latch, final Callback callback) @@ -176,4 +175,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReader.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReader.java index 001a77fe9c..cdc6108111 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReader.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReader.java @@ -113,7 +113,7 @@ public void testEachSingleBodyDataSourceMultipleTimes(final int chunkSize, final @DataProvider(name = "multipleNormalBodiesDataSource") public Object[][] multipleNormalBodiesDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(BODY_LESS_BODY); @@ -169,7 +169,7 @@ public void testMultipleNormalBodiesDataSource(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(HEADER_LESS_BODY); bodyPartList.add(BODY_LESS_BODY); bodyPartList.add(PURELY_EMPTY_BODY); @@ -202,7 +202,7 @@ public void testMultipleAbnormalBodies(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -240,7 +240,7 @@ public void testAllTypesOfBodiesDataSource(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -372,7 +372,7 @@ private void executeRequestAndAssert(final ByteString payload, final int chunkSi final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i); //Construct expected headers and verify they match - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); while (allHeaders.hasMoreElements()) @@ -473,7 +473,7 @@ public void onStreamError(Throwable throwable) private static class MultiPartMIMEReaderCallbackImpl implements MultiPartMIMEReaderCallback { final CountDownLatch _latch; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); MultiPartMIMEReaderCallbackImpl(final CountDownLatch latch) { @@ -508,4 +508,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderClientCallbackExceptions.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderClientCallbackExceptions.java index ec1e2cc713..c70d9ba7a7 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderClientCallbackExceptions.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderClientCallbackExceptions.java @@ -59,7 +59,7 @@ public class TestMIMEReaderClientCallbackExceptions extends AbstractMIMEUnitTest @DataProvider(name = "allTypesOfBodiesDataSource") public Object[][] allTypesOfBodiesDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -454,7 +454,7 @@ private enum MultiPartMIMEThrowOnFlag private static class MultiPartMIMEExceptionReaderCallbackImpl implements MultiPartMIMEReaderCallback { - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); Throwable _streamError = null; final CountDownLatch _latch; final MultiPartMIMEReader _reader; @@ -532,4 +532,4 @@ public void onStreamError(Throwable throwable) _latch.countDown(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderDrain.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderDrain.java index 64060af1db..b9fc5da40a 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderDrain.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderDrain.java @@ -96,7 +96,7 @@ public void testDrainAllWithoutCallbackRegistered() throws Exception @DataProvider(name = "allTypesOfBodiesDataSource") public Object[][] allTypesOfBodiesDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -160,7 +160,7 @@ public void testSinglePartialTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -200,7 +200,7 @@ public void testSingleAlternateTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -233,7 +233,7 @@ public void testSingleAlternateTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -271,7 +271,7 @@ public void testSingleAll(final int chunkSize, final List bodyPart final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -310,7 +310,7 @@ public void testSingleAlternate(final int chunkSize, final List bo final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -343,7 +343,7 @@ public void testSingleAlternate(final int chunkSize, final List bo final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -476,8 +476,8 @@ private static class MultiPartMIMEDrainReaderCallbackImpl implements MultiPartMI final CountDownLatch _latch; final String _drainValue; final MultiPartMIMEReader _reader; - final Map _responseHeaders = new HashMap(); - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final Map _responseHeaders = new HashMap<>(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); MultiPartMIMEDrainReaderCallbackImpl(final CountDownLatch latch, final String drainValue, final MultiPartMIMEReader reader) @@ -572,4 +572,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderExceptions.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderExceptions.java index 7a61ca2a5e..0627dd3cc8 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderExceptions.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderExceptions.java @@ -67,7 +67,7 @@ public void setup() @DataProvider(name = "multiplePartsDataSource") public Object[][] multiplePartsDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(MIMETestUtils.SMALL_DATA_SOURCE); bodyPartList.add(MIMETestUtils.BODY_LESS_BODY); @@ -167,7 +167,7 @@ public void payloadMissingFinalBoundary(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); while (allHeaders.hasMoreElements()) @@ -256,7 +256,7 @@ public void boundaryPrematurelyTerminatedNoSubsequentCRLFs(final int chunkSize, final BodyPart currentExpectedPart = multiPartMimeBody.getBodyPart(i); //Construct expected headers and verify they match - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); while (allHeaders.hasMoreElements()) @@ -519,7 +519,7 @@ private static class MultiPartMIMEExceptionReaderCallbackImpl implements MultiPa { final CountDownLatch _latch; final MultiPartMIMEReader _reader; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); Throwable _streamError = null; MultiPartMIMEExceptionReaderCallbackImpl(final CountDownLatch latch, final MultiPartMIMEReader reader) @@ -577,4 +577,4 @@ public void onStreamError(Throwable throwable) _latch.countDown(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderR2Error.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderR2Error.java index 05902e3edd..1c99b951f6 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderR2Error.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEReaderR2Error.java @@ -161,7 +161,7 @@ public void onStreamError(Throwable throwable) private class MultiPartMIMEReaderCallbackImpl implements MultiPartMIMEReaderCallback { - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); Throwable _streamError = null; final CountDownLatch _latch; @@ -207,4 +207,4 @@ public void onStreamError(Throwable throwable) _streamError = throwable; } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEWriter.java b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEWriter.java index 0728f37c04..5b7b5ca200 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEWriter.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/TestMIMEWriter.java @@ -84,14 +84,14 @@ public class TestMIMEWriter extends AbstractMIMEUnitTest public void setup() { _normalBodyData = "abc".getBytes(); - _normalBodyHeaders = new HashMap(); + _normalBodyHeaders = new HashMap<>(); _normalBodyHeaders.put("simpleheader", "simplevalue"); //Second body has no headers _headerLessBodyData = "def".getBytes(); //Third body has only headers - _bodyLessHeaders = new HashMap(); + _bodyLessHeaders = new HashMap<>(); _normalBodyHeaders.put("header1", "value1"); _normalBodyHeaders.put("header2", "value2"); _normalBodyHeaders.put("header3", "value3"); @@ -129,7 +129,7 @@ public void testSingleDataSource(final ByteString body, final Map futureCallback = new FutureCallback(); + final FutureCallback futureCallback = new FutureCallback<>(); final FullEntityReader fullEntityReader = new FullEntityReader(futureCallback); multiPartMIMEWriter.getEntityStream().setReader(fullEntityReader); futureCallback.get(_testTimeout, TimeUnit.MILLISECONDS); @@ -155,7 +155,7 @@ public void testSingleDataSource(final ByteString body, final Map expectedParts = new ArrayList(); + final List expectedParts = new ArrayList<>(); expectedParts.add(_normalBody); expectedParts.add(_normalBody); expectedParts.add(_headerLessBody); @@ -169,7 +169,7 @@ public void testMultipleDataSources() throws Exception expectedParts.add(_normalBody); expectedParts.add(_bodyLessBody); - final List inputStreamDataSources = new ArrayList(); + final List inputStreamDataSources = new ArrayList<>(); inputStreamDataSources.add(new MultiPartMIMEInputStream.Builder(new ByteArrayInputStream(_normalBodyData), _scheduledExecutorService, _normalBodyHeaders).build()); @@ -214,7 +214,7 @@ public void testMultipleDataSources() throws Exception final MultiPartMIMEWriter multiPartMIMEWriter = multiPartMIMEWriterBuilder.build(); - final FutureCallback futureCallback = new FutureCallback(); + final FutureCallback futureCallback = new FutureCallback<>(); final FullEntityReader fullEntityReader = new FullEntityReader(futureCallback); multiPartMIMEWriter.getEntityStream().setReader(fullEntityReader); futureCallback.get(_testTimeout, TimeUnit.MILLISECONDS); @@ -244,7 +244,7 @@ public void testMultipleDataSources() throws Exception @DataProvider(name = "prependDataSources") public Object[][] prependDataSources() throws Exception { - final List expectedParts = new ArrayList(); + final List expectedParts = new ArrayList<>(); expectedParts.add(_normalBody); expectedParts.add(_headerLessBody); expectedParts.add(_purelyEmptyBody); @@ -312,7 +312,7 @@ public void testPrependDataSources(final MultiPartMIMEWriter.Builder builder, Assert.assertEquals(builder.getCurrentSize(), expectedSize); final MultiPartMIMEWriter writer = builder.build(); - final FutureCallback futureCallback = new FutureCallback(); + final FutureCallback futureCallback = new FutureCallback<>(); final FullEntityReader fullEntityReader = new FullEntityReader(futureCallback); writer.getEntityStream().setReader(fullEntityReader); futureCallback.get(_testTimeout, TimeUnit.MILLISECONDS); @@ -345,7 +345,7 @@ private static class JavaxMailMultiPartMIMEReader final String _contentTypeHeaderValue; final ByteString _payload; String _preamble; //javax mail only supports reading the preamble - final List _dataSourceList = new ArrayList(); + final List _dataSourceList = new ArrayList<>(); private JavaxMailMultiPartMIMEReader(final String contentTypeHeaderValue, final ByteString payload) { @@ -394,7 +394,7 @@ public String getName() //For our purposes, javax mail converts the body part's content (based on headers) into a string final ByteString partData = ByteString.copyString((String) bodyPart.getContent(), Charset.defaultCharset()); - final Map partHeaders = new HashMap(); + final Map partHeaders = new HashMap<>(); final Enumeration allHeaders = bodyPart.getAllHeaders(); while (allHeaders.hasMoreElements()) { @@ -521,4 +521,4 @@ public CompletableFuture> readNextChunk() { return completableFuture; } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/integ/AbstractMIMEIntegrationStreamTest.java b/multipart-mime/src/test/java/com/linkedin/multipart/integ/AbstractMIMEIntegrationStreamTest.java index 8b75a3e559..b3559f05a1 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/integ/AbstractMIMEIntegrationStreamTest.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/integ/AbstractMIMEIntegrationStreamTest.java @@ -64,11 +64,11 @@ public void setup() throws IOException @AfterClass public void tearDown() throws Exception { - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); _client.shutdown(clientShutdownCallback); clientShutdownCallback.get(); - final FutureCallback factoryShutdownCallback = new FutureCallback(); + final FutureCallback factoryShutdownCallback = new FutureCallback<>(); _clientFactory.shutdown(factoryShutdownCallback); factoryShutdownCallback.get(); @@ -116,4 +116,4 @@ public void onSuccess(StreamResponse result) } }; } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEChainingMultipleSources.java b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEChainingMultipleSources.java index f747a13e04..d922efab14 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEChainingMultipleSources.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEChainingMultipleSources.java @@ -124,15 +124,15 @@ public void setup() throws IOException public void tearDown() throws Exception { _scheduledExecutorService.shutdownNow(); - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); _client.shutdown(clientShutdownCallback); clientShutdownCallback.get(); - final FutureCallback server1ClientShutdownCallback = new FutureCallback(); + final FutureCallback server1ClientShutdownCallback = new FutureCallback<>(); _server_A_client.shutdown(server1ClientShutdownCallback); server1ClientShutdownCallback.get(); - final FutureCallback factoryShutdownCallback = new FutureCallback(); + final FutureCallback factoryShutdownCallback = new FutureCallback<>(); _clientFactory.shutdown(factoryShutdownCallback); factoryShutdownCallback.get(); @@ -220,8 +220,7 @@ private class ServerAMultiPartCallback implements MultiPartMIMEReaderCallback final Callback _incomingRequestCallback; final StreamRequest _incomingRequest; boolean _firstPartConsumed = false; - final List _singlePartMIMEReaderCallbacks = - new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); ServerAMultiPartCallback(final StreamRequest incomingRequest, final Callback callback) { @@ -313,7 +312,7 @@ public void handleRequest(StreamRequest request, RequestContext requestContext, new MultiPartMIMEInputStream.Builder(new ByteArrayInputStream(BODY_4.getPartData().copyBytes()), _scheduledExecutorService, BODY_4.getPartHeaders()).withWriteChunkSize(_chunkSize).build(); - final List dataSources = new ArrayList(); + final List dataSources = new ArrayList<>(); dataSources.add(body1DataSource); dataSources.add(body2DataSource); dataSources.add(body3DataSource); @@ -414,8 +413,7 @@ public void onSuccess(StreamResponse result) //count down the latch upon finishing. private class ClientMultiPartReceiver implements MultiPartMIMEReaderCallback { - final List _singlePartMIMEReaderCallbacks = - new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); ClientMultiPartReceiver() { @@ -454,4 +452,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReader.java b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReader.java index fc447daf7b..8eec249bce 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReader.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReader.java @@ -83,7 +83,7 @@ protected TransportDispatcher getTransportDispatcher() @Override protected Map getClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, "9000000"); return clientProperties; } @@ -145,7 +145,7 @@ public void testEachSingleBodyDataSourceMultipleTimes(final int chunkSize, final @DataProvider(name = "multipleNormalBodiesDataSource") public Object[][] multipleNormalBodiesDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(BODY_LESS_BODY); @@ -201,7 +201,7 @@ public void testMultipleNormalBodiesDataSource(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(HEADER_LESS_BODY); bodyPartList.add(BODY_LESS_BODY); bodyPartList.add(PURELY_EMPTY_BODY); @@ -234,7 +234,7 @@ public void testMultipleAbnormalBodies(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -271,7 +271,7 @@ public void testAllTypesOfBodiesDataSource(final int chunkSize, final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -350,7 +350,7 @@ private void executeRequestAndAssert(final ByteString requestPayload, final int final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - Callback callback = expectSuccessCallback(latch, status, new HashMap()); + Callback callback = expectSuccessCallback(latch, status, new HashMap<>()); _client.streamRequest(request, callback); latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertEquals(status.get(), RestStatus.OK); @@ -366,7 +366,7 @@ private void executeRequestAndAssert(final ByteString requestPayload, final int final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i); //Construct expected headers and verify they match - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); while (allHeaders.hasMoreElements()) @@ -445,7 +445,7 @@ public void onStreamError(Throwable throwable) private static class MultiPartMIMEReaderCallbackImpl implements MultiPartMIMEReaderCallback { final Callback _r2callback; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); MultiPartMIMEReaderCallbackImpl(final Callback r2callback) { @@ -509,4 +509,4 @@ public void handleRequest(StreamRequest request, RequestContext requestContext, } } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderDrain.java b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderDrain.java index fa133a37e8..ce41e2ffe6 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderDrain.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderDrain.java @@ -102,7 +102,7 @@ protected TransportDispatcher getTransportDispatcher() @Override protected Map getClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, "9000000"); return clientProperties; } @@ -112,7 +112,7 @@ protected Map getClientProperties() @DataProvider(name = "allTypesOfBodiesDataSource") public Object[][] allTypesOfBodiesDataSource() throws Exception { - final List bodyPartList = new ArrayList(); + final List bodyPartList = new ArrayList<>(); bodyPartList.add(SMALL_DATA_SOURCE); bodyPartList.add(LARGE_DATA_SOURCE); bodyPartList.add(HEADER_LESS_BODY); @@ -189,7 +189,7 @@ public void testSinglePartialTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -230,7 +230,7 @@ public void testSingleAlternateTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -263,7 +263,7 @@ public void testSingleAlternateTopRemaining(final int chunkSize, final List expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -301,7 +301,7 @@ public void testSingleAll(final int chunkSize, final List bodyPart final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -341,7 +341,7 @@ public void testSingleAlternate(final int chunkSize, final List bo final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -374,7 +374,7 @@ public void testSingleAlternate(final int chunkSize, final List bo final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i); //Construct expected headers and verify they match
 - final Map expectedHeaders = new HashMap(); + final Map expectedHeaders = new HashMap<>(); @SuppressWarnings("unchecked") final Enumeration
allHeaders = currentExpectedPart.getAllHeaders(); @@ -416,7 +416,7 @@ private MimeMultipart executeRequestWithDrainStrategy(final int chunkSize, final final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final Map responseHeaders = new HashMap(); + final Map responseHeaders = new HashMap<>(); Callback callback = expectSuccessCallback(latch, status, responseHeaders); _client.streamRequest(request, callback); latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS); @@ -480,7 +480,7 @@ private static class MultiPartMIMEDrainReaderCallbackImpl implements MultiPartMI final Callback _r2callback; final String _drainValue; final MultiPartMIMEReader _reader; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); MultiPartMIMEDrainReaderCallbackImpl(final Callback r2callback, final String drainValue, final MultiPartMIMEReader reader) @@ -614,4 +614,4 @@ public void handleRequest(StreamRequest request, RequestContext requestContext, } } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderWriter.java b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderWriter.java index e8a8b1be9f..08740e004f 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderWriter.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/integ/TestMIMEIntegrationReaderWriter.java @@ -96,14 +96,14 @@ public void dataSourceSetup() scheduledExecutorService = Executors.newScheduledThreadPool(10); _normalBodyData = "some normal body that is relatively small".getBytes(); - _normalBodyHeaders = new HashMap(); + _normalBodyHeaders = new HashMap<>(); _normalBodyHeaders.put("simpleheader", "simplevalue"); //Second body has no headers _headerLessBodyData = "a body without headers".getBytes(); //Third body has only headers - _bodyLessHeaders = new HashMap(); + _bodyLessHeaders = new HashMap<>(); _normalBodyHeaders.put("header1", "value1"); _normalBodyHeaders.put("header2", "value2"); _normalBodyHeaders.put("header3", "value3"); @@ -133,7 +133,7 @@ protected TransportDispatcher getTransportDispatcher() @Override protected Map getClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, "9000000"); return clientProperties; } @@ -176,7 +176,7 @@ public void testEachSingleBodyDataSource(final int chunkSize, final MIMEDataPart public void testEachSingleBodyDataSourceMultipleTimes(final int chunkSize, final MIMEDataPart bodyPart) throws Exception { - final List dataSources = new ArrayList(); + final List dataSources = new ArrayList<>(); for (int i = 0; i < 4; i++) { final MultiPartMIMEInputStream inputStreamDataSource = @@ -254,7 +254,7 @@ private void executeRequestAndAssert(final MultiPartMIMEWriter requestWriter, fi final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - Callback callback = expectSuccessCallback(latch, status, new HashMap()); + Callback callback = expectSuccessCallback(latch, status, new HashMap<>()); _client.streamRequest(streamRequest, callback); latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertEquals(status.get(), RestStatus.OK); @@ -342,7 +342,7 @@ public void onStreamError(Throwable throwable) private static class MultiPartMIMEReaderCallbackImpl implements MultiPartMIMEReaderCallback { final Callback _r2callback; - final List _singlePartMIMEReaderCallbacks = new ArrayList(); + final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); MultiPartMIMEReaderCallbackImpl(final Callback r2callback) { @@ -415,4 +415,4 @@ public void handleRequest(StreamRequest request, RequestContext requestContext, } } } -} \ No newline at end of file +} diff --git a/multipart-mime/src/test/java/com/linkedin/multipart/utils/MIMETestUtils.java b/multipart-mime/src/test/java/com/linkedin/multipart/utils/MIMETestUtils.java index 72f14ff965..c2f328ad97 100644 --- a/multipart-mime/src/test/java/com/linkedin/multipart/utils/MIMETestUtils.java +++ b/multipart-mime/src/test/java/com/linkedin/multipart/utils/MIMETestUtils.java @@ -131,7 +131,7 @@ public static ByteString trimTrailingCRLF(final ByteString javaxMailPayload) public static List generatePrimeNumbers(final int limit) { - final List primeNumberList = new ArrayList(); + final List primeNumberList = new ArrayList<>(); for (int i = 1; i < limit; i++) { boolean isPrimeNumber = true; @@ -379,7 +379,7 @@ public static List generateInputStreamDataSources new MultiPartMIMEInputStream.Builder(new ByteArrayInputStream(BODY_D.getPartData().copyBytes()), executorService, BODY_D.getPartHeaders()).withWriteChunkSize(chunkSize).build(); - final List dataSources = new ArrayList(); + final List dataSources = new ArrayList<>(); dataSources.add(bodyADataSource); dataSources.add(bodyBDataSource); dataSources.add(bodyCDataSource); @@ -452,7 +452,7 @@ public void onStreamError(Throwable throwable) public static class MultiPartMIMEFullReaderCallback implements MultiPartMIMEReaderCallback { - private final List _singlePartMIMEReaderCallbacks = new ArrayList(); + private final List _singlePartMIMEReaderCallbacks = new ArrayList<>(); private final CountDownLatch _finishCountDownLatch; public MultiPartMIMEFullReaderCallback() @@ -501,4 +501,4 @@ public void onStreamError(Throwable throwable) Assert.fail(); } } -} \ No newline at end of file +} diff --git a/pegasus-common/src/main/java/com/linkedin/common/callback/Callbacks.java b/pegasus-common/src/main/java/com/linkedin/common/callback/Callbacks.java index a57d14faae..e144c13bce 100644 --- a/pegasus-common/src/main/java/com/linkedin/common/callback/Callbacks.java +++ b/pegasus-common/src/main/java/com/linkedin/common/callback/Callbacks.java @@ -58,7 +58,7 @@ public static Callback empty() */ public static Callback adaptSimple(final SimpleCallback simpleCallback) { - return new SimpleCallbackAdapter(simpleCallback); + return new SimpleCallbackAdapter<>(simpleCallback); } /** diff --git a/pegasus-common/src/main/java/com/linkedin/common/callback/FutureCallback.java b/pegasus-common/src/main/java/com/linkedin/common/callback/FutureCallback.java index 7d84f9ed90..3faebd0c65 100644 --- a/pegasus-common/src/main/java/com/linkedin/common/callback/FutureCallback.java +++ b/pegasus-common/src/main/java/com/linkedin/common/callback/FutureCallback.java @@ -32,7 +32,7 @@ */ public class FutureCallback implements Future, Callback { - private final AtomicReference> _result = new AtomicReference>(); + private final AtomicReference> _result = new AtomicReference<>(); private final CountDownLatch _doneLatch = new CountDownLatch(1); @Override @@ -152,12 +152,12 @@ private static final class Result public static Result createSuccess(final T t) { - return new Result(t, null, true); + return new Result<>(t, null, true); } public static Result createError(final Throwable e) { - return new Result(null, e, false); + return new Result<>(null, e, false); } private Result(final T result, final Throwable ex, final boolean isSuccess) diff --git a/pegasus-common/src/main/java/com/linkedin/common/callback/MultiCallback.java b/pegasus-common/src/main/java/com/linkedin/common/callback/MultiCallback.java index 840169c0ec..7d19db628d 100644 --- a/pegasus-common/src/main/java/com/linkedin/common/callback/MultiCallback.java +++ b/pegasus-common/src/main/java/com/linkedin/common/callback/MultiCallback.java @@ -50,7 +50,7 @@ public MultiCallback(final Callback orig, final int count) throw new IllegalArgumentException(); } _count = new AtomicInteger(count); - _exceptions = new ConcurrentLinkedQueue(); + _exceptions = new ConcurrentLinkedQueue<>(); _callback = orig; } diff --git a/pegasus-common/src/test/java/com/linkedin/common/util/TestMapUtil.java b/pegasus-common/src/test/java/com/linkedin/common/util/TestMapUtil.java index ceae8e6221..d241ca8004 100644 --- a/pegasus-common/src/test/java/com/linkedin/common/util/TestMapUtil.java +++ b/pegasus-common/src/test/java/com/linkedin/common/util/TestMapUtil.java @@ -33,8 +33,8 @@ public class TestMapUtil @BeforeTest private void prepareMap() { - _subjectMap = new HashMap(); - _probeMap = new HashMap(); + _subjectMap = new HashMap<>(); + _probeMap = new HashMap<>(); _subjectMap.put("boolean", true); _subjectMap.put("integer", 1); diff --git a/r2-core/src/main/java/com/linkedin/r2/caprep/ReplayFilter.java b/r2-core/src/main/java/com/linkedin/r2/caprep/ReplayFilter.java index aaf50f254c..e74949810f 100644 --- a/r2-core/src/main/java/com/linkedin/r2/caprep/ReplayFilter.java +++ b/r2-core/src/main/java/com/linkedin/r2/caprep/ReplayFilter.java @@ -77,7 +77,7 @@ private boolean replayResponse(RestRequest req, RequestContext requestContext, // We create an empty map instead of Collections.emptyMap, because upstream filters may // try to modify the map. - final Map wireAttrs = new HashMap(); + final Map wireAttrs = new HashMap<>(); // For symmetry with CaptureFilter - if the REST response is "not OK" then we treat it as an // exception. diff --git a/r2-core/src/main/java/com/linkedin/r2/caprep/db/DirectoryDbSource.java b/r2-core/src/main/java/com/linkedin/r2/caprep/db/DirectoryDbSource.java index 0687da35d4..9c2e01040b 100644 --- a/r2-core/src/main/java/com/linkedin/r2/caprep/db/DirectoryDbSource.java +++ b/r2-core/src/main/java/com/linkedin/r2/caprep/db/DirectoryDbSource.java @@ -85,7 +85,7 @@ public RestResponse replay(RestRequest req) private Map loadDb(File dir, MessageSerializer serializer) throws IOException { - final Map db = new HashMap(); + final Map db = new HashMap<>(); final String[] ids = DirectoryDbUtil.listRequestIds(dir); Arrays.sort(ids); diff --git a/r2-core/src/main/java/com/linkedin/r2/caprep/db/TransientDb.java b/r2-core/src/main/java/com/linkedin/r2/caprep/db/TransientDb.java index c7d8ba8c6a..73704c2b5a 100644 --- a/r2-core/src/main/java/com/linkedin/r2/caprep/db/TransientDb.java +++ b/r2-core/src/main/java/com/linkedin/r2/caprep/db/TransientDb.java @@ -31,7 +31,7 @@ */ public class TransientDb implements DbSource, DbSink { - private final ConcurrentMap _db = new ConcurrentHashMap(); + private final ConcurrentMap _db = new ConcurrentHashMap<>(); @Override public void record(RestRequest req, RestResponse res) diff --git a/r2-core/src/main/java/com/linkedin/r2/filter/FilterChainImpl.java b/r2-core/src/main/java/com/linkedin/r2/filter/FilterChainImpl.java index 725f3193f7..f324960fc1 100644 --- a/r2-core/src/main/java/com/linkedin/r2/filter/FilterChainImpl.java +++ b/r2-core/src/main/java/com/linkedin/r2/filter/FilterChainImpl.java @@ -46,8 +46,8 @@ public FilterChainImpl() private FilterChainImpl(List restFilters, List streamFilters) { - _restFilters = Collections.unmodifiableList(new ArrayList(restFilters)); - _streamFilters = Collections.unmodifiableList(new ArrayList(streamFilters)); + _restFilters = Collections.unmodifiableList(new ArrayList<>(restFilters)); + _streamFilters = Collections.unmodifiableList(new ArrayList<>(streamFilters)); } @Override @@ -80,12 +80,12 @@ public FilterChain addLast(StreamFilter filter) @Override public List getRestFilters() { - return new ArrayList(_restFilters); + return new ArrayList<>(_restFilters); } @Override public List getStreamFilters() { - return new ArrayList(_streamFilters); + return new ArrayList<>(_streamFilters); } private RestFilter decorateRestFilter(RestFilter filter) @@ -151,7 +151,7 @@ public void onStreamError(Exception ex, private List doAddFirst(List list, T obj) { - final List newFilters = new ArrayList(list.size() + 1); + final List newFilters = new ArrayList<>(list.size() + 1); newFilters.add(obj); newFilters.addAll(list); return newFilters; @@ -159,7 +159,7 @@ private List doAddFirst(List list, T obj) private List doAddLast(List list, T obj) { - final List newFilters = new ArrayList(list.size() + 1); + final List newFilters = new ArrayList<>(list.size() + 1); newFilters.addAll(list); newFilters.add(obj); return newFilters; diff --git a/r2-core/src/main/java/com/linkedin/r2/filter/transport/ResponseFilter.java b/r2-core/src/main/java/com/linkedin/r2/filter/transport/ResponseFilter.java index 0b3ffa5775..bc713070b1 100644 --- a/r2-core/src/main/java/com/linkedin/r2/filter/transport/ResponseFilter.java +++ b/r2-core/src/main/java/com/linkedin/r2/filter/transport/ResponseFilter.java @@ -107,7 +107,7 @@ private TransportCallback getCallback(RequestContext context) if (callback == null) { _log.error("No callback registered in local attributes. Caller will not get response. Attributes: " + context); - callback = new NullTransportCallback(); + callback = new NullTransportCallback<>(); } return callback; } diff --git a/r2-core/src/main/java/com/linkedin/r2/message/BaseMessageBuilder.java b/r2-core/src/main/java/com/linkedin/r2/message/BaseMessageBuilder.java index 1a0b3b3f15..aaca3500aa 100644 --- a/r2-core/src/main/java/com/linkedin/r2/message/BaseMessageBuilder.java +++ b/r2-core/src/main/java/com/linkedin/r2/message/BaseMessageBuilder.java @@ -110,7 +110,7 @@ public B addCookie(String cookie) @Override public B setCookies(List cookies) { - _cookies = new ArrayList(cookies); + _cookies = new ArrayList<>(cookies); return thisBuilder(); } @@ -216,7 +216,7 @@ public B unsafeAddHeaderValue(String name, String value) */ public B unsafeSetHeaders(Map headers) { - _headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + _headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); return unsafeOverwriteHeaders(headers); } @@ -304,7 +304,7 @@ private void validateFieldName(String name) protected Map getCanonicalHeaders() { final Map orig = getHeaders(); - final Map headers = new HashMap(orig.size()); + final Map headers = new HashMap<>(orig.size()); for (Map.Entry entry : orig.entrySet()) { final String key = entry.getKey().toLowerCase(); @@ -321,7 +321,7 @@ protected Map getCanonicalHeaders() protected List getCanonicalCookies() { final List orig = getCookies(); - final List cookies = new ArrayList(orig.size()); + final List cookies = new ArrayList<>(orig.size()); for (String entry : orig) { final String value = CANONICAL_PATTERN.matcher(entry.trim()).replaceAll(CANONICAL_REPLACEMENT); diff --git a/r2-core/src/main/java/com/linkedin/r2/message/QueryTunnelUtil.java b/r2-core/src/main/java/com/linkedin/r2/message/QueryTunnelUtil.java index 044e428f83..3435fbdaad 100644 --- a/r2-core/src/main/java/com/linkedin/r2/message/QueryTunnelUtil.java +++ b/r2-core/src/main/java/com/linkedin/r2/message/QueryTunnelUtil.java @@ -301,7 +301,7 @@ private static RestRequest doDecode(final RestRequest request, RequestContext re RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override - Map h = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map h = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); h.putAll(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); diff --git a/r2-core/src/main/java/com/linkedin/r2/message/rest/RestUtil.java b/r2-core/src/main/java/com/linkedin/r2/message/rest/RestUtil.java index 2c507655e2..0ff2379f6f 100644 --- a/r2-core/src/main/java/com/linkedin/r2/message/rest/RestUtil.java +++ b/r2-core/src/main/java/com/linkedin/r2/message/rest/RestUtil.java @@ -41,7 +41,7 @@ public class RestUtil public static List getHeaderValues(String headerValue) { final String[] elems = COMMA_PATTERN.split(headerValue); - final List values = new ArrayList(); + final List values = new ArrayList<>(); // Per RFC 2616, section 2.1, a null list element should not be treated as a value. for (String elem : elems) diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/AbstractClient.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/AbstractClient.java index db6c930351..2b5396962f 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/AbstractClient.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/AbstractClient.java @@ -64,7 +64,7 @@ public Future restRequest(RestRequest request) @Override public Future restRequest(RestRequest request, RequestContext requestContext) { - final FutureCallback future = new FutureCallback(); + final FutureCallback future = new FutureCallback<>(); restRequest(request, requestContext, future); return future; } diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/WireAttributeHelper.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/WireAttributeHelper.java index 976b478286..83d4002aa1 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/WireAttributeHelper.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/WireAttributeHelper.java @@ -49,7 +49,7 @@ public static Map newWireAttributes() */ public static Map removeWireAttributes(Map map) { - final Map wireAttrs = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map wireAttrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { @@ -77,7 +77,7 @@ public static Map removeWireAttributes(Map map) */ public static Map toWireAttributes(Map attrs) { - final Map wireAttrs = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map wireAttrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry entry : attrs.entrySet()) { diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/client/TransportClientAdapter.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/client/TransportClientAdapter.java index 571b1cc6e0..5b6b0f89b8 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/client/TransportClientAdapter.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/client/TransportClientAdapter.java @@ -67,9 +67,9 @@ public void streamRequest(StreamRequest request, RequestContext requestContext, Callback callback) { - final Map wireAttrs = new HashMap(); + final Map wireAttrs = new HashMap<>(); //make a copy of the caller's RequestContext to ensure that we have a unique instance per-request - _client.streamRequest(request, new RequestContext(requestContext), wireAttrs, new TransportCallbackAdapter(callback)); + _client.streamRequest(request, new RequestContext(requestContext), wireAttrs, new TransportCallbackAdapter<>(callback)); } @Override @@ -77,9 +77,9 @@ public void restRequest(RestRequest request, RequestContext requestContext, Call { if (!_restOverStream) { - final Map wireAttrs = new HashMap(); + final Map wireAttrs = new HashMap<>(); //make a copy of the caller's RequestContext to ensure that we have a unique instance per-request - _client.restRequest(request, new RequestContext(requestContext), wireAttrs, new TransportCallbackAdapter(callback)); + _client.restRequest(request, new RequestContext(requestContext), wireAttrs, new TransportCallbackAdapter<>(callback)); } else { diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/common/TransportResponseImpl.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/common/TransportResponseImpl.java index e8d4970f73..4ebfbe02e0 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/common/TransportResponseImpl.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/common/TransportResponseImpl.java @@ -40,7 +40,7 @@ public class TransportResponseImpl implements TransportResponse */ public static TransportResponse success(T response) { - return new TransportResponseImpl(response, null, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); + return new TransportResponseImpl<>(response, null, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); } /** @@ -55,7 +55,7 @@ public static TransportResponse success(T response, Map w { Map caseInsensitiveWireAttrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveWireAttrs.putAll(wireAttrs); - return new TransportResponseImpl(response, null, caseInsensitiveWireAttrs); + return new TransportResponseImpl<>(response, null, caseInsensitiveWireAttrs); } /** @@ -70,7 +70,7 @@ public static TransportResponse error(Throwable error, Map caseInsensitiveWireAttrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveWireAttrs.putAll(wireAttrs); - return new TransportResponseImpl(null, error, caseInsensitiveWireAttrs); + return new TransportResponseImpl<>(null, error, caseInsensitiveWireAttrs); } /** @@ -82,7 +82,7 @@ public static TransportResponse error(Throwable error, Map TransportResponse error(Throwable error) { - return new TransportResponseImpl(null, error, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); + return new TransportResponseImpl<>(null, error, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); } private TransportResponseImpl(T response, Throwable error, Map wireAttrs) diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/ContextDispatcher.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/ContextDispatcher.java index 80c72feb99..14c8e041df 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/ContextDispatcher.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/ContextDispatcher.java @@ -79,13 +79,13 @@ public void handleRequest(RestRequest request, RequestContext requestContext, Ca */ public ContextDispatcher(Map restDispatcher) { - _streamHandlers = new HashMap(); + _streamHandlers = new HashMap<>(); for (Map.Entry entry : restDispatcher.entrySet()) { _streamHandlers.put(entry.getKey(), new StreamRequestHandlerAdapter(entry.getValue())); } - _restHandlers = new HashMap(restDispatcher); + _restHandlers = new HashMap<>(restDispatcher); } @Override @@ -95,7 +95,7 @@ public void handleRestRequest(RestRequest req, Map wireAttrs, final RestRequestHandler handler = getHandler(req.getURI(), _restHandlers, DEFAULT_REST_HANDLER); try { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { @@ -113,7 +113,7 @@ public void handleStreamRequest(StreamRequest req, Map wireAttrs try { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportCallbackAdapter.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportCallbackAdapter.java index 6a2a07a338..76788e8bf0 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportCallbackAdapter.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportCallbackAdapter.java @@ -45,14 +45,14 @@ public TransportCallbackAdapter(TransportCallback callback) @Override public void onSuccess(T res) { - final Map wireAttrs = new HashMap(); + final Map wireAttrs = new HashMap<>(); _callback.onResponse(TransportResponseImpl.success(res, wireAttrs)); } @Override public void onError(Throwable e) { - final Map wireAttrs = new HashMap(); + final Map wireAttrs = new HashMap<>(); _callback.onResponse(TransportResponseImpl.error(e, wireAttrs)); } } diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherBuilder.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherBuilder.java index 8aa91e1fde..53f9f2bdfc 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherBuilder.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherBuilder.java @@ -45,14 +45,14 @@ public TransportDispatcherBuilder() public TransportDispatcherBuilder(boolean restOverStream) { - this(new HashMap(), new HashMap(), restOverStream); + this(new HashMap<>(), new HashMap<>(), restOverStream); } public TransportDispatcherBuilder(Map restHandlers, Map streamHandlers, boolean restOverStream) { - _restHandlers = new HashMap(restHandlers); - _streamHandlers = new HashMap(streamHandlers); - _adaptedHandlers = new HashMap(); + _restHandlers = new HashMap<>(restHandlers); + _streamHandlers = new HashMap<>(streamHandlers); + _adaptedHandlers = new HashMap<>(); _restOverStream = restOverStream; } @@ -98,7 +98,7 @@ public TransportDispatcherBuilder reset() public TransportDispatcher build() { - Map mergedStreamHandlers = new HashMap(_adaptedHandlers); + Map mergedStreamHandlers = new HashMap<>(_adaptedHandlers); mergedStreamHandlers.putAll(_streamHandlers); return new TransportDispatcherImpl(_restHandlers, mergedStreamHandlers); } diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherImpl.java b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherImpl.java index 55d4be2afd..ca89a1c79b 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherImpl.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/common/bridge/server/TransportDispatcherImpl.java @@ -45,8 +45,8 @@ /* package private */ TransportDispatcherImpl(Map restHandlers, Map streamHandlers) { - _streamHandlers = streamHandlers == null ? Collections.emptyMap() : new HashMap(streamHandlers); - _restHandlers = restHandlers == null ? Collections.emptyMap() : new HashMap(restHandlers); + _streamHandlers = streamHandlers == null ? Collections.emptyMap() : new HashMap<>(streamHandlers); + _restHandlers = restHandlers == null ? Collections.emptyMap() : new HashMap<>(restHandlers); } @Override @@ -63,7 +63,7 @@ public void handleRestRequest(RestRequest req, Map wireAttrs, try { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { @@ -90,7 +90,7 @@ public void handleStreamRequest(StreamRequest req, Map wireAttrs try { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/AsyncPoolImpl.java b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/AsyncPoolImpl.java index 7719b80c42..f6c8f6c53e 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/AsyncPoolImpl.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/AsyncPoolImpl.java @@ -88,7 +88,7 @@ public enum Strategy { MRU, LRU } private int _checkedOut = 0; // Unused objects live here, sorted by age. // The first object is the least recently added object. - private final Deque> _idle = new LinkedList>(); + private final Deque> _idle = new LinkedList<>(); // When no unused objects are available, callbacks live here while they wait // for a new object (either returned by another user, or newly created) private final LinkedDeque> _waiters = new LinkedDeque<>(); @@ -335,7 +335,7 @@ public Collection> cancelWaiters() { synchronized (_lock) { - List> cancelled = new ArrayList>(_waiters.size()); + List> cancelled = new ArrayList<>(_waiters.size()); for (Callback item; (item = _waiters.poll()) != null;) { cancelled.add(item); @@ -352,7 +352,7 @@ public Cancellable get(final Callback callback) boolean create = false; boolean reject = false; final LinkedDeque.Node> node; - Callback callbackWithTracking = new TimeTrackingCallback(callback); + Callback callbackWithTracking = new TimeTrackingCallback<>(callback); for (;;) { TimedObject obj = null; @@ -479,7 +479,7 @@ private void add(T obj) waiter = _waiters.poll(); if (waiter == null) { - _idle.offerLast(new TimedObject(obj)); + _idle.offerLast(new TimedObject<>(obj)); } else { @@ -754,7 +754,7 @@ private void timeoutObjects() private Collection getExpiredObjects() { - List expiredObjects = new ArrayList(); + List expiredObjects = new ArrayList<>(); long now = _clock.currentTimeMillis(); synchronized (_lock) diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/ExponentialBackOffRateLimiter.java b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/ExponentialBackOffRateLimiter.java index fdbbcf3938..fa6822a90c 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/ExponentialBackOffRateLimiter.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/ExponentialBackOffRateLimiter.java @@ -45,7 +45,7 @@ public class ExponentialBackOffRateLimiter implements RateLimiter private final long _initialIncrement; private final long _maxPeriod; private final int _maxRunningTasks; - private final Queue _pending = new LinkedList(); + private final Queue _pending = new LinkedList<>(); private long _period; private int _runningTasks; private ScheduledFuture _task; @@ -185,7 +185,7 @@ public Collection cancelPendingTasks() { synchronized (this) { - Collection cancelled = new ArrayList(_pending.size()); + Collection cancelled = new ArrayList<>(_pending.size()); for (Task item; (item = _pending.poll()) != null;) { cancelled.add(item); diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/TimeoutTransportCallback.java b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/TimeoutTransportCallback.java index a56cf85a6f..c55475f033 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/http/client/TimeoutTransportCallback.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/http/client/TimeoutTransportCallback.java @@ -60,7 +60,7 @@ public TimeoutTransportCallback(ScheduledExecutorService scheduler, final TransportCallback callback, final String timeoutMessage) { - _timeout = new Timeout>(scheduler, timeout, timeoutUnit, callback); + _timeout = new Timeout<>(scheduler, timeout, timeoutUnit, callback); _timeout.addTimeoutTask(new Runnable() { @Override diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/http/server/AbstractR2Servlet.java b/r2-core/src/main/java/com/linkedin/r2/transport/http/server/AbstractR2Servlet.java index f501208806..7f4f0d93c5 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/http/server/AbstractR2Servlet.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/http/server/AbstractR2Servlet.java @@ -89,7 +89,7 @@ protected void service(final HttpServletRequest req, final HttpServletResponse r } final AtomicReference> result = - new AtomicReference>(); + new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); TransportCallback callback = new TransportCallback() diff --git a/r2-core/src/main/java/com/linkedin/r2/transport/http/server/HttpDispatcher.java b/r2-core/src/main/java/com/linkedin/r2/transport/http/server/HttpDispatcher.java index 64f528bf5e..6ccef9847b 100644 --- a/r2-core/src/main/java/com/linkedin/r2/transport/http/server/HttpDispatcher.java +++ b/r2-core/src/main/java/com/linkedin/r2/transport/http/server/HttpDispatcher.java @@ -88,7 +88,7 @@ public void handleRequest(RestRequest req, { markOnRequestTimings(context); - final Map headers = new HashMap(req.getHeaders()); + final Map headers = new HashMap<>(req.getHeaders()); final Map wireAttrs = WireAttributeHelper.removeWireAttributes(headers); try @@ -137,7 +137,7 @@ public void handleRequest(StreamRequest req, { markOnRequestTimings(context); - final Map headers = new HashMap(req.getHeaders()); + final Map headers = new HashMap<>(req.getHeaders()); final Map wireAttrs = WireAttributeHelper.removeWireAttributes(headers); final BaseConnector connector = new BaseConnector(); diff --git a/r2-core/src/main/java/com/linkedin/r2/util/ClosableQueue.java b/r2-core/src/main/java/com/linkedin/r2/util/ClosableQueue.java index 850c4c668a..c069390c3d 100644 --- a/r2-core/src/main/java/com/linkedin/r2/util/ClosableQueue.java +++ b/r2-core/src/main/java/com/linkedin/r2/util/ClosableQueue.java @@ -53,7 +53,7 @@ public class ClosableQueue // Could consider changing this to a ConcurrentLinkedQueue, and using a spin loop // in close instead of blocking via take(). - private final BlockingQueue _queue = new LinkedBlockingQueue(); + private final BlockingQueue _queue = new LinkedBlockingQueue<>(); private final AtomicBoolean _closing = new AtomicBoolean(false); /** @@ -103,7 +103,7 @@ public List ensureClosed() } boolean interrupted = false; int count = _count.get(); - List members = new ArrayList(count); + List members = new ArrayList<>(count); while (count >= 0) { if (_count.compareAndSet(count, count - 1)) diff --git a/r2-core/src/main/java/com/linkedin/r2/util/ConfigValueExtractor.java b/r2-core/src/main/java/com/linkedin/r2/util/ConfigValueExtractor.java index 24b665dfe7..e7ae7673f7 100644 --- a/r2-core/src/main/java/com/linkedin/r2/util/ConfigValueExtractor.java +++ b/r2-core/src/main/java/com/linkedin/r2/util/ConfigValueExtractor.java @@ -19,7 +19,7 @@ public class ConfigValueExtractor */ public static List buildList(Object propertyValue, String listSeparator) { - List valueList = new ArrayList(); + List valueList = new ArrayList<>(); if (propertyValue != null) { if (propertyValue instanceof List) diff --git a/r2-core/src/main/java/com/linkedin/r2/util/LinkedDeque.java b/r2-core/src/main/java/com/linkedin/r2/util/LinkedDeque.java index 07408ec236..72bb46342d 100644 --- a/r2-core/src/main/java/com/linkedin/r2/util/LinkedDeque.java +++ b/r2-core/src/main/java/com/linkedin/r2/util/LinkedDeque.java @@ -113,7 +113,7 @@ public Node addBeforeNode(Node before, T item) { throw new IllegalStateException("node was already removed"); } - Node node = new Node(item); + Node node = new Node<>(item); if (before == null) { // Adding to tail diff --git a/r2-core/src/main/java/com/linkedin/r2/util/Timeout.java b/r2-core/src/main/java/com/linkedin/r2/util/Timeout.java index 85ccb5b2e5..2c8d7f5f40 100644 --- a/r2-core/src/main/java/com/linkedin/r2/util/Timeout.java +++ b/r2-core/src/main/java/com/linkedin/r2/util/Timeout.java @@ -44,7 +44,7 @@ public class Timeout implements TimeoutExecutor private final AtomicReference _item; private final ScheduledFuture _future; - private final ClosableQueue _queue = new ClosableQueue(); + private final ClosableQueue _queue = new ClosableQueue<>(); /** * Construct a new instance with the specified parameters. diff --git a/r2-core/src/main/java/com/linkedin/r2/util/TimeoutRunnable.java b/r2-core/src/main/java/com/linkedin/r2/util/TimeoutRunnable.java index 7397830398..e84888a39c 100644 --- a/r2-core/src/main/java/com/linkedin/r2/util/TimeoutRunnable.java +++ b/r2-core/src/main/java/com/linkedin/r2/util/TimeoutRunnable.java @@ -57,7 +57,7 @@ public TimeoutRunnable(ScheduledExecutorService executor, long timeout, TimeUnit { throw new NullPointerException(); } - _timeout = new Timeout(executor, timeout, timeoutUnit, action); + _timeout = new Timeout<>(executor, timeout, timeoutUnit, action); _timeout.addTimeoutTask(new Runnable() { @Override diff --git a/r2-core/src/test/java/com/linkedin/r2/util/TestConfigValueExtractor.java b/r2-core/src/test/java/com/linkedin/r2/util/TestConfigValueExtractor.java index f7b2990e93..4ffaaca0b6 100644 --- a/r2-core/src/test/java/com/linkedin/r2/util/TestConfigValueExtractor.java +++ b/r2-core/src/test/java/com/linkedin/r2/util/TestConfigValueExtractor.java @@ -31,7 +31,7 @@ public void testStringObject() @Test public void testListObject() { - List inputList = new ArrayList(); + List inputList = new ArrayList<>(); inputList.add("foo"); inputList.add("bar"); inputList.add("baz"); @@ -43,7 +43,7 @@ public void testListObject() @Test public void testListAndString() { - List inputList = new ArrayList(); + List inputList = new ArrayList<>(); inputList.add("foo"); inputList.add("bar"); inputList.add("baz"); diff --git a/r2-core/src/test/java/com/linkedin/r2/util/TestLinkedDeque.java b/r2-core/src/test/java/com/linkedin/r2/util/TestLinkedDeque.java index 5928fbff99..987c95c35d 100644 --- a/r2-core/src/test/java/com/linkedin/r2/util/TestLinkedDeque.java +++ b/r2-core/src/test/java/com/linkedin/r2/util/TestLinkedDeque.java @@ -45,8 +45,8 @@ public class TestLinkedDeque @Test public void testAdd() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(99); q.add(99); @@ -57,8 +57,8 @@ public void testAdd() @Test public void testAddLast() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(99); q.addLast(99); @@ -69,8 +69,8 @@ public void testAddLast() @Test public void testAddFirst() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(0, 99); q.addFirst(99); @@ -81,8 +81,8 @@ public void testAddFirst() @Test public void testOffer() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(99); Assert.assertTrue(q.offer(99)); @@ -93,8 +93,8 @@ public void testOffer() @Test public void testOfferLast() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(99); Assert.assertTrue(q.offerLast(99)); @@ -105,8 +105,8 @@ public void testOfferLast() @Test public void testOfferFirst() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); control.add(0, 99); Assert.assertTrue(q.offerFirst(99)); @@ -117,8 +117,8 @@ public void testOfferFirst() @Test public void testRemove() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.remove(), control.remove(0)); Assert.assertEquals(q, control); @@ -127,8 +127,8 @@ public void testRemove() @Test public void testRemoveFirst() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.removeFirst(), control.remove(0)); Assert.assertEquals(q, control); @@ -137,8 +137,8 @@ public void testRemoveFirst() @Test public void testRemoveLast() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.removeLast(), control.remove(control.size() - 1)); Assert.assertEquals(q, control); @@ -147,8 +147,8 @@ public void testRemoveLast() @Test public void testPoll() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.poll(), control.remove(0)); Assert.assertEquals(q, control); @@ -157,8 +157,8 @@ public void testPoll() @Test public void testPollFirst() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.pollFirst(), control.remove(0)); Assert.assertEquals(q, control); @@ -167,8 +167,8 @@ public void testPollFirst() @Test public void testPollLast() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.pollLast(), control.remove(control.size() - 1)); Assert.assertEquals(q, control); @@ -177,8 +177,8 @@ public void testPollLast() @Test public void testPeek() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.peek(), control.get(0)); Assert.assertEquals(q, control); @@ -187,8 +187,8 @@ public void testPeek() @Test public void testPeekFirst() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.peekFirst(), control.get(0)); Assert.assertEquals(q, control); @@ -197,8 +197,8 @@ public void testPeekFirst() @Test public void testPeekLast() { - List control = new ArrayList(Arrays.asList(1, 2, 3)); - LinkedDeque q = new LinkedDeque(control); + List control = new ArrayList<>(Arrays.asList(1, 2, 3)); + LinkedDeque q = new LinkedDeque<>(control); Assert.assertEquals(q.peekLast(), control.get(control.size() - 1)); Assert.assertEquals(q, control); @@ -207,7 +207,7 @@ public void testPeekLast() @Test public void testEmptyRemove() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.remove(); @@ -222,7 +222,7 @@ public void testEmptyRemove() @Test public void testEmptyRemoveFirst() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.removeFirst(); @@ -237,7 +237,7 @@ public void testEmptyRemoveFirst() @Test public void testEmptyRemoveLast() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.removeLast(); @@ -252,49 +252,49 @@ public void testEmptyRemoveLast() @Test public void testEmptyPoll() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.poll(), "poll on empty queue should return null"); } @Test public void testEmptyPollFirst() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.pollFirst(), "pollFirst on empty queue should return null"); } @Test public void testEmptyPollLast() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.pollLast(), "pollLast on empty queue should return null"); } @Test public void testEmptyPeek() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.peek(), "peek on empty queue should return null"); } @Test public void testEmptyPeekFirst() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.peekFirst(), "peekFirst on empty queue should return null"); } @Test public void testEmptyPeekLast() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); Assert.assertNull(q.peekLast(), "peekLast on empty queue should return null"); } @Test public void testAddNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.add(null); @@ -309,7 +309,7 @@ public void testAddNull() @Test public void testAddFirstNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.addFirst(null); @@ -324,7 +324,7 @@ public void testAddFirstNull() @Test public void testAddLastNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.addLast(null); @@ -339,7 +339,7 @@ public void testAddLastNull() @Test public void testOfferNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.offer(null); @@ -354,7 +354,7 @@ public void testOfferNull() @Test public void testOfferFirstNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.offerFirst(null); @@ -369,7 +369,7 @@ public void testOfferFirstNull() @Test public void testOfferLastNull() { - LinkedDeque q = new LinkedDeque(); + LinkedDeque q = new LinkedDeque<>(); try { q.offerLast(null); @@ -384,8 +384,8 @@ public void testOfferLastNull() @Test public void testForwardGeneral() { - LinkedDeque q = new LinkedDeque(); - Queue control = new ArrayDeque(); + LinkedDeque q = new LinkedDeque<>(); + Queue control = new ArrayDeque<>(); for (int i = 0; i < 10; i++) { @@ -410,8 +410,8 @@ public void testForwardGeneral() @Test public void testReverseGeneral() { - LinkedDeque q = new LinkedDeque(); - Deque control = new ArrayDeque(); + LinkedDeque q = new LinkedDeque<>(); + Deque control = new ArrayDeque<>(); for (int i = 0; i < 10; i++) { @@ -437,7 +437,7 @@ public void testReverseGeneral() public void testEquals() { List list = Arrays.asList(1, 2, 3); - LinkedDeque q = new LinkedDeque(list); + LinkedDeque q = new LinkedDeque<>(list); Assert.assertEquals(q, list); Assert.assertEquals(new LinkedDeque(), Collections.emptyList()); Assert.assertNotSame(q, Collections.emptyList()); @@ -446,7 +446,7 @@ public void testEquals() @Test public void testEarlyRemoveFails() { - LinkedDeque q = new LinkedDeque(Arrays.asList(1,2,3)); + LinkedDeque q = new LinkedDeque<>(Arrays.asList(1, 2, 3)); try { q.iterator().remove(); @@ -460,7 +460,7 @@ public void testEarlyRemoveFails() @Test public void testDoubleRemoveFails() { - LinkedDeque q = new LinkedDeque(Arrays.asList(1,2,3)); + LinkedDeque q = new LinkedDeque<>(Arrays.asList(1, 2, 3)); Iterator i = q.iterator(); i.next(); i.remove(); @@ -538,12 +538,12 @@ private void testIteratorRemoval(int target, int size, boolean ascending) { try { - List list = new ArrayList(size); + List list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(i); } - LinkedDeque q = new LinkedDeque(list); + LinkedDeque q = new LinkedDeque<>(list); Iterator it = (ascending ? q.iterator() : q.descendingIterator()); for (int i = 0; i < target + 1; i++) { @@ -569,10 +569,10 @@ public void bigTest() { Random rand = new Random(9939393); - List control = new ArrayList(); + List control = new ArrayList<>(); - List> nodes = new ArrayList>(); - LinkedDeque queue =new LinkedDeque(); + List> nodes = new ArrayList<>(); + LinkedDeque queue = new LinkedDeque<>(); for (int i = 0; i < 100000; i++) { diff --git a/r2-core/src/test/java/test/r2/filter/StreamFilterTest.java b/r2-core/src/test/java/test/r2/filter/StreamFilterTest.java index 45bef08be4..2ace82ab9a 100644 --- a/r2-core/src/test/java/test/r2/filter/StreamFilterTest.java +++ b/r2-core/src/test/java/test/r2/filter/StreamFilterTest.java @@ -84,7 +84,7 @@ private void fireStreamError(FilterChain fc) private Map createWireAttributes() { - return new HashMap(); + return new HashMap<>(); } private RequestContext createRequestContext() diff --git a/r2-core/src/test/java/test/r2/filter/TestFilterChainImpl.java b/r2-core/src/test/java/test/r2/filter/TestFilterChainImpl.java index fc0afef3e4..82748257e9 100644 --- a/r2-core/src/test/java/test/r2/filter/TestFilterChainImpl.java +++ b/r2-core/src/test/java/test/r2/filter/TestFilterChainImpl.java @@ -235,7 +235,7 @@ public void testNullStreamFilter() @Test(expectedExceptions = IllegalArgumentException.class) public void testNullFilterInList() { - List restFilters = new ArrayList(); + List restFilters = new ArrayList<>(); restFilters.add(new RestCountFilter()); restFilters.add(null); @@ -290,11 +290,11 @@ public void testFilterOrderTwoChains() AtomicInteger count = new AtomicInteger(0); CheckOrderFilter filter1 = new CheckOrderFilter(count); CheckOrderFilter filter2 = new CheckOrderFilter(count); - List restFilters = new ArrayList(); + List restFilters = new ArrayList<>(); restFilters.add(filter1); restFilters.add(filter2); - List streamFilters = new ArrayList(); + List streamFilters = new ArrayList<>(); streamFilters.add(filter1); streamFilters.add(filter2); @@ -371,7 +371,7 @@ private void fireStreamError(FilterChain fc) private Map createWireAttributes() { - return new HashMap(); + return new HashMap<>(); } private RequestContext createRequestContext() diff --git a/r2-core/src/test/java/test/r2/filter/TestServerRetryFilter.java b/r2-core/src/test/java/test/r2/filter/TestServerRetryFilter.java index d7af745440..45e9622273 100644 --- a/r2-core/src/test/java/test/r2/filter/TestServerRetryFilter.java +++ b/r2-core/src/test/java/test/r2/filter/TestServerRetryFilter.java @@ -56,7 +56,7 @@ public void onRestError(Throwable ex, RequestContext requestContext, Map()); + FilterUtil.fireRestError(filterChain, new RestException(null, new RetriableRequestException(retryMessage)), new HashMap<>()); } @Test @@ -79,7 +79,7 @@ public void onRestError(Throwable ex, RequestContext requestContext, Map()); + FilterUtil.fireRestError(filterChain, new RestException(null, nestedException), new HashMap<>()); } @Test @@ -99,7 +99,7 @@ public void onStreamError(Throwable ex, } }; FilterChain filterChain = FilterChains.createStreamChain(captureFilter, retryFilter); - FilterUtil.fireRestError(filterChain, new StreamException(null, new RetriableRequestException(retryMessage)), new HashMap()); + FilterUtil.fireRestError(filterChain, new StreamException(null, new RetriableRequestException(retryMessage)), new HashMap<>()); } @Test @@ -116,6 +116,6 @@ public void onRestError(Throwable ex, RequestContext requestContext, Map()); + FilterUtil.fireRestError(filterChain, new RuntimeException(new RuntimeException()), new HashMap<>()); } } diff --git a/r2-core/src/test/java/test/r2/message/TestRestBuilders.java b/r2-core/src/test/java/test/r2/message/TestRestBuilders.java index 50920dfff6..e1407151d1 100644 --- a/r2-core/src/test/java/test/r2/message/TestRestBuilders.java +++ b/r2-core/src/test/java/test/r2/message/TestRestBuilders.java @@ -248,7 +248,7 @@ public void testSetCookiesMultipleValues() final String cookie1 = "cookie1"; final String cookie2 = "cookie2"; final String cookie3 = "cookie3"; - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); cookies.add(cookie2); cookies.add(cookie3); @@ -274,10 +274,10 @@ public void testSetHeadersAndCookiesMultipleValues() final String value2 = "value2"; final String cookie1 = "cookie1"; final String cookie2 = "cookie2"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(header1, value1); headers.put(header2, value2); - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); cookies.add(cookie1); cookies.add(cookie2); diff --git a/r2-core/src/test/java/test/r2/message/streaming/TestEntityStream.java b/r2-core/src/test/java/test/r2/message/streaming/TestEntityStream.java index df213ed04a..73796d509a 100644 --- a/r2-core/src/test/java/test/r2/message/streaming/TestEntityStream.java +++ b/r2-core/src/test/java/test/r2/message/streaming/TestEntityStream.java @@ -1092,7 +1092,7 @@ private static class TestObserver implements Observer private AtomicInteger _isDone = new AtomicInteger(0); private AtomicInteger _error = new AtomicInteger(0); - private AtomicReference _lastEvent = new AtomicReference(); + private AtomicReference _lastEvent = new AtomicReference<>(); @Override public void onDataAvailable(ByteString data) diff --git a/r2-core/src/test/java/test/r2/transport/common/TestWireAttributeHelper.java b/r2-core/src/test/java/test/r2/transport/common/TestWireAttributeHelper.java index 3d14fe455b..a86e6aa3af 100644 --- a/r2-core/src/test/java/test/r2/transport/common/TestWireAttributeHelper.java +++ b/r2-core/src/test/java/test/r2/transport/common/TestWireAttributeHelper.java @@ -65,12 +65,12 @@ public void testCaseInsensitivity() @Test public void testReversible() { - final Map attrs = new HashMap(); + final Map attrs = new HashMap<>(); attrs.put("key1", "val1"); attrs.put("key2", "val2"); attrs.put("key3", "val3"); - final Map copy = new HashMap(attrs); + final Map copy = new HashMap<>(attrs); final Map actual = WireAttributeHelper.removeWireAttributes(WireAttributeHelper.toWireAttributes(copy)); Assert.assertEquals(actual, attrs); @@ -79,7 +79,7 @@ public void testReversible() @Test public void testRemoveWireAttributes() { - final Map headers = new HashMap(); + final Map headers = new HashMap<>(); headers.put("key1", "val1"); headers.put("X-LI-R2-W-key2", "val2"); @@ -99,7 +99,7 @@ public void testRemoveWireAttributes() @Test public void testRemoveWireAttributesCaseInsensitive() { - final Map headers = new HashMap(); + final Map headers = new HashMap<>(); headers.put("X-LI-R2-W-key2", "val2"); headers.put("x-li-r2-w-key3", "val3"); headers.put("x-li-r2-w-kEY4", "val4"); @@ -120,7 +120,7 @@ public void testRemoveWireAttributesCaseInsensitive() @Test public void testToWireAttributes() { - final Map headers = new HashMap(); + final Map headers = new HashMap<>(); headers.put("key1", "val1"); headers.put("key2", "val2"); @@ -136,7 +136,7 @@ public void testToWireAttributes() @Test public void testToWireAttributesCaseInsensitive() { - final Map headers = new HashMap(); + final Map headers = new HashMap<>(); headers.put("key1", "val1"); headers.put("key2", "val2"); diff --git a/r2-core/src/test/java/test/r2/transport/http/client/TestAsyncPool.java b/r2-core/src/test/java/test/r2/transport/http/client/TestAsyncPool.java index 612b8c676c..44aeb4924e 100644 --- a/r2-core/src/test/java/test/r2/transport/http/client/TestAsyncPool.java +++ b/r2-core/src/test/java/test/r2/transport/http/client/TestAsyncPool.java @@ -75,13 +75,13 @@ public void stopExecutor() @Test public void testMustStart() throws TimeoutException, InterruptedException { - AsyncPool pool = new AsyncPoolImpl("object pool", - new SynchronousLifecycle(), - 1, - 100, - _executor - ); - FutureCallback cb = new FutureCallback(); + AsyncPool pool = new AsyncPoolImpl<>("object pool", + new SynchronousLifecycle(), + 1, + 100, + _executor + ); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); try { @@ -97,14 +97,14 @@ public void testMustStart() throws TimeoutException, InterruptedException @Test public void testCreate() { - AsyncPool pool = new AsyncPoolImpl("object pool", - new SynchronousLifecycle(), - 1, - 100, - _executor - ); + AsyncPool pool = new AsyncPoolImpl<>("object pool", + new SynchronousLifecycle(), + 1, + 100, + _executor + ); pool.start(); - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); try { @@ -126,12 +126,12 @@ public void testMaxSize() final int POOL_SIZE = 25; final int DELAY = 1; SynchronousLifecycle lifecycle = new SynchronousLifecycle(); - final AsyncPool pool = new AsyncPoolImpl("object pool", - lifecycle, - POOL_SIZE, - 100, - _executor - ); + final AsyncPool pool = new AsyncPoolImpl<>("object pool", + lifecycle, + POOL_SIZE, + 100, + _executor + ); pool.start(); Runnable r = new Runnable() @@ -141,7 +141,7 @@ public void run() { for (int i = 0; i < ITERATIONS; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); try { @@ -159,7 +159,7 @@ public void run() } } }; - List threads = new ArrayList(THREADS); + List threads = new ArrayList<>(THREADS); for (int i = 0; i < THREADS; i++) { Thread t = new Thread(r); @@ -186,18 +186,18 @@ public void testShutdown() final int POOL_SIZE = 25; final int CHECKOUT = POOL_SIZE; SynchronousLifecycle lifecycle = new SynchronousLifecycle(); - final AsyncPool pool = new AsyncPoolImpl("object pool", - lifecycle, - POOL_SIZE, - 100, - _executor - ); + final AsyncPool pool = new AsyncPoolImpl<>("object pool", + lifecycle, + POOL_SIZE, + 100, + _executor + ); pool.start(); - List objects = new ArrayList(CHECKOUT); + List objects = new ArrayList<>(CHECKOUT); for (int i = 0; i < CHECKOUT; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); try @@ -211,7 +211,7 @@ public void testShutdown() Assert.fail("unexpected error", e); } } - FutureCallback shutdown = new FutureCallback(); + FutureCallback shutdown = new FutureCallback<>(); pool.shutdown(shutdown); for (Object o : objects) @@ -238,7 +238,7 @@ public void testShutdown() public void testCancelTriggerShutdown() throws Exception { SynchronousLifecycle lifecycle = new SynchronousLifecycle(); - AsyncPool pool = new AsyncPoolImpl("object pool", lifecycle, 1, 100, _executor); + AsyncPool pool = new AsyncPoolImpl<>("object pool", lifecycle, 1, 100, _executor); pool.start(); FutureCallback callback1 = new FutureCallback<>(); @@ -267,16 +267,16 @@ public void testLRU() throws Exception final int POOL_SIZE = 25; final int GET = 15; SynchronousLifecycle lifecycle = new SynchronousLifecycle(); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", lifecycle, POOL_SIZE, 1000, _executor, _executor, Integer.MAX_VALUE, AsyncPoolImpl.Strategy.LRU, 0); pool.start(); - ArrayList objects = new ArrayList(); + ArrayList objects = new ArrayList<>(); for(int i = 0; i < GET; i++) { - FutureCallbackcb = new FutureCallback(); + FutureCallbackcb = new FutureCallback<>(); pool.get(cb); objects.add(cb.get()); } @@ -290,7 +290,7 @@ public void testLRU() throws Exception // we should get the same objects back in FIFO order for(int i = 0; i < GET; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); Assert.assertEquals(cb.get(), objects.get(i)); } @@ -308,18 +308,18 @@ public void testMinSize() throws Exception for(AsyncPoolImpl.Strategy strategy : AsyncPoolImpl.Strategy.values()) { SynchronousLifecycle lifecycle = new SynchronousLifecycle(); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", lifecycle, POOL_SIZE, 100, _executor, _executor, Integer.MAX_VALUE, strategy, MIN_SIZE); pool.start(); Assert.assertEquals(lifecycle.getLive(), MIN_SIZE); - ArrayList objects = new ArrayList(); + ArrayList objects = new ArrayList<>(); for(int i = 0; i < GET; i++) { - FutureCallbackcb = new FutureCallback(); + FutureCallbackcb = new FutureCallback<>(); pool.get(cb); objects.add(cb.get()); } @@ -353,11 +353,11 @@ public void testGetStats() throws Exception final int DELAY = 1200; final UnreliableLifecycle lifecycle = new UnreliableLifecycle(); - final AsyncPool pool = new AsyncPoolImpl( + final AsyncPool pool = new AsyncPoolImpl<>( "object pool", lifecycle, POOL_SIZE, TIMEOUT, WAITER_TIMEOUT, _executor, MAX_WAITER_SIZE, AsyncPoolImpl.Strategy.MRU, MIN_SIZE, new NoopRateLimiter(), clock, waitTimeTracker); PoolStats stats; - final List objects = new ArrayList(); + final List objects = new ArrayList<>(); pool.start(); @@ -380,7 +380,7 @@ public void testGetStats() throws Exception // do a few gets for(int i = 0; i < GET; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); AtomicBoolean obj = cb.get(); objects.add(obj); @@ -494,18 +494,18 @@ public void testGetStatsWithErrors() throws Exception final int TIMEOUT = 100; final UnreliableLifecycle lifecycle = new UnreliableLifecycle(); - final AsyncPool pool = new AsyncPoolImpl( + final AsyncPool pool = new AsyncPoolImpl<>( "object pool", lifecycle, POOL_SIZE, TIMEOUT, _executor ); PoolStats stats; - final List objects = new ArrayList(); + final List objects = new ArrayList<>(); pool.start(); // do a few gets for(int i = 0; i < GET; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); AtomicBoolean obj = cb.get(); objects.add(obj); @@ -533,7 +533,7 @@ public void testGetStatsWithErrors() throws Exception // create some with errors for(int i = 0; i < CREATE_BAD; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); try { pool.get(cb); @@ -559,7 +559,7 @@ public void testWaitTimeStats() throws Exception final long DELAY = 100; final double DELTA = 0.1; DelayedLifecycle lifecycle = new DelayedLifecycle(DELAY); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", lifecycle, POOL_SIZE, 100, @@ -568,10 +568,10 @@ public void testWaitTimeStats() throws Exception pool.start(); PoolStats stats; - List objects = new ArrayList(CHECKOUT); + List objects = new ArrayList<>(CHECKOUT); for (int i = 0; i < CHECKOUT; i++) { - FutureCallback cb = new FutureCallback(); + FutureCallback cb = new FutureCallback<>(); pool.get(cb); Object o = cb.get(); objects.add(o); @@ -614,7 +614,7 @@ public void testObjectsAreNotCreatedWhenThereAreNoWaiters(int numberOfCheckouts, ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, executor, concurrency); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", blockableObjectCreator, poolSize, Integer.MAX_VALUE, @@ -718,7 +718,7 @@ public void testWaiterTimeout(int numberOfCheckoutsInPhaseA, int numberOfCheckou ClockedExecutor clockedExecutor = new ClockedExecutor(); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", blockableObjectCreator, poolSize, Integer.MAX_VALUE, @@ -796,7 +796,7 @@ public void testCreationTimeout(int poolSize, int concurrency) throws Exception ClockedExecutor clockedExecutor = new ClockedExecutor(); ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, clockedExecutor, concurrency); - final AsyncPool pool = new AsyncPoolImpl("object pool", + final AsyncPool pool = new AsyncPoolImpl<>("object pool", objectCreatorThatNeverCreates, poolSize, Integer.MAX_VALUE, diff --git a/r2-core/src/test/java/test/r2/transport/http/common/TestHttpBridge.java b/r2-core/src/test/java/test/r2/transport/http/common/TestHttpBridge.java index 5ae0fc01a3..bbc7b23920 100644 --- a/r2-core/src/test/java/test/r2/transport/http/common/TestHttpBridge.java +++ b/r2-core/src/test/java/test/r2/transport/http/common/TestHttpBridge.java @@ -57,8 +57,8 @@ public void testRestToHttpErrorMessage() throws TimeoutException, InterruptedExc RestRequest r = new RestRequestBuilder(uri).build(); - FutureCallback futureCallback = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(futureCallback); + FutureCallback futureCallback = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(futureCallback); TransportCallback bridgeCallback = HttpBridge.restToHttpCallback(callback, r); bridgeCallback.onResponse(TransportResponseImpl.error(new Exception())); @@ -79,9 +79,9 @@ public void testRestToHttpErrorMessage() throws TimeoutException, InterruptedExc @Test public void testHttpToRestErrorMessage() throws TimeoutException, InterruptedException, ExecutionException { - FutureCallback futureCallback = new FutureCallback(); + FutureCallback futureCallback = new FutureCallback<>(); TransportCallback callback = - new TransportCallbackAdapter(futureCallback); + new TransportCallbackAdapter<>(futureCallback); TransportCallback bridgeCallback = HttpBridge.httpToRestCallback(callback); RestResponse restResponse = new RestResponseBuilder().build(); @@ -104,8 +104,8 @@ public void testStreamToHttpErrorMessage() throws TimeoutException, InterruptedE RestRequest r = new RestRequestBuilder(uri).build(); - FutureCallback futureCallback = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(futureCallback); + FutureCallback futureCallback = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(futureCallback); TransportCallback bridgeCallback = HttpBridge.streamToHttpCallback(callback, Messages.toStreamRequest(r)); @@ -127,9 +127,9 @@ public void testStreamToHttpErrorMessage() throws TimeoutException, InterruptedE @Test public void testHttpToStreamErrorMessage() throws TimeoutException, InterruptedException, ExecutionException { - FutureCallback futureCallback = new FutureCallback(); + FutureCallback futureCallback = new FutureCallback<>(); TransportCallback callback = - new TransportCallbackAdapter(futureCallback); + new TransportCallbackAdapter<>(futureCallback); TransportCallback bridgeCallback = HttpBridge.httpToStreamCallback(callback); StreamResponse streamResponse = new StreamResponseBuilder().build(EntityStreams.emptyStream()); diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/AcceptEncoding.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/AcceptEncoding.java index 380c3391b8..07b7a55f32 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/AcceptEncoding.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/AcceptEncoding.java @@ -93,7 +93,7 @@ public static List parseAcceptEncodingHeader(String headerValue, { headerValue = headerValue.toLowerCase(); String[] entries = headerValue.split(CompressionConstants.ENCODING_DELIMITER); - List parsedEncodings = new ArrayList(); + List parsedEncodings = new ArrayList<>(); for(String entry : entries) { @@ -152,7 +152,7 @@ public static List parseAcceptEncodingHeader(String headerValue, public static EncodingType chooseBest(List entries) { Collections.sort(entries); - HashSet bannedEncoding = new HashSet(); + HashSet bannedEncoding = new HashSet<>(); //Add the banned entries to the disallow list int lastEntry = entries.size()-1; diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ClientCompressionHelper.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ClientCompressionHelper.java index 355789284a..a85965c600 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ClientCompressionHelper.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ClientCompressionHelper.java @@ -49,12 +49,12 @@ public class ClientCompressionHelper /** * The set of methods for which response compression will be turned on */ - private final Set _responseCompressionMethods = new HashSet(); + private final Set _responseCompressionMethods = new HashSet<>(); /** * The set of families for which response compression will be turned on. */ - private final Set _responseCompressionFamilies = new HashSet(); + private final Set _responseCompressionFamilies = new HashSet<>(); private final boolean _compressAllResponses; diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/EncodingType.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/EncodingType.java index 7c6a68fc9e..87f7decac4 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/EncodingType.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/EncodingType.java @@ -41,7 +41,7 @@ public enum EncodingType //Initialize the reverse map for lookups static { - Map reverseMap = new HashMap(); + Map reverseMap = new HashMap<>(); for(EncodingType t : EncodingType.values()) { reverseMap.put(t.getHttpName(), t); diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerCompressionFilter.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerCompressionFilter.java index af9008d61d..fc7df2f511 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerCompressionFilter.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerCompressionFilter.java @@ -86,7 +86,7 @@ public ServerCompressionFilter(EncodingType[] supportedEncoding, CompressionConf { throw new IllegalArgumentException(CompressionConstants.NULL_CONFIG_ERROR); } - _supportedEncoding = new HashSet(Arrays.asList(supportedEncoding)); + _supportedEncoding = new HashSet<>(Arrays.asList(supportedEncoding)); _supportedEncoding.add(EncodingType.IDENTITY); _supportedEncoding.add(EncodingType.ANY); _serverCompressionHelper = new ServerCompressionHelper(defaultResponseCompressionConfig); @@ -128,7 +128,7 @@ public void onRestRequest(RestRequest req, RequestContext requestContext, if (encoding.hasCompressor()) { ByteString decompressedContent = encoding.getCompressor().inflate(req.getEntity()); - Map headers = new HashMap(req.getHeaders()); + Map headers = new HashMap<>(req.getHeaders()); headers.remove(HttpConstants.CONTENT_ENCODING); headers.put(HttpConstants.CONTENT_LENGTH, Integer.toString(decompressedContent.length())); req = req.builder().setEntity(decompressedContent).setHeaders(headers).build(); diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerStreamCompressionFilter.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerStreamCompressionFilter.java index 6632ed0b8a..0f5720e4f3 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerStreamCompressionFilter.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/ServerStreamCompressionFilter.java @@ -80,7 +80,7 @@ public ServerStreamCompressionFilter(String acceptedFilters, Executor executor, */ public ServerStreamCompressionFilter(StreamEncodingType[] supportedEncoding, Executor executor, int compressThreshold) { - _supportedEncoding = new HashSet(Arrays.asList(supportedEncoding)); + _supportedEncoding = new HashSet<>(Arrays.asList(supportedEncoding)); _supportedEncoding.add(StreamEncodingType.IDENTITY); _supportedEncoding.add(StreamEncodingType.ANY); _executor = executor; @@ -225,7 +225,7 @@ public void onStreamError(Throwable ex, RequestContext requestContext, Map stripHeaders(Map headerMap, String...headers) { - Map newMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map newMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); newMap.putAll(headerMap); for (String header : headers) { diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/AcceptEncoding.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/AcceptEncoding.java index f3db3fa11b..8670d43d6b 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/AcceptEncoding.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/AcceptEncoding.java @@ -101,7 +101,7 @@ public static List parseAcceptEncodingHeader(String headerValue, { headerValue = headerValue.toLowerCase(); String[] entries = headerValue.split(CompressionConstants.ENCODING_DELIMITER); - List parsedEncodings = new ArrayList(); + List parsedEncodings = new ArrayList<>(); for(String entry : entries) { @@ -155,7 +155,7 @@ public static List parseAcceptEncodingHeader(String headerValue, public static StreamEncodingType chooseBest(List entries) { Collections.sort(entries); - HashSet bannedEncoding = new HashSet(); + HashSet bannedEncoding = new HashSet<>(); //Add the banned entries to the disallow list int lastEntry = entries.size()-1; diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/BufferedReaderInputStream.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/BufferedReaderInputStream.java index 2205a457f3..3aa4ec874b 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/BufferedReaderInputStream.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/BufferedReaderInputStream.java @@ -36,7 +36,7 @@ class BufferedReaderInputStream extends InputStream implements Reader private static final int CAPACITY = 3; private static final ByteString EOS = ByteString.copy(new byte[1]); - private final BlockingQueue _buffers = new ArrayBlockingQueue(CAPACITY+1); + private final BlockingQueue _buffers = new ArrayBlockingQueue<>(CAPACITY + 1); private boolean _closed = false; private volatile boolean _readFinished = false; diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/PartialReader.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/PartialReader.java index 6d13d6dd1d..766224ce68 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/PartialReader.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/PartialReader.java @@ -38,7 +38,7 @@ public class PartialReader implements Reader private final int _numBytes; private final Callback _callback; - private final Queue _buffer = new LinkedList(); + private final Queue _buffer = new LinkedList<>(); private ReadHandle _rh; private WriteHandle _remainingWh; private int _readLen; diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamEncodingType.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamEncodingType.java index 7f0442e261..4047ff3215 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamEncodingType.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamEncodingType.java @@ -38,7 +38,7 @@ public enum StreamEncodingType static { - Map reverseMap = new HashMap(); + Map reverseMap = new HashMap<>(); for(StreamEncodingType t : StreamEncodingType.values()) { reverseMap.put(t.getHttpName(), t); diff --git a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamingDeflater.java b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamingDeflater.java index 6f2a1ba895..a4dc51fe59 100644 --- a/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamingDeflater.java +++ b/r2-filter-compression/src/main/java/com/linkedin/r2/filter/compression/streaming/StreamingDeflater.java @@ -143,7 +143,7 @@ private class BufferedWriterOutputStream extends OutputStream { private static final int BUF_SIZE = R2Constants.DEFAULT_DATA_CHUNK_SIZE; - private final Queue _data = new ConcurrentLinkedQueue(); + private final Queue _data = new ConcurrentLinkedQueue<>(); private final byte[] _buffer = new byte[BUF_SIZE]; private int _writeIndex = 0; private boolean _done = false; diff --git a/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/TestClientStreamCompressionFilter.java b/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/TestClientStreamCompressionFilter.java index b812448100..074b9d8400 100644 --- a/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/TestClientStreamCompressionFilter.java +++ b/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/TestClientStreamCompressionFilter.java @@ -243,7 +243,7 @@ public void testRequestCompressionRules(CompressionConfig requestCompressionConf context.putLocalAttr(R2Constants.REQUEST_COMPRESSION_OVERRIDE, requestCompressionOverride); int entityLength = headerShouldBePresent ? compressed : original; - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); FullEntityReader reader = new FullEntityReader(callback); HeaderCaptureFilter captureFilter = diff --git a/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/stream/TestStreamingCompression.java b/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/stream/TestStreamingCompression.java index 35253feea2..7a3e35148f 100644 --- a/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/stream/TestStreamingCompression.java +++ b/r2-filter-compression/src/test/java/com/linkedin/r2/filter/compression/stream/TestStreamingCompression.java @@ -151,7 +151,7 @@ private void testCompress(StreamingCompressor compressor, byte[] uncompressed, b EntityStream uncompressedStream = EntityStreams.newEntityStream(writer); EntityStream compressedStream = compressor.deflate(uncompressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); compressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); @@ -165,7 +165,7 @@ private void testDecompress(StreamingCompressor compressor, byte[] uncompressed, EntityStream compressedStream = EntityStreams.newEntityStream(writer); EntityStream uncompressedStream = compressor.inflate(compressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); uncompressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); @@ -181,7 +181,7 @@ private void testCompressThenDecompress(StreamingCompressor compressor, byte[] o EntityStream decompressedStream = compressor.inflate(compressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); decompressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); diff --git a/r2-filter-compression/src/test/java/test/r2/filter/streaming/TestStreamingCompression.java b/r2-filter-compression/src/test/java/test/r2/filter/streaming/TestStreamingCompression.java index a66797ddaf..6f44e42242 100644 --- a/r2-filter-compression/src/test/java/test/r2/filter/streaming/TestStreamingCompression.java +++ b/r2-filter-compression/src/test/java/test/r2/filter/streaming/TestStreamingCompression.java @@ -151,7 +151,7 @@ private void testCompress(StreamingCompressor compressor, byte[] uncompressed, b EntityStream uncompressedStream = EntityStreams.newEntityStream(writer); EntityStream compressedStream = compressor.deflate(uncompressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); compressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); @@ -165,7 +165,7 @@ private void testDecompress(StreamingCompressor compressor, byte[] uncompressed, EntityStream compressedStream = EntityStreams.newEntityStream(writer); EntityStream uncompressedStream = compressor.inflate(compressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); uncompressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); @@ -181,7 +181,7 @@ private void testCompressThenDecompress(StreamingCompressor compressor, byte[] o EntityStream decompressedStream = compressor.inflate(compressedStream); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); decompressedStream.setReader(new ByteReader(callback)); byte[] result = callback.get(); diff --git a/r2-int-test/src/test/java/test/r2/integ/TestChannelPoolBehavior.java b/r2-int-test/src/test/java/test/r2/integ/TestChannelPoolBehavior.java index 30aa9a1a6e..962d6550da 100644 --- a/r2-int-test/src/test/java/test/r2/integ/TestChannelPoolBehavior.java +++ b/r2-int-test/src/test/java/test/r2/integ/TestChannelPoolBehavior.java @@ -75,14 +75,14 @@ public void setup() throws IOException public void tearDown() throws Exception { - final FutureCallback client1ShutdownCallback = new FutureCallback(); + final FutureCallback client1ShutdownCallback = new FutureCallback<>(); _client1.shutdown(client1ShutdownCallback); client1ShutdownCallback.get(); - final FutureCallback client2ShutdownCallback = new FutureCallback(); + final FutureCallback client2ShutdownCallback = new FutureCallback<>(); _client2.shutdown(client2ShutdownCallback); client2ShutdownCallback.get(); - final FutureCallback factoryShutdownCallback = new FutureCallback(); + final FutureCallback factoryShutdownCallback = new FutureCallback<>(); _clientFactory.shutdown(factoryShutdownCallback); factoryShutdownCallback.get(); @@ -165,7 +165,7 @@ public void onSuccess(StreamResponse result) private Map getClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_POOL_SIZE, "1"); clientProperties.put(HttpClientFactory.HTTP_POOL_MIN_SIZE, "1"); return clientProperties; diff --git a/r2-int-test/src/test/java/test/r2/integ/TestJetty404.java b/r2-int-test/src/test/java/test/r2/integ/TestJetty404.java index 2f17bf143d..15241403f8 100644 --- a/r2-int-test/src/test/java/test/r2/integ/TestJetty404.java +++ b/r2-int-test/src/test/java/test/r2/integ/TestJetty404.java @@ -78,7 +78,7 @@ public void handleStreamRequest(StreamRequest req, Map wireAttrs public void testJetty404() throws Exception { BytesWriter writer = new BytesWriter(200 * 1024, (byte)100); - final AtomicReference exRef = new AtomicReference(); + final AtomicReference exRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); _client.streamRequest(new StreamRequestBuilder(Bootstrap.createHttpURI(PORT, URI.create("/wrong-path"))) .build(EntityStreams.newEntityStream(writer)), new Callback() @@ -110,11 +110,11 @@ public void onSuccess(StreamResponse result) public void tearDown() throws Exception { - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); _client.shutdown(clientShutdownCallback); clientShutdownCallback.get(); - final FutureCallback factoryShutdownCallback = new FutureCallback(); + final FutureCallback factoryShutdownCallback = new FutureCallback<>(); _clientFactory.shutdown(factoryShutdownCallback); factoryShutdownCallback.get(); diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestCompressionEcho.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestCompressionEcho.java index 0c09043be1..0a132d2bbc 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestCompressionEcho.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestCompressionEcho.java @@ -57,7 +57,7 @@ public class TestCompressionEcho extends AbstractServiceTest protected static final long SMALL_BYTES_NUM = THRESHOLD - 1; private static final URI ECHO_URI = URI.create("/echo"); - private List _clients = new ArrayList(); + private List _clients = new ArrayList<>(); @Factory(dataProvider = "allStreamCombinations", dataProviderClass = ClientServerConfiguration.class) @@ -84,7 +84,7 @@ protected void tearDown(Client client, Server server) throws Exception { for (Client compressionClient : _clients) { - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); compressionClient.shutdown(clientShutdownCallback); clientShutdownCallback.get(); } @@ -160,13 +160,13 @@ public void testResponseCompression(Client client, long bytes) // add operation to enable sending accept encoding RequestContext requestContext = new RequestContext(); requestContext.putLocalAttr(R2Constants.OPERATION, "get"); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.streamRequest(request, requestContext, callback); final StreamResponse response = callback.get(60, TimeUnit.SECONDS); Assert.assertEquals(response.getStatus(), RestStatus.OK); - final FutureCallback readerCallback = new FutureCallback(); + final FutureCallback readerCallback = new FutureCallback<>(); final BytesReader reader = new BytesReader(BYTE, readerCallback); response.getEntityStream().setReader(reader); @@ -178,7 +178,7 @@ public void testResponseCompression(Client client, long bytes) @Override protected Map getHttpClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_MAX_RESPONSE_SIZE, String.valueOf(LARGE_BYTES_NUM * 2)); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, "60000"); return clientProperties; diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestGeneralEchoServiceTest.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestGeneralEchoServiceTest.java index 41a06e40b6..654c312474 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestGeneralEchoServiceTest.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestGeneralEchoServiceTest.java @@ -57,7 +57,7 @@ public void testEcho() throws Exception final EchoService client = getEchoClient(_client, Bootstrap.getEchoURI()); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); String actual = callback.get(); @@ -74,7 +74,7 @@ public void testUnknownServiceUri() final EchoService client = getEchoClient(_client, URI.create("/unknown-service")); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); try @@ -98,7 +98,7 @@ public void testBadRestURI() } final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); try @@ -121,7 +121,7 @@ public void testThrowingEchoService() throws Exception final EchoService client = getEchoClient(_client, Bootstrap.getThrowingEchoURI()); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); try @@ -141,7 +141,7 @@ public void testOnExceptionEchoService() throws Exception final EchoService client = getEchoClient(_client, Bootstrap.getOnExceptionEchoURI()); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); try @@ -161,7 +161,7 @@ public void testFilterChain() throws Exception final EchoService client = getEchoClient(_client, Bootstrap.getEchoURI()); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); callback.get(); @@ -182,7 +182,7 @@ public void testFilterChainOnException() throws Exception final EchoService client = getEchoClient(_client, URI.create("/unknown-service")); final String msg = "This is a simple echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); try diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpServer.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpServer.java index 558350ee83..2bcfae7830 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpServer.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpServer.java @@ -144,7 +144,7 @@ public void testMultiValuedHeaderEcho() throws Exception // check the number of header values received at client side // we know the headers are going to be folded into one line its way back. List echoValues = RestUtil.getHeaderValues(c.getHeaderField(MULTI_VALUE_HEADER_NAME)); - assertEquals(new HashSet(echoValues), new HashSet(values)); + assertEquals(new HashSet<>(echoValues), new HashSet<>(values)); } @Test @@ -170,7 +170,7 @@ public void testMultipleCookiesEcho() throws Exception c.addRequestProperty(HttpConstants.REQUEST_COOKIE_HEADER_NAME, cookie); } List cookiesEcho = c.getHeaderFields().get(HttpConstants.RESPONSE_COOKIE_HEADER_NAME); - assertEquals(new HashSet(cookiesEcho), new HashSet(cookies)); + assertEquals(new HashSet<>(cookiesEcho), new HashSet<>(cookies)); } protected static class ErrorHandler implements RestRequestHandler diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpsEcho.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpsEcho.java index db5b32e504..79d3b6cc85 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpsEcho.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestHttpsEcho.java @@ -56,10 +56,10 @@ public void testHttpEcho() throws Exception Bootstrap.createURI(SslContextUtil.getHttpPortFromHttps(_port), Bootstrap.getEchoURI(), false), createClient()); final String msg = "This is a simple http echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); Assert.assertEquals(callback.get(), msg); } -} \ No newline at end of file +} diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestQueryTunnel.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestQueryTunnel.java index ad71ac3f7c..854b01d9c0 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestQueryTunnel.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestQueryTunnel.java @@ -111,14 +111,14 @@ protected TransportDispatcher getTransportDispatcher() { public void handleRestRequest(RestRequest req, Map wireAttrs, RequestContext requestContext, TransportCallback callback) { - restHandler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + restHandler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } @Override public void handleStreamRequest(StreamRequest req, Map wireAttrs, RequestContext requestContext, TransportCallback callback) { - streamHandler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + streamHandler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } }; } diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRequestCompression.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRequestCompression.java index 53bad48b84..dfc6f00cd3 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRequestCompression.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRequestCompression.java @@ -69,7 +69,7 @@ public class TestRequestCompression extends AbstractServiceTest private static final int NUM_BYTES = 1024 * 1024 * 16; private ExecutorService _executor = Executors.newCachedThreadPool(); - private List _clients = new ArrayList(); + private List _clients = new ArrayList<>(); @Factory(dataProvider = "allStreamCombinations", dataProviderClass = ClientServerConfiguration.class) public TestRequestCompression(ClientProvider clientProvider, ServerProvider serverProvider, int port) @@ -82,7 +82,7 @@ protected void tearDown(Client client, Server server) throws Exception { for (Client compressionClient : _clients) { - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); compressionClient.shutdown(clientShutdownCallback); clientShutdownCallback.get(); } @@ -172,7 +172,7 @@ public void testNoCompression(Client client) BytesWriter writer = new BytesWriter(THRESHOLD-1, BYTE); StreamRequest request = builder.build(EntityStreams.newEntityStream(writer)); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.streamRequest(request, callback); final StreamResponse response = callback.get(60, TimeUnit.SECONDS); @@ -187,7 +187,7 @@ public void testRequestCompression(Client client, URI uri) BytesWriter writer = new BytesWriter(NUM_BYTES, BYTE); StreamRequest request = builder.build(EntityStreams.newEntityStream(writer)); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.streamRequest(request, callback); final StreamResponse response = callback.get(60, TimeUnit.SECONDS); diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRestCompressionEcho.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRestCompressionEcho.java index d0458e07dc..cf63afa95a 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRestCompressionEcho.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestRestCompressionEcho.java @@ -56,7 +56,7 @@ public class TestRestCompressionEcho extends AbstractServiceTest protected final RestFilter _compressionFilter = new ServerCompressionFilter(EncodingType.values(), new CompressionConfig(THRESHOLD)); - private List _clients = new ArrayList(); + private List _clients = new ArrayList<>(); @Factory(dataProvider = "allRestCombinations", dataProviderClass = ClientServerConfiguration.class) public TestRestCompressionEcho(ClientProvider clientProvider, ServerProvider serverProvider, int port) @@ -69,7 +69,7 @@ public void tearDown() throws Exception { for (Client client : _clients) { - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); client.shutdown(clientShutdownCallback); clientShutdownCallback.get(); } @@ -166,7 +166,7 @@ public void testResponseCompression(Client client, long bytes) } RestRequest request = builder.setEntity(content).build(); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); RequestContext requestContext = new RequestContext(); // OPERATION is required to enabled response compression diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeout.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeout.java index bbe72205fd..854abbd8cc 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeout.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeout.java @@ -66,7 +66,7 @@ public TestServerTimeout(ClientProvider clientProvider, ServerProvider serverPro @Override protected Map getHttpClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, String.valueOf(SERVER_IOHANDLER_TIMEOUT * 20)); clientProperties.put(HttpClientFactory.HTTP_POOL_MIN_SIZE, "1"); clientProperties.put(HttpClientFactory.HTTP_POOL_SIZE, "1"); @@ -76,7 +76,7 @@ protected Map getHttpClientProperties() @Override protected TransportDispatcher getTransportDispatcher() { - final Map handlers = new HashMap(); + final Map handlers = new HashMap<>(); handlers.put(BUGGY_SERVER_URI, new BuggyRequestHandler()); handlers.put(THROW_BUT_SHOULD_NOT_TIMEOUT_URI, new ThrowHandler()); handlers.put(BUGGY_FILTER_URI, new NormalHandler()); @@ -95,7 +95,7 @@ public void handleStreamRequest(StreamRequest req, Map wireAttrs StreamRequestHandler handler = handlers.get(req.getURI()); if (handler != null) { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } else { diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeoutAsyncEvent.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeoutAsyncEvent.java index 5cc71415ab..46b958cab8 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeoutAsyncEvent.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestServerTimeoutAsyncEvent.java @@ -171,7 +171,7 @@ protected int getServerTimeout() @Override protected Map getHttpClientProperties() { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_REQUEST_TIMEOUT, String.valueOf(ASYNC_EVENT_TIMEOUT * 20)); clientProperties.put(HttpClientFactory.HTTP_POOL_MIN_SIZE, "1"); clientProperties.put(HttpClientFactory.HTTP_POOL_SIZE, "1"); @@ -187,7 +187,7 @@ protected FilterChain getServerFilterChain() @Override protected TransportDispatcher getTransportDispatcher() { - final Map handlers = new HashMap(); + final Map handlers = new HashMap<>(); handlers.put(TIMEOUT_BEFORE_SENDING_RESPONSE_SERVER_URI, new TimeoutBeforeRespondingRequestHandler()); handlers.put(TIMEOUT_AFTER_SENDING_RESPONSE_SERVER_URI, new TimeoutAfterRespondingRequestHandler()); handlers.put(THROW_BUT_SHOULD_NOT_TIMEOUT_URI, new ThrowHandler()); @@ -207,7 +207,7 @@ public void handleStreamRequest(StreamRequest req, Map wireAttrs StreamRequestHandler handler = handlers.get(req.getURI()); if (handler != null) { - handler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + handler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } else { diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestSslTimingKey.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestSslTimingKey.java index c39c5c7058..738188dca0 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestSslTimingKey.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestSslTimingKey.java @@ -38,7 +38,7 @@ public void testSslTimingKey() throws Exception final EchoService client = new RestEchoClient( Bootstrap.createURI(_port, Bootstrap.getEchoURI(), true),createClient()); final String msg = "This is a simple http echo message"; - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); client.echo(msg, callback); Assert.assertEquals(callback.get(), msg); RequestContext context = _clientCaptureFilter.getRequestContext(); diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamClientTimeout.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamClientTimeout.java index a57add92b2..075bb84a6b 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamClientTimeout.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamClientTimeout.java @@ -113,7 +113,7 @@ public void testReadAfterTimeout() throws Exception { StreamRequest request = new StreamRequestBuilder(_clientProvider.createHttpURI(_port, NORMAL_URI)).build(EntityStreams.emptyStream()); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference response = new AtomicReference(); + final AtomicReference response = new AtomicReference<>(); _client.streamRequest(request, new Callback() { @Override @@ -135,7 +135,7 @@ public void onSuccess(StreamResponse result) // let it timeout before we read Thread.sleep(5000); - final AtomicReference throwable = new AtomicReference(); + final AtomicReference throwable = new AtomicReference<>(); final CountDownLatch errorLatch = new CountDownLatch(1); Reader reader = new DrainReader() { diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamEcho.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamEcho.java index 4d04f880bb..988a2975bf 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamEcho.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamEcho.java @@ -67,7 +67,7 @@ protected TransportDispatcher getTransportDispatcher() protected Map getHandlers() { - Map handlers = new HashMap(); + Map handlers = new HashMap<>(); handlers.put(ECHO_URI, new SteamEchoHandler()); handlers.put(ASYNC_ECHO_URI, new SteamAsyncEchoHandler(_scheduler)); handlers.put(DELAYED_ECHO_URI, new StreamRequestHandlerAdapter(new DelayedStoreAndForwardEchoHandler())); @@ -115,7 +115,7 @@ private void testNormalEcho(long bytesNum, URI uri) throws Exception final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); final Callback readerCallback = getReaderCallback(latch, error); @@ -140,7 +140,7 @@ public void testBackPressureEcho() throws Exception final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); final Callback readerCallback = getReaderCallback(latch, error); diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamRequest.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamRequest.java index 92d781934e..e1eb78db7b 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamRequest.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamRequest.java @@ -128,7 +128,7 @@ public void testErrorWriter() throws Exception StreamRequestBuilder builder = new StreamRequestBuilder(_clientProvider.createHttpURI(_port, FOOBAR_URI)); StreamRequest request = builder.setMethod("POST").build(entityStream); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); Callback callback = new Callback() { @Override @@ -157,7 +157,7 @@ public void testErrorReceiver() throws Exception StreamRequestBuilder builder = new StreamRequestBuilder(_clientProvider.createHttpURI(_port, ERROR_RECEIVER_URI)); StreamRequest request = builder.setMethod("POST").build(entityStream); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); Callback callback = new Callback() { @Override diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponse.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponse.java index 9f7b456410..7e9e763cd7 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponse.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponse.java @@ -98,7 +98,7 @@ private void testResponse(URI uri) throws Exception StreamRequest request = builder.build(EntityStreams.emptyStream()); final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); final Callback readerCallback = getReaderCallback(latch, error); final BytesReader reader = new BytesReader(BYTE, readerCallback); @@ -124,7 +124,7 @@ public void testErrorWhileStreaming() throws Exception StreamRequest request = builder.build(EntityStreams.emptyStream()); final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); final Callback readerCallback = getReaderCallback(latch, error); @@ -139,11 +139,11 @@ public void testErrorWhileStreaming() throws Exception System.out.println(_serverProvider.getClass()); Assert.assertNotNull(throwable); - final FutureCallback clientShutdownCallback = new FutureCallback(); + final FutureCallback clientShutdownCallback = new FutureCallback<>(); client.shutdown(clientShutdownCallback); clientShutdownCallback.get(); - final FutureCallback factoryShutdownCallback = new FutureCallback(); + final FutureCallback factoryShutdownCallback = new FutureCallback<>(); clientFactory.shutdown(factoryShutdownCallback); factoryShutdownCallback.get(); } @@ -155,7 +155,7 @@ public void testBackpressure() throws Exception StreamRequest request = builder.build(EntityStreams.emptyStream()); final AtomicInteger status = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); final Callback readerCallback = getReaderCallback(latch, error); final TimedBytesReader reader = new TimedBytesReader(BYTE, readerCallback) diff --git a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponseCompression.java b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponseCompression.java index 31792da7ba..5fef725340 100644 --- a/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponseCompression.java +++ b/r2-int-test/src/test/java/test/r2/integ/clientserver/TestStreamResponseCompression.java @@ -193,13 +193,13 @@ private void testResponseCompression(URI uri, long bytes, String acceptEncoding) builder.addHeaderValue(HttpConstants.ACCEPT_ENCODING, acceptEncoding); StreamRequest request = builder.build(EntityStreams.emptyStream()); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); _client.streamRequest(request, callback); final StreamResponse response = callback.get(60, TimeUnit.SECONDS); Assert.assertEquals(response.getStatus(), RestStatus.OK); - final FutureCallback readerCallback = new FutureCallback(); + final FutureCallback readerCallback = new FutureCallback<>(); final BytesReader reader = new BytesReader(BYTE, readerCallback); final EntityStream decompressedStream = response.getEntityStream(); decompressedStream.setReader(reader); @@ -219,7 +219,7 @@ public void testEncodingNotAcceptable(String acceptEncoding) } StreamRequest request = builder.build(EntityStreams.emptyStream()); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); _client.streamRequest(request, callback); try { diff --git a/r2-int-test/src/test/java/test/r2/integ/helper/CaptureWireAttributesFilter.java b/r2-int-test/src/test/java/test/r2/integ/helper/CaptureWireAttributesFilter.java index 5398e13acd..dd2b6ff7d6 100644 --- a/r2-int-test/src/test/java/test/r2/integ/helper/CaptureWireAttributesFilter.java +++ b/r2-int-test/src/test/java/test/r2/integ/helper/CaptureWireAttributesFilter.java @@ -58,7 +58,7 @@ public RequestContext getRequestContext() public void onRestRequest(RestRequest req, RequestContext requestContext, Map wireAttrs, NextFilter nextFilter) { - _request = new HashMap(wireAttrs); + _request = new HashMap<>(wireAttrs); _requestContext = requestContext; nextFilter.onRequest(req, requestContext, wireAttrs); } @@ -67,7 +67,7 @@ public void onRestRequest(RestRequest req, RequestContext requestContext, Map wireAttrs, NextFilter nextFilter) { - _response = new HashMap(wireAttrs); + _response = new HashMap<>(wireAttrs); _requestContext = requestContext; nextFilter.onResponse(res, requestContext, wireAttrs); } @@ -77,7 +77,7 @@ public void onRestError(Throwable ex, RequestContext requestContext, Map nextFilter) { _requestContext = requestContext; - _response = new HashMap(wireAttrs); + _response = new HashMap<>(wireAttrs); nextFilter.onError(ex, requestContext, wireAttrs); } @@ -88,7 +88,7 @@ public void onStreamRequest(StreamRequest req, NextFilter nextFilter) { _requestContext = requestContext; - _request = new HashMap(wireAttrs); + _request = new HashMap<>(wireAttrs); nextFilter.onRequest(req, requestContext, wireAttrs); } @@ -99,7 +99,7 @@ public void onStreamResponse(StreamResponse res, NextFilter nextFilter) { _requestContext = requestContext; - _response = new HashMap(wireAttrs); + _response = new HashMap<>(wireAttrs); nextFilter.onResponse(res, requestContext, wireAttrs); } @@ -110,7 +110,7 @@ public void onStreamError(Throwable ex, NextFilter nextFilter) { _requestContext = requestContext; - _response = new HashMap(wireAttrs); + _response = new HashMap<>(wireAttrs); nextFilter.onError(ex, requestContext, wireAttrs); } diff --git a/r2-netty/src/main/java/com/linkedin/r2/netty/callback/StreamExecutionCallback.java b/r2-netty/src/main/java/com/linkedin/r2/netty/callback/StreamExecutionCallback.java index 98bdbccaf8..edccfb7e81 100644 --- a/r2-netty/src/main/java/com/linkedin/r2/netty/callback/StreamExecutionCallback.java +++ b/r2-netty/src/main/java/com/linkedin/r2/netty/callback/StreamExecutionCallback.java @@ -47,7 +47,7 @@ public class StreamExecutionCallback implements TransportCallback _taskQueue = new LinkedBlockingQueue(); + private final Queue _taskQueue = new LinkedBlockingQueue<>(); private final AtomicInteger _pending = new AtomicInteger(0); private AtomicReference> _callbackRef; @@ -85,7 +85,7 @@ public void run() public StreamExecutionCallback(ExecutorService executor, TransportCallback callback) { _executor = executor; - _callbackRef = new AtomicReference>(callback); + _callbackRef = new AtomicReference<>(callback); } private void trySchedule(Runnable r) diff --git a/r2-netty/src/main/java/com/linkedin/r2/netty/common/SslHandlerUtil.java b/r2-netty/src/main/java/com/linkedin/r2/netty/common/SslHandlerUtil.java index 2b9a51daa9..29bb687c85 100644 --- a/r2-netty/src/main/java/com/linkedin/r2/netty/common/SslHandlerUtil.java +++ b/r2-netty/src/main/java/com/linkedin/r2/netty/common/SslHandlerUtil.java @@ -116,8 +116,8 @@ public static void validateSslParameters(SSLContext sslContext, SSLParameters ss */ private static void checkContained(String[] containingArray, String[] containedArray, String valueName) { - Set containingSet = new HashSet(Arrays.asList(containingArray)); - Set containedSet = new HashSet(Arrays.asList(containedArray)); + Set containingSet = new HashSet<>(Arrays.asList(containingArray)); + Set containedSet = new HashSet<>(Arrays.asList(containedArray)); final boolean changed = containedSet.removeAll(containingSet); if (!changed) diff --git a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/HttpClientFactory.java b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/HttpClientFactory.java index 6b1de01551..649cf2546f 100644 --- a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/HttpClientFactory.java +++ b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/HttpClientFactory.java @@ -1188,7 +1188,7 @@ private StreamEncodingType[] buildStreamAcceptEncodingSchemas(List encod { if (encodings != null) { - List encodingTypes = new ArrayList(); + List encodingTypes = new ArrayList<>(); for (String encoding : encodings) { if (StreamEncodingType.isSupported(encoding)) @@ -1208,7 +1208,7 @@ private EncodingType[] buildRestAcceptEncodingSchemaNames(List encodings { if (encodings != null) { - List encodingTypes = new ArrayList(); + List encodingTypes = new ArrayList<>(); for (String encoding : encodings) { if (EncodingType.isSupported(encoding)) diff --git a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/common/ChannelPoolManagerImpl.java b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/common/ChannelPoolManagerImpl.java index 26e3750100..f018055605 100644 --- a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/common/ChannelPoolManagerImpl.java +++ b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/common/ChannelPoolManagerImpl.java @@ -184,7 +184,7 @@ public void onError(Throwable e) @Override public Collection> cancelWaiters() { - Collection> cancelled = new ArrayList>(); + Collection> cancelled = new ArrayList<>(); final Collection> pools; synchronized (_mutex) { diff --git a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/stream/http/RAPStreamResponseDecoder.java b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/stream/http/RAPStreamResponseDecoder.java index 7686709538..846c5a3692 100644 --- a/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/stream/http/RAPStreamResponseDecoder.java +++ b/r2-netty/src/main/java/com/linkedin/r2/transport/http/client/stream/http/RAPStreamResponseDecoder.java @@ -227,7 +227,7 @@ private class TimeoutBufferedWriter implements Writer _lastChunkReceived = false; _totalBytesWritten = 0; _bufferedBytes = 0; - _buffer = new LinkedList(); + _buffer = new LinkedList<>(); // schedule a timeout to close the channel and inform use Runnable timeoutTask = new Runnable() diff --git a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestChannelPoolManager.java b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestChannelPoolManager.java index 7a4d414120..d5ddb5a4eb 100644 --- a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestChannelPoolManager.java +++ b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestChannelPoolManager.java @@ -52,18 +52,18 @@ public void test() @Override public AsyncPool getPool(SocketAddress address) { - return new FakePool(); + return new FakePool<>(); } }; ChannelPoolManager m = new ChannelPoolManagerImpl(factory, null, null); final int NUM = 100; - List addresses = new ArrayList(NUM); + List addresses = new ArrayList<>(NUM); for (int i = 0; i < NUM; i++) { addresses.add(new InetSocketAddress(i)); } - List> pools = new ArrayList>(NUM); + List> pools = new ArrayList<>(NUM); for (int i = 0; i < NUM; i++) { pools.add(m.getPoolForAddress(addresses.get(i))); diff --git a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpClientFactory.java b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpClientFactory.java index 9ca82c882b..442cbf85a1 100644 --- a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpClientFactory.java +++ b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpClientFactory.java @@ -153,7 +153,7 @@ public void testShutdownBeforeClients(boolean restOverStream, String protocolVer try { server.start(); - List clients = new ArrayList(); + List clients = new ArrayList<>(); for (int i = 0; i < 100; i++) { HashMap properties = new HashMap<>(); @@ -167,12 +167,12 @@ public void testShutdownBeforeClients(boolean restOverStream, String protocolVer c.restRequest(r).get(30, TimeUnit.SECONDS); } - FutureCallback factoryShutdown = new FutureCallback(); + FutureCallback factoryShutdown = new FutureCallback<>(); factory.shutdown(factoryShutdown); for (Client c : clients) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); c.shutdown(callback); callback.get(30, TimeUnit.SECONDS); } @@ -199,7 +199,7 @@ private void createRawClientHelper(String protocolVersion) .setShutdownScheduledExecutorService(true) .build(); - Map properties = new HashMap(); + Map properties = new HashMap<>(); String requestTimeout = "7000"; String poolSize = "10"; @@ -240,7 +240,7 @@ public void testGetHttp2RawClient() public void testNewSSLProperties() throws Exception { HttpClientFactory factory = new HttpClientFactory.Builder().build(); - Map params = new HashMap(); + Map params = new HashMap<>(); SSLParameters sslParameters = new SSLParameters(); sslParameters.setProtocols(new String[]{ "Unsupported" }); params.put(HttpClientFactory.HTTP_SSL_CONTEXT, SSLContext.getDefault()); @@ -262,7 +262,7 @@ public void testNewSSLProperties() throws Exception public void testSSLParams() throws Exception { HttpClientFactory factory = new HttpClientFactory.Builder().build(); - Map params = new HashMap(); + Map params = new HashMap<>(); SSLParameters sslParameters = new SSLParameters(); sslParameters.setProtocols(new String[]{ "Unsupported" }); @@ -291,7 +291,7 @@ public void testShutdownTimeout(boolean restOverStream, String protocolVersion) try { server.start(); - List clients = new ArrayList(); + List clients = new ArrayList<>(); for (int i = 0; i < 100; i++) { HashMap properties = new HashMap<>(); @@ -305,7 +305,7 @@ public void testShutdownTimeout(boolean restOverStream, String protocolVersion) c.restRequest(r).get(30, TimeUnit.SECONDS); } - FutureCallback factoryShutdown = new FutureCallback(); + FutureCallback factoryShutdown = new FutureCallback<>(); factory.shutdown(factoryShutdown, 1, TimeUnit.SECONDS); factoryShutdown.get(30, TimeUnit.SECONDS); @@ -329,7 +329,7 @@ public void testShutdownNoTimeout(boolean restOverStream, String protocolVersion try { server.start(); - List clients = new ArrayList(); + List clients = new ArrayList<>(); for (int i = 0; i < 100; i++) { HashMap properties = new HashMap<>(); @@ -348,7 +348,7 @@ public void testShutdownNoTimeout(boolean restOverStream, String protocolVersion server.stop(); } - FutureCallback factoryShutdown = new FutureCallback(); + FutureCallback factoryShutdown = new FutureCallback<>(); factory.shutdown(factoryShutdown); try { @@ -383,10 +383,10 @@ public void testShutdownIOThread(boolean restOverStream, String protocolVersion) URI uri = new URI(URI); Future responseFuture = client.restRequest(new RestRequestBuilder(uri).build()); - FutureCallback factoryShutdown = new FutureCallback(); + FutureCallback factoryShutdown = new FutureCallback<>(); factory.shutdown(factoryShutdown); - FutureCallback clientShutdown = new FutureCallback(); + FutureCallback clientShutdown = new FutureCallback<>(); client.shutdown(clientShutdown); // Client and factory shutdowns are now pending. When we release the latch, the response will @@ -422,7 +422,7 @@ public void testShutdownTimeoutDoesNotOccupyExecutors() ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); HttpClientFactory factory = getHttpClientFactory(eventLoop, false, scheduler, false); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); factory.shutdown(callback, 60, TimeUnit.MINUTES); callback.get(60, TimeUnit.SECONDS); scheduler.shutdown(); @@ -438,11 +438,11 @@ public void testClientShutdownBeingCalledMultipleTimes() HttpClientFactory factory = new HttpClientFactory.Builder().build(); TransportClient client = factory.getClient(Collections.emptyMap()); // first shutdown call - FutureCallback clientShutdown = new FutureCallback(); + FutureCallback clientShutdown = new FutureCallback<>(); client.shutdown(clientShutdown); clientShutdown.get(30, TimeUnit.SECONDS); // second shutdown call - clientShutdown = new FutureCallback(); + clientShutdown = new FutureCallback<>(); client.shutdown(clientShutdown); try { @@ -454,7 +454,7 @@ public void testClientShutdownBeingCalledMultipleTimes() Assert.assertTrue(ex.getCause() instanceof IllegalStateException); } - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); factory.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); } @@ -477,7 +477,7 @@ private Object[][] compressionConfigsData() @Test(dataProvider = "compressionConfigsData") public void testGetRequestCompressionConfig(String serviceName, int requestCompressionThresholdDefault, CompressionConfig expectedConfig) { - Map requestCompressionConfigs = new HashMap(); + Map requestCompressionConfigs = new HashMap<>(); requestCompressionConfigs.put("service1", new CompressionConfig(0)); requestCompressionConfigs.put("service2", new CompressionConfig(Integer.MAX_VALUE)); requestCompressionConfigs.put("service3", new CompressionConfig(111)); diff --git a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyClient.java b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyClient.java index b9bb89ca72..675418859e 100644 --- a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyClient.java +++ b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyClient.java @@ -104,9 +104,9 @@ public void testNoChannelTimeout() HttpNettyClient client = new HttpNettyClient(new NoCreations(_scheduler), _scheduler, 500, 500); RestRequest r = new RestRequestBuilder(URI.create("http://localhost/")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { // This timeout needs to be significantly larger than the getTimeout of the netty client; @@ -137,9 +137,9 @@ public void testNoResponseTimeout() .setShutdownTimeout(500).buildRestClient(); RestRequest r = new RestRequestBuilder(testServer.getNoResponseURI()).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { @@ -172,9 +172,9 @@ public void testBadAddress() throws InterruptedException, IOException, TimeoutEx .buildRestClient(); RestRequest r = new RestRequestBuilder(URI.create("http://this.host.does.not.exist.linkedin.com")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { cb.get(30, TimeUnit.SECONDS); @@ -233,9 +233,9 @@ public void testResponseSize(int responseSize, int expectedResult) .setShutdownTimeout(500).setMaxResponseSize(TEST_MAX_RESPONSE_SIZE).buildRestClient(); RestRequest r = new RestRequestBuilder(testServer.getResponseOfSizeURI(responseSize)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { @@ -276,9 +276,9 @@ public void testHeaderSize(int headerSize, int expectedResult) .setShutdownTimeout(500).setMaxHeaderSize(TEST_MAX_HEADER_SIZE).buildRestClient(); RestRequest r = new RestRequestBuilder(testServer.getResponseWithHeaderSizeURI(headerSize)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { @@ -319,9 +319,9 @@ public void testReceiveBadHeader() throws InterruptedException, IOException .setShutdownTimeout(500).buildRestClient(); RestRequest r = new RestRequestBuilder(testServer.getBadHeaderURI()).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); try { @@ -354,9 +354,9 @@ public void testSendBadHeader() throws Exception rb.setHeader("x", "makenettyunhappy\u000Bblah"); RestRequest request = rb.build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(request, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(request, new RequestContext(), new HashMap<>(), callback); try { @@ -383,14 +383,14 @@ public void testShutdown() throws ExecutionException, TimeoutException, Interrup .setShutdownTimeout(500) .buildRestClient(); - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); // Now verify a new request will also fail RestRequest r = new RestRequestBuilder(URI.create("http://no.such.host.linkedin.com")).build(); - FutureCallback callback = new FutureCallback(); - client.restRequest(r, new RequestContext(), new HashMap(), new TransportCallbackAdapter(callback)); + FutureCallback callback = new FutureCallback<>(); + client.restRequest(r, new RequestContext(), new HashMap<>(), new TransportCallbackAdapter<>(callback)); try { callback.get(30, TimeUnit.SECONDS); @@ -410,10 +410,10 @@ public void testShutdownStuckInPool() HttpNettyClient client = new HttpNettyClient(new NoCreations(_scheduler), _scheduler, 60000, 1); RestRequest r = new RestRequestBuilder(URI.create("http://some.host/")).build(); - FutureCallback futureCallback = new FutureCallback(); - client.restRequest(r, new RequestContext(), new HashMap(), new TransportCallbackAdapter(futureCallback)); + FutureCallback futureCallback = new FutureCallback<>(); + client.restRequest(r, new RequestContext(), new HashMap<>(), new TransportCallbackAdapter<>(futureCallback)); - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); @@ -457,11 +457,11 @@ private void testShutdownRequestOutstanding(int shutdownTimeout, int requestTime .setShutdownTimeout(shutdownTimeout).buildRestClient(); RestRequest r = new RestRequestBuilder(testServer.getNoResponseURI()).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); @@ -626,7 +626,7 @@ public void onProviderShutdown(PoolStatsProvider provider) Assert.fail("PoolStatsAware setPoolStatsProvider didn't get called when creating channel pool."); } // test removePoolStatsProvider - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); try { @@ -652,9 +652,9 @@ public void testMakingOutboundHttpsRequest() .buildRestClient(); RestRequest r = new RestRequestBuilder(URI.create("https://www.howsmyssl.com/a/check")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.restRequest(r, new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.restRequest(r, new RequestContext(), new HashMap<>(), callback); cb.get(30, TimeUnit.SECONDS); } @@ -734,7 +734,7 @@ public PoolStats.LifecycleStats getStats() try { FutureCallback callback = new FutureCallback<>(); - client.restRequest(r, new RequestContext(), new HashMap<>(), new TransportCallbackAdapter(callback)); + client.restRequest(r, new RequestContext(), new HashMap<>(), new TransportCallbackAdapter<>(callback)); callback.get(); } catch (Exception e) @@ -771,35 +771,29 @@ public NoCreations(ScheduledExecutorService scheduler) @Override public AsyncPool getPool(SocketAddress address) { - return new AsyncPoolImpl("fake pool", new AsyncPool.Lifecycle() - { + return new AsyncPoolImpl<>("fake pool", new AsyncPool.Lifecycle() { @Override - public void create(Callback channelCallback) - { + public void create(Callback channelCallback) { } @Override - public boolean validateGet(Channel obj) - { + public boolean validateGet(Channel obj) { return false; } @Override - public boolean validatePut(Channel obj) - { + public boolean validatePut(Channel obj) { return false; } @Override - public void destroy(Channel obj, boolean error, Callback channelCallback) - { + public void destroy(Channel obj, boolean error, Callback channelCallback) { } @Override - public PoolStats.LifecycleStats getStats() - { + public PoolStats.LifecycleStats getStats() { return null; } }, 0, 0, _scheduler); diff --git a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyStreamClient.java b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyStreamClient.java index d7ecd25d13..8efba16603 100644 --- a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyStreamClient.java +++ b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/TestHttpNettyStreamClient.java @@ -138,10 +138,10 @@ public void testNoChannelTimeout() RestRequest r = new RestRequestBuilder(URI.create("http://localhost/")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); try { @@ -284,9 +284,9 @@ public void testNoResponseTimeout(AbstractNettyStreamClient client) throws Excep server.start(); RestRequest r = new RestRequestBuilder(new URI(URL)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); // This timeout needs to be significantly larger than the getTimeout of the netty client; // we're testing that the client will generate its own timeout @@ -328,9 +328,9 @@ public Object[][] badAddressClientsProvider() public void testBadAddress(AbstractNettyStreamClient client) throws InterruptedException, IOException, TimeoutException { RestRequest r = new RestRequestBuilder(URI.create("http://this.host.does.not.exist.linkedin.com")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); try { cb.get(30, TimeUnit.SECONDS); @@ -418,13 +418,13 @@ public void testResponseSize(AbstractNettyStreamClient client, int responseSize, { server.start(); RestRequest r = new RestRequestBuilder(new URI(URL)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); StreamResponse response = cb.get(30, TimeUnit.SECONDS); final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference error = new AtomicReference(); + final AtomicReference error = new AtomicReference<>(); response.getEntityStream().setReader(new Reader() { @Override @@ -509,9 +509,9 @@ public void testHeaderSize(AbstractNettyStreamClient client, int headerSize, int { server.start(); RestRequest r = new RestRequestBuilder(new URI(URL)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); cb.get(300, TimeUnit.SECONDS); if (expectedResult == TOO_LARGE) @@ -561,15 +561,15 @@ public Object[][] shutdownClientProvider() @Test(dataProvider = "shutdownClients") public void testShutdown(AbstractNettyStreamClient client) throws Exception { - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); // Now verify a new request will also fail RestRequest r = new RestRequestBuilder(URI.create("http://no.such.host.linkedin.com")).build(); - FutureCallback callback = new FutureCallback(); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), - new TransportCallbackAdapter(callback)); + FutureCallback callback = new FutureCallback<>(); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), + new TransportCallbackAdapter<>(callback)); try { callback.get(30, TimeUnit.SECONDS); @@ -589,10 +589,10 @@ public void testShutdownStuckInPool() HttpNettyStreamClient client = new HttpNettyStreamClient(new NoCreations(_scheduler), _scheduler, 60000, 1); RestRequest r = new RestRequestBuilder(URI.create("http://some.host/")).build(); - FutureCallback futureCallback = new FutureCallback(); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), new TransportCallbackAdapter(futureCallback)); + FutureCallback futureCallback = new FutureCallback<>(); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), new TransportCallbackAdapter<>(futureCallback)); - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); @@ -644,11 +644,11 @@ private void testShutdownRequestOutstanding(AbstractNettyStreamClient client, Cl { server.start(); RestRequest r = new RestRequestBuilder(new URI(URL)).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); shutdownCallback.get(30, TimeUnit.SECONDS); @@ -925,7 +925,7 @@ public void testPoolStatsProviderManager( Assert.fail("PoolStatsAware setPoolStatsProvider didn't get called when creating channel pool."); } // test removePoolStatsProvider - FutureCallback shutdownCallback = new FutureCallback(); + FutureCallback shutdownCallback = new FutureCallback<>(); client.shutdown(shutdownCallback); try { @@ -951,9 +951,9 @@ public void testMakingOutboundHttpsRequest() .buildStreamClient(); RestRequest r = new RestRequestBuilder(URI.create("https://www.howsmyssl.com/a/check")).build(); - FutureCallback cb = new FutureCallback(); - TransportCallback callback = new TransportCallbackAdapter(cb); - client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap(), callback); + FutureCallback cb = new FutureCallback<>(); + TransportCallback callback = new TransportCallbackAdapter<>(cb); + client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<>(), callback); cb.get(30, TimeUnit.SECONDS); } @@ -969,35 +969,29 @@ public NoCreations(ScheduledExecutorService scheduler) @Override public AsyncPool getPool(SocketAddress address) { - return new AsyncPoolImpl("fake pool", new AsyncPool.Lifecycle() - { + return new AsyncPoolImpl<>("fake pool", new AsyncPool.Lifecycle() { @Override - public void create(Callback channelCallback) - { + public void create(Callback channelCallback) { } @Override - public boolean validateGet(Channel obj) - { + public boolean validateGet(Channel obj) { return false; } @Override - public boolean validatePut(Channel obj) - { + public boolean validatePut(Channel obj) { return false; } @Override - public void destroy(Channel obj, boolean error, Callback channelCallback) - { + public void destroy(Channel obj, boolean error, Callback channelCallback) { } @Override - public PoolStats.LifecycleStats getStats() - { + public PoolStats.LifecycleStats getStats() { return null; } }, 0, 0, _scheduler); diff --git a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/stream/http/TestChannelPoolStreamHandler.java b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/stream/http/TestChannelPoolStreamHandler.java index 07cc6a7e79..64a1e33a54 100644 --- a/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/stream/http/TestChannelPoolStreamHandler.java +++ b/r2-netty/src/test/java/com/linkedin/r2/transport/http/client/stream/http/TestChannelPoolStreamHandler.java @@ -70,7 +70,7 @@ public void testConnectionKeepAlive(String headerName, List headerValue) private static EmbeddedChannel getChannel() { EmbeddedChannel ch = new EmbeddedChannel(new RAPStreamResponseDecoder(1000), new RAPStreamResponseHandler(), new ChannelPoolStreamHandler()); - ch.attr(RAPStreamResponseDecoder.TIMEOUT_ATTR_KEY).set(new Timeout(Executors.newSingleThreadScheduledExecutor(), 1000, TimeUnit.MILLISECONDS, None.none())); + ch.attr(RAPStreamResponseDecoder.TIMEOUT_ATTR_KEY).set(new Timeout<>(Executors.newSingleThreadScheduledExecutor(), 1000, TimeUnit.MILLISECONDS, None.none())); ch.attr(RAPStreamResponseHandler.CALLBACK_ATTR_KEY).set(response -> { StreamResponse streamResponse = response.getResponse(); streamResponse.getEntityStream().setReader(new DrainReader()); diff --git a/r2-perf-test/src/test/java/test/r2/perf/client/AbstractClientRunnable.java b/r2-perf-test/src/test/java/test/r2/perf/client/AbstractClientRunnable.java index c76c60d055..30851e1e83 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/client/AbstractClientRunnable.java +++ b/r2-perf-test/src/test/java/test/r2/perf/client/AbstractClientRunnable.java @@ -61,7 +61,7 @@ public void run() REQ nextMsg; while ((nextMsg = _workGen.nextMessage()) != null) { - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); long start = System.nanoTime(); diff --git a/r2-perf-test/src/test/java/test/r2/perf/client/PerfClient.java b/r2-perf-test/src/test/java/test/r2/perf/client/PerfClient.java index e3788ac361..6c49b30604 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/client/PerfClient.java +++ b/r2-perf-test/src/test/java/test/r2/perf/client/PerfClient.java @@ -41,10 +41,10 @@ public PerfClient(ClientRunnableFactory runnableFactory, int numThreads) public void run() throws Exception { - final AtomicReference statsRef = new AtomicReference(); + final AtomicReference statsRef = new AtomicReference<>(); statsRef.set(new Stats(System.currentTimeMillis())); final CountDownLatch startLatch = new CountDownLatch(1); - final List workers = new ArrayList(); + final List workers = new ArrayList<>(); for (int i = 0; i < _numThreads; i++) { final Thread t = new Thread(_runnableFactory.create(statsRef, diff --git a/r2-perf-test/src/test/java/test/r2/perf/client/RestClientRunnableFactory.java b/r2-perf-test/src/test/java/test/r2/perf/client/RestClientRunnableFactory.java index 7816a2f486..1db038c698 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/client/RestClientRunnableFactory.java +++ b/r2-perf-test/src/test/java/test/r2/perf/client/RestClientRunnableFactory.java @@ -51,7 +51,7 @@ public Runnable create(AtomicReference stats, CountDownLatch startLatch) @Override public void shutdown() { - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); _client.shutdown(callback); try diff --git a/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnable.java b/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnable.java index 16066bb74a..73b9379f1c 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnable.java +++ b/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnable.java @@ -41,7 +41,7 @@ public void onError(Throwable e) @Override public void onSuccess(StreamResponse result) { - result.getEntityStream().setReader(new PerfStreamReader(timingCallback, result)); + result.getEntityStream().setReader(new PerfStreamReader<>(timingCallback, result)); } }; _client.streamRequest(nextMsg, callback); diff --git a/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnableFactory.java b/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnableFactory.java index b8b3473532..40019819e4 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnableFactory.java +++ b/r2-perf-test/src/test/java/test/r2/perf/client/StreamClientRunnableFactory.java @@ -33,7 +33,7 @@ public Runnable create(AtomicReference stats, CountDownLatch startLatch) @Override public void shutdown() { - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); _client.shutdown(callback); try diff --git a/r2-perf-test/src/test/java/test/r2/perf/server/AbstractPerfServerFactory.java b/r2-perf-test/src/test/java/test/r2/perf/server/AbstractPerfServerFactory.java index 7e4cdccfc2..3182637393 100644 --- a/r2-perf-test/src/test/java/test/r2/perf/server/AbstractPerfServerFactory.java +++ b/r2-perf-test/src/test/java/test/r2/perf/server/AbstractPerfServerFactory.java @@ -65,20 +65,16 @@ public Server createPureStreamServer(int port, URI echoUri, final int msg_size, @Override public void handleRequest(StreamRequest request, RequestContext requestContext, final Callback callback) { - request.getEntityStream().setReader(new PerfStreamReader(new Callback() - { + request.getEntityStream().setReader(new PerfStreamReader<>(new Callback() { @Override - public void onError(Throwable e) - { + public void onError(Throwable e) { callback.onError(e); } @Override - public void onSuccess(None result) - { + public void onSuccess(None result) { StreamResponseBuilder builder = new StreamResponseBuilder(); - for (int i = 0; i < numHeaders; i++) - { + for (int i = 0; i < numHeaders; i++) { builder.setHeader(STATIC_HEADER_PREFIX + i, headerContent); } diff --git a/r2-testutils/src/main/java/com/linkedin/r2/testutils/filter/FilterUtil.java b/r2-testutils/src/main/java/com/linkedin/r2/testutils/filter/FilterUtil.java index 4af09605d0..ca9d9aa219 100644 --- a/r2-testutils/src/main/java/com/linkedin/r2/testutils/filter/FilterUtil.java +++ b/r2-testutils/src/main/java/com/linkedin/r2/testutils/filter/FilterUtil.java @@ -298,7 +298,7 @@ public static Exception simpleError() public static Map emptyWireAttrs() { - return new HashMap(); + return new HashMap<>(); } public static RequestContext emptyRequestContext() diff --git a/r2-testutils/src/main/java/com/linkedin/r2/testutils/server/HttpServerBuilder.java b/r2-testutils/src/main/java/com/linkedin/r2/testutils/server/HttpServerBuilder.java index 45716b133d..9c932a4e76 100644 --- a/r2-testutils/src/main/java/com/linkedin/r2/testutils/server/HttpServerBuilder.java +++ b/r2-testutils/src/main/java/com/linkedin/r2/testutils/server/HttpServerBuilder.java @@ -295,7 +295,7 @@ private void consumeRequest(HttpServletRequest req) throws IOException public static class HttpServerStatsProvider { - private Set clientConnections = Collections.newSetFromMap(new ConcurrentHashMap()); + private Set clientConnections = Collections.newSetFromMap(new ConcurrentHashMap<>()); private AtomicInteger requestCount = new AtomicInteger(0); private Function _checkValidRequest; @@ -340,4 +340,4 @@ private void processRequest(HttpServletRequest req) } } -} \ No newline at end of file +} diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchCreateIdResponseFactory.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchCreateIdResponseFactory.java index d869b8f20a..6dc12f33d6 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchCreateIdResponseFactory.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchCreateIdResponseFactory.java @@ -39,6 +39,6 @@ private MockBatchCreateIdResponseFactory() { } */ public static BatchCreateIdResponse create(List> elements) { - return new BatchCreateIdResponse(elements); + return new BatchCreateIdResponse<>(elements); } } diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchEntityResponseFactory.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchEntityResponseFactory.java index 00701d8a99..cf89ad5249 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchEntityResponseFactory.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchEntityResponseFactory.java @@ -102,12 +102,12 @@ public static , EntityResponse> response = - (BatchKVResponse, EntityResponse>) (Object) new BatchEntityResponse(batchResponseDataMap, - new TypeSpec(ComplexResourceKey.class), - TypeSpec.forClassMaybeNull(valueClass), - null, - ComplexKeySpec.forClassesMaybeNull(keyKeyClass, keyParamsClass), - version); + (BatchKVResponse, EntityResponse>) (Object) new BatchEntityResponse<>(batchResponseDataMap, + new TypeSpec<>(ComplexResourceKey.class), + TypeSpec.forClassMaybeNull(valueClass), + null, + ComplexKeySpec.forClassesMaybeNull(keyKeyClass, keyParamsClass), + version); return response; } @@ -218,11 +218,11 @@ private static BatchKVResponse(batchResponseDataMap, - TypeSpec.forClassMaybeNull(keyClass), - TypeSpec.forClassMaybeNull(valueClass), - keyParts, - null, - version); + return new BatchEntityResponse<>(batchResponseDataMap, + TypeSpec.forClassMaybeNull(keyClass), + TypeSpec.forClassMaybeNull(valueClass), + keyParts, + null, + version); } } diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchKVResponseFactory.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchKVResponseFactory.java index f665dca84f..05f6601a36 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchKVResponseFactory.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchKVResponseFactory.java @@ -93,13 +93,13 @@ private MockBatchKVResponseFactory() { } @SuppressWarnings("unchecked") BatchKVResponse, V> response = - (BatchKVResponse, V>) (Object) new BatchKVResponse(batchResponseDataMap, - ComplexResourceKey.class, - valueClass, - null, - keyKeyClass, - keyParamsClass, - version); + (BatchKVResponse, V>) (Object) new BatchKVResponse<>(batchResponseDataMap, + ComplexResourceKey.class, + valueClass, + null, + keyKeyClass, + keyParamsClass, + version); return response; } @@ -185,12 +185,12 @@ private static DataMap buildDataMap(Map reco { DataMap batchResponseDataMap = buildDataMap(recordTemplates, errorResponses, version); - return new BatchKVResponse(batchResponseDataMap, - keyClass, - valueClass, - keyParts, - null, - null, - version); + return new BatchKVResponse<>(batchResponseDataMap, + keyClass, + valueClass, + keyParts, + null, + null, + version); } } diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchResponseFactory.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchResponseFactory.java index ef3a7f50aa..d3c4f14c69 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchResponseFactory.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockBatchResponseFactory.java @@ -50,6 +50,6 @@ public static BatchResponse create(Class entryC { rawBatchData.put(entry.getKey(), entry.getValue().data()); } - return new BatchResponse(batchResponseDataMap, entryClass); + return new BatchResponse<>(batchResponseDataMap, entryClass); } } diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockCollectionResponseFactory.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockCollectionResponseFactory.java index 66dd4186e4..94092bdc37 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockCollectionResponseFactory.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockCollectionResponseFactory.java @@ -48,7 +48,7 @@ private MockCollectionResponseFactory() { } public static CollectionResponse create(Class entryClass, Collection recordTemplates) { - List dataMapsOfRecordTemplates = new ArrayList(); + List dataMapsOfRecordTemplates = new ArrayList<>(); for (T recordTemplate : recordTemplates) { dataMapsOfRecordTemplates.add(recordTemplate.data()); @@ -56,7 +56,7 @@ public static CollectionResponse create(Class e DataMap dataMapCollection = new DataMap(); dataMapCollection.put(CollectionResponse.ELEMENTS, new DataList(dataMapsOfRecordTemplates)); - return new CollectionResponse(dataMapCollection, entryClass); + return new CollectionResponse<>(dataMapCollection, entryClass); } /** diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockFailedResponseFutureBuilder.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockFailedResponseFutureBuilder.java index 592a85bcfd..b21a21a8fd 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockFailedResponseFutureBuilder.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockFailedResponseFutureBuilder.java @@ -272,7 +272,7 @@ private ResponseFuture buildWithErrorResponse(ProtocolVersion protocolVersion ExecutionException executionException = new ExecutionException(restLiResponseException); Future> responseFuture = buildFuture(null, executionException); - return new ResponseFutureImpl(responseFuture, _errorHandlingBehavior); + return new ResponseFutureImpl<>(responseFuture, _errorHandlingBehavior); } private ResponseFuture buildWithEntity() @@ -301,7 +301,7 @@ private ResponseFuture buildWithEntity() ExecutionException executionException = new ExecutionException(restLiResponseException); Future> responseFuture = buildFuture(null, executionException); - return new ResponseFutureImpl(responseFuture, _errorHandlingBehavior); + return new ResponseFutureImpl<>(responseFuture, _errorHandlingBehavior); } private static byte[] mapToBytes(DataMap dataMap) diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockResponseBuilder.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockResponseBuilder.java index ea4fed5606..9320ebd21f 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockResponseBuilder.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockResponseBuilder.java @@ -142,7 +142,7 @@ public MockResponseBuilder setRestLiAttachmentReader(RestLiAttachmentReade */ public Response build() { - Map headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); if (_headers != null) { headers.putAll(_headers); @@ -173,7 +173,7 @@ public Response build() } List cookies = _cookies == null ? Collections.emptyList() : _cookies; - final ResponseImpl response = new ResponseImpl(status, headers, cookies, _entity, _restLiResponseException); + final ResponseImpl response = new ResponseImpl<>(status, headers, cookies, _entity, _restLiResponseException); response.setAttachmentReader(_restLiAttachmentReader); return response; diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockRestliResponseExceptionBuilder.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockRestliResponseExceptionBuilder.java index 634d692ab9..ce01be1ae5 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockRestliResponseExceptionBuilder.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockRestliResponseExceptionBuilder.java @@ -62,7 +62,7 @@ public RestLiResponseException build() String errorHeaderName = _version.equals(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion()) ? RestConstants.HEADER_LINKEDIN_ERROR_RESPONSE : RestConstants.HEADER_RESTLI_ERROR_RESPONSE; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(errorHeaderName, "true"); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, _version.toString()); headers.putAll(_headers); diff --git a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockSuccessfulResponseFutureBuilder.java b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockSuccessfulResponseFutureBuilder.java index d25a8bfa99..7116a68cec 100644 --- a/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockSuccessfulResponseFutureBuilder.java +++ b/restli-client-testutils/src/main/java/com/linkedin/restli/client/testutils/MockSuccessfulResponseFutureBuilder.java @@ -120,7 +120,7 @@ public MockSuccessfulResponseFutureBuilder setProtocolVersion(ProtocolVers @Override public ResponseFuture build() { - MockResponseBuilder responseBuilder = new MockResponseBuilder(); + MockResponseBuilder responseBuilder = new MockResponseBuilder<>(); Response response = responseBuilder .setEntity(getEntity()) .setStatus(getStatus()) @@ -129,6 +129,6 @@ public ResponseFuture build() .setProtocolVersion(getProtocolVersion()) .build(); - return new ResponseFutureImpl(buildFuture(response, null)); + return new ResponseFutureImpl<>(buildFuture(response, null)); } } diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchCreateIdResponseFactory.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchCreateIdResponseFactory.java index 9c09a77b93..b118823769 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchCreateIdResponseFactory.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchCreateIdResponseFactory.java @@ -63,9 +63,9 @@ public Object[][] provideKeys() new Object[] {new Long[] {1L, 2L, 3L}}, new Object[] {new MyCustomString[] {new MyCustomString("1"), new MyCustomString("2"), new MyCustomString("3")}}, new Object[] {new CompoundKey[] {buildCompoundKey("c1", 1), buildCompoundKey("c2", 2), buildCompoundKey("c3", 3)}}, - new Object[] {new ComplexResourceKey[] {new ComplexResourceKey(g1, g1), - new ComplexResourceKey(g2, g2), - new ComplexResourceKey(g3, g3)}} + new Object[] {new ComplexResourceKey[] {new ComplexResourceKey<>(g1, g1), + new ComplexResourceKey<>(g2, g2), + new ComplexResourceKey<>(g3, g3)}} }; } @@ -74,12 +74,12 @@ public void testCreate(K[] keys) { ProtocolVersion version = AllProtocolVersions.BASELINE_PROTOCOL_VERSION; - List> elements = new ArrayList>(); - elements.add(new CreateIdStatus(HttpStatus.S_201_CREATED.getCode(), keys[0], null, version)); - elements.add(new CreateIdStatus(HttpStatus.S_201_CREATED.getCode(), keys[1], null, version)); + List> elements = new ArrayList<>(); + elements.add(new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), keys[0], null, version)); + elements.add(new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), keys[1], null, version)); ErrorResponse error = new ErrorResponse().setMessage("3"); - elements.add(new CreateIdStatus(HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode(), keys[2], error, version)); + elements.add(new CreateIdStatus<>(HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode(), keys[2], error, version)); BatchCreateIdResponse batchResp = MockBatchCreateIdResponseFactory.create(elements); diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchKVResponseFactory.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchKVResponseFactory.java index 86fa5d75b4..0ab2146f07 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchKVResponseFactory.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchKVResponseFactory.java @@ -48,7 +48,7 @@ private Greeting buildGreeting(Long id) private EntityResponse buildEntityResponse(Greeting recordTemplate, HttpStatus status, ErrorResponse errorResponse) { - return new EntityResponse(Greeting.class).setEntity(recordTemplate, SetMode.IGNORE_NULL). + return new EntityResponse<>(Greeting.class).setEntity(recordTemplate, SetMode.IGNORE_NULL). setStatus(status, SetMode.IGNORE_NULL). setError(errorResponse, SetMode.IGNORE_NULL); } @@ -56,20 +56,20 @@ private EntityResponse buildEntityResponse(Greeting recordTemplate, Ht @DataProvider(name = "primitiveKey") public Object[][] primitiveKeyData() { - Map recordTemplates = new HashMap(); - Map errorResponses = new HashMap(); + Map recordTemplates = new HashMap<>(); + Map errorResponses = new HashMap<>(); recordTemplates.put(1L, buildGreeting(1L)); recordTemplates.put(2L, buildGreeting(2L)); errorResponses.put(3L, new ErrorResponse().setMessage("3")); - Map statuses = new HashMap(); + Map statuses = new HashMap<>(); statuses.put(1L, HttpStatus.S_200_OK); statuses.put(2L, HttpStatus.S_200_OK); statuses.put(3L, HttpStatus.S_500_INTERNAL_SERVER_ERROR); - Map> expectedResults = new HashMap>(); + Map> expectedResults = new HashMap<>(); expectedResults.put(1L, buildEntityResponse(recordTemplates.get(1L), HttpStatus.S_200_OK, null)); expectedResults.put(2L, buildEntityResponse(recordTemplates.get(2L), HttpStatus.S_200_OK, null)); expectedResults.put(3L, buildEntityResponse(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR, errorResponses.get(3L))); @@ -120,19 +120,19 @@ public Object[][] customPrimitiveTyperefKeyData() MyCustomString m2 = new MyCustomString("2"); MyCustomString m3 = new MyCustomString("3"); - Map recordTemplates = new HashMap(); - Map errorResponses = new HashMap(); + Map recordTemplates = new HashMap<>(); + Map errorResponses = new HashMap<>(); recordTemplates.put(m1, buildGreeting(1L)); recordTemplates.put(m2, buildGreeting(2L)); errorResponses.put(m3, new ErrorResponse().setMessage("3")); - Map statuses = new HashMap(); + Map statuses = new HashMap<>(); statuses.put(m1, HttpStatus.S_200_OK); statuses.put(m2, HttpStatus.S_200_OK); statuses.put(m3, HttpStatus.S_500_INTERNAL_SERVER_ERROR); - Map> expectedResults = new HashMap>(); + Map> expectedResults = new HashMap<>(); expectedResults.put(m1, buildEntityResponse(recordTemplates.get(m1), HttpStatus.S_200_OK, null)); expectedResults.put(m2, buildEntityResponse(recordTemplates.get(m2), HttpStatus.S_200_OK, null)); expectedResults.put(m3, buildEntityResponse(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR, errorResponses.get(m3))); @@ -191,23 +191,23 @@ public Object[][] compoundKeyData() CompoundKey c2 = buildCompoundKey("c2", 2); CompoundKey c3 = buildCompoundKey("c3", 3); - Map recordTemplates = new HashMap(); + Map recordTemplates = new HashMap<>(); recordTemplates.put(c1, buildGreeting(1L)); recordTemplates.put(c2, buildGreeting(2L)); - Map errorResponses = new HashMap(); + Map errorResponses = new HashMap<>(); errorResponses.put(c3, new ErrorResponse().setMessage("3")); - Map statuses = new HashMap(); + Map statuses = new HashMap<>(); statuses.put(c1, HttpStatus.S_200_OK); statuses.put(c2, HttpStatus.S_200_OK); statuses.put(c3, HttpStatus.S_500_INTERNAL_SERVER_ERROR); - Map keyParts = new HashMap(); + Map keyParts = new HashMap<>(); keyParts.put("part1", new CompoundKey.TypeInfo(String.class, String.class)); keyParts.put("part2", new CompoundKey.TypeInfo(Integer.class, Integer.class)); - Map> expectedResults = new HashMap>(); + Map> expectedResults = new HashMap<>(); expectedResults.put(c1, buildEntityResponse(recordTemplates.get(c1), HttpStatus.S_200_OK, null)); expectedResults.put(c2, buildEntityResponse(recordTemplates.get(c2), HttpStatus.S_200_OK, null)); expectedResults.put(c3, buildEntityResponse(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR, errorResponses.get(c3))); @@ -259,46 +259,46 @@ public void testCompoundKeyEntityResponse(Map keyP public Object[][] complexKeyData() { Map, Greeting> recordTemplates = - new HashMap, Greeting>(); + new HashMap<>(); Map, ErrorResponse> errorResponses = - new HashMap, ErrorResponse>(); + new HashMap<>(); Greeting g1 = buildGreeting(1L); Greeting g2 = buildGreeting(2L); Greeting g3 = buildGreeting(3L); - recordTemplates.put(new ComplexResourceKey(g1, g1), g1); - recordTemplates.put(new ComplexResourceKey(g2, g2), g2); + recordTemplates.put(new ComplexResourceKey<>(g1, g1), g1); + recordTemplates.put(new ComplexResourceKey<>(g2, g2), g2); - errorResponses.put(new ComplexResourceKey(g3, g3), new ErrorResponse().setMessage("3")); + errorResponses.put(new ComplexResourceKey<>(g3, g3), new ErrorResponse().setMessage("3")); - Map, HttpStatus> statuses = new HashMap, HttpStatus>(); - statuses.put(new ComplexResourceKey(g1, g1), HttpStatus.S_200_OK); - statuses.put(new ComplexResourceKey(g2, g2), HttpStatus.S_200_OK); - statuses.put(new ComplexResourceKey(g3, g3), HttpStatus.S_500_INTERNAL_SERVER_ERROR); + Map, HttpStatus> statuses = new HashMap<>(); + statuses.put(new ComplexResourceKey<>(g1, g1), HttpStatus.S_200_OK); + statuses.put(new ComplexResourceKey<>(g2, g2), HttpStatus.S_200_OK); + statuses.put(new ComplexResourceKey<>(g3, g3), HttpStatus.S_500_INTERNAL_SERVER_ERROR); // Strip the parameters from complex keys in expected results and expected errors. Map, Greeting> expectedRecordTemplates = - new HashMap, Greeting>(); - expectedRecordTemplates.put(new ComplexResourceKey(g1, new Greeting()), - recordTemplates.get(new ComplexResourceKey(g1, g1))); - expectedRecordTemplates.put(new ComplexResourceKey(g2, new Greeting()), - recordTemplates.get(new ComplexResourceKey(g2, g2))); + new HashMap<>(); + expectedRecordTemplates.put(new ComplexResourceKey<>(g1, new Greeting()), + recordTemplates.get(new ComplexResourceKey<>(g1, g1))); + expectedRecordTemplates.put(new ComplexResourceKey<>(g2, new Greeting()), + recordTemplates.get(new ComplexResourceKey<>(g2, g2))); Map, EntityResponse> expectedResults = - new HashMap, EntityResponse>(); - expectedResults.put(new ComplexResourceKey(g1, new Greeting()), - buildEntityResponse(recordTemplates.get(new ComplexResourceKey(g1, g1)), HttpStatus.S_200_OK, null)); - expectedResults.put(new ComplexResourceKey(g2, new Greeting()), - buildEntityResponse(recordTemplates.get(new ComplexResourceKey(g2, g2)), HttpStatus.S_200_OK, null)); - expectedResults.put(new ComplexResourceKey(g3, new Greeting()), - buildEntityResponse(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR, errorResponses.get(new ComplexResourceKey(g3, g3)))); + new HashMap<>(); + expectedResults.put(new ComplexResourceKey<>(g1, new Greeting()), + buildEntityResponse(recordTemplates.get(new ComplexResourceKey<>(g1, g1)), HttpStatus.S_200_OK, null)); + expectedResults.put(new ComplexResourceKey<>(g2, new Greeting()), + buildEntityResponse(recordTemplates.get(new ComplexResourceKey<>(g2, g2)), HttpStatus.S_200_OK, null)); + expectedResults.put(new ComplexResourceKey<>(g3, new Greeting()), + buildEntityResponse(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR, errorResponses.get(new ComplexResourceKey<>(g3, g3)))); Map, ErrorResponse> expectedErrors = - new HashMap, ErrorResponse>(); - expectedErrors.put(new ComplexResourceKey(g3, new Greeting()), - errorResponses.get(new ComplexResourceKey(g3, g3))); + new HashMap<>(); + expectedErrors.put(new ComplexResourceKey<>(g3, new Greeting()), + errorResponses.get(new ComplexResourceKey<>(g3, g3))); return new Object[][] { diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchResponseFactory.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchResponseFactory.java index 323051d0b5..ba7dc37b5b 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchResponseFactory.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockBatchResponseFactory.java @@ -37,7 +37,7 @@ public void testCreate() Greeting g1 = new Greeting().setId(1L).setMessage("g1"); Greeting g2 = new Greeting().setId(2L).setMessage("g2"); - Map recordTemplates = new HashMap(); + Map recordTemplates = new HashMap<>(); recordTemplates.put("1", g1); recordTemplates.put("2", g2); diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockFailedResponseFutureBuilder.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockFailedResponseFutureBuilder.java index 8c9d9ecc3d..69640dc421 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockFailedResponseFutureBuilder.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockFailedResponseFutureBuilder.java @@ -54,7 +54,7 @@ public void testBuildIllegalStatus() @Test public void testOnlyOneOfErrorResponseOrEntityIsSet() { - MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder(); + MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder<>(); builder.setEntity(new Greeting()); try { @@ -66,7 +66,7 @@ public void testOnlyOneOfErrorResponseOrEntityIsSet() // expected } - builder = new MockFailedResponseFutureBuilder(); + builder = new MockFailedResponseFutureBuilder<>(); builder.setErrorResponse(new ErrorResponse()); try { @@ -81,7 +81,7 @@ public void testOnlyOneOfErrorResponseOrEntityIsSet() private ResponseFuture buildWithErrorResponse(ErrorHandlingBehavior errorHandlingBehavior) { - MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder(); + MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder<>(); ErrorResponse errorResponse = new ErrorResponse().setStatus(404).setMessage("foo"); builder.setErrorResponse(errorResponse).setErrorHandlingBehavior(errorHandlingBehavior); @@ -130,7 +130,7 @@ public void testBuildWithErrorResponseTreatServerErrorAsSuccess() private ResponseFuture buildWithEntity(ErrorHandlingBehavior errorHandlingBehavior) { - MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder(); + MockFailedResponseFutureBuilder builder = new MockFailedResponseFutureBuilder<>(); Greeting greeting = new Greeting().setId(1L).setMessage("foo"); builder.setEntity(greeting).setErrorHandlingBehavior(errorHandlingBehavior).setStatus(500); diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockResponseBuilder.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockResponseBuilder.java index 96f4f7a39f..b36a35636b 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockResponseBuilder.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockResponseBuilder.java @@ -44,7 +44,7 @@ public class TestMockResponseBuilder @Test public void testBuild() { - MockResponseBuilder mockResponseBuilder = new MockResponseBuilder(); + MockResponseBuilder mockResponseBuilder = new MockResponseBuilder<>(); Greeting greeting = new Greeting().setId(1L).setMessage("message"); Map headers = Collections.singletonMap("foo", "bar"); RestLiResponseException restLiResponseException = EasyMock.createMock(RestLiResponseException.class); @@ -64,7 +64,7 @@ public void testBuild() Response response = mockResponseBuilder.build(); // when we build the Response the ID is put into the headers - Map builtHeaders = new HashMap(headers); + Map builtHeaders = new HashMap<>(headers); builtHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()); Assert.assertEquals(response.getEntity(), greeting); @@ -77,8 +77,8 @@ public void testBuild() @Test public void testCreateResponse() { - final MockResponseBuilder> mockResponseBuilder = new MockResponseBuilder>(); - mockResponseBuilder.setEntity(new CreateResponse(1L)); + final MockResponseBuilder> mockResponseBuilder = new MockResponseBuilder<>(); + mockResponseBuilder.setEntity(new CreateResponse<>(1L)); final Response> response = mockResponseBuilder.build(); final CreateResponse createResponse = response.getEntity(); @@ -91,8 +91,8 @@ public void testCreateResponse() @Test public void testIdResponse() { - final MockResponseBuilder> mockResponseBuilder = new MockResponseBuilder>(); - mockResponseBuilder.setEntity(new IdResponse(1L)); + final MockResponseBuilder> mockResponseBuilder = new MockResponseBuilder<>(); + mockResponseBuilder.setEntity(new IdResponse<>(1L)); final Response> response = mockResponseBuilder.build(); final IdResponse idResponse = response.getEntity(); diff --git a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockSuccessfulResponseFutureBuilder.java b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockSuccessfulResponseFutureBuilder.java index 2fd634861b..f02bf5275c 100644 --- a/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockSuccessfulResponseFutureBuilder.java +++ b/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockSuccessfulResponseFutureBuilder.java @@ -38,7 +38,7 @@ public class TestMockSuccessfulResponseFutureBuilder public void testBuild() throws RemoteInvocationException { - MockSuccessfulResponseFutureBuilder builder = new MockSuccessfulResponseFutureBuilder(); + MockSuccessfulResponseFutureBuilder builder = new MockSuccessfulResponseFutureBuilder<>(); Greeting greeting = new Greeting().setId(1L).setMessage("foo"); ResponseFuture future = builder.setEntity(greeting).setStatus(200).build(); @@ -50,8 +50,8 @@ public void testBuild() public void testCreateResponse() throws RemoteInvocationException { - MockSuccessfulResponseFutureBuilder> builder = new MockSuccessfulResponseFutureBuilder>(); - ResponseFuture> future = builder.setEntity(new CreateResponse(1L)).setStatus(HttpStatus.S_200_OK.getCode()).build(); + MockSuccessfulResponseFutureBuilder> builder = new MockSuccessfulResponseFutureBuilder<>(); + ResponseFuture> future = builder.setEntity(new CreateResponse<>(1L)).setStatus(HttpStatus.S_200_OK.getCode()).build(); Assert.assertEquals(future.getResponseEntity().getId().longValue(), 1L); Assert.assertEquals(future.getResponse().getStatus(), 200); @@ -61,8 +61,8 @@ public void testCreateResponse() public void testIdResponse() throws RemoteInvocationException { - MockSuccessfulResponseFutureBuilder> builder = new MockSuccessfulResponseFutureBuilder>(); - ResponseFuture> future = builder.setEntity(new IdResponse(1L)).setStatus(HttpStatus.S_200_OK.getCode()).build(); + MockSuccessfulResponseFutureBuilder> builder = new MockSuccessfulResponseFutureBuilder<>(); + ResponseFuture> future = builder.setEntity(new IdResponse<>(1L)).setStatus(HttpStatus.S_200_OK.getCode()).build(); Assert.assertEquals(future.getResponseEntity().getId().longValue(), 1L); Assert.assertEquals(future.getResponse().getStatus(), 200); diff --git a/restli-client-util-recorder/src/main/java/com/linkedin/restli/client/util/GeneratePatchMethodInterceptor.java b/restli-client-util-recorder/src/main/java/com/linkedin/restli/client/util/GeneratePatchMethodInterceptor.java index d07266f5b9..6fe133d4f5 100644 --- a/restli-client-util-recorder/src/main/java/com/linkedin/restli/client/util/GeneratePatchMethodInterceptor.java +++ b/restli-client-util-recorder/src/main/java/com/linkedin/restli/client/util/GeneratePatchMethodInterceptor.java @@ -43,7 +43,7 @@ final class GeneratePatchMethodInterceptor implements MethodInterceptor { /** Wrapped primitive types supported by {@link com.linkedin.data.DataMap} */ - private final static Set> _primitiveTypes = Collections.unmodifiableSet(new HashSet>(Arrays.>asList( + private final static Set> _primitiveTypes = Collections.unmodifiableSet(new HashSet<>(Arrays.>asList( Integer.TYPE, Integer.class, Long.TYPE, @@ -188,4 +188,4 @@ private void assertPropertyInSchema(String propertyName) _schema); } -} \ No newline at end of file +} diff --git a/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchRequestRecorder.java b/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchRequestRecorder.java index b0ecd72805..d9e7848ff7 100644 --- a/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchRequestRecorder.java +++ b/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchRequestRecorder.java @@ -39,7 +39,7 @@ public void testPatchGenerateAndPatchRequestRecorderGenerateIdenticalPatches() t2.setMessage("Foo Bar Baz"); PatchRequest patchFromGenerator = PatchGenerator.diff(t1, t2); - PatchRequestRecorder patchRecorder = new PatchRequestRecorder(TestRecord.class); + PatchRequestRecorder patchRecorder = new PatchRequestRecorder<>(TestRecord.class); patchRecorder.getRecordingProxy().setId(1L).setMessage("Foo Bar Baz"); PatchRequest patchFromRecorder = patchRecorder.generatePatchRequest(); diff --git a/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchTreeRecorder.java b/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchTreeRecorder.java index 799a3df075..4671d30a79 100644 --- a/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchTreeRecorder.java +++ b/restli-client-util-recorder/src/test/java/com/linkedin/restli/client/util/TestPatchTreeRecorder.java @@ -86,7 +86,7 @@ public void testSetCoerceEnum() @Test public void testSetCoerceTypeRef() { - PatchTreeRecorder pc = new PatchTreeRecorder(CustomPointRecord.class); + PatchTreeRecorder pc = new PatchTreeRecorder<>(CustomPointRecord.class); pc.getRecordingProxy().setCustomPoint(new TestCustom.CustomPoint(1, 2)); Assert.assertEquals(pc.generatePatchTree().getDataMap(), @@ -290,7 +290,7 @@ public void testPatchGeneratesDeepCopiesOfInternalState() private PatchTreeRecorder makeOne() { - return new PatchTreeRecorder(PatchTreeTestModel.class); + return new PatchTreeRecorder<>(PatchTreeTestModel.class); } private DataMap diffEmpty(T recordTemplate) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/AbstractRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/AbstractRequestBuilder.java index 978b035031..4ae567e6fc 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/AbstractRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/AbstractRequestBuilder.java @@ -58,11 +58,11 @@ public abstract class AbstractRequestBuilder> extends protected final ResourceSpec _resourceSpec; - private Map _headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); - private List _cookies = new ArrayList(); - private final Map _queryParams = new HashMap(); - private final Map> _queryParamClasses = new HashMap>(); - private final Map _pathKeys = new HashMap(); + private Map _headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private List _cookies = new ArrayList<>(); + private final Map _queryParams = new HashMap<>(); + private final Map> _queryParamClasses = new HashMap<>(); + private final Map _pathKeys = new HashMap<>(); private final CompoundKey _assocKey = new CompoundKey(); protected AbstractRequestBuilder(String baseUriTemplate, ResourceSpec resourceSpec, RestliRequestOptions requestOptions) @@ -123,7 +123,7 @@ protected String getHeader(String name) */ public AbstractRequestBuilder setHeaders(Map headers) { - _headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + _headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); _headers.putAll(headers); return this; } @@ -160,7 +160,7 @@ public AbstractRequestBuilder setCookies(List cookies) */ public AbstractRequestBuilder clearCookies() { - _cookies = new ArrayList(); + _cookies = new ArrayList<>(); return this; } @@ -244,7 +244,7 @@ public AbstractRequestBuilder addParam(String key, Object value, Class< final Object existingData = _queryParams.get(key); if (existingData == null) { - final Collection newData = new ArrayList(); + final Collection newData = new ArrayList<>(); newData.add(value); setParam(key, newData); } @@ -254,7 +254,7 @@ else if (existingData instanceof Collection) } else if (existingData instanceof Iterable) { - final Collection newData = new ArrayList(); + final Collection newData = new ArrayList<>(); for (Object d : (Iterable) existingData) { newData.add(d); @@ -322,7 +322,7 @@ protected final void addKeys(Collection ids) Set existingIds = (Set) _queryParams.get(RestConstants.QUERY_BATCH_IDS_PARAM); if (existingIds == null) { - existingIds = new HashSet(); + existingIds = new HashSet<>(); _queryParams.put(RestConstants.QUERY_BATCH_IDS_PARAM, existingIds); } for (K id: ids) @@ -403,7 +403,7 @@ static protected Map getReadOnlyQueryParameters(Map readOnlyCopy = new HashMap + Map readOnlyCopy = new HashMap<> (CollectionUtils.getMapInitialCapacity(queryParams.size(), 0.75f), 0.75f); for (Map.Entry entry: queryParams.entrySet()) { @@ -438,7 +438,7 @@ static public Map getReadOnlyPathKeys(Map pathKe { try { - Map readOnlyCopy = new HashMap( + Map readOnlyCopy = new HashMap<>( CollectionUtils.getMapInitialCapacity(pathKeys.size(), 0.75f), 0.75f); for (Map.Entry entry: pathKeys.entrySet()) { @@ -533,7 +533,7 @@ private static Object getReadOnlyJavaObject(Object value) throws CloneNotSupport { // array of non-primitives Object[] arr = (Object[]) value; - List list = new ArrayList(arr.length); + List list = new ArrayList<>(arr.length); for (Object o: arr) { list.add(getReadOnlyJavaObject(o)); @@ -544,7 +544,7 @@ else if (value.getClass().isArray()) { // array of primitives int length = Array.getLength(value); - List list = new ArrayList(); + List list = new ArrayList<>(); for (int i = 0; i < length; i++) { list.add(Array.get(value, i)); @@ -571,7 +571,7 @@ else if (value instanceof Set) } else if (value instanceof Iterable) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (Object o: (Iterable)value) { list.add(getReadOnlyJavaObject(o)); diff --git a/restli-client/src/main/java/com/linkedin/restli/client/ActionRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/ActionRequestBuilder.java index aa97d4ac99..32770e80ee 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/ActionRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/ActionRequestBuilder.java @@ -55,7 +55,7 @@ public class ActionRequestBuilder extends AbstractRequestBuilder _elementClass; private K _id; private String _name; - private final Map, Object> _actionParams = new HashMap, Object>(); + private final Map, Object> _actionParams = new HashMap<>(); private List _streamingAttachments; //We initialize only when we need to. public ActionRequestBuilder(String baseUriTemplate, Class elementClass, ResourceSpec resourceSpec, RestliRequestOptions requestOptions) @@ -207,7 +207,7 @@ public ActionRequest build() } else { - responseFieldDef = new FieldDef(ActionResponse.VALUE_NAME, _elementType.getType(), _elementType.getSchema()); + responseFieldDef = new FieldDef<>(ActionResponse.VALUE_NAME, _elementType.getType(), _elementType.getSchema()); responseFieldDefCollection = Collections.>singleton(responseFieldDef); } actionResponseDataSchema = DynamicRecordMetadata.buildSchema(_name,responseFieldDefCollection); @@ -221,23 +221,23 @@ public ActionRequest build() @SuppressWarnings("unchecked") ActionResponseDecoder actionResponseDecoder = - new ActionResponseDecoder(responseFieldDef, actionResponseDataSchema); + new ActionResponseDecoder<>(responseFieldDef, actionResponseDataSchema); DynamicRecordTemplate inputParameters = new DynamicRecordTemplate(requestDataSchema, buildReadOnlyActionParameters()); inputParameters.data().setReadOnly(); - return new ActionRequest(inputParameters, - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - actionResponseDecoder, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _name, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyId(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + return new ActionRequest<>(inputParameters, + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + actionResponseDecoder, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _name, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyId(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } @@ -250,7 +250,7 @@ private static Map, Object> buildReadOnlyActionParameters(Map, Object> readOnlyParameters = new HashMap, Object>(actionParams.size()); + Map, Object> readOnlyParameters = new HashMap<>(actionParams.size()); for (Map.Entry, Object> originalParameterEntry : actionParams.entrySet()) { diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdEntityRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdEntityRequestBuilder.java index 2f3939af1a..be35c99726 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdEntityRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdEntityRequestBuilder.java @@ -41,7 +41,7 @@ public class BatchCreateIdEntityRequestBuilder extends RestfulRequestBuilder> implements ReturnEntityRequestBuilder { - private final List _entities = new ArrayList(); + private final List _entities = new ArrayList<>(); private final Class _valueClass; private List _streamingAttachments; //We initialize only when we need to. @@ -161,22 +161,22 @@ public BatchCreateIdEntityRequestBuilder returnEntity(boolean value) public BatchCreateIdEntityRequest build() { @SuppressWarnings("unchecked") - BatchCreateIdEntityDecoder decoder = new BatchCreateIdEntityDecoder((TypeSpec)_resourceSpec.getKeyType(), - (TypeSpec)_resourceSpec.getValueType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - - return new BatchCreateIdEntityRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - decoder, - buildReadOnlyInput(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + BatchCreateIdEntityDecoder decoder = new BatchCreateIdEntityDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + (TypeSpec) _resourceSpec.getValueType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + + return new BatchCreateIdEntityRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + decoder, + buildReadOnlyInput(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } private CollectionRequest buildReadOnlyInput() @@ -184,7 +184,7 @@ private CollectionRequest buildReadOnlyInput() try { DataMap map = new DataMap(); - CollectionRequest input = new CollectionRequest(map, _valueClass); + CollectionRequest input = new CollectionRequest<>(map, _valueClass); for (V entity : _entities) { @@ -199,4 +199,4 @@ private CollectionRequest buildReadOnlyInput() throw new IllegalArgumentException("Entity cannot be copied.", cloneException); } } -} \ No newline at end of file +} diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdRequestBuilder.java index f617d1c33f..66ea861de8 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateIdRequestBuilder.java @@ -39,7 +39,7 @@ */ public class BatchCreateIdRequestBuilder extends RestfulRequestBuilder> { - private final List _entities = new ArrayList(); + private final List _entities = new ArrayList<>(); private final Class _valueClass; private List _streamingAttachments; //We initialize only when we need to. @@ -146,21 +146,21 @@ public BatchCreateIdRequestBuilder pathKey(String name, Object value) public BatchCreateIdRequest build() { @SuppressWarnings("unchecked") - BatchCreateIdDecoder decoder = new BatchCreateIdDecoder((TypeSpec)_resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - - return new BatchCreateIdRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - decoder, - buildReadOnlyInput(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + BatchCreateIdDecoder decoder = new BatchCreateIdDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + + return new BatchCreateIdRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + decoder, + buildReadOnlyInput(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } private CollectionRequest buildReadOnlyInput() @@ -168,7 +168,7 @@ private CollectionRequest buildReadOnlyInput() try { DataMap map = new DataMap(); - CollectionRequest input = new CollectionRequest(map, _valueClass); + CollectionRequest input = new CollectionRequest<>(map, _valueClass); for (V entity : _entities) { diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateRequestBuilder.java index d3d23c4ada..0a4cd75903 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchCreateRequestBuilder.java @@ -44,7 +44,7 @@ public class BatchCreateRequestBuilder extends RestfulRequestBuilder> { - private final List _entities = new ArrayList(); + private final List _entities = new ArrayList<>(); private final Class _valueClass; private List _streamingAttachments; //We initialize only when we need to. @@ -151,21 +151,21 @@ public BatchCreateRequestBuilder pathKey(String name, Object value) public BatchCreateRequest build() { @SuppressWarnings("unchecked") - BatchCreateDecoder decoder = new BatchCreateDecoder((TypeSpec)_resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - - return new BatchCreateRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - decoder, - buildReadOnlyInput(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + BatchCreateDecoder decoder = new BatchCreateDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + + return new BatchCreateRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + decoder, + buildReadOnlyInput(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } private CollectionRequest buildReadOnlyInput() @@ -173,7 +173,7 @@ private CollectionRequest buildReadOnlyInput() try { DataMap map = new DataMap(); - CollectionRequest input = new CollectionRequest(map, _valueClass); + CollectionRequest input = new CollectionRequest<>(map, _valueClass); for (V entity : _entities) { diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequest.java index a0864a5a27..6a2cb03d1f 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequest.java @@ -55,9 +55,9 @@ public BatchDeleteRequest(Map headers, null, headers, cookies, - new BatchUpdateResponseDecoder((TypeSpec) resourceSpec.getKeyType(), - resourceSpec.getKeyParts(), - resourceSpec.getComplexKeyType()), + new BatchUpdateResponseDecoder<>((TypeSpec) resourceSpec.getKeyType(), + resourceSpec.getKeyParts(), + resourceSpec.getComplexKeyType()), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequestBuilder.java index c6623e52e5..0f61c0ed60 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchDeleteRequestBuilder.java @@ -117,13 +117,13 @@ public BatchDeleteRequest build() { ensureBatchKeys(); - return new BatchDeleteRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions()); + return new BatchDeleteRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions()); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequest.java index 62d265f363..c5b4c256f3 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequest.java @@ -60,7 +60,7 @@ public BatchFindRequest(Map headers, null, headers, cookies, - new BatchCollectionResponseDecoder(templateClass), + new BatchCollectionResponseDecoder<>(templateClass), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequestBuilder.java index fa8d12a0c8..b9c7128c82 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchFindRequestBuilder.java @@ -154,16 +154,16 @@ public BatchFindRequestBuilder pathKey(String name, Object value) @Override public BatchFindRequest build() { - return new BatchFindRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _elementClass, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _name, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyAssocKey()); + return new BatchFindRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _elementClass, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _name, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyAssocKey()); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetEntityRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetEntityRequestBuilder.java index 9610a5a4c6..6f81374138 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetEntityRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetEntityRequestBuilder.java @@ -101,15 +101,15 @@ public static BatchGetEntityRequest batch(Li final Map batchQueryParams = getReadOnlyQueryParameters(BatchGetRequestUtil.getBatchQueryParam(requests, batchFields)); - return new BatchGetEntityRequest(firstRequest.getHeaders(), - firstRequest.getCookies(), - firstRequest.getResponseDecoder(), - batchQueryParams, - firstRequest.getQueryParamClasses(), - firstResourceSpec, - firstRequest.getBaseUriTemplate(), - firstRequest.getPathKeys(), - firstRequest.getRequestOptions()); + return new BatchGetEntityRequest<>(firstRequest.getHeaders(), + firstRequest.getCookies(), + firstRequest.getResponseDecoder(), + batchQueryParams, + firstRequest.getQueryParamClasses(), + firstResourceSpec, + firstRequest.getBaseUriTemplate(), + firstRequest.getPathKeys(), + firstRequest.getRequestOptions()); } public BatchGetEntityRequestBuilder(String baseUriTemplate, @@ -127,11 +127,11 @@ public BatchGetEntityRequestBuilder(String baseUriTemplate, RestliRequestOptions requestOptions) { this(baseUriTemplate, - new BatchEntityResponseDecoder( - (TypeSpec) resourceSpec.getValueType(), - (TypeSpec) resourceSpec.getKeyType(), - resourceSpec.getKeyParts(), - resourceSpec.getComplexKeyType()), + new BatchEntityResponseDecoder<>( + (TypeSpec) resourceSpec.getValueType(), + (TypeSpec) resourceSpec.getKeyType(), + resourceSpec.getKeyParts(), + resourceSpec.getComplexKeyType()), resourceSpec, requestOptions); } @@ -214,15 +214,15 @@ public BatchGetEntityRequest build() { ensureBatchKeys(); - return new BatchGetEntityRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _decoder, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions()); + return new BatchGetEntityRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _decoder, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions()); } public BatchGetEntityRequestBuilder fields(PathSpec... fieldPaths) @@ -230,4 +230,4 @@ public BatchGetEntityRequestBuilder fields(PathSpec... fieldPaths) addFields(fieldPaths); return this; } -} \ No newline at end of file +} diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestBuilder.java index 48589be398..71d804799a 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestBuilder.java @@ -113,15 +113,15 @@ public static BatchGetRequest batch(List batchQueryParams = getReadOnlyQueryParameters(BatchGetRequestUtil.getBatchQueryParam(requests, batchFields)); - return new BatchGetRequest(getReadOnlyHeaders(firstRequest.getHeaders()), - getReadOnlyCookies(firstRequest.getCookies()), - firstRequest.getResponseDecoder(), - batchQueryParams, - firstRequest.getQueryParamClasses(), - firstResourceSpec, - firstRequest.getBaseUriTemplate(), - getReadOnlyPathKeys(firstRequest.getPathKeys()), - firstRequest.getRequestOptions()); + return new BatchGetRequest<>(getReadOnlyHeaders(firstRequest.getHeaders()), + getReadOnlyCookies(firstRequest.getCookies()), + firstRequest.getResponseDecoder(), + batchQueryParams, + firstRequest.getQueryParamClasses(), + firstResourceSpec, + firstRequest.getBaseUriTemplate(), + getReadOnlyPathKeys(firstRequest.getPathKeys()), + firstRequest.getRequestOptions()); } /** @@ -182,16 +182,16 @@ public static BatchGetKVRequest batchKV(Li final Map batchQueryParams = getReadOnlyQueryParameters(BatchGetRequestUtil.getBatchQueryParam(requests, batchFields)); - return new BatchGetKVRequest( - getReadOnlyHeaders(firstRequest.getHeaders()), - getReadOnlyCookies(firstRequest.getCookies()), - firstRequest.getResponseDecoder(), - batchQueryParams, - Collections.>emptyMap(), - firstResourceSpec, - firstRequest.getBaseUriTemplate(), - getReadOnlyPathKeys(firstRequest.getPathKeys()), - firstRequest.getRequestOptions()); + return new BatchGetKVRequest<>( + getReadOnlyHeaders(firstRequest.getHeaders()), + getReadOnlyCookies(firstRequest.getCookies()), + firstRequest.getResponseDecoder(), + batchQueryParams, + Collections.>emptyMap(), + firstResourceSpec, + firstRequest.getBaseUriTemplate(), + getReadOnlyPathKeys(firstRequest.getPathKeys()), + firstRequest.getRequestOptions()); } /** @@ -211,36 +211,36 @@ public static BatchGetKVRequest batchKV(Ge "It is not possible to create a batch get request from a get request without an id."); } - Map queryParams = new HashMap(request.getQueryParamsObjects()); + Map queryParams = new HashMap<>(request.getQueryParamsObjects()); queryParams.put(RestConstants.QUERY_BATCH_IDS_PARAM, new HashSet<>(Arrays.asList(id))); - return new BatchGetKVRequest(getReadOnlyHeaders(request.getHeaders()), - getReadOnlyCookies(request.getCookies()), - new BatchKVResponseDecoder( - request.getEntityClass(), - (Class)request.getResourceProperties().getKeyType().getType(), - request.getResourceProperties().getKeyParts(), - request.getResourceProperties().getComplexKeyType() == null ? - null : - request. - getResourceProperties(). - getComplexKeyType(). - getKeyType(). - getType(), - request.getResourceProperties().getComplexKeyType() == null ? - null : - request. - getResourceProperties(). - getComplexKeyType(). - getParamsType(). - getType()), - getReadOnlyQueryParameters(queryParams), - request.getQueryParamClasses(), - request.getResourceSpec(), - request.getBaseUriTemplate(), - getReadOnlyPathKeys(request.getPathKeys()), - request.getRequestOptions()); + return new BatchGetKVRequest<>(getReadOnlyHeaders(request.getHeaders()), + getReadOnlyCookies(request.getCookies()), + new BatchKVResponseDecoder<>( + request.getEntityClass(), + (Class) request.getResourceProperties().getKeyType().getType(), + request.getResourceProperties().getKeyParts(), + request.getResourceProperties().getComplexKeyType() == null ? + null : + request. + getResourceProperties(). + getComplexKeyType(). + getKeyType(). + getType(), + request.getResourceProperties().getComplexKeyType() == null ? + null : + request. + getResourceProperties(). + getComplexKeyType(). + getParamsType(). + getType()), + getReadOnlyQueryParameters(queryParams), + request.getQueryParamClasses(), + request.getResourceSpec(), + request.getBaseUriTemplate(), + getReadOnlyPathKeys(request.getPathKeys()), + request.getRequestOptions()); } /** @@ -264,19 +264,19 @@ public static BatchGetRequest batch(GetRequest queryParams = new HashMap(request.getQueryParamsObjects()); + Map queryParams = new HashMap<>(request.getQueryParamsObjects()); queryParams.put(RestConstants.QUERY_BATCH_IDS_PARAM, new HashSet<>(Arrays.asList(id))); - return new BatchGetRequest(getReadOnlyHeaders(request.getHeaders()), - getReadOnlyCookies(request.getCookies()), - new BatchResponseDecoder(request.getEntityClass()), - getReadOnlyQueryParameters(queryParams), - Collections.>emptyMap(), - request.getResourceSpec(), - request.getBaseUriTemplate(), - getReadOnlyPathKeys(request.getPathKeys()), - request.getRequestOptions()); + return new BatchGetRequest<>(getReadOnlyHeaders(request.getHeaders()), + getReadOnlyCookies(request.getCookies()), + new BatchResponseDecoder<>(request.getEntityClass()), + getReadOnlyQueryParameters(queryParams), + Collections.>emptyMap(), + request.getResourceSpec(), + request.getBaseUriTemplate(), + getReadOnlyPathKeys(request.getPathKeys()), + request.getRequestOptions()); } public BatchGetRequestBuilder(String baseUriTemplate, @@ -284,7 +284,7 @@ public BatchGetRequestBuilder(String baseUriTemplate, ResourceSpec resourceSpec, RestliRequestOptions requestOptions) { - this(baseUriTemplate, new BatchResponseDecoder(modelClass), resourceSpec, requestOptions); + this(baseUriTemplate, new BatchResponseDecoder<>(modelClass), resourceSpec, requestOptions); } public BatchGetRequestBuilder(String baseUriTemplate, @@ -378,15 +378,15 @@ public BatchGetRequest build() throwIfClassCompoundOrComplex(keyClass, "build", "buildKV"); - return new BatchGetRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _decoder, - buildReadOnlyQueryParameters(), - Collections.>emptyMap(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions()); + return new BatchGetRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _decoder, + buildReadOnlyQueryParameters(), + Collections.>emptyMap(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions()); } public BatchGetKVRequest buildKV() @@ -396,20 +396,20 @@ public BatchGetKVRequest buildKV() //Framework code should ensure that the ResourceSpec matches the static types of these parameters @SuppressWarnings("unchecked") BatchKVResponseDecoder decoder = - new BatchKVResponseDecoder((TypeSpec) _resourceSpec.getValueType(), - (TypeSpec) _resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - - return new BatchGetKVRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - decoder, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions()); + new BatchKVResponseDecoder<>((TypeSpec) _resourceSpec.getValueType(), + (TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + + return new BatchGetKVRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + decoder, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions()); } public BatchGetRequestBuilder fields(PathSpec... fieldPaths) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestUtil.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestUtil.java index 53d77c64c2..ba1c1e4206 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestUtil.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchGetRequestUtil.java @@ -47,11 +47,11 @@ public static Map getBatchQueryParam( } final BatchRequest firstRequest = requests.get(0); - final BatchingKey> batchKey = new BatchingKey>(firstRequest, batchFields); - final Set ids = new HashSet(); + final BatchingKey> batchKey = new BatchingKey<>(firstRequest, batchFields); + final Set ids = new HashSet<>(); // Default to no fields or to first request's fields, depending on batchFields flag - Set fields = batchFields ? new HashSet() : firstRequest.getFields(); + Set fields = batchFields ? new HashSet<>() : firstRequest.getFields(); for (BatchRequest request : requests) { @@ -101,7 +101,7 @@ else if (fields != null) */ public static Map getQueryParamsForBatchingKey(BatchRequest request) { - final Map params = new HashMap(request.getQueryParamsObjects()); + final Map params = new HashMap<>(request.getQueryParamsObjects()); params.remove(RestConstants.QUERY_BATCH_IDS_PARAM); params.remove(RestConstants.FIELDS_PARAM); return params; @@ -132,7 +132,7 @@ public static Response unbatchKVResponse(Reques ". Verify that the batchGet endpoint returns response keys that match batchGet request IDs.", null); } - return new ResponseImpl(batchResponse, entityResult); + return new ResponseImpl<>(batchResponse, entityResult); } /** @@ -160,6 +160,6 @@ public static Response unbatchResponse(Request(batchResponse, entityResult); + return new ResponseImpl<>(batchResponse, entityResult); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchPartialUpdateRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchPartialUpdateRequest.java index 657b8e1e30..c20a20629d 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchPartialUpdateRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchPartialUpdateRequest.java @@ -65,9 +65,9 @@ public BatchPartialUpdateRequest(Map headers, entities, headers, cookies, - new BatchUpdateResponseDecoder((TypeSpec) resourceSpec.getKeyType(), - resourceSpec.getKeyParts(), - resourceSpec.getComplexKeyType()), + new BatchUpdateResponseDecoder<>((TypeSpec) resourceSpec.getKeyType(), + resourceSpec.getKeyParts(), + resourceSpec.getComplexKeyType()), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchRequest.java index 6257165267..12f8878dfb 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchRequest.java @@ -69,6 +69,6 @@ public Set getObjectIds() { return Collections.emptySet(); } - return new HashSet(ids); + return new HashSet<>(ids); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequest.java index 57b3798747..269f01a0db 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequest.java @@ -63,9 +63,9 @@ public BatchUpdateRequest(Map headers, entities, headers, cookies, - new BatchUpdateResponseDecoder((TypeSpec) resourceSpec.getKeyType(), - resourceSpec.getKeyParts(), - resourceSpec.getComplexKeyType()), + new BatchUpdateResponseDecoder<>((TypeSpec) resourceSpec.getKeyType(), + resourceSpec.getKeyParts(), + resourceSpec.getComplexKeyType()), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequestBuilder.java index b389a3216c..b280093ce6 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/BatchUpdateRequestBuilder.java @@ -61,7 +61,7 @@ public BatchUpdateRequestBuilder(String baseUriTemplate, _resourceSpec.getComplexKeyType(), _resourceSpec.getKeyParts(), _resourceSpec.getValueType()); - _updateInputMap = new HashMap(); + _updateInputMap = new HashMap<>(); } public BatchUpdateRequestBuilder input(K id, V entity) @@ -165,21 +165,21 @@ public BatchUpdateRequestBuilder pathKey(String name, Object value) public BatchUpdateRequest build() { ensureBatchKeys(); - Map readOnlyUpdateInputMap = new HashMap( + Map readOnlyUpdateInputMap = new HashMap<>( CollectionUtils.getMapInitialCapacity(_updateInputMap.size(), 0.75f), 0.75f); CollectionRequest> readOnlyInput = buildReadOnlyBatchUpdateInput(readOnlyUpdateInputMap); - return new BatchUpdateRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - readOnlyInput, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - Collections.unmodifiableMap(readOnlyUpdateInputMap), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + return new BatchUpdateRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + readOnlyInput, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + Collections.unmodifiableMap(readOnlyUpdateInputMap), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } private CollectionRequest> buildReadOnlyBatchUpdateInput(Map readOnlyInputEntities) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/CreateIdEntityRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/CreateIdEntityRequestBuilder.java index 1692dee344..63b34da43d 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/CreateIdEntityRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/CreateIdEntityRequestBuilder.java @@ -149,20 +149,20 @@ public CreateIdEntityRequestBuilder returnEntity(boolean value) public CreateIdEntityRequest build() { @SuppressWarnings("unchecked") - IdEntityResponseDecoder idEntityResponseDecoder = new IdEntityResponseDecoder((TypeSpec)_resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType(), - getValueClass()); - return new CreateIdEntityRequest(buildReadOnlyInput(), - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - idEntityResponseDecoder, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + IdEntityResponseDecoder idEntityResponseDecoder = new IdEntityResponseDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType(), + getValueClass()); + return new CreateIdEntityRequest<>(buildReadOnlyInput(), + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + idEntityResponseDecoder, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/CreateIdRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/CreateIdRequestBuilder.java index b83844a952..aacd5e4932 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/CreateIdRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/CreateIdRequestBuilder.java @@ -136,19 +136,19 @@ public CreateIdRequestBuilder pathKey(String name, Object value) public CreateIdRequest build() { @SuppressWarnings("unchecked") - IdResponseDecoder idResponseDecoder = new IdResponseDecoder((TypeSpec)_resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - return new CreateIdRequest(buildReadOnlyInput(), - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - idResponseDecoder, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + IdResponseDecoder idResponseDecoder = new IdResponseDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + return new CreateIdRequest<>(buildReadOnlyInput(), + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + idResponseDecoder, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/CreateRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/CreateRequestBuilder.java index 495ed22b13..3dd5b11927 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/CreateRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/CreateRequestBuilder.java @@ -142,19 +142,19 @@ public CreateRequestBuilder pathKey(String name, Object value) public CreateRequest build() { @SuppressWarnings("unchecked") - CreateResponseDecoder createResponseDecoder = new CreateResponseDecoder((TypeSpec)_resourceSpec.getKeyType(), - _resourceSpec.getKeyParts(), - _resourceSpec.getComplexKeyType()); - return new CreateRequest(buildReadOnlyInput(), - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - createResponseDecoder, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + CreateResponseDecoder createResponseDecoder = new CreateResponseDecoder<>((TypeSpec) _resourceSpec.getKeyType(), + _resourceSpec.getKeyParts(), + _resourceSpec.getComplexKeyType()); + return new CreateRequest<>(buildReadOnlyInput(), + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + createResponseDecoder, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/DefaultScatterGatherStrategy.java b/restli-client/src/main/java/com/linkedin/restli/client/DefaultScatterGatherStrategy.java index 0c908fb941..623546d271 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/DefaultScatterGatherStrategy.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/DefaultScatterGatherStrategy.java @@ -551,7 +551,7 @@ else if (request instanceof BatchGetKVRequest) { return (T) new BatchKVResponse(mergedData, request.getResourceSpec().getKeyType(), - new TypeSpec(UpdateStatus.class), request.getResourceSpec().getKeyParts(), + new TypeSpec<>(UpdateStatus.class), request.getResourceSpec().getKeyParts(), request.getResourceSpec().getComplexKeyType(), protocolVersion); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/DeleteRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/DeleteRequestBuilder.java index ba2c505c99..0c4e39631b 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/DeleteRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/DeleteRequestBuilder.java @@ -108,14 +108,14 @@ public DeleteRequestBuilder pathKey(String name, Object value) @Override public DeleteRequest build() { - return new DeleteRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyId()); + return new DeleteRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyId()); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/ExecutionGroup.java b/restli-client/src/main/java/com/linkedin/restli/client/ExecutionGroup.java index cbbac99503..ea6f4c657c 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/ExecutionGroup.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/ExecutionGroup.java @@ -146,7 +146,7 @@ public void execute() public void batchOn(Runnable runnable, ParSeqBasedFluentClient... fluentClients) throws Exception { List batchedClients = - fluentClients.length > 0 ? new ArrayList(Arrays.asList(fluentClients)) + fluentClients.length > 0 ? new ArrayList<>(Arrays.asList(fluentClients)) : _fluentClientAll; for (ParSeqBasedFluentClient fluentClient : batchedClients) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/FindRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/FindRequest.java index ff31895eed..8f25c5e778 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/FindRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/FindRequest.java @@ -59,7 +59,7 @@ public FindRequest(Map headers, null, headers, cookies, - new CollectionResponseDecoder(templateClass), + new CollectionResponseDecoder<>(templateClass), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/FindRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/FindRequestBuilder.java index e063c1547c..cda8e99c64 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/FindRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/FindRequestBuilder.java @@ -156,16 +156,16 @@ public FindRequestBuilder pathKey(String name, Object value) @Override public FindRequest build() { - return new FindRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _elementClass, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _name, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyAssocKey()); + return new FindRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _elementClass, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _name, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyAssocKey()); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequest.java index 878380ec2e..cc43a350f9 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequest.java @@ -51,7 +51,7 @@ public GetAllRequest(Map headers, null, headers, cookies, - new CollectionResponseDecoder(templateClass), + new CollectionResponseDecoder<>(templateClass), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequestBuilder.java index 6e7032a55d..a2278bc142 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/GetAllRequestBuilder.java @@ -141,15 +141,15 @@ public GetAllRequestBuilder pathKey(String name, Object value) @Override public GetAllRequest build() { - return new GetAllRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _elementClass, - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyAssocKey()); + return new GetAllRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _elementClass, + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyAssocKey()); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/GetRequest.java b/restli-client/src/main/java/com/linkedin/restli/client/GetRequest.java index b4b93fd728..1559c2cffe 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/GetRequest.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/GetRequest.java @@ -55,7 +55,7 @@ public GetRequest(Map headers, null, headers, cookies, - new EntityResponseDecoder(templateClass), + new EntityResponseDecoder<>(templateClass), resourceSpec, queryParams, queryParamClasses, diff --git a/restli-client/src/main/java/com/linkedin/restli/client/GetRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/GetRequestBuilder.java index d4a725c4ce..d5bd88378f 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/GetRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/GetRequestBuilder.java @@ -111,16 +111,16 @@ public GetRequestBuilder pathKey(String name, Object value) @Override public GetRequest build() { - return new GetRequest(buildReadOnlyHeaders(), - buildReadOnlyCookies(), - getValueClass(), - buildReadOnlyId(), - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - _resourceSpec, - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions()); + return new GetRequest<>(buildReadOnlyHeaders(), + buildReadOnlyCookies(), + getValueClass(), + buildReadOnlyId(), + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + _resourceSpec, + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions()); } public GetRequestBuilder fields(PathSpec... fieldPaths) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStage.java b/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStage.java index 60496e6555..c2f21c1bf9 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStage.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStage.java @@ -132,7 +132,7 @@ static Task wrapException(Task task) private ParSeqBasedCompletionStage nextStageByComposingTask(Task composedTask) { - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, ensureFuture(wrapException(composedTask))); + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ensureFuture(wrapException(composedTask))); } @Override diff --git a/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStageFactory.java b/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStageFactory.java index e7d5b86c45..e4aba71093 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStageFactory.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/ParSeqBasedCompletionStageFactory.java @@ -66,7 +66,7 @@ private void checkEngine() public ParSeqBasedCompletionStage buildStageFromTask(Task task) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor,task); + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, task); } /** @@ -88,7 +88,7 @@ public ParSeqBasedCompletionStage buildStageFromTaskToRun(Task task) { checkEngine(); ParSeqBasedCompletionStage.ensureFutureByEngine(task, _engine); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor,task); + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, task); } /** @@ -128,18 +128,18 @@ public ParSeqBasedCompletionStage buildStageFromThrowable(Throwable t) public ParSeqBasedCompletionStage buildStageFromFuture(Future future, Executor executor) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, - ParSeqBasedCompletionStage.ensureFutureByEngine(Task.async("Create from Future", () -> { - final SettablePromise promise = Promises.settable(); - executor.execute(() -> { - try { - promise.done(future.get()); - } catch (Throwable t) { - promise.fail(t); - } - }); - return promise; - }), _engine)); + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, + ParSeqBasedCompletionStage.ensureFutureByEngine(Task.async("Create from Future", () -> { + final SettablePromise promise = Promises.settable(); + executor.execute(() -> { + try { + promise.done(future.get()); + } catch (Throwable t) { + promise.fail(t); + } + }); + return promise; + }), _engine)); } /** @@ -151,10 +151,10 @@ public ParSeqBasedCompletionStage buildStageFromFuture(Future future, Exec public ParSeqBasedCompletionStage buildStageFromCompletionStage(CompletionStage stage) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ParSeqBasedCompletionStage.ensureFutureByEngine( ParSeqBasedCompletionStage.wrapException( - Task.fromCompletionStage("Create from CompletionStage:", () ->stage) + Task.fromCompletionStage("Create from CompletionStage:", () -> stage) ), _engine) ); } @@ -171,7 +171,7 @@ public ParSeqBasedCompletionStage buildStageFromCompletionStage(CompletionSta public ParSeqBasedCompletionStage buildStageFromRunnableAsync(Runnable runnable) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ParSeqBasedCompletionStage.ensureFutureByEngine(Task.callable(() -> { runnable.run(); return null; @@ -191,7 +191,7 @@ public ParSeqBasedCompletionStage buildStageFromRunnableAsync(Runnable run public ParSeqBasedCompletionStage buildStageFromRunnableAsync(Runnable runnable, Executor executor) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ParSeqBasedCompletionStage.ensureFutureByEngine(Task.blocking(() -> { runnable.run(); return null; @@ -210,14 +210,14 @@ public ParSeqBasedCompletionStage buildStageFromRunnableAsync(Runnable run public ParSeqBasedCompletionStage buildStageFromSupplierAsync(Supplier supplier) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ParSeqBasedCompletionStage.ensureFutureByEngine(Task.callable(supplier::get), _engine)); } public ParSeqBasedCompletionStage buildStageFromSupplierAsync(Supplier supplier, Executor executor) { checkEngine(); - return new ParSeqBasedCompletionStage(_engine, _asyncExecutor, + return new ParSeqBasedCompletionStage<>(_engine, _asyncExecutor, ParSeqBasedCompletionStage.ensureFutureByEngine(Task.blocking(supplier::get, executor), _engine)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/PartialUpdateRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/PartialUpdateRequestBuilder.java index ab5b4d7d0d..6501332379 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/PartialUpdateRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/PartialUpdateRequestBuilder.java @@ -145,16 +145,16 @@ public PartialUpdateRequestBuilder pathKey(String name, Object value) @Override public PartialUpdateRequest build() { - return new PartialUpdateRequest(buildReadOnlyInput(), - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyId(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + return new PartialUpdateRequest<>(buildReadOnlyInput(), + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyId(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/RestClient.java b/restli-client/src/main/java/com/linkedin/restli/client/RestClient.java index fafb097e98..0a1756af46 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/RestClient.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/RestClient.java @@ -242,16 +242,16 @@ public ResponseFuture sendRequest(Request request, RequestContext requ { FutureCallback> callback = new FutureCallback<>(); sendRequest(request, requestContext, callback); - return new ResponseFutureImpl(callback); + return new ResponseFutureImpl<>(callback); } @Override public ResponseFuture sendRequest(Request request, RequestContext requestContext, ErrorHandlingBehavior errorHandlingBehavior) { - FutureCallback> callback = new FutureCallback>(); + FutureCallback> callback = new FutureCallback<>(); sendRequest(request, requestContext, callback); - return new ResponseFutureImpl(callback, errorHandlingBehavior); + return new ResponseFutureImpl<>(callback, errorHandlingBehavior); } @Override diff --git a/restli-client/src/main/java/com/linkedin/restli/client/UpdateRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/UpdateRequestBuilder.java index 83827c68bd..6525a7bd15 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/UpdateRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/UpdateRequestBuilder.java @@ -136,16 +136,16 @@ public UpdateRequestBuilder pathKey(String name, Object value) @Override public UpdateRequest build() { - return new UpdateRequest(buildReadOnlyInput(), - buildReadOnlyHeaders(), - buildReadOnlyCookies(), - _resourceSpec, - buildReadOnlyQueryParameters(), - getQueryParamClasses(), - getBaseUriTemplate(), - buildReadOnlyPathKeys(), - getRequestOptions(), - buildReadOnlyId(), - _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); + return new UpdateRequest<>(buildReadOnlyInput(), + buildReadOnlyHeaders(), + buildReadOnlyCookies(), + _resourceSpec, + buildReadOnlyQueryParameters(), + getQueryParamClasses(), + getBaseUriTemplate(), + buildReadOnlyPathKeys(), + getRequestOptions(), + buildReadOnlyId(), + _streamingAttachments == null ? null : Collections.unmodifiableList(_streamingAttachments)); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/base/BatchGetRequestBuilderBase.java b/restli-client/src/main/java/com/linkedin/restli/client/base/BatchGetRequestBuilderBase.java index 69e138322e..be79a77b9d 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/base/BatchGetRequestBuilderBase.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/base/BatchGetRequestBuilderBase.java @@ -47,7 +47,7 @@ protected BatchGetRequestBuilderBase(String baseUriTemplate, ResourceSpec resourceSpec, RestliRequestOptions requestOptions) { - super(baseUriTemplate, new BatchResponseDecoder(modelClass), resourceSpec, requestOptions); + super(baseUriTemplate, new BatchResponseDecoder<>(modelClass), resourceSpec, requestOptions); } @SuppressWarnings({"unchecked"}) diff --git a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedCallback.java b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedCallback.java index 0b9582965b..f6adcbf485 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedCallback.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedCallback.java @@ -48,7 +48,7 @@ */ public class MultiplexedCallback implements Callback { - private final EntityResponseDecoder _decoder = new EntityResponseDecoder(MultiplexedResponseContent.class); + private final EntityResponseDecoder _decoder = new EntityResponseDecoder<>(MultiplexedResponseContent.class); private final Map> _callbacks; private final Callback _aggregatedCallback; @@ -149,4 +149,4 @@ private void notifyAggregatedCallback(Response respo MultiplexedResponse muxResponse = new MultiplexedResponse(response.getStatus(), response.getHeaders()); _aggregatedCallback.onSuccess(muxResponse); } -} \ No newline at end of file +} diff --git a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedRequestBuilder.java b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedRequestBuilder.java index bd52fa89ed..a58e64ebe5 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedRequestBuilder.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedRequestBuilder.java @@ -53,7 +53,7 @@ */ public class MultiplexedRequestBuilder { - private final List> _requestsWithCallbacks = new ArrayList>(); + private final List> _requestsWithCallbacks = new ArrayList<>(); private final boolean _isParallel; private RestliRequestOptions _requestOptions = RestliRequestOptions.DEFAULT_MULTIPLEXER_OPTIONS; /** @@ -95,7 +95,7 @@ private MultiplexedRequestBuilder(boolean isParallel) */ public MultiplexedRequestBuilder addRequest(Request request, Callback> callback) { - _requestsWithCallbacks.add(new RequestWithCallback(request, callback)); + _requestsWithCallbacks.add(new RequestWithCallback<>(request, callback)); return this; } @@ -135,7 +135,7 @@ public MultiplexedRequest build() throws RestLiEncodingException private MultiplexedRequest buildParallel() throws RestLiEncodingException { - Map> callbacks = new HashMap>(_requestsWithCallbacks.size()); + Map> callbacks = new HashMap<>(_requestsWithCallbacks.size()); IndividualRequestMap individualRequests = new IndividualRequestMap(_requestsWithCallbacks.size()); // Dependent requests map is always empty IndividualRequestMap dependentRequests = new IndividualRequestMap(); @@ -151,7 +151,7 @@ private MultiplexedRequest buildParallel() throws RestLiEncodingException private MultiplexedRequest buildSequential() throws RestLiEncodingException { - Map> callbacks = new HashMap>(_requestsWithCallbacks.size()); + Map> callbacks = new HashMap<>(_requestsWithCallbacks.size()); // Dependent requests - requests which are dependent on the current request (executed after the current request) IndividualRequestMap dependentRequests = new IndividualRequestMap(); // We start with the last request in the list and proceed backwards because sequential ordering is built using reverse dependencies diff --git a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedResponse.java b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedResponse.java index 97d68cac93..ca4ee732aa 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedResponse.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/multiplexer/MultiplexedResponse.java @@ -36,7 +36,7 @@ public MultiplexedResponse(int status, Map headers) { _status = status; // see com.linkedin.restli.internal.client.ResponseImpl.ResponseImpl() - TreeMap headersTreeMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + TreeMap headersTreeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); headersTreeMap.putAll(headers); _headers = Collections.unmodifiableSortedMap(headersTreeMap); } diff --git a/restli-client/src/main/java/com/linkedin/restli/client/response/BatchKVResponse.java b/restli-client/src/main/java/com/linkedin/restli/client/response/BatchKVResponse.java index b75facda93..0960b0f581 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/response/BatchKVResponse.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/response/BatchKVResponse.java @@ -233,11 +233,11 @@ protected void deserializeData(DataMap data, TypeSpec keyType, final DataMap resultsRaw = data.getDataMap(RESULTS); if (resultsRaw == null) { - _results = new ParamlessKeyHashMap(complexKeyType); + _results = new ParamlessKeyHashMap<>(complexKeyType); } else { - _results = new ParamlessKeyHashMap( + _results = new ParamlessKeyHashMap<>( CollectionUtils.getMapInitialCapacity(resultsRaw.size(), 0.75f), 0.75f, complexKeyType); for (Map.Entry entry : resultsRaw.entrySet()) { @@ -251,11 +251,11 @@ protected void deserializeData(DataMap data, TypeSpec keyType, final DataMap errorsRaw = data.getDataMap(ERRORS); if (errorsRaw == null) { - _errors = new ParamlessKeyHashMap(complexKeyType); + _errors = new ParamlessKeyHashMap<>(complexKeyType); } else { - _errors = new ParamlessKeyHashMap( + _errors = new ParamlessKeyHashMap<>( CollectionUtils.getMapInitialCapacity(errorsRaw.size(), 0.75f), 0.75f, complexKeyType); for (Map.Entry entry : errorsRaw.entrySet()) { diff --git a/restli-client/src/main/java/com/linkedin/restli/client/util/RestliRequestUriSignature.java b/restli-client/src/main/java/com/linkedin/restli/client/util/RestliRequestUriSignature.java index da77d66861..c6a9d8f4d8 100644 --- a/restli-client/src/main/java/com/linkedin/restli/client/util/RestliRequestUriSignature.java +++ b/restli-client/src/main/java/com/linkedin/restli/client/util/RestliRequestUriSignature.java @@ -85,7 +85,7 @@ public static enum SignatureField } public static final Set ALL_FIELDS = - Collections.unmodifiableSet(new HashSet(Arrays.asList(SignatureField.values()))); + Collections.unmodifiableSet(new HashSet<>(Arrays.asList(SignatureField.values()))); private final Set _maskFields; private final String _baseUriTemplate; @@ -170,7 +170,7 @@ else if (request instanceof GetAllRequest) } else { - _queryParams = new HashMap(); + _queryParams = new HashMap<>(); for (Map.Entry entry : rawQueryParams.entrySet()) { if (entry.getValue() instanceof Collection) diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/ActionResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/ActionResponseDecoder.java index 5215637b74..7d74463511 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/ActionResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/ActionResponseDecoder.java @@ -61,6 +61,6 @@ public Class getEntityClass() @Override public T wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) { - return dataMap == null ? null : new ActionResponse(dataMap, _returnFieldDef, _recordDataSchema).getValue(); + return dataMap == null ? null : new ActionResponse<>(dataMap, _returnFieldDef, _recordDataSchema).getValue(); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateDecoder.java index f55b69c2ba..67ad3d42d9 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateDecoder.java @@ -57,7 +57,7 @@ public BatchCreateDecoder(TypeSpec keyType, public BatchCreateResponse wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - CreateIdStatusDecoder decoder = new CreateIdStatusDecoder(_keyType, _keyParts, _complexKeyType, version); - return dataMap == null ? null : new BatchCreateResponse(dataMap, decoder); + CreateIdStatusDecoder decoder = new CreateIdStatusDecoder<>(_keyType, _keyParts, _complexKeyType, version); + return dataMap == null ? null : new BatchCreateResponse<>(dataMap, decoder); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdDecoder.java index 1ff09c820d..f03fd7eb48 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdDecoder.java @@ -61,7 +61,7 @@ public Class getEntityClass() public BatchCreateIdResponse wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - CreateIdStatusDecoder decoder = new CreateIdStatusDecoder(_keyType, _keyParts, _complexKeyType, version); - return dataMap == null ? null : new BatchCreateIdResponse(dataMap, decoder); + CreateIdStatusDecoder decoder = new CreateIdStatusDecoder<>(_keyType, _keyParts, _complexKeyType, version); + return dataMap == null ? null : new BatchCreateIdResponse<>(dataMap, decoder); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdEntityDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdEntityDecoder.java index d8ea3f2df7..3446d4b723 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdEntityDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchCreateIdEntityDecoder.java @@ -60,9 +60,9 @@ public BatchCreateIdEntityResponse wrapResponse(DataMap dataMap, Map decoder = new CreateIdEntityStatusDecoder(_keyType, _valueType, _keyParts, _complexKeyType, version); - return dataMap == null ? null : new BatchCreateIdEntityResponse(dataMap, decoder); + CreateIdEntityStatusDecoder decoder = new CreateIdEntityStatusDecoder<>(_keyType, _valueType, _keyParts, _complexKeyType, version); + return dataMap == null ? null : new BatchCreateIdEntityResponse<>(dataMap, decoder); } -} \ No newline at end of file +} diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchKVResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchKVResponseDecoder.java index db0698acb5..d7ef9f98f2 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchKVResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchKVResponseDecoder.java @@ -103,11 +103,11 @@ public Class getEntityClass() @Override public BatchKVResponse wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) { - return dataMap == null ? null : new BatchKVResponse(dataMap, - _keyType, - _elementType, - _keyParts, - _complexKeyType, - version); + return dataMap == null ? null : new BatchKVResponse<>(dataMap, + _keyType, + _elementType, + _keyParts, + _complexKeyType, + version); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchResponseDecoder.java index 13b8e38366..0aecaffe35 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/BatchResponseDecoder.java @@ -53,6 +53,6 @@ public Class getEntityClass() @Override public BatchResponse wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) { - return dataMap == null ? null : new BatchResponse(dataMap, _elementClass); + return dataMap == null ? null : new BatchResponse<>(dataMap, _elementClass); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionRequestUtil.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionRequestUtil.java index d932f59845..bf3a9fef7a 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionRequestUtil.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionRequestUtil.java @@ -101,7 +101,7 @@ public static BatchRequest convertToBatchRequest(C TypeSpec valueType, ProtocolVersion version) { - BatchRequest batchRequest = new BatchRequest(new DataMap(), valueType); + BatchRequest batchRequest = new BatchRequest<>(new DataMap(), valueType); for (KeyValueRecord keyValueRecord: elementList.getElements()) { diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionResponseDecoder.java index c1b00ebae2..454b59d50a 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/CollectionResponseDecoder.java @@ -55,6 +55,6 @@ public Class getEntityClass() public CollectionResponse wrapResponse(DataMap dataMap, Map headers, ProtocolVersion version) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - return dataMap == null ? null : new CollectionResponse(dataMap, _elementClass); + return dataMap == null ? null : new CollectionResponse<>(dataMap, _elementClass); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/CreateResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/CreateResponseDecoder.java index febf97c7f4..2850470612 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/CreateResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/CreateResponseDecoder.java @@ -78,14 +78,14 @@ public Response decodeResponse(RestResponse restResponse) final Response rawResponse = super.decodeResponse(restResponse); // ResponseImpl will make the headers unmodifiable - final Map modifiableHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map modifiableHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); modifiableHeaders.putAll(rawResponse.getHeaders()); // remove ID header to prevent user to access the weakly typed ID modifiableHeaders.remove(RestConstants.HEADER_ID); modifiableHeaders.remove(RestConstants.HEADER_RESTLI_ID); - return new ResponseImpl(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); + return new ResponseImpl<>(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); } @Override @@ -104,6 +104,6 @@ public CreateResponse wrapResponse(DataMap dataMap, Map heade key = (K) ResponseUtils.convertKey(id, _keyType, _keyParts, _complexKeyType, version); } - return new CreateResponse(key); + return new CreateResponse<>(key); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/ExceptionUtil.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/ExceptionUtil.java index 528495aef3..3d15826ab5 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/ExceptionUtil.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/ExceptionUtil.java @@ -38,7 +38,7 @@ public class ExceptionUtil { private static final EntityResponseDecoder ERROR_DECODER = - new EntityResponseDecoder(ErrorResponse.class); + new EntityResponseDecoder<>(ErrorResponse.class); private ExceptionUtil() { diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/IdEntityResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/IdEntityResponseDecoder.java index 860148d1c7..7a34731dbf 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/IdEntityResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/IdEntityResponseDecoder.java @@ -68,13 +68,13 @@ public Response> decodeResponse(RestResponse restResponse { final Response> rawResponse = super.decodeResponse(restResponse); - final Map modifiableHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map modifiableHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); modifiableHeaders.putAll(rawResponse.getHeaders()); modifiableHeaders.remove(RestConstants.HEADER_ID); modifiableHeaders.remove(RestConstants.HEADER_RESTLI_ID); - return new ResponseImpl>(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); + return new ResponseImpl<>(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); } @Override @@ -85,6 +85,6 @@ public IdEntityResponse wrapResponse(DataMap dataMap, Map String id = HeaderUtil.getIdHeaderValue(headers); K key = id == null ? null : (K) ResponseUtils.convertKey(id, _keyType, _keyParts, _complexKeyType, version); V entity = dataMap == null ? null : _entityClass.getConstructor(DataMap.class).newInstance(dataMap); - return new IdEntityResponse(key, entity); + return new IdEntityResponse<>(key, entity); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/IdResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/IdResponseDecoder.java index 415616aa20..7798fc8998 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/IdResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/IdResponseDecoder.java @@ -66,14 +66,14 @@ public Response> decodeResponse(RestResponse restResponse) final Response> rawResponse = super.decodeResponse(restResponse); // ResponseImpl will make the headers unmodifiable - final Map modifiableHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map modifiableHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); modifiableHeaders.putAll(rawResponse.getHeaders()); // remove ID header to prevent user to access the weakly typed ID modifiableHeaders.remove(RestConstants.HEADER_ID); modifiableHeaders.remove(RestConstants.HEADER_RESTLI_ID); - return new ResponseImpl>(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); + return new ResponseImpl<>(rawResponse.getStatus(), modifiableHeaders, rawResponse.getCookies(), rawResponse.getEntity(), rawResponse.getError()); } @Override @@ -91,6 +91,6 @@ public IdResponse wrapResponse(DataMap dataMap, Map headers, { key = (K) ResponseUtils.convertKey(id, _keyType, _keyParts, _complexKeyType, version); } - return new IdResponse(key); + return new IdResponse<>(key); } } diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/OptionsResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/OptionsResponseDecoder.java index a5f9791b6d..9f1f10b810 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/OptionsResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/OptionsResponseDecoder.java @@ -53,7 +53,7 @@ public OptionsResponse wrapResponse(DataMap dataMap, Map headers DataMap resources = dataMap.getDataMap(RESOURCES); if(resources == null) resources = new DataMap(); - HashMap resourceMap = new HashMap(resources.size()); + HashMap resourceMap = new HashMap<>(resources.size()); for(Map.Entry entry: resources.entrySet()) { resourceMap.put(entry.getKey(), new ResourceSchema((DataMap)entry.getValue())); @@ -62,7 +62,7 @@ public OptionsResponse wrapResponse(DataMap dataMap, Map headers DataMap schemas = dataMap.getDataMap(MODELS); if(schemas == null) schemas = new DataMap(); - HashMap dataSchemaMap = new HashMap(schemas.size()); + HashMap dataSchemaMap = new HashMap<>(schemas.size()); for(Map.Entry entry: schemas.entrySet()) { String schemaText = CODEC.mapToString((DataMap)entry.getValue()); diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/QueryParamsUtil.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/QueryParamsUtil.java index 4c216051e4..5221e66aef 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/QueryParamsUtil.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/QueryParamsUtil.java @@ -202,7 +202,7 @@ private static List stringifyArray(Object array) { assert array != null && array.getClass().isArray(); int len = Array.getLength(array); - List strings = new ArrayList(len); + List strings = new ArrayList<>(len); for (int i = 0; i < len; ++i) { Object value = Array.get(array, i); diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/RequestBodyTransformer.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/RequestBodyTransformer.java index 0b2b97ebb4..23a66ae3a8 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/RequestBodyTransformer.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/RequestBodyTransformer.java @@ -72,7 +72,7 @@ public static DataMap transform(Request request, ProtocolVersion version) resourceProperties.getKeyType(), resourceProperties.getComplexKeyType(), resourceProperties.getKeyParts(), - new TypeSpec(PatchRequest.class), + new TypeSpec<>(PatchRequest.class), version).data(); default: return request.getInputRecord().data(); diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseFutureImpl.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseFutureImpl.java index 11633d6c1b..21b9784beb 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseFutureImpl.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseFutureImpl.java @@ -151,13 +151,13 @@ private Response createResponseFromError(RestLiResponseException restLiRespon // creation which will not have an entity. if (restLiResponseException.hasDecodedResponse()) { - response = new ResponseImpl( - (Response) restLiResponseException.getDecodedResponse(), - restLiResponseException); + response = new ResponseImpl<>( + (Response) restLiResponseException.getDecodedResponse(), + restLiResponseException); } else { - response = new ResponseImpl( + response = new ResponseImpl<>( restLiResponseException.getStatus(), restLiResponseException.getResponse().getHeaders(), CookieUtil.decodeSetCookies(restLiResponseException.getResponse().getCookies()), diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseImpl.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseImpl.java index 47db4a8fea..1ac757d7db 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseImpl.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/ResponseImpl.java @@ -87,9 +87,9 @@ public ResponseImpl(int status, Map headers, List co ResponseImpl(int status, Map headers, List cookies) { _status = status; - _headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + _headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); _headers.putAll(headers); - _cookies = new ArrayList(cookies); + _cookies = new ArrayList<>(cookies); } /** diff --git a/restli-client/src/main/java/com/linkedin/restli/internal/client/RestResponseDecoder.java b/restli-client/src/main/java/com/linkedin/restli/internal/client/RestResponseDecoder.java index e605746c3d..64ea4f1693 100644 --- a/restli-client/src/main/java/com/linkedin/restli/internal/client/RestResponseDecoder.java +++ b/restli-client/src/main/java/com/linkedin/restli/internal/client/RestResponseDecoder.java @@ -169,7 +169,7 @@ public Response decodeResponse(RestResponse restResponse) throws RestLiDecodi private ResponseImpl createResponse(Map headers, int status, ByteString entity, List cookies) throws RestLiDecodingException { - ResponseImpl response = new ResponseImpl(status, headers, CookieUtil.decodeSetCookies(cookies)); + ResponseImpl response = new ResponseImpl<>(status, headers, CookieUtil.decodeSetCookies(cookies)); try { @@ -206,7 +206,7 @@ private ResponseImpl createResponse(Map headers, int status, private ResponseImpl createResponse(Map headers, int status, DataMap dataMap, List cookies) throws RestLiDecodingException { - ResponseImpl response = new ResponseImpl(status, headers, CookieUtil.decodeSetCookies(cookies)); + ResponseImpl response = new ResponseImpl<>(status, headers, CookieUtil.decodeSetCookies(cookies)); try { diff --git a/restli-client/src/test/java/com/linkedin/restli/client/BatchGetRequestBuilderTest.java b/restli-client/src/test/java/com/linkedin/restli/client/BatchGetRequestBuilderTest.java index e35c08c1ad..053826eef5 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/BatchGetRequestBuilderTest.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/BatchGetRequestBuilderTest.java @@ -83,7 +83,7 @@ public class BatchGetRequestBuilderTest private static Map createKeyParts() { - Map keyParts = new HashMap(); + Map keyParts = new HashMap<>(); keyParts.put("age", new CompoundKey.TypeInfo(Integer.class, Integer.class)); return keyParts; } @@ -93,15 +93,15 @@ private static Map createKeyParts() public void testBuildFailureForComplexKeys() { BatchGetRequestBuilder, TestRecord> builder = - new BatchGetRequestBuilder, TestRecord>( + new BatchGetRequestBuilder<>( "http://greetings", - new BatchResponseDecoder(TestRecord.class), + new BatchResponseDecoder<>(TestRecord.class), _complexResourceSpec, RestliRequestOptions.DEFAULT_OPTIONS); builder.ids( Arrays.asList( - new ComplexResourceKey( + new ComplexResourceKey<>( new TestRecord().setId(1L), new TestRecord().setId(5L)))); builder.build(); @@ -111,9 +111,9 @@ public void testBuildFailureForComplexKeys() public void testBuildFailureForCompoundKeys() { BatchGetRequestBuilder builder = - new BatchGetRequestBuilder( + new BatchGetRequestBuilder<>( "http://greetings", - new BatchResponseDecoder(TestRecord.class), + new BatchResponseDecoder<>(TestRecord.class), _compoundResourceSpec, RestliRequestOptions.DEFAULT_OPTIONS); @@ -132,15 +132,15 @@ public void testBatchConversion() String expectedProtocol2Uri = "/?fields=message,id&ids=List(1)¶m=paramValue"; GetRequestBuilder requestBuilder = - new GetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl(Collections.emptySet(), - null, - null, - int.class, - TestRecord.class, - Collections.emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl(Collections.emptySet(), + null, + null, + int.class, + TestRecord.class, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); requestBuilder.id(1) .fields(FIELDS.id(), FIELDS.message()) .setParam("param", "paramValue"); @@ -150,7 +150,7 @@ public void testBatchConversion() Assert.assertEquals(batchRequest.getPathKeys(), request.getPathKeys()); testUriGeneration(batchRequest, expectedProtocol1Uri, expectedProtocol2Uri); Assert.assertEquals(batchRequest.getFields(), request.getFields()); - Assert.assertEquals(batchRequest.getObjectIds(), new HashSet(Arrays.asList(request.getObjectId()))); + Assert.assertEquals(batchRequest.getObjectIds(), new HashSet<>(Arrays.asList(request.getObjectId()))); } @Test @@ -161,15 +161,15 @@ public void testBatchKVConversion() String expectedProtocol2Uri = "/?fields=message,id&ids=List(1)¶m=paramValue"; GetRequestBuilder requestBuilder = - new GetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl(Collections.emptySet(), - null, - null, - Integer.class, - TestRecord.class, - Collections.emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl(Collections.emptySet(), + null, + null, + Integer.class, + TestRecord.class, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); requestBuilder.id(1) .fields(FIELDS.id(), FIELDS.message()) .setParam("param", "paramValue"); @@ -179,7 +179,7 @@ public void testBatchKVConversion() Assert.assertEquals(batchRequest.getPathKeys(), request.getPathKeys()); testUriGeneration(batchRequest, expectedProtocol1Uri, expectedProtocol2Uri); Assert.assertEquals(batchRequest.getFields(), request.getFields()); - Assert.assertEquals(batchRequest.getObjectIds(), new HashSet(Arrays.asList(request.getObjectId()))); + Assert.assertEquals(batchRequest.getObjectIds(), new HashSet<>(Arrays.asList(request.getObjectId()))); } @Test @@ -193,10 +193,10 @@ public void testComplexKeyBatchConversion() String expectedProtocol2Uri = "/?fields=message,id&ids=List(($params:(id:1,message:paramMessage1),id:1,message:keyMessage1))¶m=paramValue"; GetRequestBuilder, TestRecord> requestBuilder = - new GetRequestBuilder, TestRecord>("/", - TestRecord.class, - _complexResourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>("/", + TestRecord.class, + _complexResourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey complexKey1 = buildComplexKey(1L, "keyMessage1", 1L, "paramMessage1"); requestBuilder.id(complexKey1) @@ -208,17 +208,17 @@ public void testComplexKeyBatchConversion() Assert.assertEquals(batchRequest.getPathKeys(), request.getPathKeys()); testUriGeneration(batchRequest, expectedProtocol1Uri, expectedProtocol2Uri); Assert.assertEquals(batchRequest.getFields(), request.getFields()); - Assert.assertEquals(batchRequest.getObjectIds(), new HashSet(Arrays.asList(request.getObjectId()))); + Assert.assertEquals(batchRequest.getObjectIds(), new HashSet<>(Arrays.asList(request.getObjectId()))); } @Test public void testComplexKeyBatchingWithoutTypedKeys() { GetRequestBuilder, TestRecord> requestBuilder = - new GetRequestBuilder, TestRecord>("/", - TestRecord.class, - _complexResourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>("/", + TestRecord.class, + _complexResourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey complexKey1 = buildComplexKey(1L, "keyMessage1", 1L, "paramMessage1"); requestBuilder.id(complexKey1); @@ -233,13 +233,13 @@ public void testComplexKeyBatchingWithoutTypedKeys() { } - Map queryParams = new HashMap(); + Map queryParams = new HashMap<>(); queryParams.put("ids", Arrays.asList((Object)complexKey1)); - BatchGetRequest request3 = new BatchGetRequest( + BatchGetRequest request3 = new BatchGetRequest<>( Collections.emptyMap(), Collections.emptyList(), - new BatchResponseDecoder(TestRecord.class), + new BatchResponseDecoder<>(TestRecord.class), queryParams, Collections.>emptyMap(), _complexResourceSpec, @@ -263,10 +263,10 @@ public void testComplexKeyBatchingWithoutTypedKeys() public void testCompoundKeyBatchingWithoutTypedKeys() { GetRequestBuilder requestBuilder2 = - new GetRequestBuilder("/", - TestRecord.class, - _compoundResourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>("/", + TestRecord.class, + _compoundResourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); CompoundKey key = new CompoundKey().append("abc", 1).append("def", 2); requestBuilder2.id(key); @@ -282,13 +282,13 @@ public void testCompoundKeyBatchingWithoutTypedKeys() { } - Map queryParams = new HashMap(); + Map queryParams = new HashMap<>(); queryParams.put("ids", Arrays.asList((Object)key)); - BatchGetRequest request4 = new BatchGetRequest( + BatchGetRequest request4 = new BatchGetRequest<>( Collections.emptyMap(), Collections.emptyList(), - new BatchResponseDecoder(TestRecord.class), + new BatchResponseDecoder<>(TestRecord.class), queryParams, Collections.>emptyMap(), _compoundResourceSpec, @@ -318,36 +318,36 @@ public void testSimpleBatching() "/?fields=id,message&ids=List(1,2,3)¶m1=value1¶m2=value2"; BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1, 2) .fields(FIELDS.id()) .setParam("param2", "value2") .setParam("param1", "value1"); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3) .fields(FIELDS.id(), FIELDS.message()) .setParam("param1", "value1") @@ -362,8 +362,8 @@ Collections. emptyMap()), Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), - new HashSet(Arrays.asList(FIELDS.id(), FIELDS.message()))); - Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(1, 2, 3))); + new HashSet<>(Arrays.asList(FIELDS.id(), FIELDS.message()))); + Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet<>(Arrays.asList(1, 2, 3))); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -381,10 +381,10 @@ public void testComplexKeyBatching() buildComplexKey(3L, "keyMessage3", 3L, "paramMessage3"); BatchGetRequestBuilder, TestRecord> batchRequestBuilder1 = - new BatchGetRequestBuilder, TestRecord>("/", - TestRecord.class, - _complexResourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + _complexResourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey[] complexKeys1 = new ComplexResourceKey[] {complexKey1, complexKey2}; batchRequestBuilder1.ids(complexKeys1) @@ -393,10 +393,10 @@ public void testComplexKeyBatching() .setParam("param1", "value1"); BatchGetRequestBuilder, TestRecord> batchRequestBuilder2 = - new BatchGetRequestBuilder, TestRecord>("/", - TestRecord.class, - _complexResourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + _complexResourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey[] complexKeys2 = new ComplexResourceKey[]{complexKey2, complexKey3}; batchRequestBuilder2.ids(complexKeys2) @@ -438,12 +438,12 @@ public void testComplexKeyBatching() (DataList) actualParamsDataMap.remove(RestConstants.QUERY_BATCH_IDS_PARAM); DataList expectedIds = (DataList) expectedParamsDataMap.remove(RestConstants.QUERY_BATCH_IDS_PARAM); - Assert.assertEquals(new HashSet(actualIds), new HashSet(expectedIds)); + Assert.assertEquals(new HashSet<>(actualIds), new HashSet<>(expectedIds)); Assert.assertEquals(actualParamsDataMap, expectedParamsDataMap); Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), - new HashSet(Arrays.asList(FIELDS.id(), FIELDS.message()))); + new HashSet<>(Arrays.asList(FIELDS.id(), FIELDS.message()))); Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(complexKey1, complexKey2, complexKey3))); String expectedProtocol2Uri = @@ -466,8 +466,8 @@ public void testComplexKeyBatching() String expectedProtocol2IdsAsString = expectedParams.remove("ids").get(0); DataList actualProtocol2Ids = (DataList) URIElementParser.parse(actualProtocol2IdsAsString); DataList expectedProtocol2Ids = (DataList) URIElementParser.parse(expectedProtocol2IdsAsString); - Assert.assertEquals(new HashSet(actualProtocol2Ids.values()), - new HashSet(expectedProtocol2Ids.values())); + Assert.assertEquals(new HashSet<>(actualProtocol2Ids.values()), + new HashSet<>(expectedProtocol2Ids.values())); // apart from the "ids" fields everything else should be the same Assert.assertEquals(actualParams, expectedParams); @@ -478,43 +478,43 @@ private static ComplexResourceKey buildComplexKey(Long k Long paramId, String paramMessage) { - return new ComplexResourceKey(new TestRecord().setId(keyId) - .setMessage(keyMessage), - new TestRecord().setId(paramId) - .setMessage(paramMessage)); + return new ComplexResourceKey<>(new TestRecord().setId(keyId) + .setMessage(keyMessage), + new TestRecord().setId(paramId) + .setMessage(paramMessage)); } @Test public void testSimpleBatchingFailureWithDiffParams() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1, 2).fields(FIELDS.id()).setParam("param1", "value1"); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3) .fields(FIELDS.id(), FIELDS.message()) .setParam("param1", "value1") @@ -540,31 +540,31 @@ Collections. emptyMap()), public void testBatchingWithDiffUris() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/a/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/a/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); @SuppressWarnings("unchecked") List> requests = @@ -588,34 +588,34 @@ public void testNoFieldBatching() String expectedProtocol2Uri = "/?fields=id&ids=List(1,2,3)"; BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); batchRequestBuilder1.fields(FIELDS.id()); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3); batchRequestBuilder2.fields(FIELDS.id()); @@ -628,8 +628,8 @@ Collections. emptyMap()), Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), - new HashSet(Arrays.asList(FIELDS.id()))); - Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(1, 2, 3))); + new HashSet<>(Arrays.asList(FIELDS.id()))); + Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet<>(Arrays.asList(1, 2, 3))); testUriGeneration(batchingRequest, expectedProtocol1Uri, expectedProtocol2Uri); } @@ -637,34 +637,34 @@ Collections. emptyMap()), public void testNoFieldBatchingFailure() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); batchRequestBuilder1.fields(FIELDS.id()); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3); batchRequestBuilder2.fields(FIELDS.message()); @@ -686,35 +686,35 @@ Collections. emptyMap()), public void testBatchingWithDifferentRequestOptionsFailure() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); RestliRequestOptions customOptions = new RestliRequestOptionsBuilder().setProtocolVersionOption(ProtocolVersionOption.FORCE_USE_NEXT).build(); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - customOptions); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + customOptions); batchRequestBuilder2.ids(2, 3); try @@ -739,34 +739,34 @@ public void testBatchingWithNoFields() String expectedProtocol2Uri = "/?ids=List(1,2,3)"; BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); batchRequestBuilder1.fields(); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3); batchRequestBuilder2.fields(); @@ -778,7 +778,7 @@ Collections. emptyMap()), Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), Collections.emptySet()); - Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(1, 2, 3))); + Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet<>(Arrays.asList(1, 2, 3))); testUriGeneration(batchingRequest, expectedProtocol1Uri, expectedProtocol2Uri); } @@ -786,33 +786,33 @@ Collections. emptyMap()), public void testBatchingWithNullProjectionFirst() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3); batchRequestBuilder2.fields(FIELDS.message()); @@ -824,41 +824,41 @@ Collections. emptyMap()), Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), Collections.emptySet()); - Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(1, 2, 3))); + Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet<>(Arrays.asList(1, 2, 3))); } @Test public void testBatchingWithNullProjectionLast() { BatchGetRequestBuilder batchRequestBuilder1 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder1.ids(1); batchRequestBuilder1.fields(FIELDS.message()); BatchGetRequestBuilder batchRequestBuilder2 = - new BatchGetRequestBuilder("/", - TestRecord.class, - new ResourceSpecImpl( - Collections. emptySet(), - Collections. emptyMap(), - Collections. emptyMap(), - Integer.class, - null, - null, - null, - Collections. emptyMap()), - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchGetRequestBuilder<>("/", + TestRecord.class, + new ResourceSpecImpl( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptyMap(), + Integer.class, + null, + null, + null, + Collections.emptyMap()), + RestliRequestOptions.DEFAULT_OPTIONS); batchRequestBuilder2.ids(2, 3); BatchGetRequest batchRequest1 = batchRequestBuilder1.build(); @@ -869,7 +869,7 @@ Collections. emptyMap()), Assert.assertEquals(batchingRequest.getBaseUriTemplate(), batchRequest1.getBaseUriTemplate()); Assert.assertEquals(batchingRequest.getPathKeys(), batchRequest1.getPathKeys()); Assert.assertEquals(batchingRequest.getFields(), Collections.emptySet()); - Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet(Arrays.asList(1, 2, 3))); + Assert.assertEquals(batchingRequest.getObjectIds(), new HashSet<>(Arrays.asList(1, 2, 3))); } private static void testUriGeneration(Request request, String protocol1UriString, String protocol2UriString) @@ -908,8 +908,8 @@ private static void assertProtocolURIsMatch(final MultivaluedMap actualQueryPara else { // Fields could be out of order, so we have to break it apart and compare using a set - final Set actualFieldSet = new HashSet(Arrays.asList(entry.getValue().get(0).split(","))); - final Set expectedFieldSet = new HashSet(Arrays.asList(expectedQueryParamMap.get(entry.getKey()).get(0).split(","))); + final Set actualFieldSet = new HashSet<>(Arrays.asList(entry.getValue().get(0).split(","))); + final Set expectedFieldSet = new HashSet<>(Arrays.asList(expectedQueryParamMap.get(entry.getKey()).get(0).split(","))); Assert.assertEquals(actualFieldSet, expectedFieldSet, protocolName + " URI generation did not match expected URI! Projection field names have a mismatch!"); } diff --git a/restli-client/src/test/java/com/linkedin/restli/client/MockClient.java b/restli-client/src/test/java/com/linkedin/restli/client/MockClient.java index d7ab45f2b8..f8b2a136cf 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/MockClient.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/MockClient.java @@ -59,7 +59,7 @@ public MockClient(int status, Map headers, byte[] body) public void streamRequest(StreamRequest request, RequestContext requestContext, Callback callback) { - TransportCallback adapter = HttpBridge.streamToHttpCallback(new TransportCallbackAdapter(callback), request); + TransportCallback adapter = HttpBridge.streamToHttpCallback(new TransportCallbackAdapter<>(callback), request); RestResponse response = new RestResponseBuilder() .setStatus(status()) diff --git a/restli-client/src/test/java/com/linkedin/restli/client/RestClientTest.java b/restli-client/src/test/java/com/linkedin/restli/client/RestClientTest.java index a929f40d9b..fcddf98bba 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/RestClientTest.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/RestClientTest.java @@ -491,7 +491,7 @@ public void testRestLiResponseExceptionCallback(SendRequestOption option, Request request = mockRequest(EmptyRecord.class, versionOption, contentType); RequestBuilder> requestBuilder = mockRequestBuilder(request); - FutureCallback> callback = new FutureCallback>(); + FutureCallback> callback = new FutureCallback<>(); try { sendRequest(option, client, request, requestBuilder, callback); @@ -524,7 +524,7 @@ public void testRestLiResponseExceptionCallback(SendRequestOption option, RestException re = (RestException)cause; RestResponse r = re.getResponse(); - ErrorResponse er = new EntityResponseDecoder(ErrorResponse.class).decodeResponse(r).getEntity(); + ErrorResponse er = new EntityResponseDecoder<>(ErrorResponse.class).decodeResponse(r).getEntity(); Assert.assertEquals(HTTP_CODE, r.getStatus()); Assert.assertEquals(ERR_VALUE, er.getErrorDetails().data().getString(ERR_KEY)); @@ -549,7 +549,7 @@ public void testRestLiRemoteInvocationException(SendRequestOption option, Request request = mockRequest(EmptyRecord.class, versionOption, contentType); RequestBuilder> requestBuilder = mockRequestBuilder(request); - FutureCallback> callback = new FutureCallback>(); + FutureCallback> callback = new FutureCallback<>(); try { sendRequest(option, client, request, requestBuilder, callback); @@ -781,16 +781,16 @@ private Request mockRequest(Class clazz, .setAcceptTypes(Collections.singletonList(contentType)) .build(); - return new GetRequest(Collections. emptyMap(), - Collections.emptyList(), - clazz, - null, - new DataMap(), - Collections.>emptyMap(), - new ResourceSpecImpl(), - "/foo", - Collections.emptyMap(), - restliRequestOptions); + return new GetRequest<>(Collections.emptyMap(), + Collections.emptyList(), + clazz, + null, + new DataMap(), + Collections.>emptyMap(), + new ResourceSpecImpl(), + "/foo", + Collections.emptyMap(), + restliRequestOptions); } private static class MyMockClient extends MockClient @@ -814,7 +814,7 @@ public void restRequest(RestRequest request, RequestContext requestContext, @Override protected Map headers() { - Map headers = new HashMap(super.headers()); + Map headers = new HashMap<>(super.headers()); for (Map.Entry attr : _requestContext.getLocalAttrs().entrySet()) { if (!attr.getKey().startsWith("__attr")) @@ -852,7 +852,7 @@ private RestClient mockClient(String errKey, er.setDocUrl(docUrl); er.setRequestId(requestId); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()); headers.put(errorResponseHeaderName, RestConstants.HEADER_VALUE_ERROR); @@ -881,7 +881,7 @@ private RestClient mockClient(int httpCode, String errDetails, ProtocolVersion p throw new RuntimeException(e); } - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()); return new RestClient(new MyMockClient(httpCode, headers, mapBytes), "http://localhost"); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestAbstractRequestBuilder.java b/restli-client/src/test/java/com/linkedin/restli/client/TestAbstractRequestBuilder.java index e5ac5fa89f..de84b77581 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestAbstractRequestBuilder.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestAbstractRequestBuilder.java @@ -100,7 +100,7 @@ public void testSetHeadersWithNonNullValue() Assert.assertEquals(builder.getHeader("a"), "b"); Assert.assertEquals(builder.getHeader("c"), "d"); - final Map newHeaders = new HashMap(); + final Map newHeaders = new HashMap<>(); newHeaders.put("c", "e"); builder.setHeaders(newHeaders); @@ -115,7 +115,7 @@ public void testSetHeadersWithNonNullValue() public void testSetHeadersWithNullValue() { final AbstractRequestBuilder builder = new DummyAbstractRequestBuilder(); - final Map newHeaders = new HashMap(); + final Map newHeaders = new HashMap<>(); newHeaders.put("a", "b"); newHeaders.put("c", null); @@ -128,9 +128,9 @@ public void testSetHeadersWithNullValue() public void testAddCookieWithNonNullValue() { final AbstractRequestBuilder builder = new DummyAbstractRequestBuilder(); - List cookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - new HttpCookie("Y", "2"), - new HttpCookie("Z", "3"))); + List cookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + new HttpCookie("Y", "2"), + new HttpCookie("Z", "3"))); Assert.assertSame(builder.addCookie(new HttpCookie("X", "1")), builder); Assert.assertSame(builder.addCookie(new HttpCookie("Y", "2")), builder); @@ -147,8 +147,8 @@ public void testAddCookieWithNullValue() Assert.assertSame(builder.addCookie(null), builder); Assert.assertSame(builder.addCookie(new HttpCookie("Z", "3")), builder); - List cookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - new HttpCookie("Z", "3"))); + List cookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + new HttpCookie("Z", "3"))); Assert.assertEquals(builder.getCookies(), cookies); } @@ -157,9 +157,9 @@ public void testAddCookieWithNullValue() public void testSetCookiesWithNonNullValue() { final AbstractRequestBuilder builder = new DummyAbstractRequestBuilder(); - List cookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - new HttpCookie("Y", "2"), - new HttpCookie("Z", "3"))); + List cookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + new HttpCookie("Y", "2"), + new HttpCookie("Z", "3"))); Assert.assertSame(builder.setCookies(cookies), builder); Assert.assertEquals(builder.getCookies(), cookies); @@ -169,13 +169,13 @@ public void testSetCookiesWithNonNullValue() public void testSetCookiesWithNullValue() { final AbstractRequestBuilder builder = new DummyAbstractRequestBuilder(); - List cookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - null, - new HttpCookie("Z", "3"))); + List cookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + null, + new HttpCookie("Z", "3"))); // Null element will not be passed Assert.assertSame(builder.setCookies(cookies), builder); - List resultCookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - new HttpCookie("Z", "3"))); + List resultCookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + new HttpCookie("Z", "3"))); Assert.assertEquals(builder.getCookies(), resultCookies); } @@ -183,9 +183,9 @@ public void testSetCookiesWithNullValue() public void testClearCookie() { final AbstractRequestBuilder builder = new DummyAbstractRequestBuilder(); - List cookies = new ArrayList(Arrays.asList(new HttpCookie("X", "1"), - new HttpCookie("Y", "2"), - new HttpCookie("Z", "3"))); + List cookies = new ArrayList<>(Arrays.asList(new HttpCookie("X", "1"), + new HttpCookie("Y", "2"), + new HttpCookie("Z", "3"))); Assert.assertSame(builder.setCookies(cookies), builder); Assert.assertSame(builder.clearCookies(), builder); @@ -279,7 +279,7 @@ public void testSetCollectionThenAddParam(Object value1, Object value2, Object v // AbstractList returned by Arrays.asList() does not support add() // need to wrap it with ArrayList - final Collection testData = new ArrayList(Arrays.asList(value1, value2)); + final Collection testData = new ArrayList<>(Arrays.asList(value1, value2)); builder.setParam("a", testData); builder.addParam("a", value3); @@ -350,14 +350,14 @@ public void testRemoveParam() @DataProvider(name = "testQueryParam") public static Object[][] testQueryParamDataProvider() { - final Object value3 = new ArrayList(Arrays.asList("x", "y")); + final Object value3 = new ArrayList<>(Arrays.asList("x", "y")); return new Object[][] { { "a", "b", "z" }, { "a", "b", value3 }, { new String[] { "a", "b" }, new String[] { "c", "d" }, "z" }, { new String[] { "a", "b" }, new String[] { "c", "d" }, value3 }, - { new ArrayList(Arrays.asList("a", "b")), new ArrayList(Arrays.asList("c", "d")), "z" }, - { new ArrayList(Arrays.asList("a", "b")), new ArrayList(Arrays.asList("c", "d")), value3 } + {new ArrayList<>(Arrays.asList("a", "b")), new ArrayList<>(Arrays.asList("c", "d")), "z" }, + {new ArrayList<>(Arrays.asList("a", "b")), new ArrayList<>(Arrays.asList("c", "d")), value3 } }; } @@ -488,7 +488,7 @@ public void testKeysAreReadOnly() TestRecord testRecord = new TestRecord(); TestRecord testRecord2 = new TestRecord(); ComplexResourceKey originalKey = - new ComplexResourceKey(testRecord, testRecord2); + new ComplexResourceKey<>(testRecord, testRecord2); builder.addKey(originalKey); Map parameters = builder.buildReadOnlyQueryParameters(); @@ -521,7 +521,7 @@ public void testPathKeysAreReadOnly() TestRecord testRecord = new TestRecord(); TestRecord testRecord2 = new TestRecord(); ComplexResourceKey originalKey = - new ComplexResourceKey(testRecord, testRecord2); + new ComplexResourceKey<>(testRecord, testRecord2); builder.pathKey("abc", originalKey); Map pathKeys = builder.buildReadOnlyPathKeys(); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestClientBuilders.java b/restli-client/src/test/java/com/linkedin/restli/client/TestClientBuilders.java index 489e10b08e..1aed82545c 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestClientBuilders.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestClientBuilders.java @@ -106,7 +106,7 @@ Collections. emptyMap(), TestRecord.class, Collections.> emptyMap()); - private static Map keyParts = new HashMap(); + private static Map keyParts = new HashMap<>(); static { keyParts.put("part1", Long.class); @@ -153,7 +153,7 @@ public Object[][] action() //"test/1?action=action" //"test/1?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/1", @@ -171,12 +171,12 @@ public Object[][] action() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "action") public void testActionRequestBuilder(URIDetails expectedURIDetails) { - FieldDef pParam = new FieldDef("p", String.class, DataTemplateUtil.getSchema(String.class)); - Map requestMetadataMap = new HashMap(); + FieldDef pParam = new FieldDef<>("p", String.class, DataTemplateUtil.getSchema(String.class)); + Map requestMetadataMap = new HashMap<>(); DynamicRecordMetadata requestMetadata = new DynamicRecordMetadata("action", Collections.>singleton(pParam)); requestMetadataMap.put("action", requestMetadata); DynamicRecordMetadata responseMetadata = new DynamicRecordMetadata("action", Collections.>emptyList()); - Map responseMetadataMap = new HashMap(); + Map responseMetadataMap = new HashMap<>(); responseMetadataMap.put("action", responseMetadata); ResourceSpec resourceSpec = new ResourceSpecImpl(Collections.emptySet(), requestMetadataMap, @@ -185,10 +185,10 @@ public void testActionRequestBuilder(URIDetails expectedURIDetails) TestRecord.class, Collections. emptyMap()); - ActionRequestBuilder builder = new ActionRequestBuilder(TEST_URI, - TestRecord.class, - resourceSpec, - RestliRequestOptions.DEFAULT_OPTIONS); + ActionRequestBuilder builder = new ActionRequestBuilder<>(TEST_URI, + TestRecord.class, + resourceSpec, + RestliRequestOptions.DEFAULT_OPTIONS); ActionRequest request = builder.name("action").setParam(pParam, "42").id(1L) .appendSingleAttachment(_dataSourceWriterA) @@ -204,9 +204,9 @@ public void testActionRequestBuilder(URIDetails expectedURIDetails) d, DynamicRecordMetadata.buildSchema("action", Arrays.asList( - new FieldDef("p", - String.class, - DataTemplateUtil.getSchema(String.class))))); + new FieldDef<>("p", + String.class, + DataTemplateUtil.getSchema(String.class))))); URIDetails.testUriGeneration(request, expectedURIDetails); Assert.assertEquals(request.getMethod(), ResourceMethod.ACTION); @@ -229,12 +229,12 @@ public void testActionRequestBuilder(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "action") public void testActionRequestNullOptionalParams(URIDetails expectedURIDetails) { - FieldDef pParam = new FieldDef("p", String.class, DataTemplateUtil.getSchema(String.class)); - Map requestMetadataMap = new HashMap(); + FieldDef pParam = new FieldDef<>("p", String.class, DataTemplateUtil.getSchema(String.class)); + Map requestMetadataMap = new HashMap<>(); DynamicRecordMetadata requestMetadata = new DynamicRecordMetadata("action", Collections.>singleton(pParam)); requestMetadataMap.put("action", requestMetadata); DynamicRecordMetadata responseMetadata = new DynamicRecordMetadata("action", Collections.>emptyList()); - Map responseMetadataMap = new HashMap(); + Map responseMetadataMap = new HashMap<>(); responseMetadataMap.put("action", responseMetadata); ResourceSpec resourceSpec = @@ -242,7 +242,7 @@ public void testActionRequestNullOptionalParams(URIDetails expectedURIDetails) { TestRecord.class, Collections.emptyMap()); ActionRequestBuilder builder = - new ActionRequestBuilder(TEST_URI, TestRecord.class, resourceSpec, RestliRequestOptions.DEFAULT_OPTIONS); + new ActionRequestBuilder<>(TEST_URI, TestRecord.class, resourceSpec, RestliRequestOptions.DEFAULT_OPTIONS); pParam.getField().setOptional(true); ActionRequest requestNullOptionalValue = builder.name("action").setParam(pParam, null).id(2L).build(); @@ -257,10 +257,10 @@ public void testActionRequestNullOptionalParams(URIDetails expectedURIDetails) { @SuppressWarnings("unchecked") public void testActionRequestInputIsReadOnly() { - FieldDef pParam = new FieldDef("p", - TestRecord.class, - DataTemplateUtil.getSchema(TestRecord.class)); - Map requestMetadataMap = new HashMap(); + FieldDef pParam = new FieldDef<>("p", + TestRecord.class, + DataTemplateUtil.getSchema(TestRecord.class)); + Map requestMetadataMap = new HashMap<>(); DynamicRecordMetadata requestMetadata = new DynamicRecordMetadata("action", Collections.>singleton(pParam)); @@ -268,7 +268,7 @@ public void testActionRequestInputIsReadOnly() DynamicRecordMetadata responseMetadata = new DynamicRecordMetadata("action", Collections.>emptyList()); - Map responseMetadataMap = new HashMap(); + Map responseMetadataMap = new HashMap<>(); responseMetadataMap.put("action", responseMetadata); ResourceSpec resourceSpec = new ResourceSpecImpl(Collections.emptySet(), @@ -281,7 +281,7 @@ public void testActionRequestInputIsReadOnly() Collections. emptyMap()); ActionRequestBuilder, TestRecord> builder = - new ActionRequestBuilder, TestRecord>( + new ActionRequestBuilder<>( TEST_URI, TestRecord.class, resourceSpec, @@ -289,7 +289,7 @@ public void testActionRequestInputIsReadOnly() TestRecord testRecord1 = new TestRecord(); TestRecord testRecord2 = new TestRecord(); ComplexResourceKey key = - new ComplexResourceKey(testRecord1, testRecord2); + new ComplexResourceKey<>(testRecord1, testRecord2); ActionRequest request = builder.name("action").setParam(pParam, testRecord1).id(key).build(); @@ -318,11 +318,11 @@ public Object[][] batchGetWithProjections() //"test?fields=message,id&ids=1&ids=2&ids=3" //"test?fields=message,id&ids=List(1,2,3)" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("2"); idSet.add("3"); @@ -342,7 +342,7 @@ public Object[][] batchGetWithProjections() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "batchGetWithProjections") public void testBatchGetRequestBuilder(URIDetails expectedURIDetails) { - BatchGetRequestBuilder builder = new BatchGetRequestBuilder( + BatchGetRequestBuilder builder = new BatchGetRequestBuilder<>( TEST_URI, TestRecord.class, _COLL_SPEC, @@ -350,8 +350,8 @@ public void testBatchGetRequestBuilder(URIDetails expectedURIDetails) BatchGetRequest request = builder.ids(1L, 2L, 3L).fields(TestRecord.fields().id(), TestRecord.fields().message()).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); - Assert.assertEquals(request.getObjectIds(), new HashSet(Arrays.asList(1L, 2L, 3L))); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( + Assert.assertEquals(request.getObjectIds(), new HashSet<>(Arrays.asList(1L, 2L, 3L))); + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( TestRecord.fields().id(), TestRecord.fields().message()))); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); @@ -364,7 +364,7 @@ public void testBatchGetRequestBuilder(URIDetails expectedURIDetails) public void testBatchGetKVInputIsReadOnly() { BatchGetRequestBuilder, TestRecord> builder = - new BatchGetRequestBuilder, TestRecord>( + new BatchGetRequestBuilder<>( TEST_URI, TestRecord.class, _COMPLEX_KEY_SPEC, @@ -373,7 +373,7 @@ public void testBatchGetKVInputIsReadOnly() TestRecord testRecord1 = new TestRecord(); TestRecord testRecord2 = new TestRecord(); ComplexResourceKey key = - new ComplexResourceKey(testRecord1, testRecord2); + new ComplexResourceKey<>(testRecord1, testRecord2); BatchGetKVRequest, TestRecord> request = builder.ids(key).buildKV(); @@ -397,7 +397,7 @@ public void testBatchGetKVInputIsReadOnly() public void testBatchGetEntityInputIsReadOnly() { BatchGetEntityRequestBuilder, TestRecord> builder = - new BatchGetEntityRequestBuilder, TestRecord>( + new BatchGetEntityRequestBuilder<>( TEST_URI, _COMPLEX_KEY_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); @@ -405,7 +405,7 @@ public void testBatchGetEntityInputIsReadOnly() TestRecord testRecord1 = new TestRecord(); TestRecord testRecord2 = new TestRecord(); ComplexResourceKey key = - new ComplexResourceKey(testRecord1, testRecord2); + new ComplexResourceKey<>(testRecord1, testRecord2); BatchGetEntityRequest, TestRecord> request = builder.ids(key).build(); @@ -431,17 +431,17 @@ public Object[][] batchGetWithEncoding() //"test?fields=message,id&ids=ampersand%3D%2526%2526%26equals%3D%253D%253D&ids=ampersand%3D%2526%26equals%3D%253D" //"test?fields=message,id&ids=List((ampersand:%26%26,equals:%3D%3D),(ampersand:%26,equals:%3D))" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); //Note that we need two different ID sets, one for V1 and one for V2 since batch operations on compound keys //are unique. - final Set idSetV1 = new HashSet(); + final Set idSetV1 = new HashSet<>(); idSetV1.add("ampersand=%26%26&equals=%3D%3D"); idSetV1.add("ampersand=%26&equals=%3D"); - final Set idSetV2 = new HashSet(); + final Set idSetV2 = new HashSet<>(); final DataMap map1 = new DataMap(); map1.put("ampersand", "&&"); map1.put("equals", "=="); @@ -468,7 +468,7 @@ public Object[][] batchGetWithEncoding() public void testBatchGetCompoundKeyRequestBuilder(URIDetails expectedURIDetails) { BatchGetRequestBuilder builder = - new BatchGetRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, + new BatchGetRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); CompoundKey key1 = new CompoundKey(); @@ -484,10 +484,10 @@ public void testBatchGetCompoundKeyRequestBuilder(URIDetails expectedURIDetails) testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); // Compare key sets. Note that have to convert keys to Strings as the request internally converts them to string - HashSet expectedIds = new HashSet(Arrays.asList(key1, key2)); + HashSet expectedIds = new HashSet<>(Arrays.asList(key1, key2)); Assert.assertEquals(request.getObjectIds(), expectedIds); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( - TestRecord.fields().id(), TestRecord.fields().message()))); + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( + TestRecord.fields().id(), TestRecord.fields().message()))); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); @@ -506,7 +506,7 @@ private CompoundKey buildCompoundKey() private Map getCompoundKeyFieldTypes() { - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put("part1", new CompoundKey.TypeInfo(Long.class, Long.class)); fieldTypes.put("part2", new CompoundKey.TypeInfo(String.class, String.class)); return fieldTypes; @@ -536,7 +536,7 @@ public Object[][] compoundKey() public void testGetCompoundKeyRequestBuilder(URIDetails expectedURIDetails) { GetRequestBuilder builder = - new GetRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); CompoundKey key = buildCompoundKey(); @@ -576,7 +576,7 @@ public Object[][] noEntity() public void testCreateCompoundKeyRequestBuilder(URIDetails expectedURIDetails) { CreateRequestBuilder builder = - new CreateRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new CreateRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); TestRecord record = new TestRecord().setMessage("foo"); @@ -593,7 +593,7 @@ public void testCreateCompoundKeyRequestBuilder(URIDetails expectedURIDetails) public void testUpdateCompoundKeyRequestBuilder(URIDetails expectedURIDetails) { UpdateRequestBuilder builder = - new UpdateRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new UpdateRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); TestRecord record = new TestRecord().setMessage("foo"); UpdateRequest request = builder.id(buildCompoundKey()).input(record).build(); @@ -613,7 +613,7 @@ public void testPartialUpdateCompoundKeyRequestBuilder(URIDetails expectedURIDet throws CloneNotSupportedException { PartialUpdateRequestBuilder builder = - new PartialUpdateRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new PartialUpdateRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); TestRecord t1 = new TestRecord(); TestRecord t2 = new TestRecord(t1.data().copy()); @@ -639,11 +639,11 @@ public Object[][] batchCompoundKey() //Note that we need two different ID sets, one for V1 and one for V2 since batch operations on compound keys //are unique. - final Set idSetV1 = new HashSet(); + final Set idSetV1 = new HashSet<>(); idSetV1.add("part1=1&part2=2"); idSetV1.add("part1=11&part2=22"); - final Set idSetV2 = new HashSet(); + final Set idSetV2 = new HashSet<>(); final DataMap id1 = new DataMap(); id1.put("part1", "1"); id1.put("part2", "2"); @@ -669,9 +669,9 @@ public Object[][] batchCompoundKey() public void testBatchUpdateCompoundKeyRequestBuilder(URIDetails expectedURIDetails) { BatchUpdateRequestBuilder builder = - new BatchUpdateRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new BatchUpdateRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); - Map inputs = new HashMap(); + Map inputs = new HashMap<>(); CompoundKey key1 = new CompoundKey().append("part1", 1L).append("part2", "2"); CompoundKey key2 = new CompoundKey().append("part1", 11L).append("part2", "22"); TestRecord t1 = new TestRecord().setId(1L).setMessage("1"); @@ -679,7 +679,7 @@ public void testBatchUpdateCompoundKeyRequestBuilder(URIDetails expectedURIDetai inputs.put(key1, t1); inputs.put(key2, t2); - BatchRequest expectedRequest = new BatchRequest(new DataMap(), TestRecord.class); + BatchRequest expectedRequest = new BatchRequest<>(new DataMap(), TestRecord.class); expectedRequest.getEntities().put(toEntityKey(key1, expectedURIDetails.getProtocolVersion()), t1); expectedRequest.getEntities().put(toEntityKey(key2, expectedURIDetails.getProtocolVersion()), t2); @@ -690,11 +690,11 @@ public void testBatchUpdateCompoundKeyRequestBuilder(URIDetails expectedURIDetai Assert.assertEquals(request.isIdempotent(), true); KeyValueRecordFactory factory = - new KeyValueRecordFactory(CompoundKey.class, - null, - null, - getCompoundKeyFieldTypes(), - TestRecord.class); + new KeyValueRecordFactory<>(CompoundKey.class, + null, + null, + getCompoundKeyFieldTypes(), + TestRecord.class); @SuppressWarnings({"unchecked","rawtypes"}) CollectionRequest collectionRequest = buildCollectionRequest(factory, new CompoundKey[]{key1, key2}, @@ -714,9 +714,9 @@ public void testBatchPartialUpdateCompoundKeyRequestBuilder(URIDetails expectedU throws CloneNotSupportedException { BatchPartialUpdateRequestBuilder builder = - new BatchPartialUpdateRequestBuilder(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new BatchPartialUpdateRequestBuilder<>(TEST_URI, TestRecord.class, _ASSOC_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); - Map> inputs = new HashMap>(); + Map> inputs = new HashMap<>(); CompoundKey key1 = new CompoundKey().append("part1", 1L).append("part2", "2"); CompoundKey key2 = new CompoundKey().append("part1", 11L).append("part2", "22"); TestRecord t1 = new TestRecord().setId(1L).setMessage("1"); @@ -742,11 +742,11 @@ public void testBatchPartialUpdateCompoundKeyRequestBuilder(URIDetails expectedU @SuppressWarnings({"unchecked","rawtypes"}) KeyValueRecordFactory factory = - new KeyValueRecordFactory(CompoundKey.class, - null, - null, - getCompoundKeyFieldTypes(), - PatchRequest.class); + new KeyValueRecordFactory<>(CompoundKey.class, + null, + null, + getCompoundKeyFieldTypes(), + PatchRequest.class); @SuppressWarnings({"unchecked","rawtypes"}) CollectionRequest collectionRequest = buildCollectionRequest(factory, new CompoundKey[]{key1, key2}, @@ -764,16 +764,16 @@ public void testBatchPartialUpdateCompoundKeyRequestBuilder(URIDetails expectedU @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "batchGetWithProjections") public void testBatchGetRequestBuilderCollectionIds(URIDetails expectedURIDetails) { - BatchGetRequestBuilder builder = new BatchGetRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + BatchGetRequestBuilder builder = new BatchGetRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); List ids = Arrays.asList(1L, 2L, 3L); BatchGetRequest request = builder.ids(ids).fields(TestRecord.fields().id(), TestRecord.fields().message()).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); - Assert.assertEquals(request.getObjectIds(), new HashSet(Arrays.asList(1L, 2L, 3L))); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( - TestRecord.fields().id(), TestRecord.fields().message()))); + Assert.assertEquals(request.getObjectIds(), new HashSet<>(Arrays.asList(1L, 2L, 3L))); + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( + TestRecord.fields().id(), TestRecord.fields().message()))); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); @@ -787,7 +787,7 @@ public Object[][] batch() //"test?ids=1&ids=2&ids=3" //"test?ids=List(1,2,3)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("2"); idSet.add("3"); @@ -808,8 +808,8 @@ public Object[][] batch() public void testBatchUpdateRequestBuilder(URIDetails expectedURIDetails) { BatchUpdateRequestBuilder builder = - new BatchUpdateRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); - Map updates = new HashMap(); + new BatchUpdateRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + Map updates = new HashMap<>(); updates.put(1L, new TestRecord()); updates.put(2L, new TestRecord()); updates.put(3L, new TestRecord()); @@ -819,22 +819,22 @@ public void testBatchUpdateRequestBuilder(URIDetails expectedURIDetails) .appendSingleAttachment(_dataSourceWriterB) .build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); - Assert.assertEquals(request.getObjectIds(), new HashSet(Arrays.asList(1L, 2L, 3L))); + Assert.assertEquals(request.getObjectIds(), new HashSet<>(Arrays.asList(1L, 2L, 3L))); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), true); - BatchRequest expectedRequest = new BatchRequest(new DataMap(), TestRecord.class); + BatchRequest expectedRequest = new BatchRequest<>(new DataMap(), TestRecord.class); expectedRequest.getEntities().put("1", new TestRecord()); expectedRequest.getEntities().put("2", new TestRecord()); expectedRequest.getEntities().put("3", new TestRecord()); @SuppressWarnings({"unchecked","rawtypes"}) KeyValueRecordFactory factory = - new KeyValueRecordFactory(Long.class, - null, - null, - null, - TestRecord.class); + new KeyValueRecordFactory<>(Long.class, + null, + null, + null, + TestRecord.class); @SuppressWarnings({"unchecked","rawtypes"}) CollectionRequest collectionRequest = buildCollectionRequest(factory, @@ -856,40 +856,40 @@ public void testBatchUpdateRequestBuilder(URIDetails expectedURIDetails) public void testBatchPartialUpdateRequestBuilder(URIDetails expectedURIDetails) { BatchPartialUpdateRequestBuilder builder = - new BatchPartialUpdateRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new BatchPartialUpdateRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); - builder.input(1L, new PatchRequest()); - builder.input(2L, new PatchRequest()); - builder.input(3L, new PatchRequest()); + builder.input(1L, new PatchRequest<>()); + builder.input(2L, new PatchRequest<>()); + builder.input(3L, new PatchRequest<>()); BatchPartialUpdateRequest request = builder .appendSingleAttachment(_dataSourceWriterA) .appendMultipleAttachments(_dataSourceIterator) .appendSingleAttachment(_dataSourceWriterB) .build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); - Assert.assertEquals(request.getObjectIds(), new HashSet(Arrays.asList(1L, 2L, 3L))); + Assert.assertEquals(request.getObjectIds(), new HashSet<>(Arrays.asList(1L, 2L, 3L))); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), false); // verify partialUpdateInputMap Map> expectedPartialUpdateMap = new HashMap<>(); - expectedPartialUpdateMap.put(1L, new PatchRequest()); - expectedPartialUpdateMap.put(2L, new PatchRequest()); - expectedPartialUpdateMap.put(3L, new PatchRequest()); + expectedPartialUpdateMap.put(1L, new PatchRequest<>()); + expectedPartialUpdateMap.put(2L, new PatchRequest<>()); + expectedPartialUpdateMap.put(3L, new PatchRequest<>()); Assert.assertNotNull(request.getPartialUpdateInputMap()); Assert.assertEquals(request.getPartialUpdateInputMap(), expectedPartialUpdateMap); @SuppressWarnings({"unchecked","rawtypes"}) BatchRequest> expectedRequest = new BatchRequest(new DataMap(), PatchRequest.class); - expectedRequest.getEntities().put("1", new PatchRequest()); - expectedRequest.getEntities().put("2", new PatchRequest()); - expectedRequest.getEntities().put("3", new PatchRequest()); + expectedRequest.getEntities().put("1", new PatchRequest<>()); + expectedRequest.getEntities().put("2", new PatchRequest<>()); + expectedRequest.getEntities().put("3", new PatchRequest<>()); KeyValueRecordFactory factory = - new KeyValueRecordFactory(Long.class, - null, - null, - null, - PatchRequest.class); + new KeyValueRecordFactory<>(Long.class, + null, + null, + null, + PatchRequest.class); CollectionRequest collectionRequest = buildCollectionRequest(factory, new Long[]{1L, 2L, 3L}, @@ -908,10 +908,10 @@ public void testBatchPartialUpdateRequestBuilder(URIDetails expectedURIDetails) public void testBatchDeleteRequestBuilder(URIDetails expectedURIDetails) { BatchDeleteRequestBuilder builder = - new BatchDeleteRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new BatchDeleteRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); BatchDeleteRequest request = builder.ids(1L, 2L, 3L).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); - Assert.assertEquals(request.getObjectIds(), new HashSet(Arrays.asList(1L, 2L, 3L))); + Assert.assertEquals(request.getObjectIds(), new HashSet<>(Arrays.asList(1L, 2L, 3L))); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), true); @@ -922,7 +922,7 @@ public void testBatchDeleteRequestBuilder(URIDetails expectedURIDetails) public void testBatchCreateRequestBuilder(URIDetails expectedURIDetails) { BatchCreateRequestBuilder builder = - new BatchCreateRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new BatchCreateRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); List newRecords = Arrays.asList(new TestRecord(), new TestRecord(), new TestRecord()); BatchCreateRequest request = builder.inputs(newRecords) .appendSingleAttachment(_dataSourceWriterA) @@ -945,7 +945,7 @@ public void testBatchCreateRequestBuilder(URIDetails expectedURIDetails) Assert.assertTrue(e instanceof UnsupportedOperationException); } - CollectionRequest expectedRequest = new CollectionRequest(new DataMap(), TestRecord.class); + CollectionRequest expectedRequest = new CollectionRequest<>(new DataMap(), TestRecord.class); expectedRequest.getElements().addAll(newRecords); checkBasicRequest(request, expectedURIDetails, @@ -960,10 +960,10 @@ public void testBatchCreateRequestBuilder(URIDetails expectedURIDetails) public void testBatchCreateRequestInputIsReadOnly() { BatchCreateRequestBuilder builder = - new BatchCreateRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchCreateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); TestRecord testRecord = new TestRecord(); List newRecords = Arrays.asList(testRecord); BatchCreateRequest request = builder.inputs(newRecords).build(); @@ -983,10 +983,10 @@ public void testBatchCreateRequestInputIsReadOnly() public void testBatchCreateIdRequestInputIsReadOnly() { BatchCreateIdRequestBuilder builder = - new BatchCreateIdRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchCreateIdRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); TestRecord testRecord = new TestRecord(); List newRecords = Arrays.asList(testRecord); BatchCreateIdRequest request = builder.inputs(newRecords).build(); @@ -1004,10 +1004,10 @@ public void testBatchCreateIdRequestInputIsReadOnly() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "noEntity") public void testCreateRequestBuilder(URIDetails expectedURIDetails) { - CreateRequestBuilder builder = new CreateRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + CreateRequestBuilder builder = new CreateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); CreateRequest request = builder.input(new TestRecord()) .appendSingleAttachment(_dataSourceWriterA) .appendMultipleAttachments(_dataSourceIterator) @@ -1055,10 +1055,10 @@ public Object[][] singleEntity() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "singleEntity") public void testDeleteRequestBuilder(URIDetails expectedURIDetails) { - DeleteRequestBuilder builder = new DeleteRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + DeleteRequestBuilder builder = new DeleteRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); DeleteRequest request = builder.id(1L).build(); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), true); @@ -1074,8 +1074,8 @@ public void testDeleteRequestBuilder(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "noEntity") public void testDeleteRequestBuilderWithKeylessResource(URIDetails expectedURIDetails) { - DeleteRequestBuilder builder = new DeleteRequestBuilder(TEST_URI, TestRecord.class, - _SIMPLE_RESOURCE_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + DeleteRequestBuilder builder = new DeleteRequestBuilder<>(TEST_URI, TestRecord.class, + _SIMPLE_RESOURCE_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); DeleteRequest request = builder.build(); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), true); @@ -1095,11 +1095,11 @@ public Object[][] search1() //"test/key=a%3Ab?count=4&fields=message,id&p=42&q=search&start=1" //"test/(key:a%3Ab)?count=4&fields=message,id&p=42&q=search&start=1" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("p", "42"); queryParamsMap.put("q", "search"); queryParamsMap.put("start", "1"); @@ -1120,10 +1120,10 @@ public Object[][] search1() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "search1") public void testFindRequestBuilder1(URIDetails expectedURIDetails) { - FindRequestBuilder builder = new FindRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + FindRequestBuilder builder = new FindRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); FindRequest request = builder.name("search") .assocKey("key", "a:b") @@ -1133,7 +1133,7 @@ public void testFindRequestBuilder1(URIDetails expectedURIDetails) .build(); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( TestRecord.fields().id(), TestRecord.fields().message()))); checkBasicRequest(request, expectedURIDetails, @@ -1150,7 +1150,7 @@ public Object[][] search2() //"test/key=a%3Ab?p=42&q=search&start=1" //"test/(key:a%3Ab)?p=42&q=search&start=1" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("p", "42"); queryParamsMap.put("q", "search"); queryParamsMap.put("start", "1"); @@ -1170,10 +1170,10 @@ public Object[][] search2() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "search2") public void testFindRequestBuilder2(URIDetails expectedURIDetails) { - FindRequestBuilder builder = new FindRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + FindRequestBuilder builder = new FindRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); FindRequest request = builder.name("search") .assocKey("key", "a:b") .paginateStart(1) @@ -1197,7 +1197,7 @@ public Object[][] search3() //"test/key=a%3Ab?count=4&p=42&q=search" //"test/(key:a%3Ab)?count=4&p=42&q=search" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("p", "42"); queryParamsMap.put("q", "search"); queryParamsMap.put("count", "4"); @@ -1217,10 +1217,10 @@ public Object[][] search3() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "search3") public void testFindRequestBuilder3(URIDetails expectedURIDetails) { - FindRequestBuilder builder = new FindRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + FindRequestBuilder builder = new FindRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); FindRequest request = builder.name("search") .assocKey("key", "a:b") .paginateCount(4) @@ -1244,11 +1244,11 @@ public Object[][] getAll1() //"test?count=4&fields=message,id&start=1" //"test?count=4&fields=message,id&start=1" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("count", "4"); queryParamsMap.put("start", "1"); @@ -1268,7 +1268,7 @@ public Object[][] getAll1() public void testGetAllRequestBuilder1(URIDetails expectedURIDetails) { GetAllRequestBuilder builder = - new GetAllRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new GetAllRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); GetAllRequest request = builder.paginate(1, 4) @@ -1276,7 +1276,7 @@ public void testGetAllRequestBuilder1(URIDetails expectedURIDetails) .build(); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( TestRecord.fields().id(), TestRecord.fields().message()))); checkBasicRequest(request, expectedURIDetails, @@ -1293,7 +1293,7 @@ public Object[][] getAll2() //"test?start=1" //"test?start=1" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("start", "1"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test", @@ -1312,7 +1312,7 @@ public Object[][] getAll2() public void testGetAllRequestBuilder2(URIDetails expectedURIDetails) { GetAllRequestBuilder builder = - new GetAllRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new GetAllRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); GetAllRequest request = builder.paginateStart(1).build(); Assert.assertEquals(request.isSafe(), true); @@ -1332,7 +1332,7 @@ public Object[][] getAll3() //"test?count=4" //"test?count=4" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("count", "4"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test", @@ -1351,7 +1351,7 @@ public Object[][] getAll3() public void testGetAllRequestBuilder3(URIDetails expectedURIDetails) { GetAllRequestBuilder builder = - new GetAllRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + new GetAllRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); GetAllRequest request = builder.paginateCount(4).build(); Assert.assertEquals(request.isSafe(), true); @@ -1370,7 +1370,7 @@ public Object[][] getWithProjection() //Sample URIs: //"test/1?fields=message,id" //"test/1?fields=message,id" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); @@ -1389,12 +1389,12 @@ public Object[][] getWithProjection() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "getWithProjection") public void testGetRequestBuilder(URIDetails expectedURIDetails) { - GetRequestBuilder builder = new GetRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); + GetRequestBuilder builder = new GetRequestBuilder<>(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); GetRequest request = builder.id(1L).fields(TestRecord.fields().id(), TestRecord.fields().message()).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); Assert.assertEquals(request.getObjectId(), Long.valueOf(1L)); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( - TestRecord.fields().id(), TestRecord.fields().message()))); + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( + TestRecord.fields().id(), TestRecord.fields().message()))); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); @@ -1409,20 +1409,20 @@ public void testGetRequestBuilder(URIDetails expectedURIDetails) @Test public void testRestliRequestOptionsDefault() { - GetRequestBuilder builder = new GetRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + GetRequestBuilder builder = new GetRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); Assert.assertEquals(builder.id(1L).build().getRequestOptions(), RestliRequestOptions.DEFAULT_OPTIONS); } @Test public void testRestliRequestOptionsOverride() { - GetRequestBuilder builder = new GetRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + GetRequestBuilder builder = new GetRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); RestliRequestOptions overrideOptions = new RestliRequestOptionsBuilder().setProtocolVersionOption(ProtocolVersionOption.FORCE_USE_NEXT).build(); Assert.assertEquals(builder.id(1L).setRequestOptions(overrideOptions).build().getRequestOptions(), overrideOptions); @@ -1449,7 +1449,7 @@ public Object[][] getOnKeyless() //"test?fields=message,id" //"test?fields=message,id" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("message"); fieldSet.add("id"); @@ -1468,14 +1468,14 @@ public Object[][] getOnKeyless() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "getOnKeyless") public void testGetRequestBuilderWithKeylessResource(URIDetails expectedURIDetails) { - GetRequestBuilder builder = new GetRequestBuilder(TEST_URI, - TestRecord.class, - _SIMPLE_RESOURCE_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + GetRequestBuilder builder = new GetRequestBuilder<>(TEST_URI, + TestRecord.class, + _SIMPLE_RESOURCE_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); GetRequest request = builder.fields(TestRecord.fields().id(), TestRecord.fields().message()).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); Assert.assertEquals(request.getObjectId(), null); - Assert.assertEquals(request.getFields(), new HashSet(Arrays.asList( + Assert.assertEquals(request.getFields(), new HashSet<>(Arrays.asList( TestRecord.fields().id(), TestRecord.fields().message()))); Assert.assertEquals(request.isSafe(), true); Assert.assertEquals(request.isIdempotent(), true); @@ -1495,7 +1495,7 @@ public Object[][] builderParam() //"test/1?arrayKey1=3&arrayKey1=4&arrayKey1=5&arrayKey2=3&arrayKey2=4&arrayKey2=5&simpleKey=2" //"test/1?arrayKey1=List(3,4,5)&arrayKey2=List(3,4,5)&simpleKey=2" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("simpleKey", "2"); final DataList arrayKey1List = new DataList(); arrayKey1List.add("3"); @@ -1523,10 +1523,10 @@ public Object[][] builderParam() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "builderParam") public void testBuilderParam(URIDetails expectedURIDetails) { - final GetRequestBuilder builder = new GetRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + final GetRequestBuilder builder = new GetRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); final Collection coll = Arrays.asList(3, 4, 5); final IntegerArray array = new IntegerArray(coll); final GetRequest request = builder @@ -1542,10 +1542,10 @@ public void testBuilderParam(URIDetails expectedURIDetails) public void testPartialUpdateRequestBuilder(URIDetails expectedURIDetails) throws Exception { PartialUpdateRequestBuilder builder = - new PartialUpdateRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new PartialUpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); TestRecord t1 = new TestRecord(); TestRecord t2 = new TestRecord(t1.data().copy()); t2.setId(1L); @@ -1569,10 +1569,10 @@ public void testPartialUpdateRequestBuilder(URIDetails expectedURIDetails) throw @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "noEntity") public void testPartialUpdateRequestBuilderWithKeylessResource(URIDetails expectedURIDetails) throws Exception { - PartialUpdateRequestBuilder builder = new PartialUpdateRequestBuilder(TEST_URI, - TestRecord.class, - _SIMPLE_RESOURCE_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + PartialUpdateRequestBuilder builder = new PartialUpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _SIMPLE_RESOURCE_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); TestRecord t1 = new TestRecord(); TestRecord t2 = new TestRecord(t1.data().copy()); t2.setId(1L); @@ -1593,10 +1593,10 @@ public void testPartialUpdateRequestBuilderWithKeylessResource(URIDetails expect @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "singleEntity") public void testUpdateRequestBuilder(URIDetails expectedURIDetails) { - UpdateRequestBuilder builder = new UpdateRequestBuilder(TEST_URI, - TestRecord.class, - _COLL_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + UpdateRequestBuilder builder = new UpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COLL_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); UpdateRequest request = builder.id(1L).input(new TestRecord()) .appendSingleAttachment(_dataSourceWriterA) .appendMultipleAttachments(_dataSourceIterator) @@ -1616,10 +1616,10 @@ public void testUpdateRequestBuilder(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "noEntity") public void testUpdateRequestBuilderWithKeylessResource(URIDetails expectedURIDetails) { - UpdateRequestBuilder builder = new UpdateRequestBuilder(TEST_URI, - TestRecord.class, - _SIMPLE_RESOURCE_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + UpdateRequestBuilder builder = new UpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _SIMPLE_RESOURCE_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); UpdateRequest request = builder.input(new TestRecord()).build(); Assert.assertEquals(request.isSafe(), false); Assert.assertEquals(request.isIdempotent(), true); @@ -1642,7 +1642,7 @@ public Object[][] complexKeyAndParam() final DataMap idMessageMap = new DataMap(); idMessageMap.put("id", "123"); idMessageMap.put("message", "ParamMessage"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("testParam", idMessageMap); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -1661,10 +1661,10 @@ public Object[][] complexKeyAndParam() public void testComplexKeyGetRequestBuilder(URIDetails expectedURIDetails) throws Exception { GetRequestBuilder, TestRecord> builder = - new GetRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new GetRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey id = buildComplexKey(1L, "KeyMessage", 10L, "ParamMessage"); RecordTemplate param1 = buildComplexParam(123, "ParamMessage"); @@ -1684,10 +1684,10 @@ Collections. emptyMap(), public void testComplexKeyDeleteRequestBuilder(URIDetails expectedURIDetails) throws Exception { DeleteRequestBuilder, TestRecord> builder = - new DeleteRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new DeleteRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey id = buildComplexKey(1L, "KeyMessage", 10L, "ParamMessage"); RecordTemplate param = buildComplexParam(123, "ParamMessage"); @@ -1713,10 +1713,10 @@ public Object[][] batchComplexKeyAndParam() final DataMap idMessageMap = new DataMap(); idMessageMap.put("id", "123"); idMessageMap.put("message", "ParamMessage"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("testParam", idMessageMap); - final Set idList = new HashSet(); + final Set idList = new HashSet<>(); final DataMap idMapOne = new DataMap(); idMapOne.put("id", "1"); idMapOne.put("message", "KeyMessage1"); @@ -1750,7 +1750,7 @@ public Object[][] batchComplexKeyAndParam() public void testComplexKeyBatchGetRequestBuilder(URIDetails expectedURIDetails) throws Exception { BatchGetRequestBuilder, TestRecord> builder = - new BatchGetRequestBuilder, TestRecord>(TEST_URI, + new BatchGetRequestBuilder<>(TEST_URI, TestRecord.class, _COMPLEX_KEY_SPEC, RestliRequestOptions.DEFAULT_OPTIONS); @@ -1777,10 +1777,10 @@ public void testComplexKeyBatchGetRequestBuilder(URIDetails expectedURIDetails) public void testComplexKeyBatchUpdateRequestBuilder(URIDetails expectedURIDetails) throws Exception { BatchUpdateRequestBuilder, TestRecord> builder = - new BatchUpdateRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchUpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey id1 = buildComplexKey(1L, "KeyMessage1", 10L, "ParamMessage1"); ComplexResourceKey id2 = @@ -1793,7 +1793,7 @@ public void testComplexKeyBatchUpdateRequestBuilder(URIDetails expectedURIDetail builder.input(id1, t1).input(id2, t2).setParam("testParam", param).build(); // using toStringFull (which is deprecated) because this is only used to check v1 - BatchRequest expectedRequest = new BatchRequest(new DataMap(), TestRecord.class); + BatchRequest expectedRequest = new BatchRequest<>(new DataMap(), TestRecord.class); expectedRequest.getEntities().put(toEntityKey(id1, expectedURIDetails.getProtocolVersion()), t1); expectedRequest.getEntities().put(toEntityKey(id2, expectedURIDetails.getProtocolVersion()), t2); @@ -1803,11 +1803,11 @@ public void testComplexKeyBatchUpdateRequestBuilder(URIDetails expectedURIDetail @SuppressWarnings({"unchecked","rawtypes"}) KeyValueRecordFactory factory = - new KeyValueRecordFactory(ComplexResourceKey.class, - TestRecord.class, - TestRecord.class, - null, - TestRecord.class); + new KeyValueRecordFactory<>(ComplexResourceKey.class, + TestRecord.class, + TestRecord.class, + null, + TestRecord.class); @SuppressWarnings({"unchecked","rawtypes"}) CollectionRequest collectionRequest = buildCollectionRequest(factory, new ComplexResourceKey[]{id1, id2}, @@ -1827,10 +1827,10 @@ public void testComplexKeyBatchUpdateRequestBuilder(URIDetails expectedURIDetail public void testBatchUpdateRequestInputIsReadOnly() { BatchUpdateRequestBuilder, TestRecord> builder = - new BatchUpdateRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchUpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey id1 = buildComplexKey(1L, "KeyMessage1", 10L, "ParamMessage1"); ComplexResourceKey id2 = @@ -2006,10 +2006,10 @@ public Object[][] complexKey() public void testComplexKeyUpdateRequestBuilder(URIDetails expectedURIDetails) { UpdateRequestBuilder, TestRecord> builder = - new UpdateRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new UpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); ComplexResourceKey key = buildComplexKey(1L, "keyMessage", 2L, "paramMessage"); UpdateRequest request = builder.id(key).input(new TestRecord()).build(); @@ -2029,10 +2029,10 @@ Collections. emptyMap(), public void testComplexKeyCreateRequestBuilder(URIDetails expectedURIDetails) { CreateRequestBuilder, TestRecord> builder = - new CreateRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new CreateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); CreateRequest request = builder.input(new TestRecord()).build(); testBaseUriGeneration(request, expectedURIDetails.getProtocolVersion()); @@ -2053,7 +2053,7 @@ public Object[][] batchComplexKey() //"test?ids%5B0%5D.$params.id=2&ids%5B0%5D.$params.message=paramMessage1&ids%5B0%5D.id=1&ids%5B0%5D.message=keyMessage1&ids%5B1%5D.$params.id=4&ids%5B1%5D.$params.message=paramMessage2&ids%5B1%5D.id=3&ids%5B1%5D.message=keyMessage2" //"test?ids=List(($params:(id:2,message:paramMessage1),id:1,message:keyMessage1),($params:(id:4,message:paramMessage2),id:3,message:keyMessage2))" - final Set idList = new HashSet(); + final Set idList = new HashSet<>(); final DataMap idMapOne = new DataMap(); idMapOne.put("id", "1"); idMapOne.put("message", "keyMessage1"); @@ -2088,12 +2088,12 @@ public Object[][] batchComplexKey() public void testComplexKeyBatchPartialUpdateRequestBuilder(URIDetails expectedURIDetails) { BatchPartialUpdateRequestBuilder, TestRecord> builder = - new BatchPartialUpdateRequestBuilder, TestRecord>(TEST_URI, - TestRecord.class, - _COMPLEX_KEY_SPEC, - RestliRequestOptions.DEFAULT_OPTIONS); + new BatchPartialUpdateRequestBuilder<>(TEST_URI, + TestRecord.class, + _COMPLEX_KEY_SPEC, + RestliRequestOptions.DEFAULT_OPTIONS); Map, PatchRequest> inputs = - new HashMap, PatchRequest>(); + new HashMap<>(); ComplexResourceKey key1 = buildComplexKey(1L, "keyMessage1", 2L, "paramMessage1"); ComplexResourceKey key2 = buildComplexKey(3L, "keyMessage2", 4L, "paramMessage2"); TestRecord t1 = new TestRecord().setId(1L); @@ -2119,11 +2119,11 @@ public void testComplexKeyBatchPartialUpdateRequestBuilder(URIDetails expectedUR @SuppressWarnings({"unchecked","rawtypes"}) KeyValueRecordFactory factory = - new KeyValueRecordFactory(ComplexResourceKey.class, - TestRecord.class, - TestRecord.class, - null, - PatchRequest.class); + new KeyValueRecordFactory<>(ComplexResourceKey.class, + TestRecord.class, + TestRecord.class, + null, + PatchRequest.class); @SuppressWarnings({"unchecked","rawtypes"}) CollectionRequest collectionRequest = buildCollectionRequest(factory, new ComplexResourceKey[]{key1, key2}, @@ -2143,7 +2143,7 @@ public void testComplexKeyBatchPartialUpdateRequestBuilder(URIDetails expectedUR public void testBatchPartialUpdateRequestInputIsReadOnly() { BatchPartialUpdateRequestBuilder, TestRecord> builder = - new BatchPartialUpdateRequestBuilder, TestRecord>( + new BatchPartialUpdateRequestBuilder<>( TEST_URI, TestRecord.class, _COMPLEX_KEY_SPEC, @@ -2185,7 +2185,7 @@ public Object[][] subSubResourceAction1() //"foo/1/bar/2/baz?action=action" //"foo/1/bar/2/baz?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -2203,18 +2203,18 @@ public Object[][] subSubResourceAction1() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceAction1") public void testBuilderPathKeys1(URIDetails expectedURIDetails) { - List> fieldDefs = new ArrayList>(); - fieldDefs.add(new FieldDef("key1", Integer.class, DataTemplateUtil.getSchema(Integer.class))); - fieldDefs.add(new FieldDef("key2", Integer.class, DataTemplateUtil.getSchema(Integer.class))); + List> fieldDefs = new ArrayList<>(); + fieldDefs.add(new FieldDef<>("key1", Integer.class, DataTemplateUtil.getSchema(Integer.class))); + fieldDefs.add(new FieldDef<>("key2", Integer.class, DataTemplateUtil.getSchema(Integer.class))); DynamicRecordMetadata requestMetadata = new DynamicRecordMetadata("action", fieldDefs); - Map requestMetadataMap = new HashMap(); + Map requestMetadataMap = new HashMap<>(); requestMetadataMap.put("action", requestMetadata); DynamicRecordMetadata responseMetadata = new DynamicRecordMetadata("action", Collections.>emptyList()); - Map responseMetadataMap = new HashMap(); + Map responseMetadataMap = new HashMap<>(); responseMetadataMap.put("action", responseMetadata); ResourceSpec resourceSpec = getResourceSpecForBuilderPathKeys(); - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2232,7 +2232,7 @@ public Object[][] subSubResourceAction2() //"foo/http%3A%2F%2Fexample.com%2Fimages%2F1.png/bar/http%3A%2F%2Fexample.com%2Fimages%2F2.png/baz?action=action" //"foo/http%3A%2F%2Fexample.com%2Fimages%2F1.png/bar/http%3A%2F%2Fexample.com%2Fimages%2F2.png/baz?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -2257,7 +2257,7 @@ public void testBuilderPathKeys2(URIDetails expectedURIDetails) .name("action").pathKey("key1", "http://example.com/images/1.png").pathKey("key2", "http://example.com/images/2.png").build(); URIDetails.testUriGeneration(request, expectedURIDetails); - Map pathKeys1 = new HashMap(); + Map pathKeys1 = new HashMap<>(); pathKeys1.put("key1", "http://example.com/images/1.png"); pathKeys1.put("key2", "http://example.com/images/2.png"); testPathKeys(request, SUBRESOURCE_URI, pathKeys1); @@ -2270,7 +2270,7 @@ public Object[][] subSubResourceBatch() //"foo/1/bar/2/baz?ids=1&ids=2" //"foo/1/bar/2/baz?ids=List(1,2)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("2"); @@ -2289,7 +2289,7 @@ public Object[][] subSubResourceBatch() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceBatch") public void testBuilderPathKeys3(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2321,7 +2321,7 @@ public Object[][] subSubResourceNoEntity() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceNoEntity") public void testBuilderPathKeys4(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2352,7 +2352,7 @@ public Object[][] subSubResourceSingleEntity() @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceSingleEntity") public void testBuilderPathKeys5(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2365,7 +2365,7 @@ public void testBuilderPathKeys5(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceNoEntity") public void testBuilderPathKeys6(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2378,7 +2378,7 @@ public void testBuilderPathKeys6(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceSingleEntity") public void testBuilderPathKeys7(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2391,7 +2391,7 @@ public void testBuilderPathKeys7(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceSingleEntity") public void testBuilderPathKeys8(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2404,7 +2404,7 @@ public void testBuilderPathKeys8(URIDetails expectedURIDetails) @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "subSubResourceSingleEntity") public void testBuilderPathKeys9(URIDetails expectedURIDetails) { - Map expectedPathKeys = new HashMap(); + Map expectedPathKeys = new HashMap<>(); expectedPathKeys.put("key1", 1); expectedPathKeys.put("key2", 2); @@ -2421,7 +2421,7 @@ public Object[][] subResourceAction1() //"foo/bar/1/baz?action=action" //"foo/bar/1/baz?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "foo/bar/1/baz", @@ -2456,7 +2456,7 @@ public Object[][] subResourceAction2() //"foo/bar/http%3A%2F%2Fexample.com%2Fimages%2F1.png/baz?action=action" //"foo/bar/http%3A%2F%2Fexample.com%2Fimages%2F1.png/baz?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -2493,7 +2493,7 @@ public Object[][] subResourceBatch() //"foo/bar/1/baz?ids=1&ids=2" //"foo/bar/1/baz?ids=List(1,2)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("2"); @@ -2623,7 +2623,7 @@ public Object[][] simpleSubResourceAction1() //"foo/1/bar?action=action" //"foo/1/bar?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "foo/1/bar", @@ -2657,7 +2657,7 @@ public Object[][] simpleSubResourceAction2() //"foo/http%3A%2F%2Fexample.com%2Fimages%2F1.png/bar?action=action" //"foo/http%3A%2F%2Fexample.com%2Fimages%2F1.png/bar?action=action" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "action"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -2738,15 +2738,15 @@ public void testBuilderPathKeys23(URIDetails expectedURIDetails) private ResourceSpec getResourceSpecForBuilderPathKeys() { - List> fieldDefs = new ArrayList>(); - fieldDefs.add(new FieldDef("key1", Integer.class, DataTemplateUtil.getSchema( - Integer.class))); - fieldDefs.add(new FieldDef("key2", Integer.class, DataTemplateUtil.getSchema(Integer.class))); + List> fieldDefs = new ArrayList<>(); + fieldDefs.add(new FieldDef<>("key1", Integer.class, DataTemplateUtil.getSchema( + Integer.class))); + fieldDefs.add(new FieldDef<>("key2", Integer.class, DataTemplateUtil.getSchema(Integer.class))); DynamicRecordMetadata requestMetadata = new DynamicRecordMetadata("action", fieldDefs); - Map requestMetadataMap = new HashMap(); + Map requestMetadataMap = new HashMap<>(); requestMetadataMap.put("action", requestMetadata); DynamicRecordMetadata responseMetadata = new DynamicRecordMetadata("action", Collections.>emptyList()); - Map responseMetadataMap = new HashMap(); + Map responseMetadataMap = new HashMap<>(); responseMetadataMap.put("action", responseMetadata); return new ResourceSpecImpl(Collections.emptySet(), requestMetadataMap, responseMetadataMap); } @@ -2758,7 +2758,7 @@ public Object[][] noEntityWithParam() //"test?foo=bar" //"test?foo=bar" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo", "bar"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test", @@ -2788,7 +2788,7 @@ public Object[][] entityWithParam() //"test/3?foo=bar" //"test/3?foo=bar" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo", "bar"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -2850,11 +2850,11 @@ public Object[][] batchWithParam() //"test?foo=bar&ids=1&ids=2" //"test?foo=bar&ids=List(1,2)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("2"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo", "bar"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test", @@ -2899,10 +2899,10 @@ public Object[][] batchSingleWithParam() //"test?foo=bar&ids=1" //"test?foo=bar&ids=List(1)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo", "bar"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test", @@ -2929,7 +2929,7 @@ public void testCrudBuilderParams10(URIDetails expectedURIDetails) public void testCrudBuilderParams11(URIDetails expectedURIDetails) { Request> request = new BatchPartialUpdateRequestBuilder(TEST_URI, TestRecord.class, _COLL_SPEC, RestliRequestOptions.DEFAULT_OPTIONS) - .input(1L, new PatchRequest()).setParam("foo", "bar").build(); + .input(1L, new PatchRequest<>()).setParam("foo", "bar").build(); URIDetails.testUriGeneration(request, expectedURIDetails); } @@ -2965,7 +2965,7 @@ public Object[][] encodingEqualsAnd1() //"test/3?foo=bar%26baz%3Dqux" //"test/3?foo=bar%26baz%3Dqux" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo", "bar&baz=qux"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -2995,7 +2995,7 @@ public Object[][] encodingEqualsAnd2() //"test/3?foo%26bar%3Dbaz=qux" //"test/3?foo%26bar%3Dbaz=qux" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo&bar=baz", "qux"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -3025,7 +3025,7 @@ public Object[][] encodingSlash() //"test/3?foo/bar=baz/qux" //"test/3?foo/bar=baz/qux" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo/bar", "baz/qux"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -3055,7 +3055,7 @@ public Object[][] encodingColon() //"test/3?foo:bar=baz:qux" //"test/3?foo%3Abar=baz%3Aqux" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo:bar", "baz:qux"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -3085,7 +3085,7 @@ public Object[][] encodingQuestionMark() //"test/3?foo?bar=baz?qux" //"test/3?foo?bar=baz?qux" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("foo?bar", "baz?qux"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "test/3", @@ -3182,8 +3182,8 @@ public void testBuilderExceptions() private ComplexResourceKey buildComplexKey(long keyId, String keyMessage, long paramId, String paramMessage) { ComplexResourceKey id = - new ComplexResourceKey(new TestRecord(), - new TestRecord()); + new ComplexResourceKey<>(new TestRecord(), + new TestRecord()); id.getKey().setId(keyId); id.getKey().setMessage(keyMessage); id.getParams().setId(paramId); @@ -3339,7 +3339,7 @@ public void run() } }); - final List keysToEdit = new ArrayList(); + final List keysToEdit = new ArrayList<>(); for (Object key: pathKeys.values()) { if (key instanceof CompoundKey || key instanceof ComplexResourceKey) @@ -3372,7 +3372,7 @@ else if (keytoEdit instanceof CompoundKey) } Collection queryParamObjects = request.getQueryParamsObjects().values(); - List readOnlyTargets = new ArrayList(); + List readOnlyTargets = new ArrayList<>(); for (Object queryParamObject: queryParamObjects) { @@ -3496,7 +3496,7 @@ private void checkInputForBatchUpdateAndPatch(Request request, RecordTemplate { final TypeSpec valueType = request.getMethod() == ResourceMethod.BATCH_PARTIAL_UPDATE ? - new TypeSpec(PatchRequest.class) : + new TypeSpec<>(PatchRequest.class) : request.getResourceProperties().getValueType(); Assert.assertEquals( @@ -3519,7 +3519,7 @@ private CollectionRequest buildCol V[] values) { CollectionRequest collectionRequest = - new CollectionRequest(new DataMap(), KeyValueRecord.class); + new CollectionRequest<>(new DataMap(), KeyValueRecord.class); for (int i = 0; i < keys.length; i++) { collectionRequest.getElements().add(factory.create(keys[i], values[i])); @@ -3580,4 +3580,4 @@ public void registerDataSourceReaderCallback(RestLiDataSourceIteratorCallback ca Assert.fail("Should never be called"); } } -} \ No newline at end of file +} diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestCollectionRequestUtil.java b/restli-client/src/test/java/com/linkedin/restli/client/TestCollectionRequestUtil.java index f895ea6875..99b1cb1154 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestCollectionRequestUtil.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestCollectionRequestUtil.java @@ -47,16 +47,16 @@ public class TestCollectionRequestUtil @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "versions") public void testPrimitiveKeySingleEntity(ProtocolVersion version) { - KeyValueRecordFactory factory = new KeyValueRecordFactory(Long.class, - null, - null, - null, - TestRecord.class); + KeyValueRecordFactory factory = new KeyValueRecordFactory<>(Long.class, + null, + null, + null, + TestRecord.class); TestRecord testRecord = buildTestRecord(1L, "message"); KeyValueRecord kvRecord = factory.create(1L, testRecord); @SuppressWarnings("rawtypes") - CollectionRequest collectionRequest = new CollectionRequest(KeyValueRecord.class); + CollectionRequest collectionRequest = new CollectionRequest<>(KeyValueRecord.class); collectionRequest.getElements().add(kvRecord); @SuppressWarnings("unchecked") @@ -79,15 +79,15 @@ public void testPrimitiveKeySingleEntity(ProtocolVersion version) public void testPrimitiveKeyMultipleEntities(ProtocolVersion version) { @SuppressWarnings("rawtypes") - KeyValueRecordFactory factory = new KeyValueRecordFactory(Long.class, - null, - null, - null, - TestRecord.class); + KeyValueRecordFactory factory = new KeyValueRecordFactory<>(Long.class, + null, + null, + null, + TestRecord.class); @SuppressWarnings("rawtypes") - CollectionRequest collectionRequest = new CollectionRequest(KeyValueRecord.class); + CollectionRequest collectionRequest = new CollectionRequest<>(KeyValueRecord.class); - Map inputs = new HashMap(); + Map inputs = new HashMap<>(); long[] ids = {1L, 2L, 3L}; for (long id: ids) { @@ -124,21 +124,21 @@ public void testCompoundKeyMultipleEntities(ProtocolVersion version) CompoundKey c2 = new CompoundKey().append(key1, 3L).append(key2, 4L); CompoundKey[] keys = {c1, c2}; - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put(key1, new CompoundKey.TypeInfo(Long.class, Long.class)); fieldTypes.put(key2, new CompoundKey.TypeInfo(Long.class, Long.class)); @SuppressWarnings("rawtypes") KeyValueRecordFactory factory = - new KeyValueRecordFactory(CompoundKey.class, - null, - null, - fieldTypes, - TestRecord.class); + new KeyValueRecordFactory<>(CompoundKey.class, + null, + null, + fieldTypes, + TestRecord.class); @SuppressWarnings("rawtypes") - CollectionRequest collectionRequest = new CollectionRequest(KeyValueRecord.class); + CollectionRequest collectionRequest = new CollectionRequest<>(KeyValueRecord.class); - Map inputs = new HashMap(); + Map inputs = new HashMap<>(); for (CompoundKey key: keys) { TestRecord testRecord = buildTestRecord(1L, "message" + key.hashCode()); @@ -174,20 +174,20 @@ public void testComplexKeyMultipleEntities(ProtocolVersion version) TestRecord kp1 = buildTestRecord(2, "key params 1"); TestRecord kk2 = buildTestRecord(3, "key key 2"); TestRecord kp2 = buildTestRecord(4, "key params 2"); - ComplexResourceKey key1 = new ComplexResourceKey(kk1, kp1); - ComplexResourceKey key2 = new ComplexResourceKey(kk2, kp2); + ComplexResourceKey key1 = new ComplexResourceKey<>(kk1, kp1); + ComplexResourceKey key2 = new ComplexResourceKey<>(kk2, kp2); ComplexResourceKey keys[] = {key1, key2}; KeyValueRecordFactory factory = - new KeyValueRecordFactory(ComplexResourceKey.class, - TestRecord.class, - TestRecord.class, - null, - TestRecord.class); + new KeyValueRecordFactory<>(ComplexResourceKey.class, + TestRecord.class, + TestRecord.class, + null, + TestRecord.class); - CollectionRequest collectionRequest = new CollectionRequest(KeyValueRecord.class); + CollectionRequest collectionRequest = new CollectionRequest<>(KeyValueRecord.class); Map, TestRecord> inputs = - new HashMap, TestRecord>(); + new HashMap<>(); for (ComplexResourceKey key: keys) { TestRecord testRecord = buildTestRecord(1L, "foo"); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestDefaultScatterGatherStrategy.java b/restli-client/src/test/java/com/linkedin/restli/client/TestDefaultScatterGatherStrategy.java index f62e7adb48..bd77ecd3bd 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestDefaultScatterGatherStrategy.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestDefaultScatterGatherStrategy.java @@ -613,7 +613,7 @@ private static Response>> c for (Long id: resultKeys) { - resultMap.put(id.toString(), new UpdateEntityStatus(HttpStatus.S_200_OK.getCode(), new TestRecord().setId(id)).data()); + resultMap.put(id.toString(), new UpdateEntityStatus<>(HttpStatus.S_200_OK.getCode(), new TestRecord().setId(id)).data()); } for (Long id: errorKeys) { @@ -641,4 +641,3 @@ private RequestContext getTargetHostRequestContext(URI host) return context; } } - diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestParSeqBasedCompletionStage.java b/restli-client/src/test/java/com/linkedin/restli/client/TestParSeqBasedCompletionStage.java index d4bf18c7fc..df3804cd8b 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestParSeqBasedCompletionStage.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestParSeqBasedCompletionStage.java @@ -98,7 +98,7 @@ public void setup() throws Exception _parSeqUnitTestHelper = new ParSeqUnitTestHelper(); _parSeqUnitTestHelper.setUp(); _engine = _parSeqUnitTestHelper.getEngine(); - _parSeqBasedCompletionStageFactory = new ParSeqBasedCompletionStageFactory(_engine); + _parSeqBasedCompletionStageFactory = new ParSeqBasedCompletionStageFactory<>(_engine); } @BeforeMethod diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestRequest.java b/restli-client/src/test/java/com/linkedin/restli/client/TestRequest.java index c1b5bc4a4d..2ca37a233e 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestRequest.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestRequest.java @@ -101,7 +101,7 @@ public void testHeadersCaseInsensitiveSet() @Test public void testResourceProperties() { - Set expectedSupportedMethods = new HashSet(); + Set expectedSupportedMethods = new HashSet<>(); expectedSupportedMethods.add(ResourceMethod.GET); expectedSupportedMethods.add(ResourceMethod.BATCH_PARTIAL_UPDATE); @@ -115,17 +115,17 @@ public void testResourceProperties() TestRecord.class, Collections.emptyMap()); - Map pathKeys = new HashMap(); - pathKeys.put("id", new ComplexResourceKey(new TestRecord(), new TestRecord())); + Map pathKeys = new HashMap<>(); + pathKeys.put("id", new ComplexResourceKey<>(new TestRecord(), new TestRecord())); - Request request = new Request(ResourceMethod.GET, null, - Collections.emptyMap(), - Collections.emptyList(), - new EntityResponseDecoder(TestRecord.class), - expectedResourceSpec, Collections.emptyMap(), - Collections.>emptyMap(), null, "testRecord", - pathKeys, RestliRequestOptions.DEFAULT_OPTIONS, null); + Request request = new Request<>(ResourceMethod.GET, null, + Collections.emptyMap(), + Collections.emptyList(), + new EntityResponseDecoder<>(TestRecord.class), + expectedResourceSpec, Collections.emptyMap(), + Collections.>emptyMap(), null, "testRecord", + pathKeys, RestliRequestOptions.DEFAULT_OPTIONS, null); ResourceProperties expectedResourceProperties = new ResourcePropertiesImpl(expectedResourceSpec.getSupportedMethods(), diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestSingleEntityRequestBuilder.java b/restli-client/src/test/java/com/linkedin/restli/client/TestSingleEntityRequestBuilder.java index f070f221b7..013816c973 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestSingleEntityRequestBuilder.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestSingleEntityRequestBuilder.java @@ -31,7 +31,7 @@ public void testIdReadOnliness() { SingleEntityRequestBuilder builder = new DummySingleEntityRequestBuilder(); ComplexResourceKey originalKey = - new ComplexResourceKey( + new ComplexResourceKey<>( new TestRecord(), new TestRecord()); builder.id(originalKey); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/TestVersionNegotiation.java b/restli-client/src/test/java/com/linkedin/restli/client/TestVersionNegotiation.java index b94f390f41..b02ef7428c 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/TestVersionNegotiation.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/TestVersionNegotiation.java @@ -196,7 +196,7 @@ public void testAnnouncedVersionWithVersionPercentages(ProtocolVersion versionIn String versionPercentageInput, ProtocolVersion expectedAnnouncedVersion) { - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(RestConstants.RESTLI_PROTOCOL_VERSION_PROPERTY, versionInput); properties.put(RestConstants.RESTLI_PROTOCOL_VERSION_PERCENTAGE_PROPERTY, versionPercentageInput); ProtocolVersion announcedVersion = RestClient.getAnnouncedVersion(properties); @@ -296,4 +296,4 @@ public void testForceUseNextVersionOverride(ProtocolVersionOption protocolVersio forceUseOverrideSystemProperty); Assert.assertEquals(actualProtocolVersion, expectedProtocolVersion); } -} \ No newline at end of file +} diff --git a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/MultiplexerTestBase.java b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/MultiplexerTestBase.java index 5db9283410..a149f04daa 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/MultiplexerTestBase.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/MultiplexerTestBase.java @@ -103,7 +103,7 @@ protected static CreateRequest fakeCreateRequest(TestRecord entity) protected static Response fakeResponse(int id) { TestRecord record = fakeEntity(id); - return new ResponseImpl(HttpStatus.S_200_OK.getCode(), HEADERS, Collections.emptyList(), record, null); + return new ResponseImpl<>(HttpStatus.S_200_OK.getCode(), HEADERS, Collections.emptyList(), record, null); } protected static TestRecord fakeEntity(int id) @@ -148,7 +148,7 @@ protected static IndividualResponse fakeIndividualErrorResponse() throws IOExcep private static Map normalizeHeaderName(Map headers) { - Map normalizedHeaders = new HashMap(); + Map normalizedHeaders = new HashMap<>(); for (Map.Entry header : headers.entrySet()) { // make all header names lower case @@ -159,7 +159,7 @@ private static Map normalizeHeaderName(Map heade private static Map normalizeSetCookies(List cookies) { - Map normalizedSetCookies = new HashMap(); + Map normalizedSetCookies = new HashMap<>(); for(HttpCookie cookie : CookieUtil.decodeSetCookies(cookies)) { normalizedSetCookies.put(cookie.getName(), cookie.toString()); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedCallback.java b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedCallback.java index 1f20222d7f..2706fbc727 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedCallback.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedCallback.java @@ -41,11 +41,11 @@ public class TestMultiplexedCallback extends MultiplexerTestBase @Test public void testSuccess() throws Exception { - FutureCallback callback1 = new FutureCallback(); - FutureCallback callback2 = new FutureCallback(); + FutureCallback callback1 = new FutureCallback<>(); + FutureCallback callback2 = new FutureCallback<>(); ImmutableMap> individualCallbacks = ImmutableMap.>of(ID1, callback1, ID2, callback2); - FutureCallback aggregatedCallback = new FutureCallback(); + FutureCallback aggregatedCallback = new FutureCallback<>(); TestRecord entity1 = fakeEntity(ID1); IndividualResponse ir1 = fakeIndividualResponse(entity1); @@ -69,11 +69,11 @@ public void testSuccess() throws Exception @Test public void testError() throws Exception { - FutureCallback callback1 = new FutureCallback(); - FutureCallback callback2 = new FutureCallback(); + FutureCallback callback1 = new FutureCallback<>(); + FutureCallback callback2 = new FutureCallback<>(); ImmutableMap> individualCallbacks = ImmutableMap.>of(ID1, callback1, ID2, callback2); - FutureCallback aggregatedCallback = new FutureCallback(); + FutureCallback aggregatedCallback = new FutureCallback<>(); MultiplexedCallback multiplexedCallback = new MultiplexedCallback(individualCallbacks, aggregatedCallback); RestLiDecodingException exception = new RestLiDecodingException(null, null); @@ -87,11 +87,11 @@ public void testError() throws Exception @Test public void testMixed() throws Exception { - FutureCallback callback1 = new FutureCallback(); - FutureCallback callback2 = new FutureCallback(); + FutureCallback callback1 = new FutureCallback<>(); + FutureCallback callback2 = new FutureCallback<>(); ImmutableMap> individualCallbacks = ImmutableMap.>of(ID1, callback1, ID2, callback2); - FutureCallback aggregatedCallback = new FutureCallback(); + FutureCallback aggregatedCallback = new FutureCallback<>(); TestRecord entity1 = fakeEntity(ID1); IndividualResponse ir1 = fakeIndividualResponse(entity1); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedRequestBuilder.java b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedRequestBuilder.java index e0c2c36cb6..85b463342a 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedRequestBuilder.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexedRequestBuilder.java @@ -45,8 +45,8 @@ public class TestMultiplexedRequestBuilder extends MultiplexerTestBase { - private final NoOpCallback callback1 = new NoOpCallback(); - private final NoOpCallback callback2 = new NoOpCallback(); + private final NoOpCallback callback1 = new NoOpCallback<>(); + private final NoOpCallback callback2 = new NoOpCallback<>(); @Test(expectedExceptions = {IllegalStateException.class}) public void testEmpty() throws RestLiEncodingException @@ -117,7 +117,7 @@ public void testBody() throws IOException { TestRecord entity = fakeEntity(0); CreateRequest request = fakeCreateRequest(entity); - NoOpCallback callback = new NoOpCallback(); + NoOpCallback callback = new NoOpCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createSequentialRequest() diff --git a/restli-client/src/test/java/com/linkedin/restli/client/response/TestBatchKVResponse.java b/restli-client/src/test/java/com/linkedin/restli/client/response/TestBatchKVResponse.java index 0c562a7cc6..5bec40eb27 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/response/TestBatchKVResponse.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/response/TestBatchKVResponse.java @@ -58,12 +58,12 @@ public class TestBatchKVResponse final MyComplexKey keyPart1 = new MyComplexKey(); keyPart1.setA("dolor"); keyPart1.setB(7); - final ComplexResourceKey complexKey1 = new ComplexResourceKey(keyPart1, _EMPTY_RECORD); + final ComplexResourceKey complexKey1 = new ComplexResourceKey<>(keyPart1, _EMPTY_RECORD); final MyComplexKey keyPart2 = new MyComplexKey(); keyPart2.setA("sit"); keyPart2.setB(27); - final ComplexResourceKey complexKey2 = new ComplexResourceKey(keyPart2, _EMPTY_RECORD); + final ComplexResourceKey complexKey2 = new ComplexResourceKey<>(keyPart2, _EMPTY_RECORD); @SuppressWarnings("unchecked") final List> complexKeys = Arrays.asList(complexKey1, complexKey2); @@ -101,13 +101,13 @@ public void testDeserialization(List keys, testData.put(BatchKVResponse.RESULTS, inputResults); testData.put(BatchKVResponse.ERRORS, inputErrors); - final BatchKVResponse response = new BatchKVResponse(testData, - keyClass, - TestRecord.class, - Collections.emptyMap(), - keyKeyClass, - keyParamsClass, - protocolVersion); + final BatchKVResponse response = new BatchKVResponse<>(testData, + keyClass, + TestRecord.class, + Collections.emptyMap(), + keyKeyClass, + keyParamsClass, + protocolVersion); final Map outputResults = response.getResults(); final TestRecord outRecord = outputResults.get(resultKey); Assert.assertEquals(outRecord, outRecord); diff --git a/restli-client/src/test/java/com/linkedin/restli/client/util/TestRestliRequestUriSignature.java b/restli-client/src/test/java/com/linkedin/restli/client/util/TestRestliRequestUriSignature.java index f3f417b0a7..aa03338a8a 100644 --- a/restli-client/src/test/java/com/linkedin/restli/client/util/TestRestliRequestUriSignature.java +++ b/restli-client/src/test/java/com/linkedin/restli/client/util/TestRestliRequestUriSignature.java @@ -52,13 +52,13 @@ public class TestRestliRequestUriSignature nestedMap.put("foo", 1); nestedMap.put("bar", 2); - PATH_KEYS = new HashMap(); + PATH_KEYS = new HashMap<>(); PATH_KEYS.put("pathKey1", "value1"); PATH_KEYS.put("pathKey2", nestedMap); ID = "myID"; - QUERY_PARAMS_OBJECTS = new HashMap(); + QUERY_PARAMS_OBJECTS = new HashMap<>(); QUERY_PARAMS_OBJECTS.put("queryKey1", "value1"); QUERY_PARAMS_OBJECTS.put("queryKey2", nestedMap); } @@ -97,7 +97,7 @@ public void testPartialFields() Mockito.when(request.getPathKeys()).thenReturn(PATH_KEYS); Mockito.when(request.getQueryParamsObjects()).thenReturn(QUERY_PARAMS_OBJECTS); - final Set fields = new HashSet(Arrays.asList(SignatureField.BASE_URI_TEMPLATE, SignatureField.PATH_KEYS)); + final Set fields = new HashSet<>(Arrays.asList(SignatureField.BASE_URI_TEMPLATE, SignatureField.PATH_KEYS)); final RestliRequestUriSignature signature = new RestliRequestUriSignature(request, fields); Assert.assertEquals(signature.getMaskFields(), fields); @@ -146,9 +146,9 @@ public void testEquality() Assert.assertEquals(equalSignature1.hashCode(), equalSignature2.hashCode()); Assert.assertEquals(equalSignature1, equalSignature2); - final Set nonIDFields = new HashSet(Arrays.asList(SignatureField.BASE_URI_TEMPLATE, - SignatureField.PATH_KEYS, - SignatureField.QUERY_PARAMS)); + final Set nonIDFields = new HashSet<>(Arrays.asList(SignatureField.BASE_URI_TEMPLATE, + SignatureField.PATH_KEYS, + SignatureField.QUERY_PARAMS)); final RestliRequestUriSignature equalSignature3 = new RestliRequestUriSignature(equalRequest1, nonIDFields); final RestliRequestUriSignature equalSignature4 = new RestliRequestUriSignature(idDifferRequest, RestliRequestUriSignature.ALL_FIELDS); Assert.assertEquals(equalSignature3.hashCode(), equalSignature4.hashCode()); @@ -212,10 +212,10 @@ public void testEqualRequestWithNotEqualMask() Mockito.when(getRequest.getObjectId()).thenReturn(ID); Mockito.when(getRequest.getQueryParamsObjects()).thenReturn(QUERY_PARAMS_OBJECTS); - final List> maskFields = new ArrayList>(); + final List> maskFields = new ArrayList<>(); for (SignatureField f : SignatureField.values()) { - final Set maskFieldsWithout = new HashSet(RestliRequestUriSignature.ALL_FIELDS); + final Set maskFieldsWithout = new HashSet<>(RestliRequestUriSignature.ALL_FIELDS); maskFieldsWithout.remove(f); maskFields.add(maskFieldsWithout); } diff --git a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchEntityResponseDecoder.java b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchEntityResponseDecoder.java index 95c5d9a910..a920586e21 100644 --- a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchEntityResponseDecoder.java +++ b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchEntityResponseDecoder.java @@ -91,16 +91,16 @@ public void testDecoding(List keys, ProtocolVersion protocolVersion) data.put(BatchResponse.ERRORS, errorData); final BatchEntityResponseDecoder decoder = - new BatchEntityResponseDecoder(new TypeSpec(TestRecord.class), - new TypeSpec(String.class), - Collections.emptyMap(), - null); + new BatchEntityResponseDecoder<>(new TypeSpec<>(TestRecord.class), + new TypeSpec<>(String.class), + Collections.emptyMap(), + null); final BatchKVResponse> response = decoder.wrapResponse(data, Collections.emptyMap(), protocolVersion); final Map> results = response.getResults(); final Map errors = response.getErrors(); - final Collection uniqueKeys = new HashSet(keys); + final Collection uniqueKeys = new HashSet<>(keys); Assert.assertEquals(results.size(), uniqueKeys.size()); Assert.assertEquals(errors.size(), 1); @@ -131,10 +131,10 @@ public void testDecodingWithEmptyDataMap(List keys, ProtocolVersion prot throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException { final BatchEntityResponseDecoder decoder = - new BatchEntityResponseDecoder(new TypeSpec(TestRecord.class), - new TypeSpec(String.class), - Collections.emptyMap(), - null); + new BatchEntityResponseDecoder<>(new TypeSpec<>(TestRecord.class), + new TypeSpec<>(String.class), + Collections.emptyMap(), + null); final BatchKVResponse> response = decoder.wrapResponse(null, Collections.emptyMap(), protocolVersion); Assert.assertNull(response); diff --git a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchUpdateResponseDecoder.java b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchUpdateResponseDecoder.java index 4e4c0a1067..ea2b2cabb2 100644 --- a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchUpdateResponseDecoder.java +++ b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestBatchUpdateResponseDecoder.java @@ -55,7 +55,7 @@ public void testDecodingWithEmptyDataMap(ProtocolVersion protocolVersion) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException { final BatchUpdateResponseDecoder decoder = - new BatchUpdateResponseDecoder(new TypeSpec(String.class), Collections.emptyMap(), null); + new BatchUpdateResponseDecoder<>(new TypeSpec<>(String.class), Collections.emptyMap(), null); final BatchKVResponse response = decoder.wrapResponse(null, Collections.emptyMap(), protocolVersion); Assert.assertNull(response); diff --git a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestResponse.java b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestResponse.java index aa3dfffb2f..fe01ec7d54 100644 --- a/restli-client/src/test/java/com/linkedin/restli/internal/client/TestResponse.java +++ b/restli-client/src/test/java/com/linkedin/restli/internal/client/TestResponse.java @@ -36,9 +36,9 @@ public class TestResponse public void testHeadersCaseInsensitiveGet() { int status = 200; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("header", "value"); - Response response = new ResponseImpl(status, headers, Collections.emptyList()); + Response response = new ResponseImpl<>(status, headers, Collections.emptyList()); Assert.assertEquals(response.getHeader("HEADER"), "value"); } @@ -46,10 +46,10 @@ public void testHeadersCaseInsensitiveGet() public void testHeadersCaseInsensitiveSet() { int status = 200; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("header", "value"); headers.put("HEADER", "value"); - Response response = new ResponseImpl(status, headers, Collections.emptyList()); + Response response = new ResponseImpl<>(status, headers, Collections.emptyList()); Assert.assertEquals(response.getHeaders().size(), 1); Assert.assertEquals(response.getHeader("HEADER"), "value"); } diff --git a/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/DataAssert.java b/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/DataAssert.java index e7fb5568e6..bd4b743012 100644 --- a/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/DataAssert.java +++ b/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/DataAssert.java @@ -142,10 +142,10 @@ public static void assertDataMapsEqual(DataMap actualMap, return; } - Set failKeys = new HashSet(); + Set failKeys = new HashSet<>(); // Assert key by key so it's easy to debug on assertion failure - Set allKeys = new HashSet(actualMap.keySet()); + Set allKeys = new HashSet<>(actualMap.keySet()); allKeys.addAll(expectedMap.keySet()); for(String key : allKeys) { @@ -179,7 +179,7 @@ else if(!actualObject.equals(expectedObject)) if(!failKeys.isEmpty()) { - List errorMessages = new ArrayList(); + List errorMessages = new ArrayList<>(); errorMessages.add(failKeys.size() + " properties don't match:"); for(String k : failKeys) { @@ -219,4 +219,3 @@ private static DataMap getFixedUpDataMap(RecordTemplate recordTemplate, Validati return (DataMap) ValidateDataAgainstSchema.validate(recordTemplate, validationOptions).getFixed(); } } - diff --git a/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/MockActionResponseFactory.java b/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/MockActionResponseFactory.java index e91a43d5c4..427484e0ea 100644 --- a/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/MockActionResponseFactory.java +++ b/restli-common-testutils/src/main/java/com/linkedin/restli/common/testutils/MockActionResponseFactory.java @@ -61,8 +61,8 @@ public static ActionResponse create(Class clazz, T value) */ public static ActionResponse create(Class clazz, DataSchema schema, T value) { - final FieldDef fieldDef = new FieldDef(ActionResponse.VALUE_NAME, clazz, schema); + final FieldDef fieldDef = new FieldDef<>(ActionResponse.VALUE_NAME, clazz, schema); final RecordDataSchema entitySchema = DynamicRecordMetadata.buildSchema(ActionResponse.class.getName(), Collections.>singletonList(fieldDef)); - return new ActionResponse(value, fieldDef, entitySchema); + return new ActionResponse<>(value, fieldDef, entitySchema); } } diff --git a/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestDataAssert.java b/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestDataAssert.java index 079d999442..c3344b4bef 100644 --- a/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestDataAssert.java +++ b/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestDataAssert.java @@ -94,7 +94,7 @@ public void testIgnoreKeysInDataMapChecking() expected.put("key3", "value33"); // values are different at "key3" - DataAssert.assertDataMapsEqual(actual, expected, new HashSet(Collections.singletonList("key3")), false); + DataAssert.assertDataMapsEqual(actual, expected, new HashSet<>(Collections.singletonList("key3")), false); } @Test diff --git a/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestMockActionResponseFactory.java b/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestMockActionResponseFactory.java index 606e47cfbf..1a6d591b6e 100644 --- a/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestMockActionResponseFactory.java +++ b/restli-common-testutils/src/test/java/com/linkedin/restli/common/testutils/TestMockActionResponseFactory.java @@ -55,7 +55,7 @@ public void testDynamicSchema() record.setId(42L); record.setMessage("Lorem ipsum"); - final CollectionResponse collectionResponse = new CollectionResponse(RecordTemplateWithDefaultValue.class); + final CollectionResponse collectionResponse = new CollectionResponse<>(RecordTemplateWithDefaultValue.class); collectionResponse.getElements().add(record); @SuppressWarnings("unchecked") final ActionResponse> response = diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdEntityResponse.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdEntityResponse.java index 9c0d2aea7b..a251cab75f 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdEntityResponse.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdEntityResponse.java @@ -82,7 +82,7 @@ private List> createCollectionFromDecoder(CreateIdEnt throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { DataList elements = this.data().getDataList(CollectionResponse.ELEMENTS); - List> collection = new ArrayList>(elements.size()); + List> collection = new ArrayList<>(elements.size()); for (Object obj : elements) { DataMap dataMap = (DataMap) obj; @@ -102,4 +102,4 @@ public List> getElements() { return _collection; } -} \ No newline at end of file +} diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdResponse.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdResponse.java index 1a5ec525b8..f5d32bcc81 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdResponse.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateIdResponse.java @@ -88,7 +88,7 @@ private List> createCollectionFromDecoder(CreateIdStatusDecode throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { DataList elements = this.data().getDataList(CollectionResponse.ELEMENTS); - List> collection = new ArrayList>(elements.size()); + List> collection = new ArrayList<>(elements.size()); for (Object obj : elements) { DataMap dataMap = (DataMap) obj; diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateResponse.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateResponse.java index e9dd86e5a3..afa6e4a8ba 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateResponse.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchCreateResponse.java @@ -54,7 +54,7 @@ public BatchCreateResponse(DataMap data, CreateIdStatusDecoder entityDecoder) public BatchCreateResponse(List> elements) { super(generateDataMap(elements), CreateStatus.class); - _collection = new ArrayList(elements.size()); + _collection = new ArrayList<>(elements.size()); for (CreateIdStatus element : elements) { _collection.add(element); @@ -83,7 +83,7 @@ private List createCollectionFromDecoder(CreateIdStatusDecoder throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { DataList elements = this.data().getDataList(CollectionResponse.ELEMENTS); - List collection = new ArrayList(elements.size()); + List collection = new ArrayList<>(elements.size()); for (Object obj : elements) { DataMap dataMap = (DataMap) obj; diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchFinderCriteriaResult.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchFinderCriteriaResult.java index 3ae19f524d..34f4f5eb08 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchFinderCriteriaResult.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchFinderCriteriaResult.java @@ -126,7 +126,7 @@ public RecordDataSchema schema() public List getElements() { DataList value = (DataList) data().get(ELEMENTS); - return new DynamicRecordArray(value, _arraySchema, _elementClass); + return new DynamicRecordArray<>(value, _arraySchema, _elementClass); } /** diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchRequest.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchRequest.java index 12512c1dab..ece01fc6fa 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchRequest.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchRequest.java @@ -64,12 +64,12 @@ public DynamicRecordMap(DataMap map, MapDataSchema mapSchema, Class valueClas */ public BatchRequest(DataMap data, Class valueClass) { - this(data, new TypeSpec(valueClass)); + this(data, new TypeSpec<>(valueClass)); } private BatchRequest(DataMap data, Class valueClass, int capacity) { - this(data, new TypeSpec(valueClass), capacity); + this(data, new TypeSpec<>(valueClass), capacity); } /** @@ -120,6 +120,6 @@ public Map getEntities() { DataMap value = data().getDataMap(ENTITIES); - return new DynamicRecordMap(value, _entitiesSchema, _valueType.getType()); + return new DynamicRecordMap<>(value, _entitiesSchema, _valueType.getType()); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/BatchResponse.java b/restli-common/src/main/java/com/linkedin/restli/common/BatchResponse.java index 98af89fe11..ef48d4bece 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/BatchResponse.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/BatchResponse.java @@ -98,7 +98,7 @@ private BatchResponse(DataMap data, Class valueClass, int resultsCapacity, in _errorsSchema = new MapDataSchema(new RecordDataSchema(errorSchemaName, RecordDataSchema.RecordType.RECORD)); _errorsField = new RecordDataSchema.Field(_errorsSchema); _errorsField.setName(ERRORS, errorMessageBuilder); - + if (data().get(RESULTS) == null) { data().put(RESULTS, new DataMap(resultsCapacity)); @@ -127,7 +127,7 @@ public Map getResults() { final DataMap value = data().getDataMap(RESULTS); - return new DynamicRecordMap(value, _resultsSchema, _valueClass); + return new DynamicRecordMap<>(value, _resultsSchema, _valueClass); } /** @@ -147,7 +147,7 @@ public Map getErrors() { final DataMap value = data().getDataMap(ERRORS); - return new DynamicRecordMap(value, _errorsSchema, ErrorResponse.class); + return new DynamicRecordMap<>(value, _errorsSchema, ErrorResponse.class); } /** diff --git a/restli-common/src/main/java/com/linkedin/restli/common/CollectionRequest.java b/restli-common/src/main/java/com/linkedin/restli/common/CollectionRequest.java index bb3501f58f..77aa5ee843 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/CollectionRequest.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/CollectionRequest.java @@ -105,7 +105,7 @@ public List getElements() if (_templatedCollection == null) { DataList value = (DataList) data().get(ELEMENTS); - _templatedCollection = new DynamicRecordArray(value, _arraySchema, _elementClass); + _templatedCollection = new DynamicRecordArray<>(value, _arraySchema, _elementClass); } return _templatedCollection; diff --git a/restli-common/src/main/java/com/linkedin/restli/common/CollectionResponse.java b/restli-common/src/main/java/com/linkedin/restli/common/CollectionResponse.java index 2347536407..13df3313ec 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/CollectionResponse.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/CollectionResponse.java @@ -101,7 +101,7 @@ public List getElements() { DataList value = (DataList) data().get(ELEMENTS); - return new DynamicRecordArray(value, _arraySchema, _elementClass); + return new DynamicRecordArray<>(value, _arraySchema, _elementClass); } public boolean hasPaging() diff --git a/restli-common/src/main/java/com/linkedin/restli/common/ComplexKeySpec.java b/restli-common/src/main/java/com/linkedin/restli/common/ComplexKeySpec.java index d45009342d..82c1b61360 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/ComplexKeySpec.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/ComplexKeySpec.java @@ -46,7 +46,7 @@ public static ComplexKeyS else { if(keyParamsClass == null) throw new IllegalArgumentException("keyParamsClass must be non-null."); - return new ComplexKeySpec(new TypeSpec(keyKeyClass), new TypeSpec(keyParamsClass)); + return new ComplexKeySpec<>(new TypeSpec<>(keyKeyClass), new TypeSpec<>(keyParamsClass)); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/ComplexResourceKey.java b/restli-common/src/main/java/com/linkedin/restli/common/ComplexResourceKey.java index 0ea081af9b..38bd5d405a 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/ComplexResourceKey.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/ComplexResourceKey.java @@ -263,7 +263,7 @@ public static ComplexResourceKey buildFromDataMa RecordTemplate key = validateDataMap(keyDataMap, complexKeyType.getKeyType()); RecordTemplate params = validateDataMap(paramsDataMap, complexKeyType.getParamsType()); - return new ComplexResourceKey(key, params); + return new ComplexResourceKey<>(key, params); } /** @@ -407,6 +407,6 @@ public ComplexResourceKey copy() throws CloneNotSupportedException copyParams = (P) params.copy(); } - return new ComplexResourceKey(copyKey, copyParams); + return new ComplexResourceKey<>(copyKey, copyParams); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/CompoundKey.java b/restli-common/src/main/java/com/linkedin/restli/common/CompoundKey.java index 01d68caaab..995bf0a652 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/CompoundKey.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/CompoundKey.java @@ -404,7 +404,7 @@ private Object coerceValueForDataMap(Object value, DataSchema schema) { @Override public String toString() { - List keyList = new ArrayList(_keys.keySet()); + List keyList = new ArrayList<>(_keys.keySet()); Collections.sort(keyList); StringBuilder b = new StringBuilder(); diff --git a/restli-common/src/main/java/com/linkedin/restli/common/HttpStatus.java b/restli-common/src/main/java/com/linkedin/restli/common/HttpStatus.java index 162b54e3f4..fa35fd79c4 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/HttpStatus.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/HttpStatus.java @@ -131,7 +131,7 @@ public static HttpStatus fromCode(int code) { } private static Map initialize() { - Map result = new HashMap(HttpStatus.values().length); + Map result = new HashMap<>(HttpStatus.values().length); for (HttpStatus status : HttpStatus.values()) { result.put(status.getCode(), status); } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecord.java b/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecord.java index 5ada464b55..d040e0e5ce 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecord.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecord.java @@ -236,7 +236,7 @@ KP extends RecordTemplate> ComplexResourceKey getComplexKey(ComplexKeySp KK keyKey = obtainWrapped(keyField, complexKeyType.getKeyType().getType(), GetMode.DEFAULT); KP keyParams = obtainWrapped(paramsField, complexKeyType.getParamsType().getType(), GetMode.DEFAULT); - return new ComplexResourceKey(keyKey, keyParams); + return new ComplexResourceKey<>(keyKey, keyParams); } /** @@ -263,7 +263,7 @@ public CompoundKey getCompoundKey(Map fieldTypes) public V getValue(Class valueClass) { - return getValue(new TypeSpec(valueClass)); + return getValue(new TypeSpec<>(valueClass)); } /** diff --git a/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecordFactory.java b/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecordFactory.java index 1f53acb3b5..7a0fcca56c 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecordFactory.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/KeyValueRecordFactory.java @@ -125,7 +125,7 @@ else if (type.equals(ComplexResourceKey.class)) */ public KeyValueRecord create(final K key, final V value) { - final KeyValueRecord keyValueRecord = new KeyValueRecord(); + final KeyValueRecord keyValueRecord = new KeyValueRecord<>(); switch (_resourceKeyType) { diff --git a/restli-common/src/main/java/com/linkedin/restli/common/PatchRequest.java b/restli-common/src/main/java/com/linkedin/restli/common/PatchRequest.java index 0c5d2d857a..b8cba1e396 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/PatchRequest.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/PatchRequest.java @@ -69,7 +69,7 @@ public PatchRequest(DataMap dataMap) */ public static PatchRequest createFromPatchDocument(DataMap patchDocument) { - PatchRequest result = new PatchRequest(); + PatchRequest result = new PatchRequest<>(); result.data().put(PATCH, patchDocument); return result; } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/RestConstants.java b/restli-common/src/main/java/com/linkedin/restli/common/RestConstants.java index 8c91e807b8..b0d4e01072 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/RestConstants.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/RestConstants.java @@ -83,7 +83,7 @@ public interface RestConstants String METADATA_FIELDS_PARAM = "metadataFields"; String PAGING_FIELDS_PARAM = "pagingFields"; String RETURN_ENTITY_PARAM = "$returnEntity"; - Set PROJECTION_PARAMETERS = Collections.unmodifiableSet(new LinkedHashSet( + Set PROJECTION_PARAMETERS = Collections.unmodifiableSet(new LinkedHashSet<>( Arrays.asList(FIELDS_PARAM, METADATA_FIELDS_PARAM, PAGING_FIELDS_PARAM))); /** delimiter used for separating (name=value) parts of compound key */ @@ -98,13 +98,13 @@ public interface RestConstants String RESOURCE_MODEL_FILENAME_EXTENSION = ".restspec.json"; String SNAPSHOT_FILENAME_EXTENTION = ".snapshot.json"; Set SIMPLE_RESOURCE_METHODS = Collections.unmodifiableSet( - new HashSet( - Arrays.asList( - ResourceMethod.ACTION, - ResourceMethod.DELETE, - ResourceMethod.GET, - ResourceMethod.PARTIAL_UPDATE, - ResourceMethod.UPDATE))); + new HashSet<>( + Arrays.asList( + ResourceMethod.ACTION, + ResourceMethod.DELETE, + ResourceMethod.GET, + ResourceMethod.PARTIAL_UPDATE, + ResourceMethod.UPDATE))); String RESTLI_PROTOCOL_VERSION_PROPERTY = "restli.protocol"; String RESTLI_PROTOCOL_VERSION_PERCENTAGE_PROPERTY = "restli.protocol.percentage"; diff --git a/restli-common/src/main/java/com/linkedin/restli/common/TypeSpec.java b/restli-common/src/main/java/com/linkedin/restli/common/TypeSpec.java index cb1d011e7a..7ed5ef7dcf 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/TypeSpec.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/TypeSpec.java @@ -42,7 +42,7 @@ public static TypeSpec forClassMaybeNull(Class type) } else { - return new TypeSpec(type); + return new TypeSpec<>(type); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/common/util/ProjectionMaskApplier.java b/restli-common/src/main/java/com/linkedin/restli/common/util/ProjectionMaskApplier.java index 1cf572ae4a..2ccb6fd9cc 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/util/ProjectionMaskApplier.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/util/ProjectionMaskApplier.java @@ -234,7 +234,7 @@ private static RecordDataSchema buildRecordDataSchemaByProjection(RecordDataSche Collection nonSchemaFieldsToAllowInProjectionMask) { RecordDataSchema newRecordSchema = new RecordDataSchema(new Name(originalSchema.getFullName()), RecordDataSchema.RecordType.RECORD); - List newFields = new ArrayList(); + List newFields = new ArrayList<>(); for (Map.Entry maskEntry : maskMap.entrySet()) { String maskFieldName = Escaper.unescapePathSegment(maskEntry.getKey()); diff --git a/restli-common/src/main/java/com/linkedin/restli/common/util/ResourceSchemaToResourceSpecTranslator.java b/restli-common/src/main/java/com/linkedin/restli/common/util/ResourceSchemaToResourceSpecTranslator.java index 18a8455e87..7eda62dba3 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/util/ResourceSchemaToResourceSpecTranslator.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/util/ResourceSchemaToResourceSpecTranslator.java @@ -164,7 +164,7 @@ private ResourceSpec collectionToResourceSpec(ResourceSchema resourceSchema, Col DataSchema keyParamsType = RestSpecCodec.textToSchema(identifier.getParams(), _schemaResolver); ComplexKeySpec complexKeyType = toComplexKey(keyKeyType, keyParamsType); return buildResourceSpec(supports, - new TypeSpec(ComplexResourceKey.class, null), + new TypeSpec<>(ComplexResourceKey.class, null), complexKeyType, Collections.emptyMap(), schema, @@ -188,14 +188,14 @@ private ResourceSpec associationToResourceSpec(ResourceSchema resourceSchema, As String schema = resourceSchema.getSchema(); AssocKeySchemaArray assocKeys = association.getAssocKeys(); - Map keyParts = new HashMap(); + Map keyParts = new HashMap<>(); for (AssocKeySchema assocKey : assocKeys) { TypeSpec type = toTypeSpec(RestSpecCodec.textToSchema(assocKey.getType(), _schemaResolver)); keyParts.put(assocKey.getName(), new CompoundKey.TypeInfo(type, type)); } return buildResourceSpec(supports, - new TypeSpec(CompoundKey.class, null), + new TypeSpec<>(CompoundKey.class, null), null, keyParts, schema, @@ -211,7 +211,7 @@ private ResourceSpec actionSetToResourceSpec(ActionsSetSchema actionsSet) actions = actionsSet.getActions(); } return buildResourceSpec(new StringArray(0), - new TypeSpec(Void.class), + new TypeSpec<>(Void.class), null, Collections.emptyMap(), null, @@ -265,7 +265,7 @@ private ResourceSpec buildResourceSpec(StringArray supports, private Set toResourceMethods(StringArray supports) { if(supports == null) return Collections.emptySet(); - Set resourceMethods = new HashSet(); + Set resourceMethods = new HashSet<>(); for(String method : supports) { resourceMethods.add(ResourceMethod.fromString(method)); @@ -304,8 +304,8 @@ public ActionMetadata(String name, private ActionCollectionMetadata toDynamicRecordMetadata(ActionSchemaArray actions, ActionSchemaArray entityActions) { - Map response = new HashMap(); - Map request = new HashMap(); + Map response = new HashMap<>(); + Map request = new HashMap<>(); ActionSchemaArray[] actionGroups = new ActionSchemaArray[] { actions, entityActions }; for(ActionSchemaArray actionGroup: actionGroups) @@ -326,7 +326,7 @@ private ActionCollectionMetadata toDynamicRecordMetadata(ActionSchemaArray actio @SuppressWarnings({"unchecked", "rawtypes"}) // this is dynamic, don't have concrete classes for the FieldDef private ActionMetadata toActionMetadata(ActionSchema action) { - ArrayList> fieldDefs = new ArrayList>(); + ArrayList> fieldDefs = new ArrayList<>(); if(action.hasParameters()) { for(ParameterSchema parameterSchema : action.getParameters()) diff --git a/restli-common/src/main/java/com/linkedin/restli/common/util/RichResourceSchema.java b/restli-common/src/main/java/com/linkedin/restli/common/util/RichResourceSchema.java index 631c014592..4593f4e327 100644 --- a/restli-common/src/main/java/com/linkedin/restli/common/util/RichResourceSchema.java +++ b/restli-common/src/main/java/com/linkedin/restli/common/util/RichResourceSchema.java @@ -52,7 +52,7 @@ public class RichResourceSchema { public static Collection toRichResourceSchemas(Collection resourceSchemas) { - ArrayList results = new ArrayList(resourceSchemas.size()); + ArrayList results = new ArrayList<>(resourceSchemas.size()); for(ResourceSchema resourceSchema : resourceSchemas) { results.add(new RichResourceSchema(resourceSchema)); @@ -165,37 +165,37 @@ else if(_entity != null) _subresources = Collections.emptyList(); } - _methodsByName = new HashMap(_methods.size()); + _methodsByName = new HashMap<>(_methods.size()); for(RestMethodSchema method : _methods) { _methodsByName.put(method.getMethod(), method); } - _findersByName = new HashMap(_finders.size()); + _findersByName = new HashMap<>(_finders.size()); for(FinderSchema finder : _finders) { _findersByName.put(finder.getName(), finder); } - _batchFindersByName = new HashMap(_batchFinders.size()); + _batchFindersByName = new HashMap<>(_batchFinders.size()); for(BatchFinderSchema batchFinder : _batchFinders) { _batchFindersByName.put(batchFinder.getName(), batchFinder); } - _actionsByName = new HashMap(_actions.size()); + _actionsByName = new HashMap<>(_actions.size()); for(ActionSchema action : _actions) { _actionsByName.put(action.getName(), action); } - _entityActionsByName = new HashMap(_entityActions.size()); + _entityActionsByName = new HashMap<>(_entityActions.size()); for(ActionSchema entityAction : _entityActions) { _entityActionsByName.put(entityAction.getName(), entityAction); } - _subresourcesByName = new HashMap(_subresources.size()); + _subresourcesByName = new HashMap<>(_subresources.size()); for(RichResourceSchema subresource : _subresources) { _subresourcesByName.put(subresource.getName(), subresource); diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/AsciiHexEncoding.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/AsciiHexEncoding.java index e8b85109f5..ddc4307966 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/AsciiHexEncoding.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/AsciiHexEncoding.java @@ -52,7 +52,7 @@ public AsciiHexEncoding(char escapeChar, char[] reservedChars) private static Set toSet(char[] chars) { - HashSet reservedCharsSet = new HashSet(); + HashSet reservedCharsSet = new HashSet<>(); for(char c : chars) { reservedCharsSet.add(c); diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/AttachmentUtils.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/AttachmentUtils.java index 3c1a2abe4a..3cc99af97c 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/AttachmentUtils.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/AttachmentUtils.java @@ -58,7 +58,7 @@ public static void appendSingleAttachmentToBuilder(final MultiPartMIMEWriter.Bui @Override public Map dataSourceHeaders() { - final Map dataSourceHeaders = new TreeMap(); + final Map dataSourceHeaders = new TreeMap<>(); dataSourceHeaders.put(RestConstants.HEADER_CONTENT_ID, streamingAttachment.getAttachmentID()); return dataSourceHeaders; } @@ -115,7 +115,7 @@ public void onNewDataSourceWriter(RestLiAttachmentDataSourceWriter dataSourceWri @Override public Map dataSourceHeaders() { - final Map dataSourceHeaders = new TreeMap(); + final Map dataSourceHeaders = new TreeMap<>(); dataSourceHeaders.put(RestConstants.HEADER_CONTENT_ID, dataSourceWriter.getAttachmentID()); return dataSourceHeaders; } @@ -179,7 +179,7 @@ public static MultiPartMIMEWriter createMultiPartMIMEWriter(final Writer firstPa @Override public Map dataSourceHeaders() { - final Map metadataHeaders = new TreeMap(); + final Map metadataHeaders = new TreeMap<>(); metadataHeaders.put(RestConstants.HEADER_CONTENT_TYPE, firstPartContentType); return metadataHeaders; } diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/BatchFinderCriteriaResultDecoder.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/BatchFinderCriteriaResultDecoder.java index de815695bb..ffb9c3d78e 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/BatchFinderCriteriaResultDecoder.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/BatchFinderCriteriaResultDecoder.java @@ -39,6 +39,6 @@ public BatchFinderCriteriaResultDecoder(Class elementClass) { @SuppressWarnings("unchecked") public BatchFinderCriteriaResult makeValue(DataMap dataMap) { - return new BatchFinderCriteriaResult(dataMap, _elementClass); + return new BatchFinderCriteriaResult<>(dataMap, _elementClass); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/CookieUtil.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/CookieUtil.java index 61ef3160c2..6bc599b5de 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/CookieUtil.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/CookieUtil.java @@ -34,7 +34,7 @@ public class CookieUtil */ public static List encodeCookies(List cookies) { - List cookieStrs = new ArrayList(); + List cookieStrs = new ArrayList<>(); if (cookies != null) { for (HttpCookie cookie : cookies) @@ -53,7 +53,7 @@ public static List encodeCookies(List cookies) */ public static List decodeSetCookies(List cookieStrs) { - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); if (cookieStrs != null) { for (String cookieStr : cookieStrs) @@ -82,7 +82,7 @@ public static List decodeSetCookies(List cookieStrs) */ public static List encodeSetCookies(List cookies) { - List cookieStrs = new ArrayList(); + List cookieStrs = new ArrayList<>(); if (cookies != null) { for (HttpCookie cookie : cookies) @@ -101,7 +101,7 @@ public static List encodeSetCookies(List cookies) */ public static List decodeCookies(List cookieStrs) { - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); if (cookieStrs == null) { return cookies; diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdEntityStatusDecoder.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdEntityStatusDecoder.java index cf6317d989..0ddcf14415 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdEntityStatusDecoder.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdEntityStatusDecoder.java @@ -61,7 +61,7 @@ public CreateIdEntityStatus makeValue(DataMap dataMap) } finalMap.put("entity", listElements); - return new CreateIdEntityStatus(finalMap, key, entity); + return new CreateIdEntityStatus<>(finalMap, key, entity); } -} \ No newline at end of file +} diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdStatusDecoder.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdStatusDecoder.java index 3469a6b2cd..77fc79c1ae 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdStatusDecoder.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/CreateIdStatusDecoder.java @@ -63,6 +63,6 @@ public CreateIdStatus makeValue(DataMap dataMap) throws NoSuchMethodException { key = (K) ResponseUtils.convertKey(id, _keyType, _keyParts, _complexKeyType, _version); } - return new CreateIdStatus(dataMap, key); + return new CreateIdStatus<>(dataMap, key); } } diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/HeaderUtil.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/HeaderUtil.java index dff8c42639..5839816943 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/HeaderUtil.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/HeaderUtil.java @@ -144,9 +144,9 @@ public static Map removeHeaders(Map headers, Col { return headers; } - Set headersToRemove = new TreeSet(String.CASE_INSENSITIVE_ORDER); + Set headersToRemove = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); headersToRemove.addAll(headerNames); - Map newHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map newHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for(Map.Entry header : headers.entrySet()) { String name = header.getKey(); @@ -169,7 +169,7 @@ public static Map removeHeaders(Map headers, Col */ public static Map mergeHeaders(Map headers1, Map headers2) { - TreeMap combinedHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + TreeMap combinedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); if (headers2 != null) { combinedHeaders.putAll(headers2); diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/QueryParamsDataMap.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/QueryParamsDataMap.java index f98be15922..764743aa68 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/QueryParamsDataMap.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/QueryParamsDataMap.java @@ -80,12 +80,12 @@ public static String dataMapToQueryString(DataMap dataMap, Escaping escaping) Map> queryStringParamsMap = queryString(dataMap); StringBuilder sb = new StringBuilder(); - List keys = new ArrayList(queryStringParamsMap.keySet()); + List keys = new ArrayList<>(queryStringParamsMap.keySet()); Collections.sort(keys); for (String key : keys) { - List values = new ArrayList(queryStringParamsMap.get(key)); + List values = new ArrayList<>(queryStringParamsMap.get(key)); Collections.sort(values); for (String value : values) { @@ -114,7 +114,7 @@ public static String dataMapToQueryString(DataMap dataMap, Escaping escaping) * @return the map of query string parameters. */ public static Map> queryString(DataMap dataMap){ - Map> result = new HashMap>(); + Map> result = new HashMap<>(); DataMap processedDataMap = processProjections(dataMap, result); iterate("", processedDataMap, result); return result; @@ -230,7 +230,7 @@ private static void addListValue(String keyPrefix, } else { - result.put(keyPrefix, new ArrayList(Collections.singletonList(value.toString()))); + result.put(keyPrefix, new ArrayList<>(Collections.singletonList(value.toString()))); } } } @@ -403,7 +403,7 @@ private static DataComplex convertToDataCollection(Map map) DataList result = new DataList(); ListMap listMap = (ListMap)map; - List sortedKeys = new ArrayList(listMap.keySet()); + List sortedKeys = new ArrayList<>(listMap.keySet()); Collections.sort(sortedKeys); for (Integer key : sortedKeys) @@ -429,13 +429,13 @@ private static DataComplex convertToDataCollection(Map map) public static void addSortedParams(UriBuilder uriBuilder, Map> params) { - List keysList = new ArrayList(params.keySet()); + List keysList = new ArrayList<>(params.keySet()); Collections.sort(keysList); for (String key : keysList) { // Create a new list to make sure it's modifiable and can be sorted. - List values = new ArrayList(params.get(key)); + List values = new ArrayList<>(params.get(key)); Collections.sort(values); for (String value : values) { diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/ReflectionUtils.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/ReflectionUtils.java index 7298e9533a..05e68abbb4 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/ReflectionUtils.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/ReflectionUtils.java @@ -156,7 +156,7 @@ public static List> getTypeArguments(final Class baseClass, if (typeArguments != null) { - rawTypeArguments = new ArrayList>(); + rawTypeArguments = new ArrayList<>(); for (Type type : typeArguments) { @@ -177,7 +177,7 @@ public static List> getTypeArguments(final Class baseClass, public static List getTypeArgumentsParametrized(final Class baseClass, final Class childClass) { - Map resolvedTypes = new HashMap(); + Map resolvedTypes = new HashMap<>(); Type type = walkTypeChain(baseClass, childClass, resolvedTypes); if (type == null) { @@ -196,7 +196,7 @@ public static List getTypeArgumentsParametrized(final Class baseCla { typeArguments = ((ParameterizedType) type).getActualTypeArguments(); } - List typeArgumentsAsClasses = new ArrayList(); + List typeArgumentsAsClasses = new ArrayList<>(); // resolve types by chasing down type variables. for (Type baseType : typeArguments) { diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/ResourcePropertiesImpl.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/ResourcePropertiesImpl.java index cb1f5dc884..60c8841397 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/ResourcePropertiesImpl.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/ResourcePropertiesImpl.java @@ -166,7 +166,7 @@ public String toString() private static HashMap toTypeInfoKeyParts(Map keyParts) { - final HashMap keyPartTypeInfos = new HashMap(); + final HashMap keyPartTypeInfos = new HashMap<>(); for(Map.Entry entry : keyParts.entrySet()) { if(entry.getValue() instanceof Class) { diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/URIConstants.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/URIConstants.java index ed4091089a..dd436441c5 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/URIConstants.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/URIConstants.java @@ -37,7 +37,7 @@ public class URIConstants public final static String EMPTY_STRING_REP = "''"; public static final char[] RESERVED_CHARS = { OBJ_START, KEY_VALUE_SEP, OBJ_END, ITEM_SEP, EMPTY_STR_CHAR }; - public static final Set GRAMMAR_CHARS = new HashSet(Arrays.asList(OBJ_START, KEY_VALUE_SEP, OBJ_END, ITEM_SEP)); + public static final Set GRAMMAR_CHARS = new HashSet<>(Arrays.asList(OBJ_START, KEY_VALUE_SEP, OBJ_END, ITEM_SEP)); /** * Determine if this character is a Rest.li 2.0.0 URI grammar character. diff --git a/restli-common/src/main/java/com/linkedin/restli/internal/common/URIParamUtils.java b/restli-common/src/main/java/com/linkedin/restli/internal/common/URIParamUtils.java index 55459891f6..3d5e94981d 100644 --- a/restli-common/src/main/java/com/linkedin/restli/internal/common/URIParamUtils.java +++ b/restli-common/src/main/java/com/linkedin/restli/internal/common/URIParamUtils.java @@ -118,7 +118,7 @@ public static String encodeKeyForUri(Object key, UriComponent.Type componentType public static Map encodePathKeysForUri(Map pathKeys, ProtocolVersion version) { - final Map escapedKeys = new HashMap(); + final Map escapedKeys = new HashMap<>(); for (Map.Entry entry : pathKeys.entrySet()) { @@ -240,7 +240,7 @@ else if (key instanceof CompoundKey) private static String compoundKeyToStringV1(CompoundKey key) { - List keyList = new ArrayList(key.getPartKeys()); + List keyList = new ArrayList<>(key.getPartKeys()); Collections.sort(keyList); StringBuilder b = new StringBuilder(); @@ -323,7 +323,7 @@ private static void encodeDataObject(Object obj, URLEscaper.Escaping escaping, U stringBuilder.append(URIConstants.OBJ_START); if (!dataMap.isEmpty()) { - List keys = new ArrayList(dataMap.keySet()); + List keys = new ArrayList<>(dataMap.keySet()); Collections.sort(keys); ListIterator iterator = keys.listIterator(); @@ -500,7 +500,7 @@ public static void addSortedParams(UriBuilder uriBuilder, DataMap params) // params must already be escaped. private static void addSortedParams(UriBuilder uriBuilder, Map params) { - List keysList = new ArrayList(params.keySet()); + List keysList = new ArrayList<>(params.keySet()); Collections.sort(keysList); for (String key: keysList) diff --git a/restli-common/src/test/java/com/linkedin/restli/common/TestBatchCreateIdResponse.java b/restli-common/src/test/java/com/linkedin/restli/common/TestBatchCreateIdResponse.java index 668a8a5c58..f5aea26c37 100644 --- a/restli-common/src/test/java/com/linkedin/restli/common/TestBatchCreateIdResponse.java +++ b/restli-common/src/test/java/com/linkedin/restli/common/TestBatchCreateIdResponse.java @@ -41,7 +41,7 @@ private CompoundKey buildCompoundKey(String part1, int part2) private ComplexResourceKey buildComplexResourceKey(Long id) { MyComplexKey complexKey = new MyComplexKey().setB(id).setA(id + ""); - return new ComplexResourceKey(complexKey, new EmptyRecord()); + return new ComplexResourceKey<>(complexKey, new EmptyRecord()); } @DataProvider @@ -60,14 +60,14 @@ public void testCreate(K[] keys) { ProtocolVersion version = AllProtocolVersions.BASELINE_PROTOCOL_VERSION; - List> elements = new ArrayList>(); - elements.add(new CreateIdStatus(HttpStatus.S_201_CREATED.getCode(), keys[0], null, version)); - elements.add(new CreateIdStatus(HttpStatus.S_201_CREATED.getCode(), keys[1], null, version)); + List> elements = new ArrayList<>(); + elements.add(new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), keys[0], null, version)); + elements.add(new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), keys[1], null, version)); ErrorResponse error = new ErrorResponse().setMessage("3"); - elements.add(new CreateIdStatus(HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode(), keys[2], error, version)); + elements.add(new CreateIdStatus<>(HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode(), keys[2], error, version)); - BatchCreateIdResponse batchResp = new BatchCreateIdResponse(elements); + BatchCreateIdResponse batchResp = new BatchCreateIdResponse<>(elements); Assert.assertEquals(batchResp.getElements(), elements); } diff --git a/restli-common/src/test/java/com/linkedin/restli/common/TestComplexResourceKey.java b/restli-common/src/test/java/com/linkedin/restli/common/TestComplexResourceKey.java index fc19c01d06..7546519778 100644 --- a/restli-common/src/test/java/com/linkedin/restli/common/TestComplexResourceKey.java +++ b/restli-common/src/test/java/com/linkedin/restli/common/TestComplexResourceKey.java @@ -37,12 +37,12 @@ public void testEquals() throws CloneNotSupportedException paramMap.put("paramField1", "paramValue1"); EmptyRecord param1 = new EmptyRecord(paramMap); ComplexResourceKey complexKey1 = - new ComplexResourceKey(key1, param1); + new ComplexResourceKey<>(key1, param1); EmptyRecord key2 = key1.copy(); EmptyRecord param2 = param1.copy(); ComplexResourceKey complexKey2 = - new ComplexResourceKey(key2, param2); + new ComplexResourceKey<>(key2, param2); Assert.assertTrue(complexKey1.equals(complexKey2)); @@ -57,13 +57,13 @@ public void testEquals() throws CloneNotSupportedException complexKey2.params.data().put("paramField1", "paramValue1"); // One param null, other not - complexKey1 = new ComplexResourceKey(key1, null); - complexKey2 = new ComplexResourceKey(key2, param2); + complexKey1 = new ComplexResourceKey<>(key1, null); + complexKey2 = new ComplexResourceKey<>(key2, param2); Assert.assertFalse(complexKey1.equals(complexKey2)); Assert.assertFalse(complexKey2.equals(complexKey1)); // Both param null - complexKey2 = new ComplexResourceKey(key2, null); + complexKey2 = new ComplexResourceKey<>(key2, null); Assert.assertTrue(complexKey1.equals(complexKey2)); } @@ -79,7 +79,7 @@ public void testMakeReadOnly() EmptyRecord params = new EmptyRecord(paramsDataMap); ComplexResourceKey complexResourceKey = - new ComplexResourceKey(key, params); + new ComplexResourceKey<>(key, params); complexResourceKey.makeReadOnly(); @@ -112,7 +112,7 @@ public void testReadOnlyWithNullParams() EmptyRecord key = new EmptyRecord(keyDataMap); ComplexResourceKey complexResourceKey = - new ComplexResourceKey(key, null); + new ComplexResourceKey<>(key, null); complexResourceKey.makeReadOnly(); @@ -141,10 +141,10 @@ public Object[][] keySchemaValidation() { @Test(dataProvider = "keySchemaValidation") public void testKeySchema(int keyValue, int paramValue, boolean validationFailure, Class schemaClass) { - TypeSpec keyType = new TypeSpec(schemaClass); - TypeSpec paramsType = new TypeSpec(schemaClass); + TypeSpec keyType = new TypeSpec<>(schemaClass); + TypeSpec paramsType = new TypeSpec<>(schemaClass); ComplexKeySpec keySpec = - new ComplexKeySpec(keyType, paramsType); + new ComplexKeySpec<>(keyType, paramsType); DataMap paramsData = new DataMap(); paramsData.put("int", paramValue); DataMap data = new DataMap(); diff --git a/restli-common/src/test/java/com/linkedin/restli/common/TestIdEntityResponse.java b/restli-common/src/test/java/com/linkedin/restli/common/TestIdEntityResponse.java index a812381827..dc4d85fce6 100644 --- a/restli-common/src/test/java/com/linkedin/restli/common/TestIdEntityResponse.java +++ b/restli-common/src/test/java/com/linkedin/restli/common/TestIdEntityResponse.java @@ -29,21 +29,21 @@ public class TestIdEntityResponse @Test public void testToString() { - IdEntityResponse longIdEntityResponse = new IdEntityResponse(6L, new AnyRecord()); + IdEntityResponse longIdEntityResponse = new IdEntityResponse<>(6L, new AnyRecord()); Assert.assertEquals(longIdEntityResponse.toString(), "id: 6, entity: {}"); - IdEntityResponse nullIdEntityResponse = new IdEntityResponse(null, new AnyRecord()); + IdEntityResponse nullIdEntityResponse = new IdEntityResponse<>(null, new AnyRecord()); Assert.assertEquals(nullIdEntityResponse.toString(), "id: , entity: {}"); } @Test public void testEquals() { - IdEntityResponse longIdEntityResponse1 = new IdEntityResponse(1L, new AnyRecord()); - IdEntityResponse longIdEntityResponse2 = new IdEntityResponse(1L, new AnyRecord()); - IdEntityResponse nullLongResponse = new IdEntityResponse(null, new AnyRecord()); - IdEntityResponse nullStringResponse = new IdEntityResponse(null, new AnyRecord()); - IdEntityResponse stringResponse = new IdEntityResponse("hello", new AnyRecord()); + IdEntityResponse longIdEntityResponse1 = new IdEntityResponse<>(1L, new AnyRecord()); + IdEntityResponse longIdEntityResponse2 = new IdEntityResponse<>(1L, new AnyRecord()); + IdEntityResponse nullLongResponse = new IdEntityResponse<>(null, new AnyRecord()); + IdEntityResponse nullStringResponse = new IdEntityResponse<>(null, new AnyRecord()); + IdEntityResponse stringResponse = new IdEntityResponse<>("hello", new AnyRecord()); // equals and non-null. Assert.assertTrue(longIdEntityResponse1.equals(longIdEntityResponse2)); @@ -63,10 +63,10 @@ public void testEquals() @Test public void testHashCode() { - IdEntityResponse longIdEntityResponse1 = new IdEntityResponse(1L, new AnyRecord()); - IdEntityResponse longIdEntityResponse2 = new IdEntityResponse(1L, new AnyRecord()); - IdEntityResponse nullLongResponse = new IdEntityResponse(null, new AnyRecord()); - IdEntityResponse nullStringResponse = new IdEntityResponse(null, new AnyRecord()); + IdEntityResponse longIdEntityResponse1 = new IdEntityResponse<>(1L, new AnyRecord()); + IdEntityResponse longIdEntityResponse2 = new IdEntityResponse<>(1L, new AnyRecord()); + IdEntityResponse nullLongResponse = new IdEntityResponse<>(null, new AnyRecord()); + IdEntityResponse nullStringResponse = new IdEntityResponse<>(null, new AnyRecord()); Assert.assertEquals(longIdEntityResponse1.hashCode(), longIdEntityResponse2.hashCode()); Assert.assertEquals(nullLongResponse.hashCode(), nullStringResponse.hashCode()); diff --git a/restli-common/src/test/java/com/linkedin/restli/common/TestIdResponse.java b/restli-common/src/test/java/com/linkedin/restli/common/TestIdResponse.java index 1f9ccaf73e..b584e48ca5 100644 --- a/restli-common/src/test/java/com/linkedin/restli/common/TestIdResponse.java +++ b/restli-common/src/test/java/com/linkedin/restli/common/TestIdResponse.java @@ -30,21 +30,21 @@ public class TestIdResponse @Test public void testToString() { - IdResponse longIdResponse = new IdResponse(6L); + IdResponse longIdResponse = new IdResponse<>(6L); longIdResponse.toString(); - IdResponse nullIdResponse = new IdResponse(null); + IdResponse nullIdResponse = new IdResponse<>(null); nullIdResponse.toString(); } @Test public void testEquals() { - IdResponse longResponse1 = new IdResponse(1L); - IdResponse longResponse2 = new IdResponse(1L); - IdResponse nullLongResponse = new IdResponse(null); - IdResponse stringResponse = new IdResponse("hello"); - IdResponse nullStringResponse = new IdResponse(null); + IdResponse longResponse1 = new IdResponse<>(1L); + IdResponse longResponse2 = new IdResponse<>(1L); + IdResponse nullLongResponse = new IdResponse<>(null); + IdResponse stringResponse = new IdResponse<>("hello"); + IdResponse nullStringResponse = new IdResponse<>(null); // equals and non-null. Assert.assertTrue(longResponse1.equals(longResponse2)); @@ -64,10 +64,10 @@ public void testEquals() @Test public void testHashCode() { - IdResponse longResponse1 = new IdResponse(1L); - IdResponse longResponse2 = new IdResponse(1L); - IdResponse nullLongResponse = new IdResponse(null); - IdResponse nullStringResponse = new IdResponse(null); + IdResponse longResponse1 = new IdResponse<>(1L); + IdResponse longResponse2 = new IdResponse<>(1L); + IdResponse nullLongResponse = new IdResponse<>(null); + IdResponse nullStringResponse = new IdResponse<>(null); Assert.assertEquals(longResponse1.hashCode(), longResponse2.hashCode()); Assert.assertEquals(nullLongResponse.hashCode(), nullStringResponse.hashCode()); diff --git a/restli-common/src/test/java/com/linkedin/restli/common/TestKeyValueRecord.java b/restli-common/src/test/java/com/linkedin/restli/common/TestKeyValueRecord.java index 1e384b5710..9808db31fd 100644 --- a/restli-common/src/test/java/com/linkedin/restli/common/TestKeyValueRecord.java +++ b/restli-common/src/test/java/com/linkedin/restli/common/TestKeyValueRecord.java @@ -37,11 +37,11 @@ public class TestKeyValueRecord public void testPrimitive() { KeyValueRecordFactory factory = - new KeyValueRecordFactory(Long.class, - null, - null, - null, - RecordTemplateWithPrimitiveKey.class); + new KeyValueRecordFactory<>(Long.class, + null, + null, + null, + RecordTemplateWithPrimitiveKey.class); Long id = 1L; RecordTemplateWithPrimitiveKey mockRecordTemplate = new RecordTemplateWithPrimitiveKey(); @@ -57,11 +57,11 @@ public void testPrimitive() public void testEnum() { KeyValueRecordFactory factory = - new KeyValueRecordFactory(SimpleEnum.class, - null, - null, - null, - RecordTemplateWithPrimitiveKey.class); + new KeyValueRecordFactory<>(SimpleEnum.class, + null, + null, + null, + RecordTemplateWithPrimitiveKey.class); SimpleEnum id = SimpleEnum.A; RecordTemplateWithPrimitiveKey mockRecordTemplate = new RecordTemplateWithPrimitiveKey(); mockRecordTemplate.setId(1L).setBody("foo"); @@ -83,7 +83,7 @@ public void testCompoundKeyWithEnum() SimpleEnum simpleEnum = SimpleEnum.A; compoundKey.append("enumKey", simpleEnum); - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put("longKey", new CompoundKey.TypeInfo(Long.class, Long.class)); fieldTypes.put("enumKey", new CompoundKey.TypeInfo(SimpleEnum.class, String.class)); @@ -95,16 +95,16 @@ public void testCompoundKeyWithEnum() public void testComplex() { KeyValueRecordFactory factory = - new KeyValueRecordFactory(ComplexResourceKey.class, - MyComplexKey.class, - MyComplexKey.class, - null, - RecordTemplateWithPrimitiveKey.class); + new KeyValueRecordFactory<>(ComplexResourceKey.class, + MyComplexKey.class, + MyComplexKey.class, + null, + RecordTemplateWithPrimitiveKey.class); MyComplexKey key = new MyComplexKey().setA("key").setB(1L); MyComplexKey params = new MyComplexKey().setA("params").setB(2L); ComplexResourceKey complexKey = - new ComplexResourceKey(key, params); + new ComplexResourceKey<>(key, params); RecordTemplateWithPrimitiveKey mockRecord = new RecordTemplateWithPrimitiveKey().setId(1L).setBody("foo"); @@ -126,7 +126,7 @@ public void testCompoundKeyWithPrimitiveKeys() String stringKey = "1"; compoundKey.append("stringKey", stringKey); - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put("longKey", new CompoundKey.TypeInfo(Long.class, Long.class)); fieldTypes.put("stringKey", new CompoundKey.TypeInfo(String.class, String.class)); @@ -144,7 +144,7 @@ public void testCompoundKeyWithPrimitiveTyperef() Long longKey = 1L; compoundKey.append("longKey", longKey); - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put("stringKey", new CompoundKey.TypeInfo(String.class, String.class)); fieldTypes.put("longKey", new CompoundKey.TypeInfo(Long.class, MyLongRef.class)); @@ -159,7 +159,7 @@ public void testCompoundKeysWithCustomTyperefs() MyCustomString myCustomString = new MyCustomString("myCustomString"); compoundKey.append("myCustomString", myCustomString); - Map fieldTypes = new HashMap(); + Map fieldTypes = new HashMap<>(); fieldTypes.put("myCustomString", new CompoundKey.TypeInfo(MyCustomString.class, MyCustomStringRef.class)); testCompoundKey(compoundKey, fieldTypes); @@ -170,11 +170,11 @@ private void testCompoundKey(CompoundKey compoundKey, Map factory = - new KeyValueRecordFactory(CompoundKey.class, - null, - null, - fieldTypes, - RecordTemplateWithPrimitiveKey.class); + new KeyValueRecordFactory<>(CompoundKey.class, + null, + null, + fieldTypes, + RecordTemplateWithPrimitiveKey.class); KeyValueRecord keyValueRecord = factory.create(compoundKey, mockRecord); diff --git a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestHeaderUtil.java b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestHeaderUtil.java index 7311d962e8..65937db76c 100644 --- a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestHeaderUtil.java +++ b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestHeaderUtil.java @@ -34,8 +34,8 @@ public class TestHeaderUtil @Test public void testMergeHeader() { - Map headers1 = new HashMap(); - Map headers2 = new HashMap(); + Map headers1 = new HashMap<>(); + Map headers2 = new HashMap<>(); headers1.put("X-header1", "header1Value"); headers1.put("X-commonheader", "commonHeader1Value"); headers2.put("X-header2", "header2Value"); @@ -52,7 +52,7 @@ public void testMergeHeader() @Test public void testRemoveHeaders() { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("X-header1", "header1Value"); headers.put("X-header2", "header2Value"); headers.put("X-header3", "header3Value"); diff --git a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestQueryParamsDataMap.java b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestQueryParamsDataMap.java index dcf451d0c7..8d1af00305 100644 --- a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestQueryParamsDataMap.java +++ b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestQueryParamsDataMap.java @@ -350,24 +350,24 @@ public void testProcessProjections() resultMap.put(RestConstants.PAGING_FIELDS_PARAM, pagingMask.getDataMap()); resultMap.put("someQueryString", "someValue"); - final Map> processedProjections = new LinkedHashMap>(); + final Map> processedProjections = new LinkedHashMap<>(); final DataMap processedDataMap = QueryParamsDataMap.processProjections(resultMap, processedProjections); Assert.assertTrue(processedDataMap.size() == 1, "Processed datamap should only have one item left!"); - final Map> expectedProcessedProjections = new LinkedHashMap>(); + final Map> expectedProcessedProjections = new LinkedHashMap<>(); //"{fields=[foo:($*:(bar))], metadataFields=[foo:(bar),bar:(baz),qux], pagingFields=[total,count,links:($*:(rel))]}" expectedProcessedProjections.put(RestConstants.FIELDS_PARAM, Collections.singleton("foo:($*:(bar))")); expectedProcessedProjections.put(RestConstants.METADATA_FIELDS_PARAM, - new HashSet(Arrays.asList("foo:(bar)", "bar:(baz)", "qux"))); + new HashSet<>(Arrays.asList("foo:(bar)", "bar:(baz)", "qux"))); expectedProcessedProjections.put(RestConstants.PAGING_FIELDS_PARAM, - new HashSet(Arrays.asList("total", "count", "links:($*:(rel))"))); + new HashSet<>(Arrays.asList("total", "count", "links:($*:(rel))"))); Assert.assertEquals(processedProjections.size(), expectedProcessedProjections.size(), "We must have the correct number of" + " expected projections!"); for (final Map.Entry> entry : processedProjections.entrySet()) { //Acceptable because these are always comma delimited - final Set actualProjectionValueSet = new HashSet(Arrays.asList(entry.getValue().get(0).split(","))); + final Set actualProjectionValueSet = new HashSet<>(Arrays.asList(entry.getValue().get(0).split(","))); Assert.assertEquals(actualProjectionValueSet, expectedProcessedProjections.get(entry.getKey()), "The individual projection " + "for " + entry.getKey() + " does not match what is expected!"); } diff --git a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIElementParser.java b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIElementParser.java index 27259fb69e..f10a109796 100644 --- a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIElementParser.java +++ b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIElementParser.java @@ -197,7 +197,7 @@ public void testUndecodable(String undecoable, String expectedErrorMessage) @Test public void testParseURIParams() throws PathSegment.PathSegmentSyntaxException { - Map> queryParams = new HashMap>(); + Map> queryParams = new HashMap<>(); queryParams.put("aParam", Collections.singletonList("(someField:someValue,foo:bar,empty:())")); queryParams.put("bParam", Collections.singletonList("List(x,y,z)")); diff --git a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIMaskUtil.java b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIMaskUtil.java index 426ef426b1..a4a007064f 100644 --- a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIMaskUtil.java +++ b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestURIMaskUtil.java @@ -140,7 +140,7 @@ private String inSortedOrder(String uriMask) private List getTopLevelFileds(String s) { - List tlf = new ArrayList(); + List tlf = new ArrayList<>(); int i = 0; int openingBrackets = 0; int closingBrackets = 0; diff --git a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestUriParamUtils.java b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestUriParamUtils.java index a3c9f69bc4..40b318a54e 100644 --- a/restli-common/src/test/java/com/linkedin/restli/internal/common/TestUriParamUtils.java +++ b/restli-common/src/test/java/com/linkedin/restli/internal/common/TestUriParamUtils.java @@ -199,7 +199,7 @@ public void testComplexKeyToString(ProtocolVersion version, String full, String myComplexKey2.setA("anotherStringVal"); myComplexKey2.setB(4); ComplexResourceKey complexKey = - new ComplexResourceKey(myComplexKey1, myComplexKey2); + new ComplexResourceKey<>(myComplexKey1, myComplexKey2); String complexKeyString = URIParamUtils.keyToString(complexKey, NO_ESCAPING, null, true, version); Assert.assertEquals(complexKeyString, full); diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/Graph.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/Graph.java index a10cabddba..49d89077f9 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/Graph.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/Graph.java @@ -39,11 +39,11 @@ public Node get(T o) Node node = (Node) _nodes.get(o); if (node == null) { - node = new Node(o); + node = new Node<>(o); _nodes.put(o, node); } return node; } - private final Map> _nodes = new HashMap>(); + private final Map> _nodes = new HashMap<>(); } diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/MethodGatheringResourceSchemaVisitor.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/MethodGatheringResourceSchemaVisitor.java index fc08730c10..cff62474c4 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/MethodGatheringResourceSchemaVisitor.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/MethodGatheringResourceSchemaVisitor.java @@ -107,11 +107,11 @@ public Iterator iterator() @SuppressWarnings("unchecked") public Iterator getAllMethodsIterator() { - return new ChainedIterator(_restMethods.iterator(), - _finders.iterator(), - _batchFinders.iterator(), - _collectionActions.iterator(), - _entityActions.iterator()); + return new ChainedIterator<>(_restMethods.iterator(), + _finders.iterator(), + _batchFinders.iterator(), + _collectionActions.iterator(), + _entityActions.iterator()); } @Override @@ -173,10 +173,10 @@ private boolean isTargetResourcePath(VisitContext visitContext) return _resourceNames.contains(visitContext.getResourcePath()); } - private final Set _resourceNames = new HashSet(); - private final Set _restMethods = new HashSet(); - private final Set _finders = new HashSet(); - private final Set _batchFinders = new HashSet(); - private final Set _collectionActions = new HashSet(); - private final Set _entityActions = new HashSet(); + private final Set _resourceNames = new HashSet<>(); + private final Set _restMethods = new HashSet<>(); + private final Set _finders = new HashSet<>(); + private final Set _batchFinders = new HashSet<>(); + private final Set _collectionActions = new HashSet<>(); + private final Set _entityActions = new HashSet<>(); } diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/Node.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/Node.java index 942f33b3ad..f16716730f 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/Node.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/Node.java @@ -141,5 +141,5 @@ public boolean equals(Object obj) } private final T _object; - private final Set> _neighbors = new HashSet>(); + private final Set> _neighbors = new HashSet<>(); } diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/ResourceSchemaCollection.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/ResourceSchemaCollection.java index edee149e0e..b31216a64f 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/ResourceSchemaCollection.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/ResourceSchemaCollection.java @@ -75,7 +75,7 @@ public class ResourceSchemaCollection public static ResourceSchemaCollection loadOrCreateResourceSchema(Map rootResources) { final ResourceModelEncoder encoder = new ResourceModelEncoder(new NullDocsProvider()); - final Map schemaMap = new TreeMap(); + final Map schemaMap = new TreeMap<>(); for (ResourceModel resource : rootResources.values()) { schemaMap.put(resource.getName(), encoder.loadOrBuildResourceSchema(resource)); @@ -93,7 +93,7 @@ public static ResourceSchemaCollection loadOrCreateResourceSchema(Map resourceSchemaMap = new HashMap(); + final Map resourceSchemaMap = new HashMap<>(); for (String path : restspecSearchPaths) { @@ -135,7 +135,7 @@ public static void visitResources(Collection resources, Resource { for (ResourceSchema schema : resources) { - processResourceSchema(visitor, new ArrayList(), schema); + processResourceSchema(visitor, new ArrayList<>(), schema); } } @@ -145,10 +145,10 @@ public static void visitResources(Collection resources, Resource */ public ResourceSchemaCollection(Map rootResources) { - _allResources = new TreeMap(rootResources); - _subResources = new IdentityHashMap>(); - _parentResources = new IdentityHashMap>(); - final Map flattenSubResources = new TreeMap(); + _allResources = new TreeMap<>(rootResources); + _subResources = new IdentityHashMap<>(); + _parentResources = new IdentityHashMap<>(); + final Map flattenSubResources = new TreeMap<>(); final ResourceSchemaVisitior visitor = new BaseResourceSchemaVisitor() { @@ -163,7 +163,7 @@ public void visitResourceSchema(VisitContext context, final List hierarchy = context.getResourceSchemaHierarchy(); - ArrayList parents = new ArrayList(hierarchy); + ArrayList parents = new ArrayList<>(hierarchy); parents.remove(parents.size()-1); _parentResources.put(resourceSchema, parents); @@ -171,7 +171,7 @@ public void visitResourceSchema(VisitContext context, List subList = _subResources.get(directParent); if (subList == null) { - subList = new ArrayList(); + subList = new ArrayList<>(); _subResources.put(directParent, subList); } subList.add(resourceSchema); @@ -231,7 +231,7 @@ public List getParentResources(ResourceSchema parentSchema) */ public List getAllSubResources(ResourceSchema ancestorSchema) { - return getAllSubResourcesRecursive(ancestorSchema, new ArrayList()); + return getAllSubResourcesRecursive(ancestorSchema, new ArrayList<>()); } private List getAllSubResourcesRecursive(ResourceSchema parentSchema, diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/RestLiJSONDocumentationRenderer.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/RestLiJSONDocumentationRenderer.java index 3a45276f27..e3a0ceb5bb 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/RestLiJSONDocumentationRenderer.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/RestLiJSONDocumentationRenderer.java @@ -66,7 +66,7 @@ public void renderResourceHome(OutputStream out) try { for (ResourceSchema resourceSchema: - new HashSet(_relationships.getResourceSchemaCollection().getResources().values())) + new HashSet<>(_relationships.getResourceSchemaCollection().getResources().values())) { renderResource(resourceSchema, outputMap); } @@ -108,7 +108,7 @@ public void renderDataModelHome(OutputStream out) try { - for (NamedDataSchema schema: new HashSet(_relationships.getDataModels().values())) + for (NamedDataSchema schema: new HashSet<>(_relationships.getDataModels().values())) { renderDataModel(schema, outputMap); } @@ -172,7 +172,7 @@ private void addRelatedModels(ResourceSchema resourceSchema, DataMap models) thr relatedSchemas = _relatedSchemaCache.get(resourceSchema); if (relatedSchemas == null) { - relatedSchemas = new HashMap(); + relatedSchemas = new HashMap<>(); final Node node = _relationships.getRelationships(resourceSchema); final Iterator> schemaItr = node.getAdjacency(NamedDataSchema.class).iterator(); while (schemaItr.hasNext()) @@ -217,5 +217,5 @@ private void renderDataModel(NamedDataSchema schema, DataMap outputMap) throws I private final RestLiResourceRelationship _relationships; private final JacksonDataCodec _codec = new JacksonDataCodec(); private final Map> _relatedSchemaCache = - new HashMap>(); + new HashMap<>(); } diff --git a/restli-docgen/src/main/java/com/linkedin/restli/docgen/examplegen/ExampleRequestResponseGenerator.java b/restli-docgen/src/main/java/com/linkedin/restli/docgen/examplegen/ExampleRequestResponseGenerator.java index 21976e6e52..9fc7b0b21a 100644 --- a/restli-docgen/src/main/java/com/linkedin/restli/docgen/examplegen/ExampleRequestResponseGenerator.java +++ b/restli-docgen/src/main/java/com/linkedin/restli/docgen/examplegen/ExampleRequestResponseGenerator.java @@ -323,9 +323,9 @@ public ExampleRequestResponse getAll() { checkSupports(ResourceMethod.GET_ALL); GetAllRequestBuilder getAll = - new GetAllRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new GetAllRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); addParams(getAll, ResourceMethod.GET_ALL); addPathKeys(getAll); @@ -338,9 +338,9 @@ public ExampleRequestResponse get() { checkSupports(ResourceMethod.GET); GetRequestBuilder get = - new GetRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new GetRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); if (_resourceSpec.getKeyType() != null) { @@ -356,9 +356,9 @@ public ExampleRequestResponse create() { checkSupports(ResourceMethod.CREATE); CreateRequestBuilder create = - new CreateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new CreateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); create.input(generateEntity()); addParams(create, ResourceMethod.CREATE); addPathKeys(create); @@ -370,9 +370,9 @@ public ExampleRequestResponse update() { checkSupports(ResourceMethod.UPDATE); UpdateRequestBuilder update = - new UpdateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new UpdateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); if (_resourceSpec.getKeyType() != null) { update.id(generateKey()); @@ -388,9 +388,9 @@ public ExampleRequestResponse partialUpdate() { checkSupports(ResourceMethod.PARTIAL_UPDATE); PartialUpdateRequestBuilder update = - new PartialUpdateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new PartialUpdateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); if (_resourceSpec.getKeyType() != null) { update.id(generateKey()); @@ -406,9 +406,9 @@ public ExampleRequestResponse delete() { checkSupports(ResourceMethod.DELETE); DeleteRequestBuilder delete = - new DeleteRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new DeleteRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); if (_resourceSpec.getKeyType() != null) { delete.id(generateKey()); @@ -423,9 +423,9 @@ public ExampleRequestResponse batchGet() { checkSupports(ResourceMethod.BATCH_GET); BatchGetRequestBuilder batchGet = - new BatchGetRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new BatchGetRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); Object id1 = generateKey(0); Object id2 = generateKey(1); batchGet.ids(id1, id2); @@ -433,10 +433,10 @@ public ExampleRequestResponse batchGet() addPathKeys(batchGet); BatchGetKVRequest request = batchGet.buildKV(); - final Map bgResponseData = new HashMap(); + final Map bgResponseData = new HashMap<>(); bgResponseData.put(id1, generateEntity()); bgResponseData.put(id2, generateEntity()); - BatchResult result = new BatchResult(bgResponseData, new HashMap()); + BatchResult result = new BatchResult<>(bgResponseData, new HashMap<>()); return buildRequestResponse(request, result, buildResourceMethodDescriptorForRestMethod(request)); } @@ -444,15 +444,15 @@ public ExampleRequestResponse batchCreate() { checkSupports(ResourceMethod.BATCH_CREATE); BatchCreateRequestBuilder create = - new BatchCreateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new BatchCreateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); create.input(generateEntity()); create.input(generateEntity()); addParams(create, ResourceMethod.BATCH_CREATE); addPathKeys(create); BatchCreateRequest request = create.build(); - BatchCreateResult result = new BatchCreateResult(Arrays.asList( + BatchCreateResult result = new BatchCreateResult<>(Arrays.asList( new CreateResponse(generateKey(), HttpStatus.S_201_CREATED), new CreateResponse(generateKey(), HttpStatus.S_201_CREATED))); return buildRequestResponse(request, result, buildResourceMethodDescriptorForRestMethod(request)); @@ -462,9 +462,9 @@ public ExampleRequestResponse batchUpdate() { checkSupports(ResourceMethod.BATCH_UPDATE); BatchUpdateRequestBuilder update = - new BatchUpdateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new BatchUpdateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); Object id1 = generateKey(0); Object id2 = generateKey(1); @@ -478,19 +478,19 @@ public ExampleRequestResponse batchUpdate() private BatchUpdateResult createBatchUpdateResult(Object id1, Object id2) { - Map buResponseData = new HashMap(); + Map buResponseData = new HashMap<>(); buResponseData.put(id1, new UpdateResponse(HttpStatus.S_200_OK)); buResponseData.put(id2, new UpdateResponse(HttpStatus.S_200_OK)); - return new BatchUpdateResult(buResponseData); + return new BatchUpdateResult<>(buResponseData); } public ExampleRequestResponse batchPartialUpdate() { checkSupports(ResourceMethod.BATCH_PARTIAL_UPDATE); BatchPartialUpdateRequestBuilder update = - new BatchPartialUpdateRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new BatchPartialUpdateRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); Object id1 = generateKey(0); Object id2 = generateKey(1); update.input(id1, PatchGenerator.diffEmpty(generateEntity())); @@ -505,9 +505,9 @@ public ExampleRequestResponse batchDelete() { checkSupports(ResourceMethod.BATCH_DELETE); BatchDeleteRequestBuilder delete = - new BatchDeleteRequestBuilder( - _uriTemplate, - RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); + new BatchDeleteRequestBuilder<>( + _uriTemplate, + RecordTemplatePlaceholder.class, _resourceSpec, _requestOptions); Object id1 = generateKey(0); Object id2 = generateKey(1); delete.ids(id1, id2); @@ -515,10 +515,10 @@ public ExampleRequestResponse batchDelete() addPathKeys(delete); BatchDeleteRequest request = delete.build(); - final Map bdResponseData = new HashMap(); + final Map bdResponseData = new HashMap<>(); bdResponseData.put(id1, new UpdateResponse(HttpStatus.S_200_OK)); bdResponseData.put(id2, new UpdateResponse(HttpStatus.S_200_OK)); - BatchUpdateResult result = new BatchUpdateResult(bdResponseData); + BatchUpdateResult result = new BatchUpdateResult<>(bdResponseData); return buildRequestResponse(request, result, buildResourceMethodDescriptorForRestMethod(request)); } @@ -623,7 +623,7 @@ private FindRequest buildFinderRequest(FinderSchema f { FindRequestBuilder finder = - new FindRequestBuilder( + new FindRequestBuilder<>( _uriTemplate, RecordTemplatePlaceholder.class, _resourceSpec, @@ -656,7 +656,7 @@ else if (finderSchema.hasAssocKey()) // why do we have a separate field for the private CollectionResult buildFinderResult(RecordDataSchema finderMetadataSchema) { - final List results = new ArrayList(); + final List results = new ArrayList<>(); results.add(generateEntity()); results.add(generateEntity()); @@ -664,11 +664,11 @@ private CollectionResult b { DataMap metadataDataMap = (DataMap)_dataGenerator.buildData("metadata", finderMetadataSchema); RecordTemplatePlaceholder metadata = new RecordTemplatePlaceholder(metadataDataMap, finderMetadataSchema); - return new CollectionResult(results, results.size(), metadata); + return new CollectionResult<>(results, results.size(), metadata); } else { - return new CollectionResult(results); + return new CollectionResult<>(results); } } @@ -676,7 +676,7 @@ private BatchFindRequest buildBatchFinderRequest(Batc { BatchFindRequestBuilder batchFinder = - new BatchFindRequestBuilder( + new BatchFindRequestBuilder<>( _uriTemplate, RecordTemplatePlaceholder.class, _resourceSpec, @@ -714,7 +714,7 @@ else if (batchFinderSchema.hasAssocKey()) @SuppressWarnings({"unchecked", "rawtypes"}) private BatchFinderResult buildBatchFinderResult(RecordDataSchema batchFinderMetadataSchema, RecordTemplate batchFinderCriteria) { - final List results = new ArrayList(); + final List results = new ArrayList<>(); results.add(generateEntity()); results.add(generateEntity()); @@ -724,7 +724,7 @@ private BatchFinderResult(results, results.size(), metadata); + CollectionResult cr = new CollectionResult<>(results, results.size(), metadata); batchFinderResult.putResult(batchFinderCriteria, cr); } else @@ -749,16 +749,16 @@ private ActionRequest buildActionRequest(ActionSchema action, ResourceLevel r FieldDef fieldDef = responseMetadata.getFieldDef("value"); if (fieldDef != null && fieldDef.getDataClass() != null) { - responseType = new TypeSpec( - (Class)fieldDef.getDataClass(), - responseMetadata.getRecordDataSchema()); + responseType = new TypeSpec<>( + (Class) fieldDef.getDataClass(), + responseMetadata.getRecordDataSchema()); } } ActionRequestBuilder request = - new ActionRequestBuilder( - _uriTemplate, - responseType, - _resourceSpec, + new ActionRequestBuilder<>( + _uriTemplate, + responseType, + _resourceSpec, _requestOptions); request.name(action.getName()); @@ -782,7 +782,7 @@ private ActionResult buildActionResult(ActionSchema actionSchema) { FieldDef fieldDef = returnsMetadata.getFieldDef("value"); Object returnValue = generateFieldDefValue(fieldDef); - return new ActionResult(returnValue); + return new ActionResult<>(returnValue); } else { @@ -949,13 +949,13 @@ private Object generateFieldDefValue(FieldDef fieldDef) // just use the string value already generated. Will be coerced by DataTemplateUtil.DynamicEnumCoercer. break; case ARRAY: - value = new ArrayTemplatePlaceholder((DataList)value, (ArrayDataSchema)dereferencedDataSchema, Object.class); + value = new ArrayTemplatePlaceholder<>((DataList) value, (ArrayDataSchema) dereferencedDataSchema, Object.class); break; case RECORD: value = new RecordTemplatePlaceholder((DataMap)value, (RecordDataSchema)dereferencedDataSchema); break; case MAP: - value = new MapTemplatePlaceholder((DataMap)value, (MapDataSchema)dereferencedDataSchema, Object.class); + value = new MapTemplatePlaceholder<>((DataMap) value, (MapDataSchema) dereferencedDataSchema, Object.class); break; case UNION: value = new UnionTemplatePlaceholder(value, (UnionDataSchema)dereferencedDataSchema); @@ -995,7 +995,7 @@ private Object generateKey(ResourceSpec resourceSpec, ResourceSchema resourceSch RecordDataSchema paramsSchema = (RecordDataSchema)resourceSpec.getComplexKeyType().getParamsType().getSchema(); DataMap paramsData = (DataMap)_dataGenerator.buildData(postfixBatchIdx(keySchema.getName() + "Params", batchIdx), paramsSchema); - return new ComplexResourceKey( + return new ComplexResourceKey<>( new RecordTemplatePlaceholder(keyData, keySchema), new RecordTemplatePlaceholder(paramsData, paramsSchema) ); @@ -1104,7 +1104,7 @@ private static ResourceSpec translate(ResourceSchema resourceSchema, DataSchemaR private static Map translate(List resourceSchemas, DataSchemaResolver schemaResolver) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (ResourceSchema resourceSchema : resourceSchemas) { result.put(resourceSchema, translate(resourceSchema, schemaResolver)); diff --git a/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleBasicClient.java b/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleBasicClient.java index 5e23361c52..7ef7cdbb43 100644 --- a/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleBasicClient.java +++ b/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleBasicClient.java @@ -75,7 +75,7 @@ public static void main(String[] args) throws Exception String pathInfo = args.length == 0 ? "" : args[0]; photoClient.sendRequest(pathInfo, new PrintWriter(System.out)); photoClient.shutdown(); - http.shutdown(new FutureCallback()); + http.shutdown(new FutureCallback<>()); } public RestLiExampleBasicClient(RestClient restClient) @@ -230,7 +230,7 @@ private void getAlbum(PrintWriter respWriter, long albumId) throws RemoteInvocat final FindRequest searchReq = _albumEntryBuilders.findBySearch().albumIdParam(albumId).build(); final ResponseFuture> responseFuture = _restClient.sendRequest(searchReq); final Response> response = responseFuture.getResponse(); - final List entries = new ArrayList(response.getEntity().getElements()); + final List entries = new ArrayList<>(response.getEntity().getElements()); entries.add(new AlbumEntry().setAlbumId(-1).setPhotoId(9999)); @@ -400,4 +400,3 @@ private void findPhoto(PrintWriter respWriter) throws RemoteInvocationException private final RestClient _restClient; } - diff --git a/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleD2Client.java b/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleD2Client.java index ce8139c051..8716429e43 100644 --- a/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleD2Client.java +++ b/restli-example-client/src/main/java/com/linkedin/restli/example/RestLiExampleD2Client.java @@ -40,7 +40,7 @@ public class RestLiExampleD2Client public static void main(String[] args) throws Exception { final D2Client d2Client = new D2ClientBuilder().build(); - d2Client.start(new FutureCallback()); + d2Client.start(new FutureCallback<>()); final RestClient restClient = new RestClient(d2Client, "d2://"); final RestLiExampleBasicClient photoClient = new RestLiExampleBasicClient(restClient); diff --git a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumDatabaseImpl.java b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumDatabaseImpl.java index a87f279edf..e632ac1195 100644 --- a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumDatabaseImpl.java +++ b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumDatabaseImpl.java @@ -61,5 +61,5 @@ public Map getData() // database instances and hash maps are the same for all sessions. // These shared variables need synchronization for consistency. private final AtomicLong _currId = new AtomicLong(); - private final Map _data = new ConcurrentHashMap(); + private final Map _data = new ConcurrentHashMap<>(); } diff --git a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryDatabaseImpl.java b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryDatabaseImpl.java index bed03d588b..556a69c185 100644 --- a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryDatabaseImpl.java +++ b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryDatabaseImpl.java @@ -57,5 +57,5 @@ public Map getData() // the database variables are set through dependency injection. Thus, the underlying // database instances and hash maps are the same for all sessions. // These shared variables need synchronization for consistency. - private final Map _data = new ConcurrentHashMap(); -} \ No newline at end of file + private final Map _data = new ConcurrentHashMap<>(); +} diff --git a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryResource.java b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryResource.java index c0682d1952..869add6704 100644 --- a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryResource.java +++ b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/AlbumEntryResource.java @@ -92,7 +92,7 @@ public AlbumEntry get(CompoundKey key) @Override public Map batchGet(Set ids) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (CompoundKey key : ids) result.put(key, get(key)); return result; @@ -231,7 +231,7 @@ public int purge(@Optional @ActionParam("albumId") Long albumId, public List search(@Optional @QueryParam("albumId") Long albumId, @Optional @QueryParam("photoId") Long photoId) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (Map.Entry entry : _db.getData().entrySet()) { CompoundKey key = entry.getKey(); diff --git a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoDatabaseImpl.java b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoDatabaseImpl.java index 20a9563d0f..0af8e612b0 100644 --- a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoDatabaseImpl.java +++ b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoDatabaseImpl.java @@ -67,5 +67,5 @@ public Map getData() // database instances and hash maps are the same for all sessions. // These shared variables need synchronization for consistency. private final AtomicLong _currId = new AtomicLong(); - private final Map _data = new ConcurrentHashMap(); + private final Map _data = new ConcurrentHashMap<>(); } diff --git a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoResource.java b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoResource.java index 458f87b13b..0dc704730f 100644 --- a/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoResource.java +++ b/restli-example-server/src/main/java/com/linkedin/restli/example/impl/PhotoResource.java @@ -100,9 +100,9 @@ public Photo get(Long key) @Override public BatchResult batchGet(Set ids) { - Map result = new HashMap(); + Map result = new HashMap<>(); Map errors = - new HashMap(); + new HashMap<>(); for (Long key : ids) { @@ -117,7 +117,7 @@ public BatchResult batchGet(Set ids) + " has been found.")); } } - return new BatchResult(result, errors); + return new BatchResult<>(result, errors); } // update an existing photo with given entity @@ -190,7 +190,7 @@ public List find(@PagingContextParam PagingContext pagingContext, @QueryParam("title") @Optional String title, @QueryParam("format") @Optional PhotoFormats format) { - final List photos = new ArrayList(); + final List photos = new ArrayList<>(); int index = 0; final int begin = pagingContext.getStart(); final int end = begin + pagingContext.getCount(); @@ -226,7 +226,7 @@ public BatchFinderResult searchPhotos(@PagingC for (PhotoCriteria currentCriteria: criteria) { if (currentCriteria.getTitle() != null) { // on success - final List photos = new ArrayList(); + final List photos = new ArrayList<>(); int index = 0; final int begin = pagingContext.getStart(); final int end = begin + pagingContext.getCount(); diff --git a/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestAlbumEntryResource.java b/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestAlbumEntryResource.java index 1fdbc8ae70..7f4a2be28e 100644 --- a/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestAlbumEntryResource.java +++ b/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestAlbumEntryResource.java @@ -43,7 +43,7 @@ public class TestAlbumEntryResource private static Map buildResourceModels(Class... rootResourceClasses) { - final Map map = new HashMap(); + final Map map = new HashMap<>(); for (Class rootResourceClass : rootResourceClasses) { final ResourceModel model = RestLiAnnotationReader.processResource(rootResourceClass); @@ -152,7 +152,7 @@ public void testBadUpdateIdsInEntry() public void testBatchGet() { // get keys 1-3 - Set batchIds = new HashSet(); + Set batchIds = new HashSet<>(); for (int i = 1; i <= 3; i++) { batchIds.add(_keys[i]); @@ -170,8 +170,8 @@ public void testBatchGet() public void testSearch() { // we previously put the first 3 entries in album 1 - Set result = new HashSet(_entryRes.search(Long.valueOf(1), null)); - Set expected = new HashSet(); + Set result = new HashSet<>(_entryRes.search(Long.valueOf(1), null)); + Set expected = new HashSet<>(); for (int i = 0; i < 3; i++) { expected.add(_entries[i]); @@ -185,4 +185,4 @@ public void testResourcePurge() // we put 2 photos in album 2; delete them Assert.assertEquals(_entryRes.purge(Long.valueOf(2), null), 2); } -} \ No newline at end of file +} diff --git a/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestPhotoResource.java b/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestPhotoResource.java index 7aa2e4b53f..aa61748079 100644 --- a/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestPhotoResource.java +++ b/restli-example-server/src/test/java/com/linkedin/restli/example/impl/TestPhotoResource.java @@ -47,7 +47,7 @@ public class TestPhotoResource private static Map buildResourceModels(Class... rootResourceClasses) { - final Map map = new HashMap(); + final Map map = new HashMap<>(); for (Class rootResourceClass : rootResourceClasses) { final ResourceModel model = RestLiAnnotationReader.processResource(rootResourceClass); @@ -127,7 +127,7 @@ public void testBatchGet() { ids[i] = createPhoto(titles[i]); // validate all data are correct - Set batchIds = new HashSet(); + Set batchIds = new HashSet<>(); batchIds.add(ids[1]); batchIds.add(ids[2]); Map batchPhotos = _res.batchGet(batchIds); diff --git a/restli-extras/src/main/java/com/linkedin/restli/client/AllPartitionsRequestBuilder.java b/restli-extras/src/main/java/com/linkedin/restli/client/AllPartitionsRequestBuilder.java index 48f94f7632..0aeb2c8bb2 100644 --- a/restli-extras/src/main/java/com/linkedin/restli/client/AllPartitionsRequestBuilder.java +++ b/restli-extras/src/main/java/com/linkedin/restli/client/AllPartitionsRequestBuilder.java @@ -70,7 +70,7 @@ public HostSet sendRequests(RestClient client, Request request, RequestContex throw new IllegalArgumentException(e); } - final Collection queryAllRequestContext = new ArrayList(); + final Collection queryAllRequestContext = new ArrayList<>(); final HostSet uriResult = _mapper.getAllPartitionsMultipleHosts(serviceUri, 1); for (URI targetHost : uriResult.getAllHosts()) { diff --git a/restli-extras/src/main/java/com/linkedin/restli/client/ScatterGatherBuilder.java b/restli-extras/src/main/java/com/linkedin/restli/client/ScatterGatherBuilder.java index 00b1fd44a0..b397bad0eb 100644 --- a/restli-extras/src/main/java/com/linkedin/restli/client/ScatterGatherBuilder.java +++ b/restli-extras/src/main/java/com/linkedin/restli/client/ScatterGatherBuilder.java @@ -70,14 +70,14 @@ public ScatterGatherResult buildRequestsV2(BatchGetRequest request, Reques MapKeyResult mapKeyResult = mapKeys(request, idObjects); Map> batches = mapKeyResult.getMapResult(); - Collection> scatterGatherRequests = new ArrayList>(batches.size()); + Collection> scatterGatherRequests = new ArrayList<>(batches.size()); for (Map.Entry> batch : batches.entrySet()) { - BatchGetRequestBuilder builder = new BatchGetRequestBuilder(request.getBaseUriTemplate(), - request.getResponseDecoder(), - request.getResourceSpec(), - request.getRequestOptions()); + BatchGetRequestBuilder builder = new BatchGetRequestBuilder<>(request.getBaseUriTemplate(), + request.getResponseDecoder(), + request.getResourceSpec(), + request.getRequestOptions()); builder.ids(batch.getValue()); for (Map.Entry param : request.getQueryParamsObjects().entrySet()) { @@ -95,10 +95,10 @@ public ScatterGatherResult buildRequestsV2(BatchGetRequest request, Reques RequestContext context = requestContext.clone(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, batch.getKey()); - scatterGatherRequests.add(new RequestInfo(builder.build(), context)); + scatterGatherRequests.add(new RequestInfo<>(builder.build(), context)); } - return new ScatterGatherResult(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); + return new ScatterGatherResult<>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); } @SuppressWarnings("deprecation") @@ -111,14 +111,14 @@ public KVScatterGatherResult> buildRequests(BatchGetEnt final MapKeyResult mapKeyResult = mapKeys(request, idObjects); final Map> batches = mapKeyResult.getMapResult(); - final Collection>> scatterGatherRequests = new ArrayList>>(batches.size()); + final Collection>> scatterGatherRequests = new ArrayList<>(batches.size()); for (Map.Entry> batch : batches.entrySet()) { - final BatchGetEntityRequestBuilder builder = new BatchGetEntityRequestBuilder(request.getBaseUriTemplate(), - request.getResponseDecoder(), - request.getResourceSpec(), - request.getRequestOptions()); + final BatchGetEntityRequestBuilder builder = new BatchGetEntityRequestBuilder<>(request.getBaseUriTemplate(), + request.getResponseDecoder(), + request.getResourceSpec(), + request.getRequestOptions()); builder.ids(batch.getValue()); for (Map.Entry param : request.getQueryParamsObjects().entrySet()) { @@ -136,10 +136,10 @@ public KVScatterGatherResult> buildRequests(BatchGetEnt final RequestContext context = requestContext.clone(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, batch.getKey()); - scatterGatherRequests.add(new KVRequestInfo>(builder.build(), context)); + scatterGatherRequests.add(new KVRequestInfo<>(builder.build(), context)); } - return new KVScatterGatherResult>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); + return new KVScatterGatherResult<>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); } @SuppressWarnings({ "unchecked", "deprecation" }) @@ -151,15 +151,15 @@ public KVScatterGatherResult buildRequestsKV(BatchGetKVRequest r MapKeyResult mapKeyResult = mapKeys(request, idObjects); Map> batches = mapKeyResult.getMapResult(); - Collection> scatterGatherRequests = new ArrayList>(batches.size()); + Collection> scatterGatherRequests = new ArrayList<>(batches.size()); for (Map.Entry> batch : batches.entrySet()) { BatchGetRequestBuilder builder = - new BatchGetRequestBuilder(request.getBaseUriTemplate(), - (Class)request.getResourceProperties().getValueType().getType(), - request.getResourceSpec(), - request.getRequestOptions()); + new BatchGetRequestBuilder<>(request.getBaseUriTemplate(), + (Class) request.getResourceProperties().getValueType().getType(), + request.getResourceSpec(), + request.getRequestOptions()); builder.ids(batch.getValue()); for (Map.Entry param : request.getQueryParamsObjects().entrySet()) @@ -178,10 +178,10 @@ public KVScatterGatherResult buildRequestsKV(BatchGetKVRequest r RequestContext context = requestContext.clone(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, batch.getKey()); - scatterGatherRequests.add(new KVRequestInfo(builder.buildKV(), context)); + scatterGatherRequests.add(new KVRequestInfo<>(builder.buildKV(), context)); } - return new KVScatterGatherResult(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); + return new KVScatterGatherResult<>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); } @SuppressWarnings("deprecation") @@ -189,7 +189,7 @@ public KVScatterGatherResult buildRequests(BatchUpdateReque throws ServiceUnavailableException { Set idObjects = request.getObjectIds(); - Collection ids = new HashSet(idObjects.size()); + Collection ids = new HashSet<>(idObjects.size()); for (Object o : idObjects) { @SuppressWarnings("unchecked") @@ -202,14 +202,14 @@ public KVScatterGatherResult buildRequests(BatchUpdateReque @SuppressWarnings("unchecked") TypeSpec valueType = (TypeSpec) request.getResourceProperties().getValueType(); Map> batches = keyMapToInput(mapKeyResult, request); - Collection> scatterGatherRequests = new ArrayList>(batches.size()); + Collection> scatterGatherRequests = new ArrayList<>(batches.size()); for (Map.Entry> batch : batches.entrySet()) { - BatchUpdateRequestBuilder builder = new BatchUpdateRequestBuilder(request.getBaseUriTemplate(), - valueType.getType(), - request.getResourceSpec(), - request.getRequestOptions()); + BatchUpdateRequestBuilder builder = new BatchUpdateRequestBuilder<>(request.getBaseUriTemplate(), + valueType.getType(), + request.getResourceSpec(), + request.getRequestOptions()); builder.inputs(batch.getValue()); for (Map.Entry param : request.getQueryParamsObjects().entrySet()) { @@ -226,10 +226,10 @@ public KVScatterGatherResult buildRequests(BatchUpdateReque RequestContext context = requestContext.clone(); KeyMapper.TargetHostHints.setRequestContextTargetHost(context, batch.getKey()); - scatterGatherRequests.add(new KVRequestInfo(builder.build(), context)); + scatterGatherRequests.add(new KVRequestInfo<>(builder.build(), context)); } - return new KVScatterGatherResult(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); + return new KVScatterGatherResult<>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); } private MapKeyResult mapKeys(BatchRequest request, Collection ids) @@ -273,11 +273,11 @@ private Map> keyMapToInput(MapKeyResult mapKeyResult, } Map> map = mapKeyResult.getMapResult(); - Map> result = new HashMap>(map.size()); + Map> result = new HashMap<>(map.size()); for(Map.Entry> entry : map.entrySet()) { Collection keyList = entry.getValue(); - Map keyRecordMap = new HashMap(keyList.size()); + Map keyRecordMap = new HashMap<>(keyList.size()); for(K key : keyList) { T record = updateInput.get(key); @@ -297,7 +297,7 @@ public KVScatterGatherResult buildRequests(BatchDeleteReque throws ServiceUnavailableException { Set idObjects = request.getObjectIds(); - Collection ids = new HashSet(idObjects.size()); + Collection ids = new HashSet<>(idObjects.size()); for (Object o : idObjects) { @SuppressWarnings("unchecked") @@ -307,17 +307,17 @@ public KVScatterGatherResult buildRequests(BatchDeleteReque MapKeyResult mapKeyResult = mapKeys(request, ids); Map> batches = mapKeyResult.getMapResult(); - Collection> scatterGatherRequests = new ArrayList>(batches.size()); + Collection> scatterGatherRequests = new ArrayList<>(batches.size()); for (Map.Entry> batch : batches.entrySet()) { TypeSpec value = request.getResourceProperties().getValueType(); @SuppressWarnings("unchecked") Class valueClass = (Class) ((value == null) ? null : value.getType()); - BatchDeleteRequestBuilder builder = new BatchDeleteRequestBuilder(request.getBaseUriTemplate(), - valueClass, - request.getResourceSpec(), - request.getRequestOptions()); + BatchDeleteRequestBuilder builder = new BatchDeleteRequestBuilder<>(request.getBaseUriTemplate(), + valueClass, + request.getResourceSpec(), + request.getRequestOptions()); builder.ids(batch.getValue()); for (Map.Entry param : request.getQueryParamsObjects().entrySet()) { @@ -335,10 +335,10 @@ public KVScatterGatherResult buildRequests(BatchDeleteReque KeyMapper.TargetHostHints.setRequestContextTargetHost(context, batch.getKey()); BatchRequest> build = builder.build(); - scatterGatherRequests.add(new KVRequestInfo(build, context)); + scatterGatherRequests.add(new KVRequestInfo<>(build, context)); } - return new KVScatterGatherResult(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); + return new KVScatterGatherResult<>(scatterGatherRequests, mapKeyResult.getUnmappedKeys()); } /** diff --git a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/greetings/TestCustomTypesRequestBuilders.java b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/greetings/TestCustomTypesRequestBuilders.java index 1690a786ce..2284e07628 100644 --- a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/greetings/TestCustomTypesRequestBuilders.java +++ b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/greetings/TestCustomTypesRequestBuilders.java @@ -85,7 +85,7 @@ public void testFinderCustomLong(RootBuilderWrapper builders, Pr public void testFinderCustomLongArray(RootBuilderWrapper builders, ProtocolVersion version, String expectedUri) throws IOException, RestException { - List ls = new ArrayList(2); + List ls = new ArrayList<>(2); ls.add(new CustomLong(2L)); ls.add(new CustomLong(4L)); Request> request = builders.findBy("CustomLongArray").setQueryParam("ls", ls).build(); diff --git a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestGroupsRequestBuilders.java b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestGroupsRequestBuilders.java index 617ceae025..c88af031d6 100644 --- a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestGroupsRequestBuilders.java +++ b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestGroupsRequestBuilders.java @@ -118,7 +118,7 @@ public void testEntityCreateId(URIDetails expectedURIDetails) throws IOException public void testEntityUpdate(RootBuilderWrapper builders, URIDetails expectedURIDetails) throws IOException, RestException { - Request request = builders.partialUpdate().id(1).input(new PatchRequest()).build(); + Request request = builders.partialUpdate().id(1).input(new PatchRequest<>()).build(); checkRequestBuilder(request, ResourceMethod.PARTIAL_UPDATE, EmptyResponseDecoder.class, expectedURIDetails, new Group()); } @@ -386,9 +386,9 @@ public void testAction(RootBuilderWrapper builders, URIDetails e .setActionParam("Request", ownershipRequest) .build(); - Map , Object> parameters = new HashMap , Object>(1); - parameters.put(new FieldDef("request", TransferOwnershipRequest.class, - DataTemplateUtil.getSchema(TransferOwnershipRequest.class)), ownershipRequest); + Map , Object> parameters = new HashMap<>(1); + parameters.put(new FieldDef<>("request", TransferOwnershipRequest.class, + DataTemplateUtil.getSchema(TransferOwnershipRequest.class)), ownershipRequest); DynamicRecordTemplate requestInput = createDynamicRecordTemplate("transferOwnership", parameters); checkRequestBuilder(request, ResourceMethod.ACTION, ActionResponseDecoder.class, expectedURIDetails, requestInput); } @@ -519,7 +519,7 @@ public void testActionOnSubresource(RootBuilderWrapper bu { Request request = builders.action("SpamContacts").setPathKey("groupId", 42).build(); - Map , Object> parameters = new HashMap , Object>(1); + Map , Object> parameters = new HashMap<>(1); DynamicRecordTemplate requestInput = createDynamicRecordTemplate("spamContacts", parameters); checkRequestBuilder(request, ResourceMethod.ACTION, ActionResponseDecoder.class, expectedURIDetails, requestInput); } @@ -570,7 +570,7 @@ private static Object[][] requestGroupsBuilderDataProviderEntityWithFields() //"groups/1?fields=badge" //"groups/1?fields=badge" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("badge"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "groups/1", @@ -613,11 +613,11 @@ private static Object[][] requestGroupsBuilderDataProviderFindByEmailDomainWithF //"groups?count=10&emailDomain=foo.com&fields=locale,state&q=emailDomain&start=0" //"groups?count=10&emailDomain=foo.com&fields=locale,state&q=emailDomain&start=0" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("locale"); fieldSet.add("state"); - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("count", "10"); queryParamsMap.put("emailDomain", "foo.com"); queryParamsMap.put("q", "emailDomain"); @@ -644,7 +644,7 @@ private static Object[][] requestGroupsBuilderDataProviderFindByManagerId() //"groups?managerMemberID=1&q=manager" //"groups?managerMemberID=1&q=manager" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("managerMemberID", "1"); queryParamsMap.put("q", "manager"); @@ -669,7 +669,7 @@ private static Object[][] requestGroupsBuilderDataProviderSearch() //"groups?groupID=1&keywords=linkedin&nameKeywords=test&q=search" //"groups?groupID=1&keywords=linkedin&nameKeywords=test&q=search" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("groupID", "1"); queryParamsMap.put("keywords", "linkedin"); queryParamsMap.put("nameKeywords", "test"); @@ -696,7 +696,7 @@ private static Object[][] requestGroupsBuilderDataProviderSearchWithOptional1() //"groups?keywords=linkedin&q=search" //"groups?keywords=linkedin&q=search" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("keywords", "linkedin"); queryParamsMap.put("q", "search"); @@ -721,7 +721,7 @@ private static Object[][] requestGroupsBuilderDataProviderSearchWithOptional2() //"groups?keywords=linkedin&nameKeywords=test&q=search" //"groups?keywords=linkedin&nameKeywords=test&q=search" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("keywords", "linkedin"); queryParamsMap.put("nameKeywords", "test"); queryParamsMap.put("q", "search"); @@ -747,7 +747,7 @@ private static Object[][] requestGroupsBuilderDataProviderSearchWithOptional3() //"groups?groupID=1&q=search" //"groups?groupID=1&q=search" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("groupID", "1"); queryParamsMap.put("q", "search"); @@ -772,10 +772,10 @@ private static Object[][] requestGroupsBatchDataProviderBatch() //"groups?fields=approvalModes&ids=1&ids=3" //"groups?fields=approvalModes&ids=List(1,3)" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("approvalModes"); - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("3"); @@ -819,7 +819,7 @@ private static Object[][] requestContactsBuilderDataProviderEntityWithFields() //"groups/1/contacts/1?fields=lastName,firstName" //"groups/1/contacts/1?fields=lastName,firstName" - final Set fieldSet = new HashSet(); + final Set fieldSet = new HashSet<>(); fieldSet.add("lastName"); fieldSet.add("firstName"); @@ -844,7 +844,7 @@ private static Object[][] requestContactsBatchDataProvider() //"groups/1/contacts?ids=1&ids=3" //"groups/1/contacts?ids=List(1,3)" - final Set idSet = new HashSet(); + final Set idSet = new HashSet<>(); idSet.add("1"); idSet.add("3"); @@ -886,7 +886,7 @@ private static Object[][] requestGroupsBuilderDataProviderEntityAction() //"groups/1?action=transferOwnership" //"groups/1?action=transferOwnership" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "transferOwnership"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "groups/1", @@ -933,12 +933,12 @@ private static Object[][] requestMembershipsBatchDataProviderBatch() //Note that we need two different ID sets, one for V1 and one for V2 since batch operations on compound keys //are unique. - final Set idSetV1 = new HashSet(); + final Set idSetV1 = new HashSet<>(); idSetV1.add("groupID=2&memberID=1"); idSetV1.add("groupID=2&memberID=2"); idSetV1.add("groupID=1&memberID=1"); - final Set idSetV2 = new HashSet(); + final Set idSetV2 = new HashSet<>(); final DataMap id1 = new DataMap(); id1.put("groupID", "2"); id1.put("memberID", "1"); @@ -971,7 +971,7 @@ private static Object[][] requestMembershipsBuilderDataProviderEntityFinderByMem //"groupMemberships/memberID=1?q=member" //"groupMemberships/(memberID:1)?q=member" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("q", "member"); final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), @@ -995,7 +995,7 @@ private static Object[][] requestMembershipsBuilderDataProviderEntityFinderByGro //"groupMemberships/groupID=1?email=bruce@test.linkedin.com&firstName=Bruce&lastName=Willis&level=MEMBER&q=group&sort=LAST_NAME_ASC" //"groupMemberships/(groupID:1)?email=bruce@test.linkedin.com&firstName=Bruce&lastName=Willis&level=MEMBER&q=group&sort=LAST_NAME_ASC" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("email", "bruce@test.linkedin.com"); queryParamsMap.put("firstName", "Bruce"); queryParamsMap.put("lastName", "Willis"); @@ -1024,7 +1024,7 @@ private static Object[][] requestMembershipsBuilderDataProviderEntityFinderByGro //"groupMemberships/groupID=1?firstName=Bruce&q=group" //"groupMemberships/(groupID:1)?firstName=Bruce&q=group" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("firstName", "Bruce"); queryParamsMap.put("q", "group"); @@ -1082,10 +1082,10 @@ private static Object[][] requestContactsBuilderDataProviderAction() //"groups/42/contacts?action=spamContacts" //"groups/42/contacts?action=spamContacts" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("action", "spamContacts"); - final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), + final URIDetails uriDetails1 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "groups/42/contacts", null, queryParamsMap, null); final URIDetails uriDetails2 = new URIDetails(AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion(), diff --git a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestPatchGeneration.java b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestPatchGeneration.java index d5cbf373c6..ec2e627898 100644 --- a/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestPatchGeneration.java +++ b/restli-int-test-client/src/test/java/com/linkedin/restli/examples/groups/TestPatchGeneration.java @@ -88,8 +88,8 @@ public void testSimplePositiveMask() throws Exception //The ordering might be different but the URI should look something like: //"id,description,name"; final String actualEncodedMaskURI = URIMaskUtil.encodeMaskForURI(mask); - final Set maskURISet = new HashSet(Arrays.asList(actualEncodedMaskURI.split(","))); - final Set expectedURISet = new HashSet(); + final Set maskURISet = new HashSet<>(Arrays.asList(actualEncodedMaskURI.split(","))); + final Set expectedURISet = new HashSet<>(); expectedURISet.add("id"); expectedURISet.add("description"); expectedURISet.add("name"); @@ -138,8 +138,8 @@ public void testNegativeMask() throws Exception //The ordering might be different but the URI should look something like: //"-id,owner:(-id),-badge"; final String actualEncodedMaskURI = URIMaskUtil.encodeMaskForURI(mask); - final Set maskURISet = new HashSet(Arrays.asList(actualEncodedMaskURI.split(","))); - final Set expectedURISet = new HashSet(); + final Set maskURISet = new HashSet<>(Arrays.asList(actualEncodedMaskURI.split(","))); + final Set expectedURISet = new HashSet<>(); expectedURISet.add("-id"); expectedURISet.add("owner:(-id)"); expectedURISet.add("-badge"); @@ -375,4 +375,4 @@ void testRoundtripModifyEscapedField() throws Exception assertEquals(g1, g2); } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/AssociationResourceHelpers.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/AssociationResourceHelpers.java index 400734bca0..c7ed876671 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/AssociationResourceHelpers.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/AssociationResourceHelpers.java @@ -43,7 +43,7 @@ public class AssociationResourceHelpers .setMessage("src1-dest1") .setTone(Tone.SINCERE); - public static Map DB = new HashMap(); + public static Map DB = new HashMap<>(); static { DB.put(URL_COMPOUND_KEY, URL_MESSAGE); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsResource.java index d1dd2972e4..b7052f6a85 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsResource.java @@ -84,7 +84,7 @@ public Message get(CompoundKey id) @Override public Map batchGet(Set ids) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (CompoundKey key: ids) { result.put(key, DB.get(key)); @@ -116,12 +116,12 @@ public BatchUpdateResult batchUpdate(BatchPatchRequest buildUpdateResult(Set keys) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (CompoundKey key: keys) { result.put(key, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(result); + return new BatchUpdateResult<>(result); } @Finder("assocKeyFinder") diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsSubResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsSubResource.java index f20e0cfcdd..b01d123879 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsSubResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AssociationsSubResource.java @@ -64,7 +64,7 @@ public Message get(String key) @Finder("tone") public List findByTone(@QueryParam("tone") Tone tone) { - List messages = new ArrayList(2); + List messages = new ArrayList<>(2); Message message1 = new Message(); message1.setId("one"); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationDemoResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationDemoResource.java index e31b63c28a..dac1a777c6 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationDemoResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationDemoResource.java @@ -92,14 +92,14 @@ public CreateKVResponse create(final ValidationDemo ent // Return valid entity returnedEntity = _validReturnEntity; } - return new CreateKVResponse(1234, returnedEntity); + return new CreateKVResponse<>(1234, returnedEntity); } @RestMethod.BatchCreate @ReturnEntity public BatchCreateKVResult batchCreate(final BatchCreateRequest entities) { - List> results = new ArrayList>(); + List> results = new ArrayList<>(); int id = 0; for (ValidationDemo entity : entities.getInput()) { @@ -120,10 +120,10 @@ else if (entity.getStringB().equals("b2")) { returnEntity = _validReturnEntity; } - results.add(new CreateKVResponse(id, returnEntity)); + results.add(new CreateKVResponse<>(id, returnEntity)); id++; } - return new BatchCreateKVResult(results); + return new BatchCreateKVResult<>(results); } @RestMethod.Update @@ -135,15 +135,15 @@ public UpdateResponse update(final Integer key, final ValidationDemo entity) @RestMethod.BatchUpdate public BatchUpdateResult batchUpdate(final BatchUpdateRequest entities) { - Map results = new HashMap(); - Map errors = new HashMap(); + Map results = new HashMap<>(); + Map errors = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { Integer key = entry.getKey(); ValidationDemo entity = entry.getValue(); results.put(key, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(results, errors); + return new BatchUpdateResult<>(results, errors); } @RestMethod.PartialUpdate @@ -155,15 +155,15 @@ public UpdateResponse update(final Integer key, final PatchRequest batchUpdate(final BatchPatchRequest entityUpdates) { - Map results = new HashMap(); - Map errors = new HashMap(); + Map results = new HashMap<>(); + Map errors = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { Integer key = entry.getKey(); PatchRequest patch = entry.getValue(); results.put(key, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(results, errors); + return new BatchUpdateResult<>(results, errors); } @RestMethod.Get @@ -183,8 +183,8 @@ public ValidationDemo get(final Integer key) @RestMethod.BatchGet public BatchResult batchGet(Set ids) { - Map resultMap = new HashMap(); - Map errorMap = new HashMap(); + Map resultMap = new HashMap<>(); + Map errorMap = new HashMap<>(); // Generate entities that are missing a required field for (Integer id : ids) { @@ -206,13 +206,13 @@ else if (id == 1) resultMap.put(id, validationDemo); } }; - return new BatchResult(resultMap, errorMap); + return new BatchResult<>(resultMap, errorMap); } @RestMethod.GetAll public List getAll() { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); // Generate entities with stringA fields that are too long for (int i = 0; i < 4; i++) { @@ -231,7 +231,7 @@ public List search(@QueryParam("intA") Integer intA) { throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST); } - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); // Generate entities that are missing stringB fields for (int i = 0; i < 3; i++) { @@ -249,7 +249,7 @@ public BatchFinderResult searchVa BatchFinderResult batchFinderResult = new BatchFinderResult<>(); for (ValidationDemoCriteria currentCriteria : criteria) { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); if (currentCriteria.getIntA() == 1111) { // Generate entities that are missing stringB fields for (int i = 0; i < 3; i++) diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationWithProjectionResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationWithProjectionResource.java index 365ddb4ce3..15eba82220 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationWithProjectionResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/AutomaticValidationWithProjectionResource.java @@ -116,7 +116,7 @@ public class AutomaticValidationWithProjectionResource implements KeyValueResour // _returnEntity.setIntA() valid, missing optional _returnEntity.setValidationDemoNext(nextDemo); - _returnEntityList = new ArrayList(); + _returnEntityList = new ArrayList<>(); _returnEntityList.add(_returnEntity); } @@ -124,16 +124,16 @@ public class AutomaticValidationWithProjectionResource implements KeyValueResour @ReturnEntity public CreateKVResponse create() throws CloneNotSupportedException { - return new CreateKVResponse(1, _returnEntity); + return new CreateKVResponse<>(1, _returnEntity); } @RestMethod.BatchCreate @ReturnEntity public BatchCreateKVResult batchCreate() { - List> results = new ArrayList>(); - results.add(new CreateKVResponse(1, _returnEntity)); - return new BatchCreateKVResult(results); + List> results = new ArrayList<>(); + results.add(new CreateKVResponse<>(1, _returnEntity)); + return new BatchCreateKVResult<>(results); } @RestMethod.Get @@ -145,9 +145,9 @@ public ValidationDemo get() @RestMethod.BatchGet public BatchResult batchGet() { - Map resultMap = new HashMap(); + Map resultMap = new HashMap<>(); resultMap.put(1, _returnEntity); - return new BatchResult(resultMap, new HashMap()); + return new BatchResult<>(resultMap, new HashMap<>()); } @RestMethod.GetAll @@ -159,7 +159,7 @@ public List getAll() @Finder("searchWithProjection") public List searchWithProjection() { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); validationDemos.add(_returnEntity); return validationDemos; } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchFinderResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchFinderResource.java index a6182d1af0..09bf58db1c 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchFinderResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchFinderResource.java @@ -77,8 +77,8 @@ public BatchFinderResult searchGreetings(@Pag @Finder("searchWithMetadata") public CollectionResult searchWithMetadata() { - return new CollectionResult(Collections.emptyList(), - 0, - new SearchMetadata()); + return new CollectionResult<>(Collections.emptyList(), + 0, + new SearchMetadata()); } } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchGreetingResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchGreetingResource.java index 01057be0d0..178d3471fe 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchGreetingResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/BatchGreetingResource.java @@ -90,8 +90,8 @@ public class BatchGreetingResource extends CollectionResourceTemplate batchGet(Set ids) { - Map batch = new HashMap(); - Map errors = new HashMap(); + Map batch = new HashMap<>(); + Map errors = new HashMap<>(); for (Long id : ids) { Greeting greeting = DB.get(id); @@ -112,7 +112,7 @@ public Map batchGet(Set ids) @MaxBatchSize(value = 2) public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); @@ -124,7 +124,7 @@ public BatchUpdateResult batchUpdate(BatchUpdateRequest batchUpdate(BatchPatchRequest entityUpdates) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); @@ -149,7 +149,7 @@ public BatchCreateResult batchCreate(BatchCreateRequest batchDelete(BatchDeleteRequest deleteRequest) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Long id : deleteRequest.getKeys()) { responseMap.put(id, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); @@ -214,4 +214,4 @@ public UpdateResponse update(Long id, Greeting entity) return new UpdateResponse(HttpStatus.S_204_NO_CONTENT); } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ChainedTyperefResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ChainedTyperefResource.java index ce4f25011c..cf0341d0f3 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ChainedTyperefResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ChainedTyperefResource.java @@ -73,14 +73,14 @@ public Greeting get(CompoundKey key) public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { Set keys = entities.getData().keySet(); - Map responseMap = new HashMap(); - Map errorMap = new HashMap(); + Map responseMap = new HashMap<>(); + Map errorMap = new HashMap<>(); for(CompoundKey key : keys) { responseMap.put(key, new UpdateResponse(HttpStatus.S_201_CREATED)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Finder("dateOnly") diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexArrayResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexArrayResource.java index 1845c80e5b..3b8d7fe45f 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexArrayResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexArrayResource.java @@ -60,7 +60,7 @@ public Greeting get(ComplexResourceKey key) @Override public Map, Greeting> batchGet(Set> keys) { - Map, Greeting> map = new HashMap, Greeting>(); + Map, Greeting> map = new HashMap<>(); for(ComplexResourceKey key: keys) { map.put(key, get(key)); @@ -74,7 +74,7 @@ public List finder(@QueryParam("array") ComplexArray array) array.getArray(); array.getNext().getArray(); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(DEFAULT_GREETING); return list; } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysDataProvider.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysDataProvider.java index 8d80064abb..e099baaeab 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysDataProvider.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysDataProvider.java @@ -42,7 +42,7 @@ public class ComplexKeysDataProvider { - private Map _db = new HashMap(); + private Map _db = new HashMap<>(); public ComplexKeysDataProvider() { @@ -69,7 +69,7 @@ public ComplexResourceKey create(Message message) key.setMinor(message.getMessage()); _db.put(keyToString(key), message); - return new ComplexResourceKey(key, new TwoPartKey()); + return new ComplexResourceKey<>(key, new TwoPartKey()); } public void update(ComplexResourceKey key, Message message) { @@ -86,7 +86,7 @@ public void partialUpdate( public List findByPrefix(String prefix) { - ArrayList results = new ArrayList(); + ArrayList results = new ArrayList<>(); for (Map.Entry entry : _db.entrySet()) { @@ -103,9 +103,9 @@ public BatchResult, Message> batchGet Set> keys) { Map, Message> data = - new HashMap, Message>(); + new HashMap<>(); Map, RestLiServiceException> errors = - new HashMap, RestLiServiceException>(); + new HashMap<>(); for (ComplexResourceKey key : keys) { @@ -120,16 +120,16 @@ public BatchResult, Message> batchGet } } - return new BatchResult, Message>(data, errors); + return new BatchResult<>(data, errors); } public BatchUpdateResult, Message> batchUpdate( BatchUpdateRequest, Message> entities) { final Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); final Map, RestLiServiceException> errors = - new HashMap, RestLiServiceException>(); + new HashMap<>(); for (Map.Entry, Message> entry : entities.getData().entrySet()) { @@ -144,14 +144,14 @@ public BatchUpdateResult, Message> ba } } - return new BatchUpdateResult, Message>(results, errors); + return new BatchUpdateResult<>(results, errors); } public BatchUpdateResult, Message> batchUpdate( BatchPatchRequest, Message> patches) { final Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (Map.Entry, PatchRequest> patch : patches.getData().entrySet()) { @@ -166,14 +166,14 @@ public BatchUpdateResult, Message> ba } } - return new BatchUpdateResult, Message>(results); + return new BatchUpdateResult<>(results); } public BatchUpdateResult, Message> batchDelete( BatchDeleteRequest, Message> ids) { final Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (ComplexResourceKey id : ids.getKeys()) { @@ -181,12 +181,12 @@ public BatchUpdateResult, Message> ba results.put(id, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult, Message>(results); + return new BatchUpdateResult<>(results); } public List getAll() { - ArrayList results = new ArrayList(); + ArrayList results = new ArrayList<>(); for (Map.Entry entry : _db.entrySet()) { diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysResource.java index e7332915ac..c733c27d60 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ComplexKeysResource.java @@ -77,7 +77,7 @@ public CreateResponse create(final Message message) @Override public BatchCreateResult, Message> batchCreate(final BatchCreateRequest, Message> entities) { - List createResponses = new ArrayList(entities.getInput().size()); + List createResponses = new ArrayList<>(entities.getInput().size()); for(Message message : entities.getInput()) { @@ -86,7 +86,7 @@ public BatchCreateResult, Message> ba createResponses.add(createResponse); } - return new BatchCreateResult, Message>(createResponses); + return new BatchCreateResult<>(createResponses); } @Override diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CompressionResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CompressionResource.java index a8de329ce5..8a6f17173c 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CompressionResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CompressionResource.java @@ -56,7 +56,7 @@ public static String getNoRedundantQueryExample() @Finder("repeatedGreetings") public List serveRepeatedGreeting(@QueryParam(value="repeat", typeref=CustomLongRef.class) CustomLong l) { - List result = new ArrayList(); + List result = new ArrayList<>(); Greeting g = new Greeting(); g.setId(1); @@ -73,4 +73,4 @@ public List serveRepeatedGreeting(@QueryParam(value="repeat", typeref= return result; } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CookieResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CookieResource.java index e69bbbb049..ea52cad3c3 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CookieResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CookieResource.java @@ -49,7 +49,7 @@ public Greeting get(Long Key) @Override public Map batchGet(Set keys) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Long key : keys) { result.put(key, new Greeting().setId(key).setMessage("NO CONTENT").setTone(Tone.FRIENDLY)); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomMetadataProjectionResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomMetadataProjectionResource.java index 32f46f4650..0e083cbb9e 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomMetadataProjectionResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomMetadataProjectionResource.java @@ -69,7 +69,7 @@ public class CustomMetadataProjectionResource extends CollectionResourceTemplate GREETING_TWO.setId(15l); GREETING_TWO.setMessage("I really like you!"); - LIST = new ArrayList(); + LIST = new ArrayList<>(); LIST.add(GREETING_ONE); LIST.add(GREETING_TWO); @@ -89,7 +89,7 @@ public CollectionResult rootAutomaticMetadataAutomatic( final @MetadataProjectionParam MaskTree metadataProjection, final @PagingProjectionParam MaskTree pagingProjection) { - return new CollectionResult(LIST, 2, CUSTOM_METADATA_GREETING); + return new CollectionResult<>(LIST, 2, CUSTOM_METADATA_GREETING); } /** @@ -104,7 +104,7 @@ public CollectionResult rootAutomaticMetadataManual( final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(LIST, 2, applyMetadataProjection(metadataProjection)); + return new CollectionResult<>(LIST, 2, applyMetadataProjection(metadataProjection)); } /** @@ -119,7 +119,7 @@ public CollectionResult rootManualMetadataAutomatic( final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(applyRootObjectProjection(rootObjectProjection), + return new CollectionResult<>(applyRootObjectProjection(rootObjectProjection), 2, CUSTOM_METADATA_GREETING); } @@ -136,7 +136,7 @@ public CollectionResult rootManualMetadataManual( { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); super.getContext().setProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(applyRootObjectProjection(rootObjectProjection), + return new CollectionResult<>(applyRootObjectProjection(rootObjectProjection), 2, applyMetadataProjection(metadataProjection)); } @@ -153,7 +153,7 @@ public CollectionResult getAllRootAutomaticMetadataManual( final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(LIST, 2, applyMetadataProjection(metadataProjection)); + return new CollectionResult<>(LIST, 2, applyMetadataProjection(metadataProjection)); } /** @@ -168,7 +168,7 @@ public CollectionResult rootAutomaticMetadataAutomaticNull( final @MetadataProjectionParam MaskTree metadataProjection, final @PagingProjectionParam MaskTree pagingProjection) { - return new CollectionResult(LIST, 2, null); + return new CollectionResult<>(LIST, 2, null); } private List applyRootObjectProjection(final MaskTree rootObjectProjection) throws CloneNotSupportedException @@ -200,4 +200,4 @@ private Greeting applyMetadataProjection(final MaskTree metadataProjection) thro } return clonedGreeting; } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource2.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource2.java index 27c920c84a..ee531e63c0 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource2.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource2.java @@ -61,7 +61,7 @@ public Greeting get(CustomLong lo) @Override public Map batchGet(Set ids) { - Map result = new HashMap(ids.size()); + Map result = new HashMap<>(ids.size()); for (CustomLong id: ids) { @@ -74,34 +74,34 @@ public Map batchGet(Set ids) @Override public BatchUpdateResult batchDelete(BatchDeleteRequest ids) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (CustomLong id: ids.getKeys()) { results.put(id, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } @Override public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (CustomLong id: entityUpdates.getData().keySet()) { results.put(id, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } @Override public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (CustomLong id: entities.getData().keySet()) { results.put(id, new UpdateResponse(HttpStatus.S_204_NO_CONTENT)); } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } @RestMethod.Create @@ -114,12 +114,12 @@ public CreateResponse create(final Greeting greeting, @QueryParam(value="unionRe @Override public BatchCreateResult batchCreate(BatchCreateRequest entities) { - List results = new ArrayList(); + List results = new ArrayList<>(); for (Greeting greeting: entities.getInput()) { // just echo back the provided ids (for testing only, this would not a be correct implementation of POST) results.add(new CreateResponse(new CustomLong(greeting.getId()), HttpStatus.S_204_NO_CONTENT)); } - return new BatchCreateResult(results); + return new BatchCreateResult<>(results); } } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource3.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource3.java index 4bf2001bdd..36211c7c4b 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource3.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/CustomTypesResource3.java @@ -71,14 +71,14 @@ public Greeting get(CompoundKey key) public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { Set keys = entities.getData().keySet(); - Map responseMap = new HashMap(); - Map errorMap = new HashMap(); + Map responseMap = new HashMap<>(); + Map errorMap = new HashMap<>(); for(CompoundKey key : keys) { responseMap.put(key, new UpdateResponse(HttpStatus.S_201_CREATED)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Finder("dateOnly") diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource.java index e5c85b6473..04af88efcd 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource.java @@ -96,7 +96,7 @@ public CreateResponse create(Greeting g) @Override public BatchCreateResult batchCreate(BatchCreateRequest entities) { - List responses = new ArrayList(entities.getInput().size()); + List responses = new ArrayList<>(entities.getInput().size()); for (Greeting g : entities.getInput()) { @@ -109,7 +109,7 @@ public BatchCreateResult batchCreate(BatchCreateRequest(responses); + return new BatchCreateResult<>(responses); } @Action(name = "errorResponseFormatMinimal") diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource2.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource2.java index a8e9a1985a..d1467cf849 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource2.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ExceptionsResource2.java @@ -38,7 +38,7 @@ public class ExceptionsResource2 extends CollectionResourceTemplate getWithResult(Long key) { final Greeting value = new Greeting().setMessage("Hello, sorry for the mess"); - return new GetResult(value, HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new GetResult<>(value, HttpStatus.S_500_INTERNAL_SERVER_ERROR); } /** @@ -47,7 +47,7 @@ public GetResult getWithResult(Long key) @Action(name = "exceptionWithValue") public ActionResult exceptionWithValue() { - return new ActionResult(42, HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new ActionResult<>(42, HttpStatus.S_500_INTERNAL_SERVER_ERROR); } /** @@ -56,6 +56,6 @@ public ActionResult exceptionWithValue() @Action(name = "exceptionWithoutValue") public ActionResult exceptionWithoutValue() { - return new ActionResult(HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new ActionResult<>(HttpStatus.S_500_INTERNAL_SERVER_ERROR); } } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/FindersResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/FindersResource.java index 193bd2b8e5..83285c2a1e 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/FindersResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/FindersResource.java @@ -39,21 +39,21 @@ public class FindersResource extends CollectionResourceTemplate @Finder("searchWithoutMetadata") public CollectionResult search() { - return new CollectionResult(Collections.emptyList(), 0, null); + return new CollectionResult<>(Collections.emptyList(), 0, null); } @Finder("searchWithMetadata") public CollectionResult searchWithMetadata() { - return new CollectionResult(Collections.emptyList(), - 0, - new SearchMetadata()); + return new CollectionResult<>(Collections.emptyList(), + 0, + new SearchMetadata()); } @Finder("basicSearch") public BasicCollectionResult basicSearch() { - return new BasicCollectionResult(Collections.emptyList(), 0); + return new BasicCollectionResult<>(Collections.emptyList(), 0); } @Finder("predefinedSearch") @@ -62,4 +62,3 @@ public GreetingFinderResult predefinedSearch() return new GreetingFinderResult(Collections.emptyList(), 0); } } - diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceCodeGenerator.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceCodeGenerator.java index e1b5322c83..45e5c2d0ab 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceCodeGenerator.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceCodeGenerator.java @@ -449,7 +449,7 @@ private String toStrGenericType(final Type t) private static final Map, String> PRIMITIVES_TO_CLASSES; static { - final Map, String> map = new HashMap, String>(); + final Map, String> map = new HashMap<>(); map.put(byte.class, "Byte"); map.put(short.class, "Short"); map.put(int.class, "Integer"); @@ -524,7 +524,7 @@ private String toStrAnnotation(final Annotation anno) sb.append(className(annoType)); final Method[] methods = annoType.getDeclaredMethods(); - final Map values = new TreeMap(); + final Map values = new TreeMap<>(); for (final Method method : methods) { try @@ -590,8 +590,8 @@ private String genericWrapper(final Class genericClass, final Type typeArg) return String.format("%s<%s>", className(genericClass), toStrGenericType(typeArg, true)); } - private final Set _importedShort = new TreeSet(); - private final Set _importedFull = new TreeSet(); + private final Set _importedShort = new TreeSet<>(); + private final Set _importedFull = new TreeSet<>(); /** * Import the class and give the short name if possible diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceImpl.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceImpl.java index deb90f2764..fde084074d 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceImpl.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/GreetingsResourceImpl.java @@ -100,7 +100,7 @@ class GreetingsResourceImpl implements KeyValueResource } private final AtomicLong _idSeq = new AtomicLong(); - private final Map _db = Collections.synchronizedMap(new LinkedHashMap()); + private final Map _db = Collections.synchronizedMap(new LinkedHashMap<>()); private final String _resourceName; public GreetingsResourceImpl(String resourceName) @@ -134,8 +134,8 @@ public CreateResponse create(Greeting entity, @QueryParam("isNullId") @Optional( @RestMethod.BatchGet public Map batchGet(Set ids) { - Map batch = new HashMap(); - Map errors = new HashMap(); + Map batch = new HashMap<>(); + Map errors = new HashMap<>(); for (long id : ids) { Greeting g = _db.get(id); @@ -149,52 +149,52 @@ public Map batchGet(Set ids) } } - return new BatchResult(batch, errors); + return new BatchResult<>(batch, errors); } @RestMethod.BatchUpdate public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.BatchPartialUpdate public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.BatchCreate public BatchCreateResult batchCreate(BatchCreateRequest entities) { - List responses = new ArrayList(entities.getInput().size()); + List responses = new ArrayList<>(entities.getInput().size()); for (Greeting g : entities.getInput()) { responses.add(create(g, false)); } - return new BatchCreateResult(responses); + return new BatchCreateResult<>(responses); } @RestMethod.BatchDelete public BatchUpdateResult batchDelete(BatchDeleteRequest deleteRequest) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Long id : deleteRequest.getKeys()) { responseMap.put(id, delete(id)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.Get @@ -257,7 +257,7 @@ public List getAll(@PagingContextParam PagingContext ctx) { // Deterministic behaviour of getAll to make it easier to test as part of the integration test suite // Just return those greetings that have "GetAll" present in their message - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); for (Greeting greeting: _db.values()) { if (greeting.getMessage().contains("GetAll")) @@ -278,7 +278,7 @@ public List searchWithDefault(@PagingContextParam PagingContext ctx, @Finder("search") public List search(@PagingContextParam PagingContext ctx, @QueryParam("tone") @Optional Tone tone) { - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); int idx = 0; int start = ctx.getStart(); int stop = start + ctx.getCount(); @@ -303,7 +303,7 @@ public List search(@PagingContextParam PagingContext ctx, @QueryParam( @Finder("searchWithPostFilter") public CollectionResult searchWithPostFilter(@PagingContextParam PagingContext ctx) { - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); int idx = 0; int start = ctx.getStart(); int stop = start + ctx.getCount(); @@ -324,14 +324,14 @@ public CollectionResult searchWithPostFilter(@PagingContextPara int total = _db.values().size(); // but we keep the numElements returned as the full count despite the fact that with the filter removed 1 // this is to keep paging consistent even in the presence of a post filter. - return new CollectionResult(greetings, total, null, PageIncrement.FIXED); + return new CollectionResult<>(greetings, total, null, PageIncrement.FIXED); } @Finder("searchWithTones") public List searchWithTones(@PagingContextParam PagingContext ctx, @QueryParam("tones") @Optional Tone[] tones) { - Set toneSet = new HashSet(Arrays.asList(tones)); - List greetings = new ArrayList(); + Set toneSet = new HashSet<>(Arrays.asList(tones)); + List greetings = new ArrayList<>(); int idx = 0; int start = ctx.getStart(); int stop = start + ctx.getCount(); @@ -358,7 +358,7 @@ public CollectionResult searchWithFacets(@PagingContex { List greetings = search(ctx, tone); - Map toneCounts = new HashMap(); + Map toneCounts = new HashMap<>(); for (Greeting g : greetings) { if (!toneCounts.containsKey(g.getTone())) @@ -378,7 +378,7 @@ public CollectionResult searchWithFacets(@PagingContex metadata.getFacets().add(f); } - return new CollectionResult(greetings, null, metadata); + return new CollectionResult<>(greetings, null, metadata); } // test if @{link EmptyArray} is generated from ArrayOfEmptys.pdsc diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/NullGreetingsResourceImpl.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/NullGreetingsResourceImpl.java index 287aec1f6e..118894268d 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/NullGreetingsResourceImpl.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/NullGreetingsResourceImpl.java @@ -78,7 +78,7 @@ public class NullGreetingsResourceImpl extends CollectionResourceTemplate DB = new HashMap(); + private static final Map DB = new HashMap<>(); private static final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(1); private static final int DELAY = 100; @@ -135,7 +135,7 @@ public List searchReturnNullList(@PagingContextParam PagingContext ctx else { //return a list with a null element in it - final List greetings = new ArrayList(); + final List greetings = new ArrayList<>(); greetings.add(null); greetings.add(DB.get(1)); return greetings; @@ -154,15 +154,15 @@ public CollectionResult searchReturnNullCollectionList else if (tone == Tone.SINCERE) { //return a CollectionResult with a null list - return new CollectionResult(null); + return new CollectionResult<>(null); } else { //return a CollectionResult with a list that has a null element in it - final List greetings = new ArrayList(); + final List greetings = new ArrayList<>(); greetings.add(null); greetings.add(DB.get(1)); - return new CollectionResult(greetings); + return new CollectionResult<>(greetings); } } @@ -181,7 +181,7 @@ public CollectionResult getAllCollectionResult(@PagingContextPa @RestMethod.BatchGet public BatchResult batchGetBatchResult(Set ids) { - final Map greetingMap = new HashMap(); + final Map greetingMap = new HashMap<>(); greetingMap.put(0l, DB.get(0l)); if (ids.contains(1l)) @@ -192,20 +192,20 @@ public BatchResult batchGetBatchResult(Set ids) else if (ids.contains(2l)) { //Return BatchResult with null maps - return new BatchResult(null, null, null); + return new BatchResult<>(null, null, null); } else if (ids.contains(3l)) { //Return a BatchResult with a null key in the status map. - final Map statusMap = new HashMap(); + final Map statusMap = new HashMap<>(); statusMap.put(null, null); - return new BatchResult(greetingMap, statusMap, null); + return new BatchResult<>(greetingMap, statusMap, null); } else if (ids.contains(4l)) { //Return a BatchResult that has a map with a null key. greetingMap.put(null, null); - return new BatchResult(greetingMap, null, null); + return new BatchResult<>(greetingMap, null, null); } else { @@ -216,9 +216,9 @@ else if (ids.contains(4l)) * Rest.li resource methods do not cause such NPEs. * This is one of the few cases in this file where an error will not be generated by Rest.li. */ - final Map concurrentGreetingMap = new ConcurrentHashMap(greetingMap); - return new BatchResult(concurrentGreetingMap, - new ConcurrentHashMap(), new ConcurrentHashMap()); + final Map concurrentGreetingMap = new ConcurrentHashMap<>(greetingMap); + return new BatchResult<>(concurrentGreetingMap, + new ConcurrentHashMap<>(), new ConcurrentHashMap<>()); } } @@ -240,7 +240,7 @@ public UpdateResponse update(Long key, Greeting entity) @RestMethod.BatchCreate public BatchCreateResult batchCreate(BatchCreateRequest entities) { - List responses = new ArrayList(1); + List responses = new ArrayList<>(1); if (entities.getInput().size() == 0) { //Return null @@ -249,24 +249,24 @@ public BatchCreateResult batchCreate(BatchCreateRequest(null); + return new BatchCreateResult<>(null); } else { //Return a new BatchCreateResult with a response list that has a null inside of it responses.add(new CreateResponse(1l)); responses.add(null); - return new BatchCreateResult(responses); + return new BatchCreateResult<>(responses); } } @RestMethod.BatchUpdate public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - final Map responseMap = new HashMap(); + final Map responseMap = new HashMap<>(); responseMap.put(3l, new UpdateResponse(HttpStatus.S_201_CREATED)); - final Map errorsMap = new HashMap(); + final Map errorsMap = new HashMap<>(); errorsMap.put(8l, new RestLiServiceException(HttpStatus.S_202_ACCEPTED)); if (entities.getData().containsKey(1l)) @@ -277,30 +277,30 @@ public BatchUpdateResult batchUpdate(BatchUpdateRequest(null); + return new BatchUpdateResult<>(null); } else if (entities.getData().containsKey(3l)) { //Return a BatchUpdateResult with a null errors Map - return new BatchUpdateResult(responseMap, null); + return new BatchUpdateResult<>(responseMap, null); } else if (entities.getData().containsKey(4l)) { //Return a BatchUpdateResult with a errors Map that has a null key in it errorsMap.put(null, new RestLiServiceException(HttpStatus.S_202_ACCEPTED)); - return new BatchUpdateResult(responseMap, errorsMap); + return new BatchUpdateResult<>(responseMap, errorsMap); } else if (entities.getData().containsKey(5l)) { //Return a BatchUpdateResult with a errors Map that has a null value in it errorsMap.put(9l, null); - return new BatchUpdateResult(responseMap, errorsMap); + return new BatchUpdateResult<>(responseMap, errorsMap); } else if (entities.getData().containsKey(6l)) { //Return a BatchUpdateResult with a map that has a null key in it responseMap.put(null, new UpdateResponse(HttpStatus.S_201_CREATED)); - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } else { @@ -312,15 +312,15 @@ else if (entities.getData().containsKey(6l)) * Rest.li resource methods do not cause such NPEs. * This is one of the few cases in this file where an error will not be generated by Rest.li. */ - final Map concurrentResponseMap = new ConcurrentHashMap(responseMap); - return new BatchUpdateResult(concurrentResponseMap, new ConcurrentHashMap()); + final Map concurrentResponseMap = new ConcurrentHashMap<>(responseMap); + return new BatchUpdateResult<>(concurrentResponseMap, new ConcurrentHashMap<>()); } } @RestMethod.BatchPartialUpdate public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - final Map responseMap = new HashMap(); + final Map responseMap = new HashMap<>(); responseMap.put(3l, new UpdateResponse(HttpStatus.S_201_CREATED)); if (entityUpdates.getData().containsKey(1l)) @@ -331,18 +331,18 @@ public BatchUpdateResult batchUpdate(BatchPatchRequest(null); + return new BatchUpdateResult<>(null); } else if (entityUpdates.getData().containsKey(3l)) { //Return a BatchUpdateResult with a null errors Map - return new BatchUpdateResult(responseMap, null); + return new BatchUpdateResult<>(responseMap, null); } else { //Return a BatchUpdateResult with a map that has a null key in it responseMap.put(null, new UpdateResponse(HttpStatus.S_201_CREATED)); - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } } @@ -382,14 +382,14 @@ public ActionResult returnActionResultWithNullValue() { //Return an ActionResult with a null Value final Integer nullInteger = null; - return new ActionResult(nullInteger); + return new ActionResult<>(nullInteger); } @Action(name = "returnActionResultWithNullStatus") public ActionResult returnActionResultWithNullStatus() { //Return an ActionResult with a null HttpStatus - return new ActionResult(3, null); + return new ActionResult<>(3, null); } @Finder("finderCallbackNullList") @@ -449,4 +449,4 @@ protected Promise> run(final com.linkedin.parseq.Context context) } }; } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/PagingProjectionResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/PagingProjectionResource.java index d14538c5ac..8a2a713bfe 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/PagingProjectionResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/PagingProjectionResource.java @@ -71,7 +71,7 @@ public class PagingProjectionResource extends CollectionResourceTemplate(); + LIST = new ArrayList<>(); LIST.add(GREETING_ONE); LIST.add(GREETING_TWO); @@ -92,7 +92,7 @@ public CollectionResult metadataAutomaticPagingFullyAutomati final @MetadataProjectionParam MaskTree metadataProjection, final @PagingProjectionParam MaskTree pagingProjection) { - return new CollectionResult(LIST, 2, CUSTOM_METADATA_GREETING); + return new CollectionResult<>(LIST, 2, CUSTOM_METADATA_GREETING); } /** @@ -106,7 +106,7 @@ public CollectionResult metadataAutomaticPagingAutomaticPart final @MetadataProjectionParam MaskTree metadataProjection, final @PagingProjectionParam MaskTree pagingProjection) { - return new CollectionResult(LIST, calculateTotal(pagingProjection), CUSTOM_METADATA_GREETING); + return new CollectionResult<>(LIST, calculateTotal(pagingProjection), CUSTOM_METADATA_GREETING); } /** @@ -135,7 +135,7 @@ public CollectionResult metadataAutomaticPagingAutomaticPart } //Restli should correctly strip away the total (because its not in the MaskTree) even though the resource //method returned it here - return new CollectionResult(LIST, total, CUSTOM_METADATA_GREETING); + return new CollectionResult<>(LIST, total, CUSTOM_METADATA_GREETING); } /** @@ -150,7 +150,7 @@ public CollectionResult metadataManualPagingFullyAutomatic( final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(LIST, 2, applyMetadataProjection(metadataProjection)); + return new CollectionResult<>(LIST, 2, applyMetadataProjection(metadataProjection)); } /** @@ -166,7 +166,7 @@ public CollectionResult metadataManualPagingAutomaticPartial final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(LIST, + return new CollectionResult<>(LIST, calculateTotal(pagingProjection), applyMetadataProjection(metadataProjection)); } @@ -183,7 +183,7 @@ public CollectionResult getAllMetadataManualPagingAutomaticP final @PagingProjectionParam MaskTree pagingProjection) throws CloneNotSupportedException { super.getContext().setMetadataProjectionMode(ProjectionMode.MANUAL); - return new CollectionResult(LIST, calculateTotal(pagingProjection), + return new CollectionResult<>(LIST, calculateTotal(pagingProjection), applyMetadataProjection(metadataProjection)); } @@ -224,13 +224,13 @@ private Greeting applyMetadataProjection(final MaskTree metadataProjection) thro @Finder("searchWithLinksResult") public CollectionResult searchWithLinksResult(@PagingContextParam PagingContext ctx) { - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); for (int i = 0; i<5; i++) { greetings.add(GREETING_ONE); greetings.add(GREETING_TWO); } - return new CollectionResult(greetings, 50); + return new CollectionResult<>(greetings, 50); } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/SimpleResourceUnderCollectionResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/SimpleResourceUnderCollectionResource.java index 7ef522fe27..7d74166f25 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/SimpleResourceUnderCollectionResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/SimpleResourceUnderCollectionResource.java @@ -43,7 +43,7 @@ public class SimpleResourceUnderCollectionResource extends SimpleResourceTemplat { private static final Tone DEFAULT_TONE = Tone.FRIENDLY; - private static Map TONES = new HashMap(); + private static Map TONES = new HashMap<>(); static { diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysResource.java index e5211d61e0..1662ce625f 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysResource.java @@ -92,7 +92,7 @@ private String generateId() { return "message" + _idSeq.getAndIncrement(); } - private final Map _db = Collections.synchronizedMap(new LinkedHashMap()); + private final Map _db = Collections.synchronizedMap(new LinkedHashMap<>()); public StringKeysResource() { @@ -122,8 +122,8 @@ public CreateResponse create(Message entity) @RestMethod.BatchGet public Map batchGet(Set ids) { - Map batch = new HashMap(); - Map errors = new HashMap(); + Map batch = new HashMap<>(); + Map errors = new HashMap<>(); for (String id : ids) { Message g = _db.get(id); @@ -137,52 +137,52 @@ public Map batchGet(Set ids) } } - return new BatchResult(batch, errors); + return new BatchResult<>(batch, errors); } @RestMethod.BatchUpdate public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.BatchPartialUpdate public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.BatchCreate public BatchCreateResult batchCreate(BatchCreateRequest entities) { - List responses = new ArrayList(entities.getInput().size()); + List responses = new ArrayList<>(entities.getInput().size()); for (Message g : entities.getInput()) { responses.add(create(g)); } - return new BatchCreateResult(responses); + return new BatchCreateResult<>(responses); } @RestMethod.BatchDelete public BatchUpdateResult batchDelete(BatchDeleteRequest deleteRequest) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (String id : deleteRequest.getKeys()) { responseMap.put(id, delete(id)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @RestMethod.Get @@ -240,7 +240,7 @@ public UpdateResponse update(String key, Message entity) public List search(@PagingContextParam PagingContext ctx, @QueryParam("keyword") @Optional String keyword) { keyword = keyword.toLowerCase(); - List messages = new ArrayList(); + List messages = new ArrayList<>(); int idx = 0; int start = ctx.getStart(); int stop = start + ctx.getCount(); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysSubResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysSubResource.java index 6adeee9b93..8fdb4c1bad 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysSubResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/StringKeysSubResource.java @@ -43,7 +43,7 @@ ) public class StringKeysSubResource extends CollectionResourceTemplate { - private Map _db = new HashMap(); + private Map _db = new HashMap<>(); public StringKeysSubResource() { diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/TyperefKeysResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/TyperefKeysResource.java index 9b32a76cb1..1b179d1d26 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/TyperefKeysResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/TyperefKeysResource.java @@ -45,7 +45,7 @@ public CreateResponse create(Greeting entity) @Override public Map batchGet(Set keys) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Long key : keys) { result.put(key, new Greeting().setId(key)); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ValidationDemoResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ValidationDemoResource.java index bc9769bcaf..368de38170 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ValidationDemoResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/ValidationDemoResource.java @@ -85,7 +85,7 @@ public CreateResponse create(final ValidationDemo entity, @ValidatorParam RestLi public BatchCreateResult batchCreate(final BatchCreateRequest entities, @ValidatorParam RestLiDataValidator validator) { - List results = new ArrayList(); + List results = new ArrayList<>(); int id = 0; for (ValidationDemo entity : entities.getInput()) { @@ -100,7 +100,7 @@ public BatchCreateResult batchCreate(final BatchCreateR results.add(new CreateResponse(new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, result.getMessages().toString()))); } } - return new BatchCreateResult(results); + return new BatchCreateResult<>(results); } @RestMethod.Update @@ -118,8 +118,8 @@ public UpdateResponse update(final Integer key, final ValidationDemo entity, @Va public BatchUpdateResult batchUpdate(final BatchUpdateRequest entities, @ValidatorParam RestLiDataValidator validator) { - Map results = new HashMap(); - Map errors = new HashMap(); + Map results = new HashMap<>(); + Map errors = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { Integer key = entry.getKey(); @@ -134,7 +134,7 @@ public BatchUpdateResult batchUpdate(final BatchUpdateR errors.put(key, new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, result.getMessages().toString())); } } - return new BatchUpdateResult(results, errors); + return new BatchUpdateResult<>(results, errors); } @RestMethod.PartialUpdate @@ -157,8 +157,8 @@ public UpdateResponse update(final Integer key, final PatchRequest batchUpdate(final BatchPatchRequest entityUpdates, @ValidatorParam RestLiDataValidator validator) { - Map results = new HashMap(); - Map errors = new HashMap(); + Map results = new HashMap<>(); + Map errors = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { Integer key = entry.getKey(); @@ -173,7 +173,7 @@ public BatchUpdateResult batchUpdate(final BatchPatchRe errors.put(key, new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, result.getMessages().toString())); } } - return new BatchUpdateResult(results, errors); + return new BatchUpdateResult<>(results, errors); } private void check(boolean condition) @@ -212,7 +212,7 @@ public ValidationDemo get(final Integer key, @ValidatorParam RestLiDataValidator @RestMethod.BatchGet public Map batchGet(Set ids, @ValidatorParam RestLiDataValidator validator) { - Map resultMap = new HashMap(); + Map resultMap = new HashMap<>(); // Generate entities that are missing a required field for (Integer id : ids) @@ -250,7 +250,7 @@ public Map batchGet(Set ids, @ValidatorParam R @RestMethod.GetAll public List getAll(@ValidatorParam RestLiDataValidator validator) { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); // Generate entities with stringA fields that are too long for (int i = 0; i < 10; i++) @@ -288,7 +288,7 @@ public List getAll(@ValidatorParam RestLiDataValidator validator @Finder("search") public List search(@QueryParam("intA") Integer intA, @ValidatorParam RestLiDataValidator validator) { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); // Generate entities that are missing stringB fields for (int i = 0; i < 3; i++) @@ -331,7 +331,7 @@ public BatchFinderResult searchVa for (ValidationDemoCriteria currentCriteria : criteria) { - List validationDemos = new ArrayList(); + List validationDemos = new ArrayList<>(); // Generate entities that are missing stringB fields for (int i = 0; i < 3; i++) @@ -368,4 +368,4 @@ public BatchFinderResult searchVa return batchFinderResult; } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/WithContextResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/WithContextResource.java index 6f03f4b4dc..8c61ba6b87 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/WithContextResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/WithContextResource.java @@ -58,7 +58,7 @@ public Greeting get(Long key, @ProjectionParam MaskTree projection, @PathKeysPar @Finder("finder") public List finder(@HeaderParam("Expected-Header") String header, @ProjectionParam MaskTree projection, @PathKeysParam PathKeys keys) { - List list = new ArrayList(); + List list = new ArrayList<>(); Greeting greeting1 = createGreeting(projection, keys); greeting1.setId(1L); diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/AssociationAltKeyResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/AssociationAltKeyResource.java index 7cdb5f48e6..368cb473f4 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/AssociationAltKeyResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/AssociationAltKeyResource.java @@ -116,23 +116,23 @@ public UpdateResponse update(CompoundKey key, PatchRequest patch) @Override public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Override public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Override @@ -146,11 +146,11 @@ public UpdateResponse delete(CompoundKey key) @Override public BatchUpdateResult batchDelete(BatchDeleteRequest deleteRequest) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (CompoundKey id : deleteRequest.getKeys()) { responseMap.put(id, delete(id)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/CollectionAltKeyResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/CollectionAltKeyResource.java index af192b8790..330330e9ba 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/CollectionAltKeyResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/CollectionAltKeyResource.java @@ -111,23 +111,23 @@ public UpdateResponse update(Long key, PatchRequest patch) @Override public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Override public BatchUpdateResult batchUpdate(BatchPatchRequest entityUpdates) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry> entry : entityUpdates.getData().entrySet()) { responseMap.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } @Override @@ -141,11 +141,11 @@ public UpdateResponse delete(Long key) @Override public BatchUpdateResult batchDelete(BatchDeleteRequest deleteRequest) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Long id : deleteRequest.getKeys()) { responseMap.put(id, delete(id)); } - return new BatchUpdateResult(responseMap); + return new BatchUpdateResult<>(responseMap); } } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/ComplexKeyAltKeyResource.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/ComplexKeyAltKeyResource.java index b99c3aac72..47ef2dd74d 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/ComplexKeyAltKeyResource.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/ComplexKeyAltKeyResource.java @@ -56,7 +56,7 @@ public CreateResponse create(Message entity) TwoPartKey key = new TwoPartKey(); key.setMajor("testKey"); key.setMinor("testKey"); - ComplexResourceKey complexKey = new ComplexResourceKey(key, new TwoPartKey()); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, new TwoPartKey()); return new CreateResponse(complexKey, HttpStatus.S_201_CREATED); } @@ -130,13 +130,13 @@ public BatchUpdateResult, Message> ba final BatchDeleteRequest, Message> ids) { Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (ComplexResourceKey id : ids.getKeys()) { results.put(id, delete(id)); } - return new BatchUpdateResult, Message>(results); + return new BatchUpdateResult<>(results); } } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/StringComplexKeyCoercer.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/StringComplexKeyCoercer.java index 862167847b..ffc92b7ebf 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/StringComplexKeyCoercer.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/altkey/StringComplexKeyCoercer.java @@ -36,7 +36,7 @@ public class StringComplexKeyCoercer implements KeyCoercer coerceToKey(String object) throws InvalidAlternativeKeyException { String[] keys = object.split("x"); - return new ComplexResourceKey( + return new ComplexResourceKey<>( new TwoPartKey().setMajor(keys[1]).setMinor(keys[3]), new TwoPartKey()); } @@ -52,4 +52,4 @@ public String coerceFromKey(ComplexResourceKey object) { return "major" + "x" + object.getKey().getMajor() + "x" + "minor" + "x" + object.getKey().getMinor(); } -} \ No newline at end of file +} diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/defaults/FieldFillInDefaultResources.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/defaults/FieldFillInDefaultResources.java index 34d39c7804..66538a747c 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/defaults/FieldFillInDefaultResources.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/greetings/server/defaults/FieldFillInDefaultResources.java @@ -82,13 +82,12 @@ public BatchFinderResult sear @QueryParam("criteria") RecordCriteria[] criteria) { - BatchFinderResult result = new BatchFinderResult(); + BatchFinderResult result = new BatchFinderResult<>(); for (int i = 0; i < criteria.length; i++) { List currentCriteriaResult = Collections.singletonList( new HighLevelRecordWithDefault().setNoDefaultFieldA(criteria[i].getIntWithoutDefault())); - CollectionResult cr = new CollectionResult( + CollectionResult cr = new CollectionResult<>( currentCriteriaResult, currentCriteriaResult.size()); result.putResult(criteria[i], cr); } @@ -98,7 +97,7 @@ public BatchFinderResult sear @Action(name = "defaultFillAction") public ActionResult takeAction(@ActionParam("actionParam") Long id) { - return new ActionResult(new HighLevelRecordWithDefault().setNoDefaultFieldA( + return new ActionResult<>(new HighLevelRecordWithDefault().setNoDefaultFieldA( Math.toIntExact(id)), HttpStatus.S_200_OK); } diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashGroupMembershipMgr.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashGroupMembershipMgr.java index 00c8273981..1a654e978c 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashGroupMembershipMgr.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashGroupMembershipMgr.java @@ -49,7 +49,7 @@ public class HashGroupMembershipMgr implements GroupMembershipMgr public HashGroupMembershipMgr() { - _data = new HashMap(); + _data = new HashMap<>(); } @Override @@ -61,7 +61,7 @@ public GroupMembership get(CompoundKey key) @Override public Map batchGetByGroup(int groupID, Set memberIDs) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Map.Entry entry : _data.entrySet()) { CompoundKey key = entry.getKey(); @@ -77,7 +77,7 @@ public Map batchGetByGroup(int groupID, Set m @Override public Map batchGetByMember(int memberID, Set groupIDs) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Map.Entry entry : _data.entrySet()) { CompoundKey key = entry.getKey(); @@ -117,7 +117,7 @@ public boolean delete(CompoundKey key) @Override public List search(GroupMembershipSearchQuery query) { - List result = new ArrayList(); + List result = new ArrayList<>(); int counter = 0; for (Map.Entry entry : _data.entrySet()) @@ -162,7 +162,7 @@ public List search(GroupMembershipSearchQuery query) public List getByMember(int memberID, MembershipLevel level, int start, int count) { - List result = new ArrayList(); + List result = new ArrayList<>(); int idx = 0; for (GroupMembership value : _data.values()) { diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashMapGroupMgr.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashMapGroupMgr.java index 75803c71a9..9616c9fd3f 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashMapGroupMgr.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/impl/HashMapGroupMgr.java @@ -47,7 +47,7 @@ public class HashMapGroupMgr implements GroupMgr public HashMapGroupMgr(GroupMembershipMgr membershipMgr) { - _data = new HashMap(); + _data = new HashMap<>(); _sequence = new AtomicInteger(); _membershipMgr = membershipMgr; } @@ -55,7 +55,7 @@ public HashMapGroupMgr(GroupMembershipMgr membershipMgr) @Override public Map batchGet(Set ids) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (Integer id : ids) { Group g = _data.get(id); @@ -102,7 +102,7 @@ public Map getGroupContacts(Set ids) @Override public List findByEmailDomain(String emailDomain, int start, int count) { - List result = new ArrayList(); + List result = new ArrayList<>(); int idx = 0; for (Group g : _data.values()) @@ -129,7 +129,7 @@ public List findByManager(int managerMemberID, int start, int count) public List search(String keywords, String nameKeywords, Integer groupID, int start, int count) { - List result = new ArrayList(); + List result = new ArrayList<>(); int idx = 0; for (Group g : _data.values()) diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource2.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource2.java index 81d1782ef9..bfce3b3c18 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource2.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource2.java @@ -81,8 +81,8 @@ public class GroupMembershipsResource2 extends AssociationResourceTemplate batchGet(Set ids) { - Map result = new HashMap(ids.size()); - Map errors = new HashMap(); + Map result = new HashMap<>(ids.size()); + Map errors = new HashMap<>(); Iterator iterator = ids.iterator(); while (iterator.hasNext()) { CompoundKey key = iterator.next(); @@ -96,7 +96,7 @@ public BatchResult batchGet(Set ids) errors.put(key, new RestLiServiceException(HttpStatus.S_404_NOT_FOUND)); } } - return new BatchResult(result, errors); + return new BatchResult<>(result, errors); } // TODO Better search interface (needs parameter binding to Query object, results object w/total) @@ -155,7 +155,7 @@ public UpdateResponse delete(CompoundKey id) @Override public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (Map.Entry entry : entities.getData().entrySet()) { CompoundKey id = entry.getKey(); @@ -167,13 +167,13 @@ public BatchUpdateResult batchUpdate(BatchUpdateRe _app.getMembershipMgr().save(membership); results.put(id, new UpdateResponse(S_204_NO_CONTENT)); } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } @Override public BatchUpdateResult batchUpdate(BatchPatchRequest patches) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (Map.Entry> entry: patches.getData().entrySet()) { CompoundKey key = entry.getKey(); @@ -199,19 +199,19 @@ public BatchUpdateResult batchUpdate(BatchPatchReq } } } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } /** @see com.linkedin.restli.server.resources.AssociationResourceTemplate#batchDelete(com.linkedin.restli.server.BatchDeleteRequest) */ @Override public BatchUpdateResult batchDelete(BatchDeleteRequest ids) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (CompoundKey key: ids.getKeys()) { results.put(key, delete(key)); } - return new BatchUpdateResult(results); + return new BatchUpdateResult<>(results); } /** diff --git a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource3.java b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource3.java index 369db08a88..a09c5bf41d 100644 --- a/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource3.java +++ b/restli-int-test-server/src/main/java/com/linkedin/restli/examples/groups/server/rest/impl/GroupMembershipsResource3.java @@ -86,8 +86,8 @@ public CreateResponse create(ComplexKeyGroupMembership groupMembership) groupMembershipKey.setMemberID(groupMembership.getId().getMemberID()); groupMembershipKey.setGroupID(groupMembership.getId().getGroupID()); ComplexResourceKey complexResourceKey = - new ComplexResourceKey(groupMembershipKey, - new GroupMembershipParam()); + new ComplexResourceKey<>(groupMembershipKey, + new GroupMembershipParam()); groupMembership.setId(complexResourceKey.getKey()); _app.getMembershipMgr().save(toGroupMembership(groupMembership)); return new CreateResponse(complexResourceKey, HttpStatus.S_201_CREATED); @@ -98,13 +98,13 @@ public CreateResponse create(ComplexKeyGroupMembership groupMembership) public BatchUpdateResult, ComplexKeyGroupMembership> batchUpdate(BatchUpdateRequest, ComplexKeyGroupMembership> entities) { Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (Map.Entry, ComplexKeyGroupMembership> entry : entities.getData() .entrySet()) { results.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult, ComplexKeyGroupMembership>(results); + return new BatchUpdateResult<>(results); } /** @see com.linkedin.restli.server.resources.ComplexKeyResourceTemplate#batchUpdate(com.linkedin.restli.server.BatchPatchRequest) */ @@ -112,25 +112,25 @@ public BatchUpdateResult, ComplexKeyGroupMembership> batchUpdate(BatchPatchRequest, ComplexKeyGroupMembership> patches) { Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (Map.Entry, PatchRequest> entry : patches.getData() .entrySet()) { results.put(entry.getKey(), update(entry.getKey(), entry.getValue())); } - return new BatchUpdateResult, ComplexKeyGroupMembership>(results); + return new BatchUpdateResult<>(results); } /** @see com.linkedin.restli.server.resources.ComplexKeyResourceTemplate#batchCreate(com.linkedin.restli.server.BatchCreateRequest) */ @Override public BatchCreateResult, ComplexKeyGroupMembership> batchCreate(BatchCreateRequest, ComplexKeyGroupMembership> groupMemberships) { - List list = new LinkedList(); + List list = new LinkedList<>(); for (ComplexKeyGroupMembership groupMembership : groupMemberships.getInput()) { list.add(create(groupMembership)); } - return new BatchCreateResult, ComplexKeyGroupMembership>(list); + return new BatchCreateResult<>(list); } /** @see com.linkedin.restli.server.resources.ComplexKeyResourceTemplate#batchDelete(com.linkedin.restli.server.BatchDeleteRequest) */ @@ -138,12 +138,12 @@ public BatchCreateResult, ComplexKeyGroupMembership> batchDelete(BatchDeleteRequest, ComplexKeyGroupMembership> ids) { Map, UpdateResponse> results = - new HashMap, UpdateResponse>(); + new HashMap<>(); for (ComplexResourceKey key : ids.getKeys()) { results.put(key, delete(key)); } - return new BatchUpdateResult, ComplexKeyGroupMembership>(results); + return new BatchUpdateResult<>(results); } /** @@ -153,9 +153,9 @@ public BatchUpdateResult, ComplexKeyGroupMembership> batchGet(Set> ids) { Map, ComplexKeyGroupMembership> result = - new HashMap, ComplexKeyGroupMembership>(ids.size()); + new HashMap<>(ids.size()); Map, RestLiServiceException> errors = - new HashMap, RestLiServiceException>(); + new HashMap<>(); Iterator> iterator = ids.iterator(); while (iterator.hasNext()) @@ -172,8 +172,8 @@ public BatchResult, errors.put(key, new RestLiServiceException(HttpStatus.S_404_NOT_FOUND)); } } - return new BatchResult, ComplexKeyGroupMembership>(result, - errors); + return new BatchResult<>(result, + errors); } /** * @see AssociationResource#get @@ -213,7 +213,7 @@ public UpdateResponse delete(ComplexResourceKey id, PatchRequest patch) { - + ComplexKeyGroupMembership membership = fromGroupMembership(_app.getMembershipMgr().get(complexKeyToCompoundKey(id))); try @@ -255,7 +255,7 @@ private static CompoundKey complexKeyToCompoundKey(ComplexResourceKey buildResourceModels(Class... resourceClasses) { - final Set> classes = new HashSet>(Arrays.asList(resourceClasses)); + final Set> classes = new HashSet<>(Arrays.asList(resourceClasses)); return RestLiApiBuilder.buildResourceModels(classes); } @@ -549,7 +549,7 @@ ValidationResult validateCollectionResponse(RestResponse response, throws IOException { final DataMap respData = _codec.bytesToMap(response.getEntity().copyBytes()); - final CollectionResponse collResp = new CollectionResponse(respData, recordClass); + final CollectionResponse collResp = new CollectionResponse<>(respData, recordClass); final DataSchema recordSchema = DataTemplateUtil.getSchema(recordClass); for (T record: collResp.getElements()) @@ -571,12 +571,12 @@ ValidationResult validateActionResponse(RestResponse response, throws IOException { final DataMap respData = _codec.bytesToMap(response.getEntity().copyBytes()); - final FieldDef responseFieldDef = new FieldDef(ActionResponse.VALUE_NAME, - recordClass, - DataTemplateUtil.getSchema(recordClass)); + final FieldDef responseFieldDef = new FieldDef<>(ActionResponse.VALUE_NAME, + recordClass, + DataTemplateUtil.getSchema(recordClass)); final RecordDataSchema recordDataSchema = DynamicRecordMetadata.buildSchema(ActionResponse.class.getName(), Collections.>singletonList(responseFieldDef)); - final ActionResponse actionResp = new ActionResponse(respData, responseFieldDef, recordDataSchema); + final ActionResponse actionResp = new ActionResponse<>(respData, responseFieldDef, recordDataSchema); final DataSchema recordSchema = DataTemplateUtil.getSchema(recordClass); return ValidateDataAgainstSchema.validate(actionResp.getValue().data(), recordSchema, options); diff --git a/restli-int-test-server/src/test/java/com/linkedin/restli/docgen/TestResourceSchemaCollection.java b/restli-int-test-server/src/test/java/com/linkedin/restli/docgen/TestResourceSchemaCollection.java index 21ebb74635..778823ae9e 100644 --- a/restli-int-test-server/src/test/java/com/linkedin/restli/docgen/TestResourceSchemaCollection.java +++ b/restli-int-test-server/src/test/java/com/linkedin/restli/docgen/TestResourceSchemaCollection.java @@ -51,7 +51,7 @@ public TestResourceSchemaCollection() @Test public void testRootWithResourceModel() { - final Map expectedTypes = new HashMap(); + final Map expectedTypes = new HashMap<>(); expectedTypes.put("com.linkedin.restli.examples.greetings.client.actions", ResourceType.ACTIONS); expectedTypes.put("com.linkedin.restli.examples.greetings.client.annotatedComplexKeys", ResourceType.COLLECTION); expectedTypes.put("com.linkedin.restli.examples.greetings.client.autoValidationDemos", ResourceType.COLLECTION); @@ -187,7 +187,7 @@ public void testSubresource() final List actualNoNamespaceSubresources = _schemas.getSubResources(noNamespaceResource); Assert.assertEquals(actualNoNamespaceSubresources.size(), 2); - final Set expectedNoNamespaceSubresources = new HashSet(); + final Set expectedNoNamespaceSubresources = new HashSet<>(); expectedNoNamespaceSubresources.add("noNamespaceSub"); expectedNoNamespaceSubresources.add("com.linkedin.restli.examples.noNamespace"); diff --git a/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestAnnotationResource.java b/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestAnnotationResource.java index 058061d9d7..55d092f33f 100644 --- a/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestAnnotationResource.java +++ b/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestAnnotationResource.java @@ -52,7 +52,7 @@ public class TestAnnotationResource extends CollectionResourceTemplate getWithResult(Long id, @QueryParam("extra") @UnnamedAnnotation(123) String extraParam) { - return new GetResult(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new GetResult<>(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR); } @Override diff --git a/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestDeprecationAnnotationResource.java b/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestDeprecationAnnotationResource.java index 938e8f2664..cb8563f9ca 100644 --- a/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestDeprecationAnnotationResource.java +++ b/restli-int-test-server/src/test/java/com/linkedin/restli/restspec/TestDeprecationAnnotationResource.java @@ -50,7 +50,7 @@ public class TestDeprecationAnnotationResource extends CollectionResourceTemplat public GetResult getWithResult(Long id, @QueryParam("extra") @UnnamedAnnotation(123) String extraParam) { - return new GetResult(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new GetResult<>(null, HttpStatus.S_500_INTERNAL_SERVER_ERROR); } /** diff --git a/restli-int-test/src/main/java/com/linkedin/restli/test/util/BatchCreateHelper.java b/restli-int-test/src/main/java/com/linkedin/restli/test/util/BatchCreateHelper.java index 6aaee769c7..95e5d1448a 100644 --- a/restli-int-test/src/main/java/com/linkedin/restli/test/util/BatchCreateHelper.java +++ b/restli-int-test/src/main/java/com/linkedin/restli/test/util/BatchCreateHelper.java @@ -73,7 +73,7 @@ private static List> batchCreate BatchCreateRequest request = builder.inputs(entities).build(); Response> response = restClient.sendRequest(request).getResponse(); List elements = response.getEntity().getElements(); - List> result = new ArrayList>(elements.size()); + List> result = new ArrayList<>(elements.size()); for (CreateStatus status : elements) { @SuppressWarnings("unchecked") diff --git a/restli-int-test/src/main/java/com/linkedin/restli/test/util/RootBuilderWrapper.java b/restli-int-test/src/main/java/com/linkedin/restli/test/util/RootBuilderWrapper.java index 87e11d402e..5a886fcc63 100644 --- a/restli-int-test/src/main/java/com/linkedin/restli/test/util/RootBuilderWrapper.java +++ b/restli-int-test/src/main/java/com/linkedin/restli/test/util/RootBuilderWrapper.java @@ -301,7 +301,7 @@ private MethodBuilderWrapper invoke(Method method, Object... args) @SuppressWarnings("unchecked") final RequestBuilder> builder = (RequestBuilder>) method.invoke(_methodBuilder, args); - return new MethodBuilderWrapper(builder, _isRestLi2Builder, _valueClass); + return new MethodBuilderWrapper<>(builder, _isRestLi2Builder, _valueClass); } catch (IllegalAccessException e) { @@ -476,7 +476,7 @@ private MethodBuilderWrapper invoke(String methodName) @SuppressWarnings("unchecked") final RequestBuilder> builder = (RequestBuilder>) _rootBuilder.getClass().getMethod(methodName).invoke(_rootBuilder); - return new MethodBuilderWrapper( + return new MethodBuilderWrapper<>( builder, areRestLi2Builders(), _valueClass); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/MockLBFactory.java b/restli-int-test/src/test/java/com/linkedin/restli/client/MockLBFactory.java index 5a14757739..53ca6197da 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/MockLBFactory.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/MockLBFactory.java @@ -58,20 +58,20 @@ static SimpleLoadBalancer createLoadBalancer() { // define the load balancing strategies that we support (round robin, etc) Map> loadBalancerStrategyFactories = - new HashMap>(); + new HashMap<>(); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); Map clientFactories = - new HashMap(); + new HashMap<>(); clientFactories.put("http", new HttpClientFactory.Builder().build()); SynchronousExecutorService executorService = new SynchronousExecutorService(); - MockStore serviceRegistry = new MockStore(); - MockStore clusterRegistry = new MockStore(); - MockStore uriRegistry = new MockStore(); + MockStore serviceRegistry = new MockStore<>(); + MockStore clusterRegistry = new MockStore<>(); + MockStore uriRegistry = new MockStore<>(); SimpleLoadBalancerState state = new SimpleLoadBalancerState(executorService, @@ -85,9 +85,9 @@ static SimpleLoadBalancer createLoadBalancer() state.listenToService("groups", new LoadBalancerState.NullStateListenerCallback()); state.listenToCluster("testcluster", new LoadBalancerState.NullStateListenerCallback()); state.listenToCluster("badcluster", new LoadBalancerState.NullStateListenerCallback()); - List schemes = new ArrayList(); + List schemes = new ArrayList<>(); schemes.add("http"); - Map metadataProperties = new HashMap(); + Map metadataProperties = new HashMap<>(); metadataProperties.put(RestConstants.RESTLI_PROTOCOL_VERSION_PROPERTY, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()); serviceRegistry.put("greetings", new ServiceProperties("greetings", "testcluster", "/greetings", @@ -121,9 +121,9 @@ static SimpleLoadBalancer createLoadBalancer() private static Map> createUriData(String uriString) { URI uri = URI.create(uriString); - Map partitionData = new HashMap(1); + Map partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); - Map> uriData = new HashMap>(1); + Map> uriData = new HashMap<>(1); uriData.put(uri, partitionData); return uriData; } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/MockStore.java b/restli-int-test/src/test/java/com/linkedin/restli/client/MockStore.java index e1c1123bb1..6dafd78013 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/MockStore.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/MockStore.java @@ -44,7 +44,7 @@ public class MockStore implements PropertyEventPublisher, PropertyStore public MockStore() { - _properties = Collections.synchronizedMap(new HashMap()); + _properties = Collections.synchronizedMap(new HashMap<>()); _shutdown = false; } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/TestResponseDecoder.java b/restli-int-test/src/test/java/com/linkedin/restli/client/TestResponseDecoder.java index b673c036b9..78c855a51a 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/TestResponseDecoder.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/TestResponseDecoder.java @@ -71,7 +71,7 @@ public void shutDown() throws Exception @Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "dataProvider", retryAnalyzer = ThreeRetries.class) public void testNonRestliServerErrorHandling(RestliRequestOptions requestOptions) throws Exception { - Set keys = new HashSet(); + Set keys = new HashSet<>(); keys.add(createDataSize(SERVER_HEADER_OVERLOAD_SIZE)); BatchGetEntityRequest req = new StringKeysRequestBuilders(requestOptions).batchGet().ids(keys).build(); ResponseFuture>> batchKVResponseResponseFuture = getClient().sendRequest(req); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/TestScatterGather.java b/restli-int-test/src/test/java/com/linkedin/restli/client/TestScatterGather.java index 7d408aebdd..0d2cd4d5ca 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/TestScatterGather.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/TestScatterGather.java @@ -181,7 +181,7 @@ public static void testBuildSGRequests(int endPointsNum, { mapper = getKeyToHostMapper(endPointsNum); } - ScatterGatherBuilder sg = new ScatterGatherBuilder(mapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(mapper); final int NUM_IDS = 100; Long[] ids = generateIds(NUM_IDS); @@ -206,7 +206,7 @@ public static void testBuildSGKVRequests(int endPointsNum, { mapper = getKeyToHostMapper(endPointsNum); } - ScatterGatherBuilder sg = new ScatterGatherBuilder(mapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(mapper); final int NUM_IDS = 100; Long[] ids = generateIds(NUM_IDS); @@ -231,7 +231,7 @@ public static void testBuildSGEntityRequests(int endPointsNum, { mapper = getKeyToHostMapper(endPointsNum); } - ScatterGatherBuilder sg = new ScatterGatherBuilder(mapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(mapper); final int NUM_IDS = 100; Long[] ids = generateIds(NUM_IDS); @@ -250,12 +250,12 @@ private static void testBuildSGDeleteRequests(int numEndpoints, Collection> requests = buildScatterGatherDeleteRequests(sg, ids, builders); Assert.assertEquals(requests.size(), numEndpoints); - Set> requestIdSets = new HashSet>(); - Set requestIds = new HashSet(); + Set> requestIdSets = new HashSet<>(); + Set requestIds = new HashSet<>(); for (ScatterGatherBuilder.KVRequestInfo requestInfo : requests) { BatchRequest> request = requestInfo.getRequest(); - Set expectedParams = new HashSet(); + Set expectedParams = new HashSet<>(); expectedParams.add(RestConstants.QUERY_BATCH_IDS_PARAM); expectedParams.add("foo"); @@ -274,12 +274,12 @@ private static void testBuildSGUpdateRequests(int numEndpoints, Collection> requests = buildScatterGatherUpdateRequests(sg, greetingMap, builders); Assert.assertEquals(requests.size(), numEndpoints); - Set> requestIdSets = new HashSet>(); - Set requestIds = new HashSet(); + Set> requestIdSets = new HashSet<>(); + Set requestIds = new HashSet<>(); for (ScatterGatherBuilder.KVRequestInfo requestInfo : requests) { BatchRequest> request = requestInfo.getRequest(); - Set expectedParams = new HashSet(); + Set expectedParams = new HashSet<>(); expectedParams.add(RestConstants.QUERY_BATCH_IDS_PARAM); expectedParams.add("foo"); @@ -298,13 +298,13 @@ private static void testBuildSGGetRequests(int numEndpoints, Collection> requests = buildScatterGatherGetRequests(sg, ids); Assert.assertEquals(requests.size(), numEndpoints); - Set> requestIdSets = new HashSet>(); - Set requestIds = new HashSet(); + Set> requestIdSets = new HashSet<>(); + Set requestIds = new HashSet<>(); for (ScatterGatherBuilder.RequestInfo requestInfo : requests) { //URI will be something like "greetings/?ids=21&ids=4&ids=53&ids=60&ids=66&ids=88&ids=93&foo=bar" BatchRequest> request = requestInfo.getBatchRequest(); - Set expectedParams = new HashSet(); + Set expectedParams = new HashSet<>(); expectedParams.add(RestConstants.QUERY_BATCH_IDS_PARAM); expectedParams.add("foo"); expectedParams.add(RestConstants.FIELDS_PARAM); @@ -324,13 +324,13 @@ private static void testBuildSGGetEntityRequests(int numEndpoints, Collection>> requests = buildScatterGatherGetEntityRequests(sg, ids); Assert.assertEquals(requests.size(), numEndpoints); - Set> requestIdSets = new HashSet>(); - Set requestIds = new HashSet(); + Set> requestIdSets = new HashSet<>(); + Set requestIds = new HashSet<>(); for (ScatterGatherBuilder.KVRequestInfo> requestInfo : requests) { //URI will be something like "greetings/?ids=21&ids=4&ids=53&ids=60&ids=66&ids=88&ids=93&foo=bar" BatchRequest>> request = requestInfo.getRequest(); - Set expectedParams = new HashSet(); + Set expectedParams = new HashSet<>(); expectedParams.add(RestConstants.QUERY_BATCH_IDS_PARAM); expectedParams.add("foo"); expectedParams.add(RestConstants.FIELDS_PARAM); @@ -350,13 +350,13 @@ private static void testBuildSGGetKVRequests(int numEndpoints, Collection> requests = buildScatterGatherGetKVRequests(sg, ids); Assert.assertEquals(requests.size(), numEndpoints); - Set> requestIdSets = new HashSet>(); - Set requestIds = new HashSet(); + Set> requestIdSets = new HashSet<>(); + Set requestIds = new HashSet<>(); for (ScatterGatherBuilder.KVRequestInfo requestInfo : requests) { //URI will be something like "greetings/?ids=21&ids=4&ids=53&ids=60&ids=66&ids=88&ids=93&foo=bar" BatchRequest> request = requestInfo.getRequest(); - Set expectedParams = new HashSet(); + Set expectedParams = new HashSet<>(); expectedParams.add(RestConstants.QUERY_BATCH_IDS_PARAM); expectedParams.add("foo"); expectedParams.add(RestConstants.FIELDS_PARAM); @@ -462,7 +462,7 @@ public static void testSendSGRequests(RootBuilderWrapper builder { final int NUM_ENDPOINTS = 4; ConsistentHashKeyMapper mapper = getKeyToHostMapper(NUM_ENDPOINTS); - ScatterGatherBuilder sg = new ScatterGatherBuilder(mapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(mapper); final int NUM_IDS = 20; @@ -501,11 +501,11 @@ private static void testSendGetSGRequests(ScatterGatherBuilder sg, Collection> scatterGatherRequests = buildScatterGatherGetRequests(sg, requestIds); - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size()); - final List errors = new ArrayList(); + final List errors = new ArrayList<>(); - final List> responses = new ArrayList>(); + final List> responses = new ArrayList<>(); for (ScatterGatherBuilder.RequestInfo requestInfo : scatterGatherRequests) { Callback>> cb = new Callback>>() @@ -543,8 +543,8 @@ public void onError(Throwable e) Assert.assertEquals(results.values().size(), requestIds.length); - Set> responseIdSets = new HashSet>(); - Set responseIds = new HashSet(); + Set> responseIdSets = new HashSet<>(); + Set responseIds = new HashSet<>(); for (BatchResponse response : responses) { Set theseIds = response.getResults().keySet(); @@ -567,11 +567,11 @@ private static void testSendGetKVSGRequests(ScatterGatherBuilder sg, Collection> scatterGatherRequests = buildScatterGatherGetKVRequests(sg, requestIds); - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size()); - final List errors = new ArrayList(); + final List errors = new ArrayList<>(); - final List> responses = new ArrayList>(); + final List> responses = new ArrayList<>(); for (ScatterGatherBuilder.KVRequestInfo requestInfo : scatterGatherRequests) { Callback>> cb = new Callback>>() @@ -609,8 +609,8 @@ public void onError(Throwable e) Assert.assertEquals(results.values().size(), requestIds.length); - Set> responseIdSets = new HashSet>(); - Set responseIds = new HashSet(); + Set> responseIdSets = new HashSet<>(); + Set responseIds = new HashSet<>(); for (BatchKVResponse response : responses) { Set theseIds = response.getResults().keySet(); @@ -651,11 +651,11 @@ public static void testSendSGDeleteRequests(ScatterGatherBuilder sg, private static void testSendSGKVRequests(Collection> scatterGatherRequests, Long[] requestIds) throws InterruptedException { - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size()); - final List errors = new ArrayList(); + final List errors = new ArrayList<>(); - final List> responses = new ArrayList>(); + final List> responses = new ArrayList<>(); for (ScatterGatherBuilder.KVRequestInfo requestInfo : scatterGatherRequests) { Callback>> cb = new Callback>>() @@ -695,8 +695,8 @@ public void onError(Throwable e) Assert.assertEquals(results.values().size(), requestIds.length); - Set> responseIdSets = new HashSet>(); - Set responseIds = new HashSet(); + Set> responseIdSets = new HashSet<>(); + Set responseIds = new HashSet<>(); for (BatchKVResponse response : responses) { Set theseIds = response.getResults().keySet(); @@ -729,7 +729,7 @@ public static void testScatterGatherLoadBalancerIntegration(RootBuilderWrapper sg = new ScatterGatherBuilder(keyMapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(keyMapper); final int NUM_IDS = 20; Long[] requestIds = generateIds(NUM_IDS); @@ -754,7 +754,7 @@ public static void testScatterGatherKVLoadBalancerIntegration(RootBuilderWrapper //expected } - ScatterGatherBuilder sg = new ScatterGatherBuilder(keyMapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(keyMapper); final int NUM_IDS = 20; Long[] requestIds = generateIds(NUM_IDS); @@ -779,7 +779,7 @@ public static void testScatterGatherEntityLoadBalancerIntegration(RootBuilderWra //expected } - ScatterGatherBuilder sg = new ScatterGatherBuilder(keyMapper); + ScatterGatherBuilder sg = new ScatterGatherBuilder<>(keyMapper); final int NUM_IDS = 20; Long[] requestIds = generateIds(NUM_IDS); @@ -854,7 +854,7 @@ private static Long[] generateIds(int n) private static List generateCreate(int num) { - List creates = new ArrayList(); + List creates = new ArrayList<>(); for (int i = 0; i < num; ++i) { Greeting greeting = new Greeting(); @@ -866,7 +866,7 @@ private static List generateCreate(int num) private static Map generateUpdates(Long[] ids) { - Map updates = new HashMap(); + Map updates = new HashMap<>(); for (long l : ids) { Greeting greeting = new Greeting(); @@ -878,13 +878,13 @@ private static Map generateUpdates(Long[] ids) private static ConsistentHashKeyMapper getKeyToHostMapper(int n) throws URISyntaxException { - Map endpoints = new HashMap(); + Map endpoints = new HashMap<>(); for (int ii=0; ii testRing = new ConsistentHashRing(endpoints); + ConsistentHashRing testRing = new ConsistentHashRing<>(endpoints); ConsistentHashKeyMapper mapper = new ConsistentHashKeyMapper(new StaticRingProvider(testRing), new TestPartitionInfoProvider()); @@ -893,31 +893,31 @@ private static ConsistentHashKeyMapper getKeyToHostMapper(int n) throws URISynta private static ConsistentHashKeyMapper getKeyToHostMapper(int n, int partitionNum) throws URISyntaxException { - Map endpoints = new HashMap(); + Map endpoints = new HashMap<>(); for (int ii=0; ii> mapList = new ArrayList>(); + List> mapList = new ArrayList<>(); int count = 0; for(final URI uri : endpoints.keySet()) { final int index = count / partitionSize; if (index == mapList.size()) { - mapList.add(new HashMap()); + mapList.add(new HashMap<>()); } Map map = mapList.get(index); map.put(uri, endpoints.get(uri)); count++; } - List> rings = new ArrayList>(); + List> rings = new ArrayList<>(); for (final Map map : mapList) { - final ConsistentHashRing ring = new ConsistentHashRing(map); + final ConsistentHashRing ring = new ConsistentHashRing<>(map); rings.add(ring); } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/TestUnstructuredDataClient.java b/restli-int-test/src/test/java/com/linkedin/restli/client/TestUnstructuredDataClient.java index 3c90630328..835181227f 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/TestUnstructuredDataClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/TestUnstructuredDataClient.java @@ -71,8 +71,8 @@ public void init() private void cleanup() throws Exception { - final FutureCallback factoryCallback = new FutureCallback(); - final FutureCallback clientCallback = new FutureCallback(); + final FutureCallback factoryCallback = new FutureCallback<>(); + final FutureCallback clientCallback = new FutureCallback<>(); _client.shutdown(clientCallback); _clientFactory.shutdown(factoryCallback); clientCallback.get(); @@ -208,4 +208,4 @@ public void onSuccess(ByteString result) latch.await(10, TimeUnit.SECONDS); if (!success.get()) fail("Failed to read response data from stream!"); } -} \ No newline at end of file +} diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerDelays.java b/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerDelays.java index 296017ec6a..efe5a3d392 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerDelays.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerDelays.java @@ -91,7 +91,7 @@ public void parallelTasksExecutionDelay() throws Exception private long measureExecutionTime(MultiplexedRequest multiplexedRequest) throws ExecutionException, InterruptedException { - FutureCallback aggregatedCallback = new FutureCallback(); + FutureCallback aggregatedCallback = new FutureCallback<>(); long startTime = System.currentTimeMillis(); getClient().sendRequest(multiplexedRequest, aggregatedCallback); MultiplexedResponse multiplexedResponse = aggregatedCallback.get(); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerIntegration.java b/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerIntegration.java index a1f60bb08f..d8e514dec7 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerIntegration.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/client/multiplexer/TestMultiplexerIntegration.java @@ -59,9 +59,9 @@ public void shutDown() throws Exception public void singleCall() throws Exception { GetRequest request = new GreetingsCallbackBuilders().get().id(1L).build(); - FutureCallback> muxCallback = new FutureCallback>(); - FutureCallback> directCallback = new FutureCallback>(); - FutureCallback aggregatedCallback = new FutureCallback(); + FutureCallback> muxCallback = new FutureCallback<>(); + FutureCallback> directCallback = new FutureCallback<>(); + FutureCallback aggregatedCallback = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createParallelRequest() @@ -82,8 +82,8 @@ public void singleCall() throws Exception public void singleCallWithError() throws Exception { GetRequest request = new GreetingsCallbackBuilders().get().id(Long.MAX_VALUE).build(); - FutureCallback> muxCallback = new FutureCallback>(); - FutureCallback> directCallback = new FutureCallback>(); + FutureCallback> muxCallback = new FutureCallback<>(); + FutureCallback> directCallback = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createParallelRequest() @@ -100,12 +100,12 @@ public void singleCallWithError() throws Exception public void twoParallelCalls() throws Exception { GetRequest request1 = new GreetingsCallbackBuilders().get().id(1L).build(); - FutureCallback> muxCallback1 = new FutureCallback>(); - FutureCallback> directCallback1 = new FutureCallback>(); + FutureCallback> muxCallback1 = new FutureCallback<>(); + FutureCallback> directCallback1 = new FutureCallback<>(); GetRequest request2 = new GreetingsCallbackBuilders().get().id(2L).build(); - FutureCallback> muxCallback2 = new FutureCallback>(); - FutureCallback> directCallback2 = new FutureCallback>(); + FutureCallback> muxCallback2 = new FutureCallback<>(); + FutureCallback> directCallback2 = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createParallelRequest() @@ -125,12 +125,12 @@ public void twoParallelCalls() throws Exception public void twoParallelCallsWithOneError() throws Exception { GetRequest request1 = new GreetingsCallbackBuilders().get().id(1L).build(); - FutureCallback> muxCallback1 = new FutureCallback>(); - FutureCallback> directCallback1 = new FutureCallback>(); + FutureCallback> muxCallback1 = new FutureCallback<>(); + FutureCallback> directCallback1 = new FutureCallback<>(); GetRequest request2 = new GreetingsCallbackBuilders().get().id(Long.MAX_VALUE).build(); - FutureCallback> muxCallback2 = new FutureCallback>(); - FutureCallback> directCallback2 = new FutureCallback>(); + FutureCallback> muxCallback2 = new FutureCallback<>(); + FutureCallback> directCallback2 = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createParallelRequest() @@ -150,12 +150,12 @@ public void twoParallelCallsWithOneError() throws Exception public void twoSequentialCalls() throws Exception { GetRequest request1 = new GreetingsCallbackBuilders().get().id(1L).build(); - FutureCallback> muxCallback1 = new FutureCallback>(); - FutureCallback> directCallback1 = new FutureCallback>(); + FutureCallback> muxCallback1 = new FutureCallback<>(); + FutureCallback> directCallback1 = new FutureCallback<>(); GetRequest request2 = new GreetingsCallbackBuilders().get().id(2L).build(); - FutureCallback> muxCallback2 = new FutureCallback>(); - FutureCallback> directCallback2 = new FutureCallback>(); + FutureCallback> muxCallback2 = new FutureCallback<>(); + FutureCallback> directCallback2 = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createSequentialRequest() @@ -175,12 +175,12 @@ public void twoSequentialCalls() throws Exception public void twoSequentialCallsWithOneError() throws Exception { GetRequest request1 = new GreetingsCallbackBuilders().get().id(1L).build(); - FutureCallback> muxCallback1 = new FutureCallback>(); - FutureCallback> directCallback1 = new FutureCallback>(); + FutureCallback> muxCallback1 = new FutureCallback<>(); + FutureCallback> directCallback1 = new FutureCallback<>(); GetRequest request2 = new GreetingsCallbackBuilders().get().id(Long.MAX_VALUE).build(); - FutureCallback> muxCallback2 = new FutureCallback>(); - FutureCallback> directCallback2 = new FutureCallback>(); + FutureCallback> muxCallback2 = new FutureCallback<>(); + FutureCallback> directCallback2 = new FutureCallback<>(); MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder .createSequentialRequest() diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/RestLiIntegrationTest.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/RestLiIntegrationTest.java index c5f650d4af..5d0c9bced6 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/RestLiIntegrationTest.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/RestLiIntegrationTest.java @@ -164,7 +164,7 @@ private void initClient(String uriPrefix) private void initClient(String uriPrefix, Map transportProperties) { _clientFactory = new HttpClientFactory.Builder().setUsePipelineV2(false).build(); - _transportClients = new ArrayList(); + _transportClients = new ArrayList<>(); Client client = newTransportClient(transportProperties); RestLiClientConfig restLiClientConfig = new RestLiClientConfig(); restLiClientConfig.setUseStreaming(Boolean.parseBoolean(System.getProperty("test.useStreamCodecClient", "false"))); @@ -197,14 +197,14 @@ public void shutdown() throws Exception { for (Client client : _transportClients) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); client.shutdown(callback); callback.get(); } } if (_clientFactory != null) { - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); _clientFactory.shutdown(callback); callback.get(); } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestActionsResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestActionsResource.java index 31b77b4e33..896997ba49 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestActionsResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestActionsResource.java @@ -289,22 +289,22 @@ public void testBasicParseqBasedAction(RootBuilderWrapper builders, String private static Object[][] requestBuilderDataProviderForParseqActions() { return new Object[][] { - { new RootBuilderWrapper(new ActionsBuilders()), "parseq" }, + {new RootBuilderWrapper<>(new ActionsBuilders()), "parseq" }, // This test cannot be compiled until we build with Java 8 by default. //{ new RootBuilderWrapper(new ActionsBuilders()), "parseq2" }, - { new RootBuilderWrapper(new ActionsBuilders()), "parseq3" }, - { new RootBuilderWrapper(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq" }, + {new RootBuilderWrapper<>(new ActionsBuilders()), "parseq3" }, + {new RootBuilderWrapper<>(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq" }, // This test cannot be compiled until we build with Java 8 by default. //{ new RootBuilderWrapper(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq2" }, - { new RootBuilderWrapper(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq3" }, - { new RootBuilderWrapper(new ActionsRequestBuilders()), "parseq" }, + {new RootBuilderWrapper<>(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq3" }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders()), "parseq" }, // This test cannot be compiled until we build with Java 8 by default. //{ new RootBuilderWrapper(new ActionsRequestBuilders()), "parseq2" }, - { new RootBuilderWrapper(new ActionsRequestBuilders()), "parseq3" }, - { new RootBuilderWrapper(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq" }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders()), "parseq3" }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq" }, // This test cannot be compiled until we build with Java 8 by default. //{ new RootBuilderWrapper(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq2" }, - { new RootBuilderWrapper(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq3" } + {new RootBuilderWrapper<>(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)), "parseq3" } }; } @@ -312,10 +312,10 @@ private static Object[][] requestBuilderDataProviderForParseqActions() private static Object[][] requestBuilderDataProvider() { return new Object[][] { - { new RootBuilderWrapper(new ActionsBuilders()) }, - { new RootBuilderWrapper(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) }, - { new RootBuilderWrapper(new ActionsRequestBuilders()) }, - { new RootBuilderWrapper(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) } + {new RootBuilderWrapper<>(new ActionsBuilders()) }, + {new RootBuilderWrapper<>(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders()) }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) } }; } } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAllPartitionsRequestBuilder.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAllPartitionsRequestBuilder.java index 321ed0aea4..3622211395 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAllPartitionsRequestBuilder.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAllPartitionsRequestBuilder.java @@ -114,20 +114,20 @@ public void shutDown() throws Exception public void testSendAllPartitionsRequests(RestliRequestOptions options, RingFactory ringFactory) throws ServiceUnavailableException, URISyntaxException, RestException, InterruptedException { final int PARTITION_NUM = 5; - List expectedUris = new ArrayList(); + List expectedUris = new ArrayList<>(); ConsistentHashKeyMapper mapper = getKeyToHostMapper(PARTITION_NUM, expectedUris, ringFactory); - AllPartitionsRequestBuilder searchRB = new AllPartitionsRequestBuilder(mapper); - ActionRequestBuilder builder = new ActionRequestBuilder(TEST_URI, - Greeting.class, - _COLL_SPEC, - options); + AllPartitionsRequestBuilder searchRB = new AllPartitionsRequestBuilder<>(mapper); + ActionRequestBuilder builder = new ActionRequestBuilder<>(TEST_URI, + Greeting.class, + _COLL_SPEC, + options); ActionRequest request = builder.name("updateTone").id(1L). - setParam(new FieldDef("newTone", Tone.class, DataTemplateUtil.getSchema(Tone.class)), Tone.FRIENDLY).build(); + setParam(new FieldDef<>("newTone", Tone.class, DataTemplateUtil.getSchema(Tone.class)), Tone.FRIENDLY).build(); - final Map results = new ConcurrentHashMap(); + final Map results = new ConcurrentHashMap<>(); final CountDownLatch latch = new CountDownLatch(PARTITION_NUM); - final List errors = new ArrayList(); - final List responses = new ArrayList(); + final List errors = new ArrayList<>(); + final List responses = new ArrayList<>(); Callback> cb = new Callback>() { @@ -170,18 +170,18 @@ public void onSuccess(Response response) private ConsistentHashKeyMapper getKeyToHostMapper(int partitionNum, List expectedUris, RingFactory ringFactory) throws URISyntaxException { - Map> partitionDescriptions = new HashMap>(); + Map> partitionDescriptions = new HashMap<>(); for (int i = 0; i < partitionNum; i++) { final URI foo = new URI("http://foo" + i + ".com"); expectedUris.add(foo); - Map foo1Data = new HashMap(); + Map foo1Data = new HashMap<>(); foo1Data.put(i, new PartitionData(1.0)); partitionDescriptions.put(foo, foo1Data); } - List orderedStrategies = new ArrayList(); + List orderedStrategies = new ArrayList<>(); LoadBalancerStrategy strategy = new ConsistentHashKeyMapperTest.TestLoadBalancerStrategy(partitionDescriptions, ringFactory); orderedStrategies.add(new LoadBalancerState.SchemeStrategyPair("http", strategy)); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAltKeyResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAltKeyResource.java index d8811b2325..a7d854180d 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAltKeyResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAltKeyResource.java @@ -804,7 +804,7 @@ public void testComplexKeyAltKeyCreate() throws Throwable TwoPartKey key = new TwoPartKey(); key.setMajor("testKey"); key.setMinor("testKey"); - ComplexResourceKey complexKey = new ComplexResourceKey(key, new TwoPartKey()); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, new TwoPartKey()); String altKey = coercer.coerceFromKey(complexKey); Message message = new Message().setMessage("message"); @@ -847,4 +847,4 @@ private static byte[] dataTemplateToBytes(final DataTemplate record) throw new RestLiInternalException(e); } } -} \ No newline at end of file +} diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAssociationsResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAssociationsResource.java index 2ac51d6115..9586048cc5 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAssociationsResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestAssociationsResource.java @@ -247,9 +247,9 @@ public void testBatchUpdate(RootBuilderWrapper builders) public void testBatchPartialUpdate(RootBuilderWrapper> builders) throws RemoteInvocationException { - Map> patches = new HashMap>(); - patches.put(URL_COMPOUND_KEY, new PatchRequest()); - patches.put(SIMPLE_COMPOUND_KEY, new PatchRequest()); + Map> patches = new HashMap<>(); + patches.put(URL_COMPOUND_KEY, new PatchRequest<>()); + patches.put(SIMPLE_COMPOUND_KEY, new PatchRequest<>()); Request> request = builders.batchPartialUpdate().inputs(patches).build(); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexArrayResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexArrayResource.java index 68cb6b5957..6f447c32b4 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexArrayResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexArrayResource.java @@ -62,7 +62,7 @@ public class TestComplexArrayResource extends RestLiIntegrationTest public void initClass(ITestContext ctx) throws Exception { Set includedGroups = - new HashSet(ctx.getCurrentXmlTest().getIncludedGroups()); + new HashSet<>(ctx.getCurrentXmlTest().getIncludedGroups()); super.init(includedGroups.contains("async")); } @@ -81,7 +81,7 @@ public void testGet(RootBuilderWrapper complexKey = new ComplexResourceKey(key, params); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, params); Request request = builders.get().id(complexKey).build(); @@ -176,17 +176,17 @@ private static List> getBatchComp ComplexArray key1 = new ComplexArray().setArray(singleton1).setNext(next1); ComplexArray params1 = new ComplexArray().setArray(singleton1).setNext(next1); ComplexResourceKey complexKey1 = - new ComplexResourceKey(key1, params1); + new ComplexResourceKey<>(key1, params1); LongArray singleton2 = new LongArray(2L); ComplexArray next2 = new ComplexArray().setArray(singleton2); ComplexArray key2 = new ComplexArray().setArray(singleton2).setNext(next2); ComplexArray params2 = new ComplexArray().setArray(singleton2).setNext(next2); ComplexResourceKey complexKey2 = - new ComplexResourceKey(key2, params2); + new ComplexResourceKey<>(key2, params2); List> complexKeys = - new ArrayList>(); + new ArrayList<>(); complexKeys.add(complexKey1); complexKeys.add(complexKey2); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexByteKeyResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexByteKeyResource.java index 7b60d8caf4..04b6399bae 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexByteKeyResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexByteKeyResource.java @@ -67,7 +67,7 @@ private void testGetMain(RootBuilderWrapper.MethodBuilderWrapper getComplexKey(ByteString bytes) { - return new ComplexResourceKey( + return new ComplexResourceKey<>( new TyperefRecord().setBytes(bytes), new TwoPartKey()); } @@ -82,4 +82,4 @@ private static Object[][] requestBuilderDataProvider() { new RootBuilderWrapper, TyperefRecord>(new ComplexByteKeysRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) } }; } -} \ No newline at end of file +} diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexKeysResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexKeysResource.java index 1d160b8ba1..bc23bc8a27 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexKeysResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestComplexKeysResource.java @@ -104,7 +104,7 @@ public void testSubGet(RootBuilderWrapper builders) throws E TwoPartKey param = new TwoPartKey(); param.setMajor("c"); param.setMinor("d"); - ComplexResourceKey complexKey = new ComplexResourceKey(key, param); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, param); Request request = builders.get().setPathKey("keys", complexKey).id("stringKey").build(); TwoPartKey response = getClient().sendRequest(request).get().getEntity(); Assert.assertEquals(response.getMajor(), "aANDc"); @@ -120,7 +120,7 @@ public void testSubGetWithReservedChars(RootBuilderWrapper b TwoPartKey param = new TwoPartKey(); param.setMajor("c&3"); param.setMinor("d&4"); - ComplexResourceKey complexKey = new ComplexResourceKey(key, param); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, param); Request request = builders.get().setPathKey("keys", complexKey).id("stringKey").build(); TwoPartKey response = getClient().sendRequest(request).get().getEntity(); Assert.assertEquals(response.getMajor(), "a&1ANDc&3"); @@ -367,7 +367,7 @@ private void testBatchCreateMain(BatchCreateRequestBuilder messages = new ArrayList(2); + List messages = new ArrayList<>(2); messages.add(message1); messages.add(message2); @@ -379,7 +379,7 @@ private void testBatchCreateMain(BatchCreateRequestBuilder> future = getClient().sendRequest(request); Response> response = future.getResponse(); Assert.assertEquals(response.getStatus(), 200); - Set> expectedComplexKeys = new HashSet>(2); + Set> expectedComplexKeys = new HashSet<>(2); expectedComplexKeys.add(expectedComplexKey1); expectedComplexKeys.add(expectedComplexKey2); for (CreateStatus createStatus : response.getEntity().getElements()) @@ -405,7 +405,7 @@ private void testBatchCreateMain(BatchCreateRequestBuilder> createdKeys = new ArrayList>(2); + List> createdKeys = new ArrayList<>(2); createdKeys.add(expectedComplexKey1); createdKeys.add(expectedComplexKey2); BatchGetKVRequest, Message> getRequest = batchGetRequestBuilder.ids(createdKeys).buildKV(); @@ -427,7 +427,7 @@ private void testBatchCreateIdMain(BatchCreateIdRequestBuilder messages = new ArrayList(2); + List messages = new ArrayList<>(2); messages.add(message1); messages.add(message2); @@ -438,7 +438,7 @@ private void testBatchCreateIdMain(BatchCreateIdRequestBuilder, Message> request = batchCreateRequestBuilder.inputs(messages).build(); Response>> response = getClient().sendRequest(request).getResponse(); Assert.assertEquals(response.getStatus(), 200); - Set> expectedComplexKeys = new HashSet>(2); + Set> expectedComplexKeys = new HashSet<>(2); expectedComplexKeys.add(expectedComplexKey1); expectedComplexKeys.add(expectedComplexKey2); for (CreateIdStatus> status : response.getEntity().getElements()) @@ -462,7 +462,7 @@ private void testBatchCreateIdMain(BatchCreateIdRequestBuilder> createdKeys = new ArrayList>(2); + List> createdKeys = new ArrayList<>(2); createdKeys.add(expectedComplexKey1); createdKeys.add(expectedComplexKey2); Request, EntityResponse>> getRequest = batchGetRequestBuilder.ids(createdKeys).build(); @@ -555,7 +555,7 @@ public void testBatchGetEntityEmpty(BatchGetEntityRequestBuilder, EntityResponse>> request = builder.build(); - final FutureCallback callback = new FutureCallback(); + final FutureCallback callback = new FutureCallback<>(); getClient().sendRestRequest(request, new RequestContext(), callback); final RestResponse result = callback.get(); @@ -581,7 +581,7 @@ private void testBatchUpdateMain( message2.setMessage(messageText2); message2.setTone(Tone.INSULTING); - final Map, Message> inputs = new HashMap, Message>(); + final Map, Message> inputs = new HashMap<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); ComplexResourceKey key3 = getComplexKey(StringTestKeys.ERROR, StringTestKeys.ERROR); @@ -615,7 +615,7 @@ private void testBatchUpdateMain( Assert.assertNotNull(response.getErrors().get(key3)); - ArrayList> ids = new ArrayList>(); + ArrayList> ids = new ArrayList<>(); ids.add(key1); ids.add(key2); BatchGetEntityRequest, Message> batchGetRequest = @@ -640,7 +640,7 @@ private void testBatchPartialUpdateMain( PatchRequest patch = PatchGenerator.diffEmpty(message); final Map, PatchRequest> inputs = - new HashMap, PatchRequest>(); + new HashMap<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); inputs.put(key1, patch); @@ -664,7 +664,7 @@ private void testBatchPartialUpdateMain( Assert.assertTrue(response.getErrors().isEmpty()); - ArrayList> ids = new ArrayList>(); + ArrayList> ids = new ArrayList<>(); ids.add(key1); ids.add(key2); Request, EntityResponse>> batchGetRequest = @@ -704,7 +704,7 @@ private void testBatchDeleteMain( ComplexResourceKey key1 = getComplexKey(messageText, messageText); ComplexResourceKey key2 = getComplexKey(messageText2, messageText2); - ArrayList> ids = new ArrayList>(); + ArrayList> ids = new ArrayList<>(); ids.add(key1); ids.add(key2); final Request, UpdateStatus>> request = @@ -736,7 +736,7 @@ private void testBatchDeleteMain( private static List> getBatchComplexKeys() { List> ids = - new ArrayList>(); + new ArrayList<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); ComplexResourceKey key3 = getComplexKey(StringTestKeys.ERROR, StringTestKeys.ERROR); @@ -749,7 +749,7 @@ private static List> getBatchComplexK private static ComplexResourceKey getComplexKey(String major, String minor) { - return new ComplexResourceKey( + return new ComplexResourceKey<>( new TwoPartKey().setMajor(major).setMinor(minor), new TwoPartKey()); } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCompressionServer.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCompressionServer.java index a9c861d563..b9a48c3edd 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCompressionServer.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCompressionServer.java @@ -170,7 +170,7 @@ public Object[][] clientsCompressedResponsesBatchDataProvider() int index = entries * 4 - 1; for (String operation: compressionOperations) { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_RESPONSE_COMPRESSION_OPERATIONS, operation); RestClient client = new RestClient(newTransportClient(clientProperties), URI_PREFIX, getClientConfig()); result[index--] = new Object[]{ client, operation, RestliRequestOptions.DEFAULT_OPTIONS, Arrays.asList(1000L, 2000L), 0 }; @@ -199,7 +199,7 @@ public Object[][] clientsCompressedResponsesBuilderDataProvider() int index = entries * 4 - 1; for (String operation: compressionOperations) { - Map clientProperties = new HashMap(); + Map clientProperties = new HashMap<>(); clientProperties.put(HttpClientFactory.HTTP_RESPONSE_COMPRESSION_OPERATIONS, operation); RestClient client = new RestClient(newTransportClient(clientProperties), URI_PREFIX, getClientConfig()); result[index--] = new Object[]{ client, operation, new RootBuilderWrapper(new GreetingsBuilders()), @@ -715,7 +715,7 @@ public void testSearchWithPostFilter(RestClient client, String operationsForComp //Query parameter order is non deterministic //greetings?count=5&start=5&q=searchWithPostFilter" - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("count", "5"); queryParamsMap.put("start", "5"); queryParamsMap.put("q", "searchWithPostFilter"); @@ -875,9 +875,9 @@ private boolean shouldCompress(Set families, Set methods, String */ private Map> getCompressionMethods(String operationsConfig) { - Map> methodsAndFamilies = new HashMap>(); - methodsAndFamilies.put("methods", new HashSet()); - methodsAndFamilies.put("families", new HashSet()); + Map> methodsAndFamilies = new HashMap<>(); + methodsAndFamilies.put("methods", new HashSet<>()); + methodsAndFamilies.put("families", new HashSet<>()); for (String operation: operationsConfig.split(",")) { operation = operation.trim(); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomContextData.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomContextData.java index e283ca7006..575fa45636 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomContextData.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomContextData.java @@ -86,7 +86,7 @@ public CompletableFuture onResponse(FilterRequestContext requestContext, if (customData.isPresent() && customData.get().equals("newbar")) { return CompletableFuture.completedFuture(null); } - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR)); return future; } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomTypesClient.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomTypesClient.java index f1ee322511..322625159d 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomTypesClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestCustomTypesClient.java @@ -137,7 +137,7 @@ public void testCalendarRefArrayQueryParam() throws RemoteInvocationException response = getClient().sendRequest(findRequest).getResponse(); Assert.assertEquals(response.getEntity().getElements().size(), 0); - List calendars = new ArrayList(); + List calendars = new ArrayList<>(); calendars.add(new GregorianCalendar()); findRequest = new CustomTypesRequestBuilders().findByCalendars().calendarsParam(calendars).build(); response = getClient().sendRequest(findRequest).getResponse(); @@ -155,7 +155,7 @@ public void testCustomLong(RootBuilderWrapper builders) throws R @Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestBuilderDataProvider") public void testCustomLongArray(RootBuilderWrapper builders) throws RemoteInvocationException { - List ls = new ArrayList(2); + List ls = new ArrayList<>(2); ls.add(new CustomLong(1L)); ls.add(new CustomLong(2L)); @@ -281,7 +281,7 @@ public void testCollectionBatchUpdate(RootBuilderWrapper b public void testCollectionBatchPartialUpdate(RootBuilderWrapper builders) throws RemoteInvocationException { RequestBuilder>> request = builders.batchPartialUpdate().input(new CustomLong(1L), - new PatchRequest()).input(new CustomLong(2L), new PatchRequest()).getBuilder(); + new PatchRequest<>()).input(new CustomLong(2L), new PatchRequest<>()).getBuilder(); Map statuses = getClient().sendRequest(request).getResponse().getEntity().getResults(); Assert.assertEquals(statuses.size(), 2); @@ -320,7 +320,7 @@ public void testCollectionBatchCreate(RestliRequestOptions options) throws Remot Response> response = getClient().sendRequest(request).getResponse(); List results = response.getEntity().getElements(); - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); expectedKeys.add(new CustomLong(1L)); expectedKeys.add(new CustomLong(2L)); @@ -347,7 +347,7 @@ public void testCollectionBatchCreateId(RestliRequestOptions options) throws Rem Response> response = getClient().sendRequest(request).getResponse(); List> results = response.getEntity().getElements(); - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); expectedKeys.add(new CustomLong(1L)); expectedKeys.add(new CustomLong(2L)); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestEscapeCharsInStringKeys.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestEscapeCharsInStringKeys.java index ad546021f9..f45e002695 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestEscapeCharsInStringKeys.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestEscapeCharsInStringKeys.java @@ -108,7 +108,7 @@ public void testGetWithSimpleKey(RootBuilderWrapper builders) t @Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestStringKeysOptionsDataProvider") public void testBatchGetWithSimpleKey(RestliRequestOptions requestOptions) throws Exception { - Set keys = new HashSet(); + Set keys = new HashSet<>(); keys.add(key1()); keys.add(key2()); Request> req = new StringKeysBuilders(requestOptions).batchGet().ids(keys).build(); @@ -121,7 +121,7 @@ public void testBatchGetWithSimpleKey(RestliRequestOptions requestOptions) throw @Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestStringKeysOptionsDataProvider") public void testBatchGetKVWithSimpleKey(RestliRequestOptions requestOptions) throws Exception { - Set keys = new HashSet(); + Set keys = new HashSet<>(); keys.add(key1()); keys.add(key2()); Request> req = new StringKeysBuilders(requestOptions).batchGet().ids(keys).buildKV(); @@ -134,7 +134,7 @@ public void testBatchGetKVWithSimpleKey(RestliRequestOptions requestOptions) thr @Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestStringKeysOptionsDataProvider") public void testBatchGetEntityWithSimpleKey(RestliRequestOptions requestOptions) throws Exception { - Set keys = new HashSet(); + Set keys = new HashSet<>(); keys.add(key1()); keys.add(key2()); Request>> req = new StringKeysRequestBuilders(requestOptions).batchGet().ids(keys).build(); @@ -168,7 +168,7 @@ public void testGetWithComplexKey(RootBuilderWrapper complexKey = new ComplexResourceKey(key, params); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, params); Request request = builders.get().id(complexKey).build(); Message response = getClient().sendRequest(request).get().getEntity(); Assert.assertNotNull(response); @@ -263,10 +263,10 @@ private static Object[][] requestComplexKeysBuilderDataProvider() private static Object[][] requestActionBuilderDataProvider() { return new Object[][] { - { new RootBuilderWrapper(new ActionsBuilders()) }, - { new RootBuilderWrapper(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) }, - { new RootBuilderWrapper(new ActionsRequestBuilders()) }, - { new RootBuilderWrapper(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) } + {new RootBuilderWrapper<>(new ActionsBuilders()) }, + {new RootBuilderWrapper<>(new ActionsBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders()) }, + {new RootBuilderWrapper<>(new ActionsRequestBuilders(TestConstants.FORCE_USE_NEXT_OPTIONS)) } }; } } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestFilters.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestFilters.java index 006f3e5514..baa95e4cbc 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestFilters.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestFilters.java @@ -310,14 +310,14 @@ private Object[][] requestBuilderDataProvider() new GreetingsTaskBuilders(FORCE_USE_NEXT_OPTIONS), new GreetingsTaskRequestBuilders(FORCE_USE_NEXT_OPTIONS) }; - Set builderWrapperSet = new HashSet(); + Set builderWrapperSet = new HashSet<>(); for (Object builder : builders) { builderWrapperSet.add(new RootBuilderWrapper(builder)); } - Set toneSet = new HashSet(Arrays.asList(Tone.FRIENDLY, Tone.INSULTING)); - Set responseFilterSet = new HashSet(Arrays.asList(false, true)); - Set exceptionSet = new HashSet(Arrays.asList( + Set toneSet = new HashSet<>(Arrays.asList(Tone.FRIENDLY, Tone.INSULTING)); + Set responseFilterSet = new HashSet<>(Arrays.asList(false, true)); + Set exceptionSet = new HashSet<>(Arrays.asList( new RestLiServiceException(RESP_FILTER_ERROR_STATUS, RESP_FILTER_ERROR_MESSAGE), new RestLiServiceException(RESP_FILTER_ERROR_STATUS, RESP_FILTER_ERROR_MESSAGE, new RuntimeException("Original cause")), new RoutingException(RESP_FILTER_ERROR_MESSAGE, RESP_FILTER_ERROR_STATUS.getCode()) @@ -444,7 +444,7 @@ public CompletableFuture onError(Throwable t, final FilterRequestContext r { throw _responseFilterException; } - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGreetingsClient.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGreetingsClient.java index 7011f44cca..cd63a25b47 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGreetingsClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGreetingsClient.java @@ -534,7 +534,7 @@ public void testSearchWithPostFilter(RootBuilderWrapper builders //Query parameter order is non deterministic //"/" + resourceName + "?count=5&start=5&q=searchWithPostFilter"; - final Map queryParamsMap = new HashMap(); + final Map queryParamsMap = new HashMap<>(); queryParamsMap.put("count", "5"); queryParamsMap.put("start", "5"); queryParamsMap.put("q", "searchWithPostFilter"); @@ -682,7 +682,7 @@ private void deleteAndVerifyBatchTestDataSerially(RootBuilderWrapper getBatchTestDataSerially(RootBuilderWrapper builders, List idsToGet) throws RemoteInvocationException { - List fetchedGreetings = new ArrayList(); + List fetchedGreetings = new ArrayList<>(); for (int i = 0; i < idsToGet.size(); i++) { try @@ -769,7 +769,7 @@ private void getAndVerifyBatchTestDataSerially(RootBuilderWrapper generateBatchTestData(int numItems, String baseMessage, Tone tone) { - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); for (int i = 0; i < numItems; i++) { greetings.add(generateTestGreeting(baseMessage + " " + i, tone)); @@ -788,7 +788,7 @@ private List generateBatchTestData(int numItems, String baseMessage, T private List createBatchTestDataSerially(RootBuilderWrapper builders, List greetings) throws RemoteInvocationException { - List createdIds = new ArrayList(); + List createdIds = new ArrayList<>(); for (Greeting greeting: greetings) { @@ -840,7 +840,7 @@ public void testBatchCreate(RootBuilderWrapper builders, String List greetings = generateBatchTestData(3, "BatchCreate", Tone.FRIENDLY); List> statuses = BatchCreateHelper.batchCreate(getClient(), builders, greetings, false); - List createdIds = new ArrayList(statuses.size()); + List createdIds = new ArrayList<>(statuses.size()); for (CreateIdStatus status: statuses) { @@ -909,8 +909,8 @@ public void testBatchUpdate(RootBuilderWrapper builders) addIdsToGeneratedGreetings(createdIds, greetings); // Update the created greetings - List updatedGreetings = new ArrayList(); - Map updateGreetingsRequestMap = new HashMap(); + List updatedGreetings = new ArrayList<>(); + Map updateGreetingsRequestMap = new HashMap<>(); for (Greeting greeting: greetings) { @@ -946,8 +946,8 @@ public void testBatchPartialUpdate(RootBuilderWrapper builders) addIdsToGeneratedGreetings(createdIds, greetings); // Patch the created Greetings - Map> patchedGreetingsDiffs = new HashMap>(); - List patchedGreetings = new ArrayList(); + Map> patchedGreetingsDiffs = new HashMap<>(); + List patchedGreetings = new ArrayList<>(); for (Greeting greeting: greetings) { diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGroupsClient.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGroupsClient.java index cc9b6b999d..7e06d040f0 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGroupsClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestGroupsClient.java @@ -353,7 +353,7 @@ public void testAssociationBatchCreateGetUpdatePatchDelete(ProtocolVersion versi GroupMembership patchedGroupMembership1 = buildGroupMembership(null, "ALFRED@test.linkedin.com", "ALFRED", "Hitchcock"); GroupMembership patchedGroupMembership2 = buildGroupMembership(null, "BRUCE@test.linkedin.com", "BRUCE", "Willis"); - Map> patchInputs = new HashMap>(); + Map> patchInputs = new HashMap<>(); patchInputs.put(key1, PatchGenerator.diff(groupMembership1, patchedGroupMembership1)); patchInputs.put(key2, PatchGenerator.diff(groupMembership2, patchedGroupMembership2)); @@ -584,7 +584,7 @@ public void testAssociationBatchGetKVCompoundKeyResponse(RestliRequestOptions re { CompoundKey key1 = buildCompoundKey(1, 1); CompoundKey key2 = buildCompoundKey(2, 1); - Set allRequestedKeys = new HashSet(Arrays.asList(key1, key2)); + Set allRequestedKeys = new HashSet<>(Arrays.asList(key1, key2)); Request> request = new GroupMembershipsBuilders(requestOptions).batchGet() .ids(key1, key2) @@ -594,7 +594,7 @@ public void testAssociationBatchGetKVCompoundKeyResponse(RestliRequestOptions re Assert.assertTrue(allRequestedKeys.containsAll(groupMemberships.getResults().keySet())); Assert.assertTrue(allRequestedKeys.containsAll(groupMemberships.getErrors().keySet())); - Set allResponseKeys = new HashSet(groupMemberships.getResults().keySet()); + Set allResponseKeys = new HashSet<>(groupMemberships.getResults().keySet()); allResponseKeys.addAll(groupMemberships.getErrors().keySet()); Assert.assertEquals(allResponseKeys, allRequestedKeys); } @@ -605,7 +605,7 @@ public void testAssociationBatchGetEntityCompoundKeyResponse(RestliRequestOption { CompoundKey key1 = buildCompoundKey(1, 1); CompoundKey key2 = buildCompoundKey(2, 1); - Set allRequestedKeys = new HashSet(Arrays.asList(key1, key2)); + Set allRequestedKeys = new HashSet<>(Arrays.asList(key1, key2)); Request>> request = new GroupMembershipsRequestBuilders(requestOptions).batchGet() .ids(key1, key2) @@ -615,7 +615,7 @@ public void testAssociationBatchGetEntityCompoundKeyResponse(RestliRequestOption Assert.assertTrue(allRequestedKeys.containsAll(groupMemberships.getResults().keySet())); Assert.assertTrue(allRequestedKeys.containsAll(groupMemberships.getErrors().keySet())); - Set allResponseKeys = new HashSet(groupMemberships.getResults().keySet()); + Set allResponseKeys = new HashSet<>(groupMemberships.getResults().keySet()); allResponseKeys.addAll(groupMemberships.getErrors().keySet()); Assert.assertEquals(allResponseKeys, allRequestedKeys); } @@ -677,8 +677,8 @@ private static ComplexResourceKey buil String stringParam) { ComplexResourceKey complexKey = - new ComplexResourceKey(new GroupMembershipKey(), - new GroupMembershipParam()); + new ComplexResourceKey<>(new GroupMembershipKey(), + new GroupMembershipParam()); complexKey.getKey().setMemberID(memberID); complexKey.getKey().setGroupID(groupID); complexKey.getParams().setIntParameter(intParam); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestHttp11With204AndException.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestHttp11With204AndException.java index 6842a4a257..88559cfa5f 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestHttp11With204AndException.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestHttp11With204AndException.java @@ -38,7 +38,7 @@ public void shutDown() throws Exception @Test public void test204ExceptionWithHttp11() throws Exception { - RootBuilderWrapper builderWrapper = new RootBuilderWrapper(new GreetingsBuilders()); + RootBuilderWrapper builderWrapper = new RootBuilderWrapper<>(new GreetingsBuilders()); Request request = builderWrapper.get() .id(204L) .build(); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestNullGreetingsClient.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestNullGreetingsClient.java index 26d9ef6d6f..7ad95947c6 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestNullGreetingsClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestNullGreetingsClient.java @@ -85,7 +85,7 @@ public CompletableFuture onError(Throwable t, FilterRequestContext request //Add a custom header to the response to make sure that 404s/500s returned by //nulls in resource methods are also given a chance to experience the filter responseContext.getResponseData().getHeaders().put("X-Null-Greetings-Filter", "Ack"); - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } @@ -395,7 +395,7 @@ public void testBatchUpdateUnsupportedNullKeyMap(final RootBuilderWrapper actualResults = response.getEntity().getResults(); - Map expectedResults = new HashMap(); + Map expectedResults = new HashMap<>(); UpdateStatus updateStatus = new UpdateStatus().setStatus(201); expectedResults.put(3l, updateStatus); Assert.assertEquals(actualResults, expectedResults, "The results map should be correct"); @@ -427,8 +427,8 @@ private void sendBatchPartialUpdateAndAssert(final RootBuilderWrapper> patchedGreetingsDiffs = new HashMap>(); - patchedGreetingsDiffs.put(id, new PatchRequest()); + final Map> patchedGreetingsDiffs = new HashMap<>(); + patchedGreetingsDiffs.put(id, new PatchRequest<>()); final Request> batchUpdateRequest = builders.batchPartialUpdate().patchInputs(patchedGreetingsDiffs).build(); getClient().sendRequest(batchUpdateRequest).getResponse(); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestParseqBasedFluentClientApi.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestParseqBasedFluentClientApi.java index bb622fb027..bd76422ee5 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestParseqBasedFluentClientApi.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestParseqBasedFluentClientApi.java @@ -670,7 +670,7 @@ private CompoundKey getAssociateResourceSimpleKey(Associations client) private Map getAssociateResourceMockDB(Associations client) { - HashMap mapDB = new HashMap(); + HashMap mapDB = new HashMap<>(); CompoundKey urlKey = getAssociateResourceUrlKey(client); CompoundKey simpleKey = getAssociateResourceSimpleKey(client); mapDB.put(urlKey, new Message().setId(urlKey.getPartAsString("src") + " " + urlKey.getPartAsString("dest")) @@ -734,9 +734,9 @@ public void testAssociateResourceBatchPartialUpdate() throws Exception Associations associations = new AssociationsFluentClient(_parSeqRestliClient, _parSeqUnitTestHelper.getEngine()); - Map> patches = new HashMap>(); - patches.put(getAssociateResourceUrlKey(associations), new PatchRequest()); - patches.put(getAssociateResourceSimpleKey(associations), new PatchRequest()); + Map> patches = new HashMap<>(); + patches.put(getAssociateResourceUrlKey(associations), new PatchRequest<>()); + patches.put(getAssociateResourceSimpleKey(associations), new PatchRequest<>()); Map ids = associations.batchPartialUpdate(patches).toCompletableFuture().get(5000, TimeUnit.MILLISECONDS); @@ -1063,7 +1063,7 @@ public void testAssociationBatchFinderUsingAssocKey() throws Exception TwoPartKey param = new TwoPartKey(); param.setMajor("c"); param.setMinor("d"); - ComplexResourceKey complexKey = new ComplexResourceKey(key, param); + ComplexResourceKey complexKey = new ComplexResourceKey<>(key, param); ComplexKeysSubFluentClient subFluentClient = new ComplexKeysSubFluentClient(_parSeqRestliClient, _parSeqUnitTestHelper.getEngine()); subFluentClient.withKeys(complexKey); @@ -1184,7 +1184,7 @@ public void testCollectionActionWithException() throws Throwable // ----- Testing ComplexKeysResource ------ private static ComplexResourceKey getComplexKey(String major, String minor) { - return new ComplexResourceKey( + return new ComplexResourceKey<>( new TwoPartKey().setMajor(major).setMinor(minor), new TwoPartKey()); } @@ -1192,7 +1192,7 @@ private static ComplexResourceKey getComplexKey(String m private static List> getBatchComplexKeys() { List> ids = - new ArrayList>(); + new ArrayList<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); ComplexResourceKey key3 = getComplexKey(StringTestKeys.ERROR, StringTestKeys.ERROR); @@ -1258,7 +1258,7 @@ private static List> getBatchComplexK message2.setMessage(messageText2); message2.setTone(Tone.INSULTING); - final Map, Message> inputs = new HashMap, Message>(); + final Map, Message> inputs = new HashMap<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); inputs.put(key1, message); @@ -1285,7 +1285,7 @@ private static List> getBatchComplexK PatchRequest patch = PatchGenerator.diffEmpty(message); final Map, PatchRequest> inputs = - new HashMap, PatchRequest>(); + new HashMap<>(); ComplexResourceKey key1 = getComplexKey(StringTestKeys.SIMPLEKEY, StringTestKeys.SIMPLEKEY2); ComplexResourceKey key2 = getComplexKey(StringTestKeys.URL, StringTestKeys.URL2); inputs.put(key1, patch); @@ -1325,7 +1325,7 @@ private static List> getBatchComplexK ComplexResourceKey key1 = getComplexKey(messageText, messageText); ComplexResourceKey key2 = getComplexKey(messageText2, messageText2); - ArrayList> ids = new ArrayList>(); + ArrayList> ids = new ArrayList<>(); ids.add(key1); ids.add(key2); Map, UpdateStatus> deleteResponse = diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRequestCompression.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRequestCompression.java index 9516d57655..318338a0ea 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRequestCompression.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRequestCompression.java @@ -226,7 +226,7 @@ public void testUpdate(CompressionConfig requestCompressionConfig, TimeoutException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("R2 Netty Scheduler")); - Map requestCompressionConfigs = new HashMap(); + Map requestCompressionConfigs = new HashMap<>(); if (requestCompressionConfig != null) { requestCompressionConfigs.put(SERVICE_NAME, requestCompressionConfig); @@ -243,13 +243,13 @@ public void testUpdate(CompressionConfig requestCompressionConfig, .setRequestCompressionThresholdDefault(500) .setRequestCompressionConfigs(requestCompressionConfigs) .build(); - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(HttpClientFactory.HTTP_REQUEST_CONTENT_ENCODINGS, supportedEncodings); properties.put(HttpClientFactory.HTTP_SERVICE_NAME, SERVICE_NAME); TransportClientAdapter clientAdapter1 = new TransportClientAdapter(httpClientFactory.getClient(properties)); RestClient client = new RestClient(clientAdapter1, FILTERS_URI_PREFIX); - RootBuilderWrapper builders = new RootBuilderWrapper(new GreetingsRequestBuilders(restliRequestOptions)); + RootBuilderWrapper builders = new RootBuilderWrapper<>(new GreetingsRequestBuilders(restliRequestOptions)); // GET Request request = builders.get().id(1L).build(); @@ -275,11 +275,11 @@ public void testUpdate(CompressionConfig requestCompressionConfig, Assert.assertEquals(response2, message); - FutureCallback callback1 = new FutureCallback(); + FutureCallback callback1 = new FutureCallback<>(); client.shutdown(callback1); callback1.get(30, TimeUnit.SECONDS); - FutureCallback callback2 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback<>(); httpClientFactory.shutdown(callback2); callback2.get(30, TimeUnit.SECONDS); } diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestResponseCompression.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestResponseCompression.java index b51b1f44ef..71f82682f3 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestResponseCompression.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestResponseCompression.java @@ -196,7 +196,7 @@ public void testResponseCompression(Boolean useResponseCompression, CompressionC throws RemoteInvocationException, CloneNotSupportedException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("R2 Netty Scheduler")); - Map responseCompressionConfigs = new HashMap(); + Map responseCompressionConfigs = new HashMap<>(); if (responseCompressionConfig != null) { responseCompressionConfigs.put(SERVICE_NAME, responseCompressionConfig); @@ -214,7 +214,7 @@ public void testResponseCompression(Boolean useResponseCompression, CompressionC .setResponseCompressionConfigs(responseCompressionConfigs) .setUseClientCompression(true) .build(); - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(HttpClientFactory.HTTP_SERVICE_NAME, SERVICE_NAME); if (useResponseCompression != null) { @@ -263,7 +263,7 @@ private Object[][] encodingsData() @Test(dataProvider = "encodingsData", retryAnalyzer = SingleRetry.class) // Often fails in CI without a retry public void testAcceptEncodingConfiguration(String responseContentEncodings, String expectedAcceptEncoding, String expectedContentEncoding) throws RemoteInvocationException { - Map properties = new HashMap(); + Map properties = new HashMap<>(); properties.put(HttpClientFactory.HTTP_RESPONSE_CONTENT_ENCODINGS, responseContentEncodings); properties.put(HttpClientFactory.HTTP_USE_RESPONSE_COMPRESSION, "true"); Client client = newTransportClient(properties); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidation.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidation.java index b7de74d484..f55fc7df0c 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidation.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidation.java @@ -250,8 +250,8 @@ public void testCreateFailure(RestClient restClient, Object builder, ValidationD @DataProvider public static Object[][] batchCreateFailureData() { - List validationDemos = new ArrayList(); - List errorMessages = new ArrayList(); + List validationDemos = new ArrayList<>(); + List errorMessages = new ArrayList<>(); Object[][] cases = createFailures(); for (int i = 0; i < cases.length; i++) { @@ -331,8 +331,8 @@ private static Object[][] batchCreateAndGetFailures() @DataProvider public static Object[][] batchCreateAndGetFailureData() { - List validationDemos = new ArrayList(); - List errorMessages = new ArrayList(); + List validationDemos = new ArrayList<>(); + List errorMessages = new ArrayList<>(); Object[][] cases = batchCreateAndGetFailures(); for (int i = 0; i < cases.length; i++) { @@ -590,8 +590,8 @@ public static Object[][] batchPartialUpdateData() throws DataProcessingException { String[][] failures = partialUpdateFailures(); String[] successes = partialUpdateSuccesses(); - Map> inputs = new HashMap>(); - Map errorMessages = new HashMap(); + Map> inputs = new HashMap<>(); + Map errorMessages = new HashMap<>(); for (int i = 0; i < failures.length; i++) { inputs.put(i, PatchBuilder.buildPatchFromString(failures[i][0])); diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationFromClient.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationFromClient.java index db4f4901a5..0b7becb167 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationFromClient.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationFromClient.java @@ -256,7 +256,7 @@ public void testInvalidPatchValidation() } try { - ValidationDemosPartialUpdateRequestBuilder.validateInput(new PatchRequest(new DataMap())); + ValidationDemosPartialUpdateRequestBuilder.validateInput(new PatchRequest<>(new DataMap())); Assert.fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationWithProjection.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationWithProjection.java index f0463cd2a9..dd35cc77d3 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationWithProjection.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestRestLiValidationWithProjection.java @@ -88,7 +88,7 @@ public void shutDown() throws Exception @Test public void testNoProjection() throws RemoteInvocationException { - RootBuilderWrapper wrapper = new RootBuilderWrapper(new AutoValidationWithProjectionBuilders()); + RootBuilderWrapper wrapper = new RootBuilderWrapper<>(new AutoValidationWithProjectionBuilders()); Request> request = wrapper.findBy("searchWithProjection").build(); try { @@ -112,7 +112,7 @@ private Object[][] provideProjectionWithValidFieldsBuilders() throws DataProcess ValidationDemo.fields().validationDemoNext().intB()); RootBuilderWrapper wrapper = - new RootBuilderWrapper(new AutoValidationWithProjectionBuilders()); + new RootBuilderWrapper<>(new AutoValidationWithProjectionBuilders()); Request> findRequest = wrapper.findBy("searchWithProjection").fields(spec.toArray(new PathSpec[spec.size()])).build(); @@ -157,7 +157,7 @@ public void testProjectionWithValidFields(Request request, HttpStatus expecte @Test public void testProjectionWithInvalidFields() throws RemoteInvocationException { - RootBuilderWrapper wrapper = new RootBuilderWrapper(new AutoValidationWithProjectionBuilders()); + RootBuilderWrapper wrapper = new RootBuilderWrapper<>(new AutoValidationWithProjectionBuilders()); Request> request = wrapper.findBy("searchWithProjection") .fields(ValidationDemo.fields().stringA(), //invalid diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestReturnEntityWithCreate.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestReturnEntityWithCreate.java index aaaa525374..2e57b9e66c 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestReturnEntityWithCreate.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestReturnEntityWithCreate.java @@ -125,7 +125,7 @@ public void testBatchCreateWithEntity(RestClient restClient, String expectedCont Greeting greeting2 = new Greeting(); greeting2.setMessage("first time!"); greeting2.setTone(Tone.FRIENDLY); - List greetings = new ArrayList(); + List greetings = new ArrayList<>(); greetings.add(greeting); greetings.add(greeting2); @@ -183,7 +183,7 @@ public void testBatchCreateWithEntityWithError(RestClient restClient, String exp Greeting greeting2 = new Greeting(); greeting2.setMessage("too much!"); greeting2.setTone(Tone.FRIENDLY); - List greetings = new ArrayList(Arrays.asList(greeting, greeting, greeting, greeting2)); + List greetings = new ArrayList<>(Arrays.asList(greeting, greeting, greeting, greeting2)); BatchCreateIdEntityRequest batchCreateIdEntityRequest = builders.batchCreateAndGet().inputs( diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestSimpleResourceHierarchy.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestSimpleResourceHierarchy.java index d0ab01da7a..d51049fa95 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestSimpleResourceHierarchy.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestSimpleResourceHierarchy.java @@ -357,14 +357,14 @@ public void testSubCollectionBatchCreate(RootBuilderWrapper buil greeting.setMessage("Message2"); greeting.setTone(Tone.FRIENDLY); - ArrayList greetings = new ArrayList(); + ArrayList greetings = new ArrayList<>(); greetings.add(greeting); greetings.add(greeting2); //POST List> statuses = BatchCreateHelper.batchCreate(getClient(), builders, greetings, false); - ArrayList ids = new ArrayList(); + ArrayList ids = new ArrayList<>(); for(CreateIdStatus status : statuses) { diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestStreamingGreetings.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestStreamingGreetings.java index 53db8f54b2..d79af19bf3 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestStreamingGreetings.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestStreamingGreetings.java @@ -278,7 +278,7 @@ private static Object[][] requestBuilderDataProvider() private static class GreetingBlobReaderCallback implements RestLiAttachmentReaderCallback { private final CountDownLatch _countDownLatch; - private List _attachmentsRead = new ArrayList(); + private List _attachmentsRead = new ArrayList<>(); private GreetingBlobReaderCallback(CountDownLatch countDownLatch) { @@ -368,4 +368,4 @@ public void onAttachmentError(Throwable throwable) //No need to do anything since the top level callback will get invoked with an error anyway } } -} \ No newline at end of file +} diff --git a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestTyperefCustomDoubleAssociationKeyResource.java b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestTyperefCustomDoubleAssociationKeyResource.java index 52142ec360..63df42717b 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/examples/TestTyperefCustomDoubleAssociationKeyResource.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/examples/TestTyperefCustomDoubleAssociationKeyResource.java @@ -83,20 +83,20 @@ public void shutDown() throws Exception @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestOptionsDataProvider") public void testGet(RestliRequestOptions requestOptions) throws RemoteInvocationException, URISyntaxException { - HashMap keyParts = new HashMap(); + HashMap keyParts = new HashMap<>(); keyParts.put("src", new CompoundKey.TypeInfo(CustomDouble.class, CustomDoubleRef.class)); keyParts.put("dest", new CompoundKey.TypeInfo(URI.class, UriRef.class)); - GetRequestBuilder getBuilder = new GetRequestBuilder( + GetRequestBuilder getBuilder = new GetRequestBuilder<>( "typerefCustomDoubleAssociationKeyResource", Message.class, new ResourceSpecImpl(EnumSet.of(ResourceMethod.GET), - new HashMap(), - new HashMap(), - CompoundKey.class, - null, - null, - Message.class, - keyParts), + new HashMap<>(), + new HashMap<>(), + CompoundKey.class, + null, + null, + Message.class, + keyParts), requestOptions); final String[] stringArray = {"foo"}; diff --git a/restli-int-test/src/test/java/com/linkedin/restli/test/util/TestRootBuilderWrapper.java b/restli-int-test/src/test/java/com/linkedin/restli/test/util/TestRootBuilderWrapper.java index 7027aae8e4..30ca080e5d 100644 --- a/restli-int-test/src/test/java/com/linkedin/restli/test/util/TestRootBuilderWrapper.java +++ b/restli-int-test/src/test/java/com/linkedin/restli/test/util/TestRootBuilderWrapper.java @@ -32,9 +32,9 @@ public class TestRootBuilderWrapper public void testBuilderVersion() { RootBuilderWrapper rootBuilderWrapper1 = - new RootBuilderWrapper(new GreetingsBuilders()); + new RootBuilderWrapper<>(new GreetingsBuilders()); RootBuilderWrapper rootBuilderWrapper2 = - new RootBuilderWrapper(new GreetingsRequestBuilders()); + new RootBuilderWrapper<>(new GreetingsRequestBuilders()); Assert.assertFalse(rootBuilderWrapper1.areRestLi2Builders()); Assert.assertTrue(rootBuilderWrapper2.areRestLi2Builders()); @@ -43,7 +43,7 @@ public void testBuilderVersion() Assert.assertTrue(rootBuilderWrapper2.get().isRestLi2Builder()); RootBuilderWrapper dummyBuilder = - new RootBuilderWrapper(new MyRequestBuilders()); + new RootBuilderWrapper<>(new MyRequestBuilders()); Assert.assertFalse(dummyBuilder.areRestLi2Builders()); } @@ -51,9 +51,9 @@ public void testBuilderVersion() public void testWrapperMethodNameGeneration() { RootBuilderWrapper rootBuilderWrapper1 = - new RootBuilderWrapper(new GreetingsBuilders()); + new RootBuilderWrapper<>(new GreetingsBuilders()); RootBuilderWrapper rootBuilderWrapper2 = - new RootBuilderWrapper(new GreetingsRequestBuilders()); + new RootBuilderWrapper<>(new GreetingsRequestBuilders()); rootBuilderWrapper1.findBy("searchWithTones").addQueryParam("tones", Tone.FRIENDLY); rootBuilderWrapper1.findBy("searchWithTones").setParam("Tones", new Tone[3]); diff --git a/restli-internal-testutils/src/test/java/com/linkedin/restli/internal/testutils/URIDetails.java b/restli-internal-testutils/src/test/java/com/linkedin/restli/internal/testutils/URIDetails.java index 1e8374b157..53248a601c 100644 --- a/restli-internal-testutils/src/test/java/com/linkedin/restli/internal/testutils/URIDetails.java +++ b/restli-internal-testutils/src/test/java/com/linkedin/restli/internal/testutils/URIDetails.java @@ -201,7 +201,7 @@ public static void testUriGeneration(String createdURIString, URIDetails expecte //Just a single object, (i.e String, DataMap, etc...) idList = Arrays.asList(actualURIDataMap.get("ids")); } - idSet = new HashSet(idList); + idSet = new HashSet<>(idList); Assert.assertEquals("The set of IDs must match", expectedURIDetails._ids, idSet); } @@ -209,7 +209,7 @@ public static void testUriGeneration(String createdURIString, URIDetails expecte if(expectedURIDetails._fields != null) { final String[] fieldsArray = ((String) actualURIDataMap.get("fields")).split(","); - final Set actualFieldSet = new HashSet(Arrays.asList(fieldsArray)); + final Set actualFieldSet = new HashSet<>(Arrays.asList(fieldsArray)); Assert.assertEquals("The set of projection fields should be correct", expectedURIDetails._fields, actualFieldSet); } @@ -225,4 +225,4 @@ public static void testUriGeneration(String createdURIString, URIDetails expecte Assert.fail("Unexpected exception when parsing created URI with exception: " + e); } } -} \ No newline at end of file +} diff --git a/restli-server-extras/src/test/java/com/linkedin/restli/server/TestParseqTraceDebugRequestHandler.java b/restli-server-extras/src/test/java/com/linkedin/restli/server/TestParseqTraceDebugRequestHandler.java index d816b28750..43cea5bf56 100644 --- a/restli-server-extras/src/test/java/com/linkedin/restli/server/TestParseqTraceDebugRequestHandler.java +++ b/restli-server-extras/src/test/java/com/linkedin/restli/server/TestParseqTraceDebugRequestHandler.java @@ -140,7 +140,7 @@ public void testStaticContent() throws IOException //Collect all files under tracevis folder in the jar containing the parseq trace debug request handler. Enumeration resources = classLoader.getResources( ParseqTraceDebugRequestHandler.class.getName().replace('.', '/') + ".class"); - List files = new ArrayList(); + List files = new ArrayList<>(); while (resources.hasMoreElements()) { @@ -265,4 +265,4 @@ else if (extension.equals(".png")) return null; } -} \ No newline at end of file +} diff --git a/restli-server-testutils/src/main/java/com/linkedin/restli/server/testutils/MockHttpServerFactory.java b/restli-server-testutils/src/main/java/com/linkedin/restli/server/testutils/MockHttpServerFactory.java index 6afa4feba8..de7c452dae 100644 --- a/restli-server-testutils/src/main/java/com/linkedin/restli/server/testutils/MockHttpServerFactory.java +++ b/restli-server-testutils/src/main/java/com/linkedin/restli/server/testutils/MockHttpServerFactory.java @@ -110,7 +110,7 @@ public static HttpServer create(int port, boolean enableAsync) { RestLiConfig config = createConfig(port); - Set resourceClassNames = new HashSet(); + Set resourceClassNames = new HashSet<>(); for (Class clazz: resourceClasses) { resourceClassNames.add(clazz.getName()); diff --git a/restli-server-testutils/src/test/java/com/linkedin/restli/server/testutils/test/TestMockHttpServerFactory.java b/restli-server-testutils/src/test/java/com/linkedin/restli/server/testutils/test/TestMockHttpServerFactory.java index 8e74a476df..ff74aafec2 100644 --- a/restli-server-testutils/src/test/java/com/linkedin/restli/server/testutils/test/TestMockHttpServerFactory.java +++ b/restli-server-testutils/src/test/java/com/linkedin/restli/server/testutils/test/TestMockHttpServerFactory.java @@ -64,7 +64,7 @@ public class TestMockHttpServerFactory public void testCreateUsingClassNames() throws IOException, RemoteInvocationException { - Set> resourceClasses = new HashSet>(); + Set> resourceClasses = new HashSet<>(); resourceClasses.add(PhotoResource.class); resourceClasses.add(AlbumResource.class); @@ -104,7 +104,7 @@ public void testCreateUsingPackageNames() */ private Map getBeans() { - Map beans = new HashMap(); + Map beans = new HashMap<>(); final PhotoDatabase photoDb = new PhotoDatabaseImpl(10); beans.put("photoDb", photoDb); beans.put("albumDb", new AlbumDatabaseImpl(5)); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/PathKeysImpl.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/PathKeysImpl.java index d1bad8717e..775d8a2e33 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/PathKeysImpl.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/PathKeysImpl.java @@ -35,7 +35,7 @@ public class PathKeysImpl implements MutablePathKeys public PathKeysImpl() { super(); - _keyMap = new HashMap(4); + _keyMap = new HashMap<>(4); } @Override diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/RestLiRouter.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/RestLiRouter.java index 4d2952f6ef..73ddd2cccf 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/RestLiRouter.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/RestLiRouter.java @@ -280,7 +280,7 @@ private ResourceMethodDescriptor findMethodDescriptor(final ResourceModel resour // when it's not necessary, as long as it doesn't conflict with the rest of the parameters. private static Map setupResourceMethodLookup() { - HashMap result = new HashMap(); + HashMap result = new HashMap<>(); // METHOD RMETHOD ACTION QUERY BATCHFINDER BATCH ENTITY Object[] config = { @@ -664,7 +664,7 @@ private Set parseAlternativeBatchKeys(final ResourceModel resource, { String altKeyName = context.getParameter(RestConstants.ALT_KEY_PARAM); List ids = context.getParameterValues(RestConstants.QUERY_BATCH_IDS_PARAM); - Set batchKeys = new HashSet(); + Set batchKeys = new HashSet<>(); if (ids == null) { batchKeys = null; diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/methods/arguments/ArgumentBuilder.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/methods/arguments/ArgumentBuilder.java index 5cc10384a1..fc35850400 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/methods/arguments/ArgumentBuilder.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/methods/arguments/ArgumentBuilder.java @@ -560,7 +560,7 @@ static Map buildBatchRequestMap(RoutingRes return null; } - BatchRequest batchRequest = new BatchRequest<>(data, new TypeSpec(valueClass)); + BatchRequest batchRequest = new BatchRequest<>(data, new TypeSpec<>(valueClass)); Map result = new HashMap<>(CollectionUtils.getMapInitialCapacity(batchRequest.getEntities().size(), 0.75f), 0.75f); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/AnnotationSet.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/AnnotationSet.java index b9e2bafed7..f1cbb6d290 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/AnnotationSet.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/AnnotationSet.java @@ -44,7 +44,7 @@ public class AnnotationSet */ public AnnotationSet(final Annotation[] annos) { - _map = new HashMap, Annotation>(); + _map = new HashMap<>(); for (Annotation anno : annos) { _map.put(anno.annotationType(), anno); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodDescriptor.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodDescriptor.java index 8331d8c3dc..bc3c29e55f 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodDescriptor.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodDescriptor.java @@ -403,7 +403,7 @@ public List> getParameters() */ public List> getParametersWithType(final Parameter.ParamType type) { - List> params = new ArrayList>(); + List> params = new ArrayList<>(); for (Parameter p : _parameters) { if (p.getParamType() == type) diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodLookup.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodLookup.java index 63fae6805a..88e7fd637d 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodLookup.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceMethodLookup.java @@ -36,7 +36,7 @@ private ResourceMethodLookup() } private static final Map _methodNameToResourceMethodMap = - new HashMap(ResourceMethod.values().length); + new HashMap<>(ResourceMethod.values().length); static { _methodNameToResourceMethodMap.put(includePartial("create", false), diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModel.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModel.java index 3b2a223f10..8e8ac49b24 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModel.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModel.java @@ -117,7 +117,7 @@ public ResourceModel(final Key primaryKey, _keyKeyClass = keyKeyClass; _keyParamsClass = keyParamsClass; _keys = keys; - _keyClasses = new HashMap>(CollectionUtils.getMapInitialCapacity(_keys.size(), 0.75f), 0.75f); + _keyClasses = new HashMap<>(CollectionUtils.getMapInitialCapacity(_keys.size(), 0.75f), 0.75f); for (Key key : _keys) { _keyClasses.put(key.getName(), key.getType()); @@ -131,7 +131,7 @@ public ResourceModel(final Key primaryKey, _resourceMethodDescriptors = new ArrayList<>(5); _primaryKey = primaryKey; _resourceType = resourceType; - _pathSubResourceMap = new HashMap(); + _pathSubResourceMap = new HashMap<>(); } /** @@ -221,7 +221,7 @@ public Key getKey(final String name) */ public Set getKeyNames() { - Set keyNames = new HashSet(); + Set keyNames = new HashSet<>(); for (Key key : _keys) { keyNames.add(key.getName()); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelAnnotation.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelAnnotation.java index 26c166031c..8ddee59b88 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelAnnotation.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelAnnotation.java @@ -226,7 +226,7 @@ private static AnnotationTrait getTraits(Class clazz, bool trait.masterTrait = new MetaTrait(classAnnotation, clazz.getCanonicalName()); } - trait.memberTraits = new HashMap(); + trait.memberTraits = new HashMap<>(); for (Method m: clazz.getDeclaredMethods()) { final RestSpecAnnotation methodAnnotation = m.getAnnotation(RestSpecAnnotation.class); @@ -289,5 +289,5 @@ public MetaTrait(RestSpecAnnotation a, String customName) public final boolean skipDefault; } - private static final Map, AnnotationTrait> _traits = new HashMap, AnnotationTrait>(); + private static final Map, AnnotationTrait> _traits = new HashMap<>(); } diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelEncoder.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelEncoder.java index 982f883fa6..66cd5e3bef 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelEncoder.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/ResourceModelEncoder.java @@ -642,7 +642,7 @@ private void appendKeys(final AssociationSchema associationSchema, final ResourceModel collectionModel) { AssocKeySchemaArray assocKeySchemaArray = new AssocKeySchemaArray(); - List sortedKeys = new ArrayList(collectionModel.getKeys()); + List sortedKeys = new ArrayList<>(collectionModel.getKeys()); Collections.sort(sortedKeys, new Comparator() { @Override @@ -1167,7 +1167,7 @@ private StringArray buildSupportsNode(ResourceModel resourceModel) private void buildSupportsArray(final ResourceModel resourceModel, final StringArray supportsArray) { - List supportsStrings = new ArrayList(); + List supportsStrings = new ArrayList<>(); for (ResourceMethodDescriptor resourceMethodDescriptor : resourceModel.getResourceMethodDescriptors()) { ResourceMethod type = resourceMethodDescriptor.getType(); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiAnnotationReader.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiAnnotationReader.java index 5eeeb1f10f..82adf2b99f 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiAnnotationReader.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiAnnotationReader.java @@ -281,7 +281,7 @@ private static void addAlternativeKeys(ResourceModel model, Class resourceCla alternativeKeyAnnotations = new AlternativeKey[]{resourceClass.getAnnotation(AlternativeKey.class)}; } - Map> alternativeKeyMap = new HashMap>(alternativeKeyAnnotations.length); + Map> alternativeKeyMap = new HashMap<>(alternativeKeyAnnotations.length); for (AlternativeKey altKeyAnnotation : alternativeKeyAnnotations) { @SuppressWarnings("unchecked") @@ -292,7 +292,7 @@ private static void addAlternativeKeys(ResourceModel model, Class resourceCla } else { - model.putAlternativeKeys(new HashMap>()); + model.putAlternativeKeys(new HashMap<>()); } } @@ -420,7 +420,7 @@ private static void checkPathsAgainstSchema(RecordDataSchema dataSchema, String private static void checkRestLiDataAnnotations(final Class resourceClass, RecordDataSchema dataSchema) { - Map annotations = new HashMap(); + Map annotations = new HashMap<>(); if (resourceClass.isAnnotationPresent(ReadOnly.class)) { annotations.put(ReadOnly.class.getSimpleName(), resourceClass.getAnnotation(ReadOnly.class).value()); @@ -436,7 +436,7 @@ private static void checkRestLiDataAnnotations(final Class resourceClass, Rec checkPathsAgainstSchema(dataSchema, resourceClassName, annotationEntry.getKey(), annotationEntry.getValue()); } // Check for redundant or conflicting information. - Map pathToAnnotation = new HashMap(); + Map pathToAnnotation = new HashMap<>(); for (Map.Entry annotationEntry : annotations.entrySet()) { String annotationName = annotationEntry.getKey(); @@ -607,7 +607,7 @@ else if (TyperefInfo.class.isAssignableFrom(keyClass)) } Key primaryKey = buildKey(name, keyName, keyClass, annotationData.typerefInfoClass()); - Set keys = new HashSet(); + Set keys = new HashSet<>(); if (annotationData.keys() == null) { keys.add(primaryKey); @@ -995,9 +995,9 @@ private static List> getParameters(final ResourceModel model, final Method method, final ResourceMethod methodType) { - Set paramNames = new HashSet(); + Set paramNames = new HashSet<>(); - List> queryParameters = new ArrayList>(); + List> queryParameters = new ArrayList<>(); Annotation[][] paramsAnnos = method.getParameterAnnotations(); // Iterate over the method parameters. @@ -1267,14 +1267,14 @@ else if (paramAnnotationType.equals(ParSeqContextParam.class)) { throw new ResourceConfigException("Param Annotation type must be 'ParseqContextParam' or the deprecated 'ParseqContext' for ParseqContext"); } - return new Parameter("", - Context.class, - null, - false, - null, - parameter, - false, - annotations); + return new Parameter<>("", + Context.class, + null, + false, + null, + parameter, + false, + annotations); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -1430,7 +1430,7 @@ private static boolean checkParameterHasTyperefSchema(Parameter parameter) private static Set buildKeys(String resourceName, com.linkedin.restli.server.annotations.Key[] annoKeys) { - Set keys = new HashSet(); + Set keys = new HashSet<>(); for(com.linkedin.restli.server.annotations.Key key : annoKeys) { keys.add(buildKey(resourceName, key.name(), key.type(), key.typeref())); @@ -2032,7 +2032,7 @@ private static void validateAssociation(final ResourceModel model) private static void validateCrudMethods(final ResourceModel model) { Map crudMethods = - new HashMap(); + new HashMap<>(); for (ResourceMethodDescriptor descriptor : model.getResourceMethodDescriptors()) { ResourceMethod type = descriptor.getType(); diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiApiBuilder.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiApiBuilder.java index 63a485e4f8..0e4c8c13f3 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiApiBuilder.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiApiBuilder.java @@ -143,8 +143,8 @@ private static void processResourceInOrder(Class annotatedClass, Map public static Map buildResourceModels(final Set> restliAnnotatedClasses) { - Map rootResourceModels = new HashMap(); - Map, ResourceModel> resourceModels = new HashMap, ResourceModel>(); + Map rootResourceModels = new HashMap<>(); + Map, ResourceModel> resourceModels = new HashMap<>(); for (Class annotatedClass : restliAnnotatedClasses) { diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiClasspathScanner.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiClasspathScanner.java index 5f2fbfe2e4..ca41c9d85b 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiClasspathScanner.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/model/RestLiClasspathScanner.java @@ -65,7 +65,7 @@ class RestLiClasspathScanner private static Set> buildAnnotations() { - Set> annotations = new HashSet>(); + Set> annotations = new HashSet<>(); annotations.add(RestLiCollection.class); annotations.add(RestLiAssociation.class); annotations.add(RestLiActions.class); @@ -82,14 +82,14 @@ private static Set> buildAnnotations() public RestLiClasspathScanner(final Set packageNames, final Set classNames, final ClassLoader classLoader) { _classLoader = classLoader; - _packagePaths = new HashSet(); + _packagePaths = new HashSet<>(); //convert package names to paths, to optimize matching against .class paths for (String packageName : packageNames) { _packagePaths.add(nameToPath(packageName)); } _classNames = classNames; - _matchedClasses = new HashSet>(); + _matchedClasses = new HashSet<>(); } private String nameToPath(final String name) diff --git a/restli-server/src/main/java/com/linkedin/restli/internal/server/util/MIMEParse.java b/restli-server/src/main/java/com/linkedin/restli/internal/server/util/MIMEParse.java index 9b61b0a3e8..c3040addd6 100644 --- a/restli-server/src/main/java/com/linkedin/restli/internal/server/util/MIMEParse.java +++ b/restli-server/src/main/java/com/linkedin/restli/internal/server/util/MIMEParse.java @@ -103,7 +103,7 @@ protected static ParseResults parseMimeType(String mimeType) { String[] parts = StringUtils.split(mimeType, ";"); ParseResults results = new ParseResults(); - results.params = new HashMap(); + results.params = new HashMap<>(); for (int i = 1; i < parts.length; ++i) { @@ -257,7 +257,7 @@ protected static float qualityParsed(String mimeType, */ public static float quality(String mimeType, String ranges) { - List results = new LinkedList(); + List results = new LinkedList<>(); for (String r : StringUtils.split(ranges, ',')) results.add(parseMediaRange(r)); return qualityParsed(mimeType, results); @@ -276,8 +276,8 @@ public static float quality(String mimeType, String ranges) */ public static String bestMatch(Collection supported, String header) { - List parseResults = new LinkedList(); - List weightedMatches = new LinkedList(); + List parseResults = new LinkedList<>(); + List weightedMatches = new LinkedList<>(); for (String r : StringUtils.split(header, ',')) parseResults.add(parseMediaRange(r)); @@ -306,7 +306,7 @@ public static String bestMatch(Collection supported, String header) */ public static List parseAcceptType(final String header) { - List acceptTypes = new LinkedList(); + List acceptTypes = new LinkedList<>(); for (String acceptType : StringUtils.split(header, ',')) { final ParseResults parseResults = parseMimeType(acceptType); diff --git a/restli-server/src/main/java/com/linkedin/restli/server/BatchFinderResult.java b/restli-server/src/main/java/com/linkedin/restli/server/BatchFinderResult.java index 6805360242..def4c59e35 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/BatchFinderResult.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/BatchFinderResult.java @@ -52,7 +52,7 @@ public BatchFinderResult() public BatchFinderResult(Map> resultList, Map errors) { _results = resultList == null ? new HashMap<>() : resultList; - _errors = errors == null ? new HashMap() : errors; + _errors = errors == null ? new HashMap<>() : errors; } /** diff --git a/restli-server/src/main/java/com/linkedin/restli/server/BatchResult.java b/restli-server/src/main/java/com/linkedin/restli/server/BatchResult.java index fd9363bc26..0e7aced621 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/BatchResult.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/BatchResult.java @@ -48,9 +48,9 @@ public BatchResult(final Map data, final Map er public BatchResult(final Map data, final Map statuses, final Map errors) { - _data = data == null ? new HashMap() : data; - _statuses = statuses == null ? new HashMap() : statuses; - _errors = errors == null ? new HashMap() : errors; + _data = data == null ? new HashMap<>() : data; + _statuses = statuses == null ? new HashMap<>() : statuses; + _errors = errors == null ? new HashMap<>() : errors; } @Override diff --git a/restli-server/src/main/java/com/linkedin/restli/server/DelegatingTransportDispatcher.java b/restli-server/src/main/java/com/linkedin/restli/server/DelegatingTransportDispatcher.java index 8343dbb9a5..0f601962b2 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/DelegatingTransportDispatcher.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/DelegatingTransportDispatcher.java @@ -67,7 +67,7 @@ public void handleRestRequest(RestRequest req, Map wireAttrs, { try { - _restHandler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + _restHandler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { @@ -83,7 +83,7 @@ public void handleStreamRequest(final StreamRequest req, { try { - _streamHandler.handleRequest(req, requestContext, new TransportCallbackAdapter(callback)); + _streamHandler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback)); } catch (Exception e) { diff --git a/restli-server/src/main/java/com/linkedin/restli/server/RestLiConfig.java b/restli-server/src/main/java/com/linkedin/restli/server/RestLiConfig.java index 4a2087a4d1..f35a3623b4 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/RestLiConfig.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/RestLiConfig.java @@ -258,7 +258,7 @@ public void addDebugRequestHandlers(final Collection */ public void setDebugRequestHandlers(final List handlers) { - _debugRequestHandlers = new ArrayList(handlers); + _debugRequestHandlers = new ArrayList<>(handlers); } /** diff --git a/restli-server/src/main/java/com/linkedin/restli/server/RestLiRequestDataImpl.java b/restli-server/src/main/java/com/linkedin/restli/server/RestLiRequestDataImpl.java index f50b9cb50f..ed10825eec 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/RestLiRequestDataImpl.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/RestLiRequestDataImpl.java @@ -142,9 +142,9 @@ public static class Builder public Builder() { - _keys = new ArrayList(); - _entities = new ArrayList(); - _keyEntityMap = new HashMap(); + _keys = new ArrayList<>(); + _entities = new ArrayList<>(); + _keyEntityMap = new HashMap<>(); } public Builder key(Object key) diff --git a/restli-server/src/main/java/com/linkedin/restli/server/RestliServlet.java b/restli-server/src/main/java/com/linkedin/restli/server/RestliServlet.java index ea18a175cb..94865ad5e3 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/RestliServlet.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/RestliServlet.java @@ -190,7 +190,7 @@ private long getAsyncTimeout(ServletConfig servletConfig) private Set getResourcePackageSet(ServletConfig servletConfig) { String resourcePackages = servletConfig.getInitParameter(RESOURCE_PACKAGES_PARAM); - Set resourcePackageSet = new HashSet(); + Set resourcePackageSet = new HashSet<>(); for(String resourcePackage : resourcePackages.split(PACKAGE_PARAM_SEPARATOR)) { resourcePackageSet.add(resourcePackage.trim()); diff --git a/restli-server/src/main/java/com/linkedin/restli/server/annotations/RestMethod.java b/restli-server/src/main/java/com/linkedin/restli/server/annotations/RestMethod.java index e1c57bceb9..a42316e6fc 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/annotations/RestMethod.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/annotations/RestMethod.java @@ -53,7 +53,7 @@ public class RestMethod } static Map, ResourceMethod> _restMethodAnnotationToResourceMethodMap = - new HashMap, ResourceMethod>(); + new HashMap<>(); // Build annotation-to-resourceMethod mapping. Check for absent or ambiguous mappings static { diff --git a/restli-server/src/main/java/com/linkedin/restli/server/filter/Filter.java b/restli-server/src/main/java/com/linkedin/restli/server/filter/Filter.java index daeb9d744d..08cf5f72b6 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/filter/Filter.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/filter/Filter.java @@ -130,7 +130,7 @@ default CompletableFuture onResponse(final FilterRequestContext requestCon default CompletableFuture onError(Throwable th, final FilterRequestContext requestContext, final FilterResponseContext responseContext) { - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(th); return future; } diff --git a/restli-server/src/main/java/com/linkedin/restli/server/mock/InjectMockResourceFactory.java b/restli-server/src/main/java/com/linkedin/restli/server/mock/InjectMockResourceFactory.java index e0e6f6e777..0f83a6814f 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/mock/InjectMockResourceFactory.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/mock/InjectMockResourceFactory.java @@ -61,7 +61,7 @@ public R create(final Class resourceClass) @Override public void setRootResources(final Map rootResources) { - Collection> allResourceClasses = new HashSet>(); + Collection> allResourceClasses = new HashSet<>(); for (ResourceModel resourceModel : rootResources.values()) { processChildResource(resourceModel, allResourceClasses); diff --git a/restli-server/src/main/java/com/linkedin/restli/server/mock/SimpleBeanProvider.java b/restli-server/src/main/java/com/linkedin/restli/server/mock/SimpleBeanProvider.java index a05d5d9f79..670ff59102 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/mock/SimpleBeanProvider.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/mock/SimpleBeanProvider.java @@ -38,7 +38,7 @@ public class SimpleBeanProvider implements BeanProvider public SimpleBeanProvider() { - _beans = new HashMap(); + _beans = new HashMap<>(); } public SimpleBeanProvider add(final String name, final Object bean) @@ -62,7 +62,7 @@ public Object getBean(final String name) @Override public Map getBeansOfType(final Class clazz) { - Map result = new HashMap(); + Map result = new HashMap<>(); synchronized (_beans) { for (Map.Entry entry : _beans.entrySet()) diff --git a/restli-server/src/main/java/com/linkedin/restli/server/resources/InjectResourceFactory.java b/restli-server/src/main/java/com/linkedin/restli/server/resources/InjectResourceFactory.java index ae6ff9690a..b55883ab93 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/resources/InjectResourceFactory.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/resources/InjectResourceFactory.java @@ -61,7 +61,7 @@ public void setRootResources(final Map rootResources) _rootResources = rootResources; - Collection> allResourceClasses = new HashSet>(); + Collection> allResourceClasses = new HashSet<>(); for (ResourceModel resourceModel : _rootResources.values()) { processChildResource(resourceModel, allResourceClasses); diff --git a/restli-server/src/main/java/com/linkedin/restli/server/resources/Jsr330Adapter.java b/restli-server/src/main/java/com/linkedin/restli/server/resources/Jsr330Adapter.java index 20d66ab5f0..15888c8e89 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/resources/Jsr330Adapter.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/resources/Jsr330Adapter.java @@ -49,17 +49,17 @@ public class Jsr330Adapter private final BeanProvider _beanProvider; - private final Map, InjectableConstructor> _constructorParameterDependencies = new HashMap, InjectableConstructor>(); + private final Map, InjectableConstructor> _constructorParameterDependencies = new HashMap<>(); - private final Map, Object[]> _constructorParameterBindings = new HashMap, Object[]>(); + private final Map, Object[]> _constructorParameterBindings = new HashMap<>(); //map of field dependency declarations (unbound dependencies) for each bean class //bean class => InjectableFields, i.e., (Field => DependencyDecl) - private final Map, InjectableFields> _fieldDependencyDeclarations = new HashMap, InjectableFields>(); + private final Map, InjectableFields> _fieldDependencyDeclarations = new HashMap<>(); //map of bound field dependencies for each bean class //bean class => BeanDependencies, i.e., (Field => Object) - private final Map, BeanDependencies> _fieldDependencyBindings = new HashMap, BeanDependencies>(); + private final Map, BeanDependencies> _fieldDependencyBindings = new HashMap<>(); public Jsr330Adapter(final Collection> managedBeans, final BeanProvider beanProvider) @@ -135,7 +135,7 @@ private void scanInjectableConstructors(Class beanClazz) Class[] parameters = constructor.getParameterTypes(); Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); - List parameterDecls = new ArrayList(parameters.length); + List parameterDecls = new ArrayList<>(parameters.length); for (int i = 0; i < parameters.length; ++i) { @@ -178,7 +178,7 @@ private void scanInjectableFields(Class beanClazz) InjectableFields fieldDecls = new InjectableFields(); List fieldsToScan = - new ArrayList(Arrays.asList(beanClazz.getDeclaredFields())); + new ArrayList<>(Arrays.asList(beanClazz.getDeclaredFields())); Class superclazz = beanClazz.getSuperclass(); while (superclazz != Object.class) { @@ -287,7 +287,7 @@ private Object resolveDependency(DependencyDecl decl, Class beanClazz, protected static class BeanDependencies { - Map _dependencyMap = new HashMap(); + Map _dependencyMap = new HashMap<>(); public void add(final Field field, final Object bean) { @@ -329,7 +329,7 @@ public List getParameterDecls() protected static class InjectableFields { - Map _fieldMap = new HashMap(); + Map _fieldMap = new HashMap<>(); public Iterable> iterator() { diff --git a/restli-server/src/main/java/com/linkedin/restli/server/util/ChainedIterator.java b/restli-server/src/main/java/com/linkedin/restli/server/util/ChainedIterator.java index 087ee63459..c6a113f95b 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/util/ChainedIterator.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/util/ChainedIterator.java @@ -33,7 +33,7 @@ public class ChainedIterator implements Iterator @SafeVarargs public ChainedIterator(Iterator... iterators) { - final List> list = new ArrayList>(); + final List> list = new ArrayList<>(); for (Iterator itr : iterators) { list.add(itr); diff --git a/restli-server/src/main/java/com/linkedin/restli/server/util/FileClassNameScanner.java b/restli-server/src/main/java/com/linkedin/restli/server/util/FileClassNameScanner.java index 7961db041c..0a2922a23f 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/util/FileClassNameScanner.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/util/FileClassNameScanner.java @@ -64,7 +64,7 @@ public static Map scan(String sourceDir, String requiredExtensio } final Collection files = FileUtils.listFiles(dir, null, true); - final Map classFileNames = new HashMap(); + final Map classFileNames = new HashMap<>(); final int prefixLength = sourceDirWithSeparator.length(); for (File f : files) { diff --git a/restli-server/src/main/java/com/linkedin/restli/server/util/PatchHelper.java b/restli-server/src/main/java/com/linkedin/restli/server/util/PatchHelper.java index 86c6954234..336d3cb26a 100644 --- a/restli-server/src/main/java/com/linkedin/restli/server/util/PatchHelper.java +++ b/restli-server/src/main/java/com/linkedin/restli/server/util/PatchHelper.java @@ -89,7 +89,7 @@ private static void trim(DataMap doc, DataMap projected) { DataMap toAddDoc = new DataMap(); Set fields = doc.keySet(); - List toRemoveDoc = new ArrayList(fields.size()); + List toRemoveDoc = new ArrayList<>(fields.size()); for (String f : fields) { Object v = doc.get(f); @@ -114,7 +114,7 @@ else if (f.equals(PatchConstants.SET_COMMAND)) { DataMap setFields = (DataMap)v; Set setFieldNames = setFields.keySet(); - List toRemove = new LinkedList(); + List toRemove = new LinkedList<>(); DataMap filteredSetFields = new DataMap(); for (String setFieldName: setFieldNames) { diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/TestFilterRequestContextInternalImpl.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/TestFilterRequestContextInternalImpl.java index b2d3958b00..e9feec89ff 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/TestFilterRequestContextInternalImpl.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/TestFilterRequestContextInternalImpl.java @@ -94,7 +94,7 @@ public void testFilterRequestContextAdapter() throws Exception final MaskTree metadataMaskTree = new MaskTree(); final MaskTree pagingMaskTree = new MaskTree(); final MutablePathKeys pathKeys = new PathKeysImpl(); - final Map requestHeaders = new HashMap(); + final Map requestHeaders = new HashMap<>(); requestHeaders.put("Key1", "Value1"); final URI requestUri = new URI("foo.bar.com"); final ProtocolVersion protoVersion = AllProtocolVersions.BASELINE_PROTOCOL_VERSION; @@ -228,4 +228,4 @@ public void testGetActionReturnType() when(resourceMethod.getMethodType()).thenReturn(ResourceMethod.GET); Assert.assertNull(filterContext.getActionReturnType()); } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/testfilters/CountFilter.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/testfilters/CountFilter.java index a26b873997..28e9e35852 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/testfilters/CountFilter.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/filter/testfilters/CountFilter.java @@ -78,7 +78,7 @@ public int getNumErrors() { */ protected CompletableFuture completedFutureWithError(Throwable t) { - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestArgumentBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestArgumentBuilder.java index 7c0f6ad6a0..0143d23080 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestArgumentBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestArgumentBuilder.java @@ -352,7 +352,7 @@ public void testPagingContextParamType() EasyMock.expect(mockResourceContext.getRequestAttachmentReader()).andReturn(null); EasyMock.replay(mockResourceContext); - List> parameters = new ArrayList>(); + List> parameters = new ArrayList<>(); Parameter param1 = new Parameter<>(testParamKey, PagingContext.class, null, false, null, Parameter.ParamType.PAGING_CONTEXT_PARAM, false, AnnotationSet.EMPTY); Parameter param2 = new Parameter<>(testParamKey, PagingContext.class, null, @@ -878,4 +878,4 @@ public void testQueryParameterValidation(String paramKey, Class dataType, } } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestGetArgumentBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestGetArgumentBuilder.java index 9d9d8533af..81452cea0e 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestGetArgumentBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/methods/arguments/TestGetArgumentBuilder.java @@ -119,7 +119,7 @@ private Object[][] keyArgumentData() { complexResourceKeyParam, "complexKeyTestId", - new ComplexResourceKey( + new ComplexResourceKey<>( new MyComplexKey().setA("keyString").setB(1234L), new EmptyRecord()), null } @@ -270,7 +270,7 @@ public void testHeaderArgument() Object keyValue = Integer.valueOf(123); DataSchema keySchema = new IntegerDataSchema(); Key key = new Key(keyName, keyValue.getClass(), keySchema); - Map headers = new HashMap(); + Map headers = new HashMap<>(); String headerString = "An extra string."; headers.put("extra", headerString); List> headerParams = new ArrayList<>(); @@ -361,4 +361,4 @@ public void testFailure(Parameter param, String errorMessage) verify(descriptor, context, routingResult, request); } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestParameterDefaultValue.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestParameterDefaultValue.java index 64bb4b7f09..91076e8407 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestParameterDefaultValue.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestParameterDefaultValue.java @@ -157,49 +157,49 @@ public void testWrappedMap() Object result; result = test("{\"key1\": \"Hello\", \"key2\": \"World\"}", StringMap.class); - final Map stringFixture = new HashMap(); + final Map stringFixture = new HashMap<>(); stringFixture.put("key1", "Hello"); stringFixture.put("key2", "World"); Assert.assertEquals(result, new StringMap(stringFixture)); Assert.assertSame(result.getClass(), StringMap.class); result = test("{\"key1\": true, \"key2\": false}", BooleanMap.class); - final Map booleanFixture = new HashMap(); + final Map booleanFixture = new HashMap<>(); booleanFixture.put("key1", true); booleanFixture.put("key2", false); Assert.assertEquals(result, new BooleanMap(booleanFixture)); Assert.assertSame(result.getClass(), BooleanMap.class); result = test("{\"key1\": 1, \"key2\": 2}", IntegerMap.class); - final Map integerFixture = new HashMap(); + final Map integerFixture = new HashMap<>(); integerFixture.put("key1", 1); integerFixture.put("key2", 2); Assert.assertEquals(result, new IntegerMap(integerFixture)); Assert.assertSame(result.getClass(), IntegerMap.class); result = test("{\"key1\": 2, \"key2\": 3}", LongMap.class); - final Map longFixture = new HashMap(); + final Map longFixture = new HashMap<>(); longFixture.put("key1", 2L); longFixture.put("key2", 3L); Assert.assertEquals(result, new LongMap(longFixture)); Assert.assertSame(result.getClass(), LongMap.class); result = test("{\"key1\": 1.1, \"key2\": 2.2}", FloatMap.class); - final Map floatFixture = new HashMap(); + final Map floatFixture = new HashMap<>(); floatFixture.put("key1", 1.1F); floatFixture.put("key2", 2.2F); Assert.assertEquals(result, new FloatMap(floatFixture)); Assert.assertSame(result.getClass(), FloatMap.class); result = test("{\"key1\": 2.2, \"key2\": 3.3}", DoubleMap.class); - final Map doubleFixture = new HashMap(); + final Map doubleFixture = new HashMap<>(); doubleFixture.put("key1", 2.2D); doubleFixture.put("key2", 3.3D); Assert.assertEquals(result, new DoubleMap(doubleFixture)); Assert.assertSame(result.getClass(), DoubleMap.class); result = test("{\"key1\": " + _bytes16Quoted + ", \"key2\": " + _bytes16Quoted + "}", BytesMap.class); - final Map bytesFixture = new HashMap(); + final Map bytesFixture = new HashMap<>(); bytesFixture.put("key1", ByteString.copyAvroString(_bytes16, true)); bytesFixture.put("key2", ByteString.copyAvroString(_bytes16, true)); Assert.assertEquals(result, new BytesMap(new DataMap(bytesFixture))); @@ -212,7 +212,7 @@ public void testWrappedMap() dataFixture2.put("location", "MTV"); final RecordBar record1 = new RecordBar(dataFixture1); final RecordBar record2 = new RecordBar(dataFixture2); - final Map recordFixture = new HashMap(); + final Map recordFixture = new HashMap<>(); recordFixture.put("key1", record1); recordFixture.put("key2", record2); Assert.assertEquals(result, new RecordBarMap(recordFixture)); @@ -230,7 +230,7 @@ public void testRecord() { final Map fixture; - fixture = new HashMap(); + fixture = new HashMap<>(); fixture.put("location", "LinkedIn"); Assert.assertEquals(test("{\"location\": \"LinkedIn\"}", RecordBar.class), new RecordBar(new DataMap(fixture))); } @@ -285,12 +285,12 @@ public void testCustomParamArray() private static Object test(String value, Class type) { - return new Parameter("", type, null, true, value, null, false, AnnotationSet.EMPTY).getDefaultValue(); + return new Parameter<>("", type, null, true, value, null, false, AnnotationSet.EMPTY).getDefaultValue(); } private static Object test(String value, Class type, DataSchema typrefSchema) { - return new Parameter("", type, typrefSchema, true, value, null, false, AnnotationSet.EMPTY).getDefaultValue(); + return new Parameter<>("", type, typrefSchema, true, value, null, false, AnnotationSet.EMPTY).getDefaultValue(); } private final String _bytes16 = "\u0001\u0002\u0003\u0004" + diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestRestLiApiBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestRestLiApiBuilder.java index f7a58d6edb..d713b977c6 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestRestLiApiBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/model/TestRestLiApiBuilder.java @@ -58,7 +58,7 @@ public Object[][] provideResourcesWithClashingNames() @Test(dataProvider = "resourcesWithClashingNamesDataProvider") public void testResourceNameClash(Class[] classes) { - Set> resourceClasses = new HashSet>(Arrays.>asList(classes)); + Set> resourceClasses = new HashSet<>(Arrays.>asList(classes)); try { RestLiApiBuilder.buildResourceModels(resourceClasses); @@ -294,4 +294,4 @@ public void testPathKeyParamAnnotations() exception.getMessage()); } } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/ResponseBuilderUtil.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/ResponseBuilderUtil.java index 2573b852b1..0afac253d4 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/ResponseBuilderUtil.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/ResponseBuilderUtil.java @@ -41,7 +41,7 @@ public class ResponseBuilderUtil */ public static Map getHeaders() { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(KEY1, VALUE1); headers.put(KEY2_LOWER, VALUE2); headers.put(KEY2_UPPER, VALUE2); diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchCreateResponseBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchCreateResponseBuilder.java index 27e1e2bcf2..191d611473 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchCreateResponseBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchCreateResponseBuilder.java @@ -72,16 +72,16 @@ public class TestBatchCreateResponseBuilder @DataProvider(name = "createResultBuilderTestData") public Object[][] createResultBuilderTestData() { - Map> alternativeKeyMap = new HashMap>(); - alternativeKeyMap.put("alt", new AlternativeKey(new TestKeyCoercer(), String.class, new StringDataSchema())); + Map> alternativeKeyMap = new HashMap<>(); + alternativeKeyMap.put("alt", new AlternativeKey<>(new TestKeyCoercer(), String.class, new StringDataSchema())); - List> expectedStatuses = new ArrayList>(2); - expectedStatuses.add(new CreateIdStatus(201, 1L, "/foo/1", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - expectedStatuses.add(new CreateIdStatus(201, 2L, "/foo/2", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); + List> expectedStatuses = new ArrayList<>(2); + expectedStatuses.add(new CreateIdStatus<>(201, 1L, "/foo/1", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); + expectedStatuses.add(new CreateIdStatus<>(201, 2L, "/foo/2", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - List> expectedAltStatuses = new ArrayList>(2); - expectedAltStatuses.add(new CreateIdStatus(201, "Alt1", "/foo/Alt1?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - expectedAltStatuses.add(new CreateIdStatus(201, "Alt2", "/foo/Alt2?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); + List> expectedAltStatuses = new ArrayList<>(2); + expectedAltStatuses.add(new CreateIdStatus<>(201, "Alt1", "/foo/Alt1?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); + expectedAltStatuses.add(new CreateIdStatus<>(201, "Alt2", "/foo/Alt2?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); return new Object[][] { @@ -101,7 +101,7 @@ public void testCreateResultBuilder(String uriString, { List createResponses = Arrays.asList(new CreateResponse(1L), new CreateResponse(2L)); BatchCreateResult results = - new BatchCreateResult(createResponses); + new BatchCreateResult<>(createResponses); Map headers = ResponseBuilderUtil.getHeaders(); ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(alternativeKeyMap); @@ -122,14 +122,14 @@ public void testCreateResultBuilder(String uriString, Assert.assertFalse(responseData.getResponseEnvelope().isGetAfterCreate()); - List> items = new ArrayList>(); + List> items = new ArrayList<>(); for (BatchCreateResponseEnvelope.CollectionCreateResponseItem item : responseData.getResponseEnvelope() .getCreateResponses()) { items.add((CreateIdStatus) item.getRecord()); } - Assert.assertEquals(restResponse.getEntity(), new BatchCreateIdResponse(items)); + Assert.assertEquals(restResponse.getEntity(), new BatchCreateIdResponse<>(items)); Assert.assertEquals(expectedStatuses, items); Assert.assertEquals(restResponse.getStatus(), HttpStatus.S_200_OK); } @@ -137,23 +137,23 @@ public void testCreateResultBuilder(String uriString, @DataProvider(name = "createKVResultBuilderTestData") public Object[][] createKVResultBuilderTestData() { - Map> alternativeKeyMap = new HashMap>(); - alternativeKeyMap.put("alt", new AlternativeKey(new TestKeyCoercer(), String.class, new StringDataSchema())); + Map> alternativeKeyMap = new HashMap<>(); + alternativeKeyMap.put("alt", new AlternativeKey<>(new TestKeyCoercer(), String.class, new StringDataSchema())); Foo foo1 = new Foo(); foo1.setStringField("foo1"); Foo foo2 = new Foo(); foo2.setStringField("foo2"); - List> expectedResponses = new ArrayList>(2); - expectedResponses.add(new CreateIdEntityStatus(201, 1L, foo1, "/foo/1", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - expectedResponses.add(new CreateIdEntityStatus(201, 2L, foo2, "/foo/2", null, + List> expectedResponses = new ArrayList<>(2); + expectedResponses.add(new CreateIdEntityStatus<>(201, 1L, foo1, "/foo/1", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); + expectedResponses.add(new CreateIdEntityStatus<>(201, 2L, foo2, "/foo/2", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - List> expectedAltResponses = new ArrayList>(2); - expectedAltResponses.add(new CreateIdEntityStatus(201, "Alt1", foo1, "/foo/Alt1?altkey=alt",null, + List> expectedAltResponses = new ArrayList<>(2); + expectedAltResponses.add(new CreateIdEntityStatus<>(201, "Alt1", foo1, "/foo/Alt1?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); - expectedAltResponses.add(new CreateIdEntityStatus(201, "Alt2", foo2, "/foo/Alt2?altkey=alt",null, + expectedAltResponses.add(new CreateIdEntityStatus<>(201, "Alt2", foo2, "/foo/Alt2?altkey=alt", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion())); return new Object[][] @@ -168,14 +168,14 @@ public void testCreateKVResultBuilder(String altKeyName, Map> alternativeKeyMap, List> expectedResponses) throws URISyntaxException { - List> createKVResponses = new ArrayList>(2); + List> createKVResponses = new ArrayList<>(2); Foo foo1 = new Foo(); foo1.setStringField("foo1"); Foo foo2 = new Foo(); foo2.setStringField("foo2"); - createKVResponses.add(new CreateKVResponse(1L, foo1)); - createKVResponses.add(new CreateKVResponse(2L, foo2)); - BatchCreateKVResult results = new BatchCreateKVResult(createKVResponses); + createKVResponses.add(new CreateKVResponse<>(1L, foo1)); + createKVResponses.add(new CreateKVResponse<>(2L, foo2)); + BatchCreateKVResult results = new BatchCreateKVResult<>(createKVResponses); Map headers = ResponseBuilderUtil.getHeaders(); ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(alternativeKeyMap); @@ -198,7 +198,7 @@ public void testCreateKVResultBuilder(String altKeyName, Assert.assertTrue(responseData.getResponseEnvelope().isGetAfterCreate()); - List> items = new ArrayList>(); + List> items = new ArrayList<>(); for (BatchCreateResponseEnvelope.CollectionCreateResponseItem item : responseData.getResponseEnvelope() .getCreateResponses()) { @@ -331,12 +331,12 @@ public void testProjectionInBuildRestLiResponseData() throws URISyntaxException ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(null); RoutingResult routingResult = new RoutingResult(mockContext, mockDescriptor); - List> createKVResponses = new ArrayList>(); + List> createKVResponses = new ArrayList<>(); Foo foo = new Foo(); foo.setStringField("foo1"); foo.setFruitsField(Fruits.APPLE); - createKVResponses.add(new CreateKVResponse(1L, foo)); - BatchCreateKVResult results = new BatchCreateKVResult(createKVResponses); + createKVResponses.add(new CreateKVResponse<>(1L, foo)); + BatchCreateKVResult results = new BatchCreateKVResult<>(createKVResponses); BatchCreateResponseBuilder responseBuilder = new BatchCreateResponseBuilder(new ErrorResponseBuilder()); RestRequest request = new RestRequestBuilder(new URI("/foo")).build(); diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchFinderResponseBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchFinderResponseBuilder.java index a3ac417ea2..734542b774 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchFinderResponseBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestBatchFinderResponseBuilder.java @@ -277,7 +277,7 @@ public Class annotationType() private static List generateCriteria(int nb) { - List criteria = new ArrayList(nb); + List criteria = new ArrayList<>(nb); for (int i = 1; i <= nb; i++) { Foo item = new Foo().setStringField("criteria_" + i) @@ -296,7 +296,7 @@ private static List generateCriteria(int nb) private static List generateTestList(Foo criteria) { - List items = new ArrayList(criteria.getIntField()); + List items = new ArrayList<>(criteria.getIntField()); for (int i = 0; i < criteria.getIntField(); i++) { items.add(new Foo().setStringField(criteria.getStringField()).setIntField(i)); @@ -306,11 +306,11 @@ private static List generateTestList(Foo criteria) private static BatchFinderResult generateResults(List criteria) { - BatchFinderResult results = new BatchFinderResult(); + BatchFinderResult results = new BatchFinderResult<>(); for (int i = 0; i < criteria.size(); i++) { List items = generateTestList(criteria.get(i).criteria); - results.putResult(criteria.get(i).getCriteria(), new CollectionResult(items)); + results.putResult(criteria.get(i).getCriteria(), new CollectionResult<>(items)); } return results; @@ -319,7 +319,7 @@ private static BatchFinderResult generateResults(List c @SuppressWarnings("deprecation") private static BatchFinderResult generateResultsWithErrors(List criteria) { - BatchFinderResult results = new BatchFinderResult(); + BatchFinderResult results = new BatchFinderResult<>(); for (int i = 0; i < criteria.size(); i++) { if (i % 2 == 0) @@ -332,7 +332,7 @@ private static BatchFinderResult generateResultsWithErrors(List items = generateTestList(criteria.get(i).criteria); - results.putResult(criteria.get(i).criteria, new CollectionResult(items)); + results.putResult(criteria.get(i).criteria, new CollectionResult<>(items)); } } diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestCreateResponseBuilder.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestCreateResponseBuilder.java index d98e834365..d58c56fc20 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestCreateResponseBuilder.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestCreateResponseBuilder.java @@ -68,8 +68,8 @@ public class TestCreateResponseBuilder public Object[][] testDataProvider() { CompoundKey compoundKey = new CompoundKey().append("a", "a").append("b", 1); - Map> alternativeKeyMap = new HashMap>(); - alternativeKeyMap.put("alt", new AlternativeKey(new TestKeyCoercer(), String.class, new StringDataSchema())); + Map> alternativeKeyMap = new HashMap<>(); + alternativeKeyMap.put("alt", new AlternativeKey<>(new TestKeyCoercer(), String.class, new StringDataSchema())); return new Object[][] { { AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), "/foo", compoundKey, "/foo/a=a&b=1", "a=a&b=1", null, null }, @@ -92,12 +92,12 @@ public void testBuilder(ProtocolVersion protocolVersion, { CompoundKey compoundKey = new CompoundKey().append("a", "a").append("b", 1); CreateResponse createResponse = new CreateResponse(compoundKey); - IdResponse expectedIdResponse = new IdResponse(expectedId); + IdResponse expectedIdResponse = new IdResponse<>(expectedId); RestRequest restRequest = new RestRequestBuilder(new URI(uriString)).build(); Map headers = ResponseBuilderUtil.getHeaders(); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()); // the headers passed in are modified - Map expectedHeaders = new HashMap(headers); + Map expectedHeaders = new HashMap<>(headers); ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(alternativeKeyMap); ServerResourceContext mockContext = getMockResourceContext(protocolVersion, altKeyName); diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiCallback.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiCallback.java index da3a17bfe5..6ade4b9fc4 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiCallback.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiCallback.java @@ -1177,7 +1177,7 @@ else if (entityFromFilter2 instanceof List) } else { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for (Map.Entry entry : ((Map) entityFromFilter2).entrySet()) { responseMap.put(entry.getKey(), new BatchResponseEnvelope.BatchResponseEntry(HttpStatus.S_200_OK, entry.getValue())); @@ -1345,7 +1345,7 @@ static Foo createFoo(String key, String value) */ private static CompletableFuture completedFutureWithError(Throwable t) { - CompletableFuture future = new CompletableFuture(); + CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponse.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponse.java index 61d91f0f3e..8b1ca3fed4 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponse.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponse.java @@ -32,7 +32,7 @@ public class TestRestLiResponse @Test public void testHeaders() { - Map inputHeaderMap = new HashMap(); + Map inputHeaderMap = new HashMap<>(); inputHeaderMap.put("foo", "bar"); inputHeaderMap.put("bar", "baz"); RestLiResponse response = new RestLiResponse.Builder().headers(inputHeaderMap).build(); diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponseEnvelope.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponseEnvelope.java index d0dd31b7fd..dcce225d7d 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponseEnvelope.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/response/TestRestLiResponseEnvelope.java @@ -228,7 +228,7 @@ public void testSetNewEnvelopeData(RestLiResponseEnvelope responseEnvelope, Reso RecordTemplate newResponseRecord = new EmptyRecord(); RestLiServiceException newResponseException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR); Map newBatchResponses = - new HashMap(); + new HashMap<>(); newBatchResponses.put("id1", new BatchResponseEnvelope.BatchResponseEntry(HttpStatus.S_200_OK, newResponseRecord)); newBatchResponses.put("id2", @@ -258,7 +258,7 @@ public void testSetNewEnvelopeData(RestLiResponseEnvelope responseEnvelope, Reso List oldItems = batchFinderResponseEnvelope.getItems(); - List newItems = new ArrayList(2); + List newItems = new ArrayList<>(2); RestLiServiceException newBFResponseException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR); newItems.add(new BatchFinderResponseEnvelope.BatchFinderEntry(newBFResponseException)); diff --git a/restli-server/src/test/java/com/linkedin/restli/internal/server/util/TestRestUtils.java b/restli-server/src/test/java/com/linkedin/restli/internal/server/util/TestRestUtils.java index a9dbde2184..bdb7b7cf8c 100644 --- a/restli-server/src/test/java/com/linkedin/restli/internal/server/util/TestRestUtils.java +++ b/restli-server/src/test/java/com/linkedin/restli/internal/server/util/TestRestUtils.java @@ -136,7 +136,7 @@ public void testPickBestEncodingWithInvalidHeaders(String header) @Test() public void testValidateRequestHeadersWithValidAcceptHeaderAndNoMatch() throws Exception { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("Accept", "text/html"); ServerResourceContext resourceContext = new ResourceContextImpl(); try @@ -157,7 +157,7 @@ public void testValidateRequestHeadersWithValidAcceptHeaderAndNoMatch() throws E @Test() public void testValidateRequestHeadersWithValidAcceptHeaderAndMatch() throws Exception { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("Accept", "application/json"); ServerResourceContext resourceContext = new ResourceContextImpl(); RestUtils.validateRequestHeadersAndUpdateResourceContext(headers, Collections.emptySet(), resourceContext); diff --git a/restli-server/src/test/java/com/linkedin/restli/server/RestLiTestHelper.java b/restli-server/src/test/java/com/linkedin/restli/server/RestLiTestHelper.java index e2b4608656..9629a10bbd 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/RestLiTestHelper.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/RestLiTestHelper.java @@ -37,7 +37,7 @@ public static M buildResourceModel(Class rootResour public static Map buildResourceModels(Class... rootResourceClasses) { - Map map = new HashMap(); + Map map = new HashMap<>(); for (Class rootResourceClass : rootResourceClasses) { ResourceModel model = RestLiAnnotationReader.processResource(rootResourceClass); diff --git a/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiRequestDataImpl.java b/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiRequestDataImpl.java index 89ea21adba..48e29b531e 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiRequestDataImpl.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiRequestDataImpl.java @@ -40,7 +40,7 @@ public void testBatchRequest() { List batchEntities = Arrays.asList(Foo.createFoo("foo", "bar")); List batchKeys = Arrays.asList("key1", "key2", "key3"); - Map batchKeyEntityMap = new HashMap(); + Map batchKeyEntityMap = new HashMap<>(); batchKeyEntityMap.put("key1", Foo.createFoo("foo1", "bar1")); batchKeyEntityMap.put("key2", Foo.createFoo("foo2", "bar2")); RestLiRequestData requestData1 = new RestLiRequestDataImpl.Builder().batchKeys(batchKeys).build(); @@ -112,4 +112,4 @@ public static Foo createFoo(String key, String value) return new Foo(dataMap); } } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiServer.java b/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiServer.java index 5fed2c60f5..e4e79b69e9 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiServer.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/TestRestLiServer.java @@ -1441,7 +1441,7 @@ public void testRestLiConfig() config.setResourcePackageNames("foo, bar , baz"); assertEquals(ImmutableSet.of("foo", "bar", "baz"), config.getResourcePackageNamesSet()); - Set packageSet = new HashSet(); + Set packageSet = new HashSet<>(); packageSet.add("a"); packageSet.add("b"); config.setResourcePackageNamesSet(packageSet); diff --git a/restli-server/src/test/java/com/linkedin/restli/server/combined/CombinedResources.java b/restli-server/src/test/java/com/linkedin/restli/server/combined/CombinedResources.java index 5c24955ed1..464eb90ec8 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/combined/CombinedResources.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/combined/CombinedResources.java @@ -142,7 +142,7 @@ public Map batchGet(Set key) @Finder("find") public List find(@PagingContextParam PagingContext context, @AssocKeyParam("foo") int foo, @AssocKeyParam("bar") int bar) { - return new ArrayList(); + return new ArrayList<>(); } } diff --git a/restli-server/src/test/java/com/linkedin/restli/server/multiplexer/TestMultiplexedRequestHandlerImpl.java b/restli-server/src/test/java/com/linkedin/restli/server/multiplexer/TestMultiplexedRequestHandlerImpl.java index 3e0217f454..5d45d8586a 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/multiplexer/TestMultiplexedRequestHandlerImpl.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/multiplexer/TestMultiplexedRequestHandlerImpl.java @@ -121,7 +121,7 @@ public void testHandleWrongMethod(MultiplexerRunMode multiplexerRunMode) throws { MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexerRunMode); RestRequest request = muxRequestBuilder().setMethod(HttpMethod.PUT.name()).build(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, new RequestContext(), callback); assertEquals(getErrorStatus(callback), HttpStatus.S_405_METHOD_NOT_ALLOWED); } @@ -135,7 +135,7 @@ public void testHandleWrongContentType(MultiplexerRunMode multiplexerRunMode) th .setMethod(HttpMethod.POST.name()) .setHeader(RestConstants.HEADER_CONTENT_TYPE, "text/plain") .build(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, new RequestContext(), callback); assertEquals(getErrorStatus(callback), HttpStatus.S_415_UNSUPPORTED_MEDIA_TYPE); } @@ -165,7 +165,7 @@ public void testHandleEmptyRequest(MultiplexerRunMode multiplexerRunMode) throws { MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexerRunMode); RestRequest request = fakeMuxRestRequest(); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, new RequestContext(), callback); assertEquals(getErrorStatus(callback), HttpStatus.S_400_BAD_REQUEST); } @@ -178,7 +178,7 @@ public void testHandleTooManyParallelRequests(MultiplexerRunMode multiplexerRunM RestRequest request = fakeMuxRestRequest(ImmutableMap.of("0", fakeIndRequest(FOO_URL), "1", fakeIndRequest(FOO_URL), "2", fakeIndRequest(FOO_URL))); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, new RequestContext(), callback); assertEquals(getErrorStatus(callback), HttpStatus.S_400_BAD_REQUEST); } @@ -192,7 +192,7 @@ public void testHandleTooManySequentialRequests(MultiplexerRunMode multiplexerRu IndividualRequest ir1 = fakeIndRequest(FOO_URL, ImmutableMap.of("2", ir2)); IndividualRequest ir0 = fakeIndRequest(FOO_URL, ImmutableMap.of("1", ir1)); RestRequest request = fakeMuxRestRequest(ImmutableMap.of("0", ir0)); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, new RequestContext(), callback); assertEquals(getErrorStatus(callback), HttpStatus.S_400_BAD_REQUEST); } @@ -235,7 +235,7 @@ public void testCustomMultiplexedSingletonFilter(MultiplexerRunMode multiplexerR replay(mockHandler); replay(mockMuxFilter); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); @@ -267,7 +267,7 @@ public void testCustomFilterFailsForAllRequest(MultiplexerRunMode multiplexerRun replay(mockHandler); replay(mockMuxFilter); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); @@ -287,8 +287,8 @@ public void testIndividualRequestInheritHeadersAndCookiesFromEnvelopeRequest(Mul // envelope request. // Create a mockHandler. Captures all headers and cookies found in the request. - final Map headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); - final Map cookies = new HashMap(); + final Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + final Map cookies = new HashMap<>(); SynchronousRequestHandler mockHandler = new SynchronousRequestHandler() { @Override @@ -312,7 +312,7 @@ public RestResponse handleRequestSync(RestRequest request, RequestContext reques // Create a mock MultiplexerSingletonFilter to put request headers inside another headers so // we can do assertion on it later. - final Map headersSeenInMuxFilter = new TreeMap(String.CASE_INSENSITIVE_ORDER); + final Map headersSeenInMuxFilter = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); MultiplexerSingletonFilter muxFilterWithSimulatedFailures = new MultiplexerSingletonFilter() { @Override public IndividualRequest filterIndividualRequest(IndividualRequest request) @@ -329,7 +329,7 @@ public IndividualResponse filterIndividualResponse(IndividualResponse response) }; // Prepare request to mux handler - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); RequestContext requestContext = new RequestContext(); Map individualRequests = ImmutableMap.of( "0", fakeIndRequest("/request", @@ -337,7 +337,7 @@ public IndividualResponse filterIndividualResponse(IndividualResponse response) "X-OverridableHeader", "overrideHeader"), Collections.emptyMap())); - Set headerWhiteList = new HashSet(); + Set headerWhiteList = new HashSet<>(); headerWhiteList.add("X-IndividualHeader"); headerWhiteList.add("X-OverridableHeader"); @@ -368,7 +368,7 @@ public IndividualResponse filterIndividualResponse(IndividualResponse response) IndividualResponse response = muxResponseContent.getResponses().get("0"); assertEquals(response.getStatus().intValue(), 200, "Individual request should not fail. Response body is: " + response.getBody().toString()); - Map expectedHeaders = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map expectedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); expectedHeaders.putAll(ImmutableMap.of( RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_JSON, "X-IndividualHeader", "individualHeader", @@ -420,7 +420,7 @@ public RestResponse handleRequestSync(RestRequest request, RequestContext reques } }; // Prepare request to mux handler - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); RequestContext requestContext = new RequestContext(); Map individualRequests = ImmutableMap.of( "0", fakeIndRequest("/request1", @@ -430,7 +430,7 @@ public RestResponse handleRequestSync(RestRequest request, RequestContext reques ImmutableMap.of("X-Malicious-Header", "evilHeader"), Collections.emptyMap())); - Set headerWhiteList = new HashSet(); + Set headerWhiteList = new HashSet<>(); headerWhiteList.add("X-I-AM-A-GOOD-HEADER"); // Create mux handler instance @@ -470,7 +470,7 @@ public RestResponse handleRequestSync(RestRequest request, RequestContext reques RestResponseBuilder restResponseBuilder = new RestResponseBuilder(); restResponseBuilder.setStatus(HttpStatus.S_200_OK.getCode()); restResponseBuilder.setEntity(jsonBodyToByteString(fakeIndividualBody("don't care"))); - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); if (uri.getPath().contains("req1")) { HttpCookie cookie = new HttpCookie("cookie1", "cookie1Value"); @@ -517,7 +517,7 @@ else if (uri.getPath().contains("req2")) }; // Prepare request to mux handler - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); RequestContext requestContext = new RequestContext(); Map individualRequests = ImmutableMap.of( "0", fakeIndRequest("/req1"), @@ -647,9 +647,9 @@ else if (response.getBody().data().getString("value").contains("error_response") }; // Prepare request to mux handler - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); RequestContext requestContext = new RequestContext(); - Map individualRequests = new HashMap(); + Map individualRequests = new HashMap<>(); individualRequests.put("0", fakeIndRequest("/good_request")); individualRequests.put("1", fakeIndRequest("/bad_request")); individualRequests.put("2", fakeIndRequest("/error_request")); @@ -705,7 +705,7 @@ public void testHandleSingleRequest(MultiplexerRunMode multiplexerRunMode) throw // switch into replay mode replay(mockHandler); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); @@ -733,7 +733,7 @@ public void testHandleParallelRequests(MultiplexerRunMode multiplexerRunMode) th // switch into replay mode replay(mockHandler); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); @@ -763,7 +763,7 @@ public void testHandleSequentialRequests(MultiplexerRunMode multiplexerRunMode) // switch into replay mode replay(mockHandler); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); @@ -791,7 +791,7 @@ public void testHandleError(MultiplexerRunMode multiplexerRunMode) throws Except // switch into replay mode replay(mockHandler); - FutureCallback callback = new FutureCallback(); + FutureCallback callback = new FutureCallback<>(); multiplexer.handleRequest(request, requestContext, callback); diff --git a/restli-server/src/test/java/com/linkedin/restli/server/resources/TestInjectResourceFactory.java b/restli-server/src/test/java/com/linkedin/restli/server/resources/TestInjectResourceFactory.java index e7a4b1cf91..a91f1541c4 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/resources/TestInjectResourceFactory.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/resources/TestInjectResourceFactory.java @@ -59,7 +59,7 @@ public void testHappyPath() EasyMock.expect(ctx.getBean(EasyMock.eq("dep1"))).andReturn(new SomeDependency1()).anyTimes(); EasyMock.expect(ctx.getBean(EasyMock.eq("dep3"))).andReturn(new SomeDependency1()).anyTimes(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("someBeanName", new SomeDependency2()); EasyMock.expect(ctx.getBeansOfType(EasyMock.eq(SomeDependency2.class))) @@ -119,13 +119,13 @@ public void testAmbiguousBeanResolution() throws Exception BeanProvider ctx = EasyMock.createMock(BeanProvider.class); EasyMock.expect(ctx.getBean(EasyMock.eq("dep1"))).andReturn(new SomeDependency1()).anyTimes(); - Map map2 = new HashMap(); + Map map2 = new HashMap<>(); map2.put("someBeanName", new SomeDependency2()); EasyMock.expect(ctx.getBeansOfType(EasyMock.eq(SomeDependency2.class))) .andReturn(map2).anyTimes(); - Map map1 = new HashMap(); + Map map1 = new HashMap<>(); map1.put("someDep1", new SomeDependency1()); map1.put("anotherDep1", new SomeDependency1()); EasyMock.expect(ctx.getBeansOfType(EasyMock.eq(SomeDependency1.class))) @@ -162,7 +162,7 @@ public void testMissingNamedDependency() EasyMock.expect(ctx.getBean(EasyMock.eq("dep1"))).andReturn(null).anyTimes(); EasyMock.expect(ctx.getBean(EasyMock.eq("dep3"))).andReturn(new SomeDependency1()).anyTimes(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("someBeanName", new SomeDependency2()); EasyMock.expect(ctx.getBeansOfType(EasyMock.eq(SomeDependency2.class))) @@ -198,7 +198,7 @@ public void testInjectConstructorArgs() EasyMock.expect(ctx.getBean(EasyMock.eq("dep1"))).andReturn(new SomeDependency1()).anyTimes(); EasyMock.expect(ctx.getBean(EasyMock.eq("dep3"))).andReturn(new SomeDependency1()).anyTimes(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("someBeanName", new SomeDependency2()); EasyMock.expect(ctx.getBeansOfType(EasyMock.eq(SomeDependency2.class))) diff --git a/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockResourceFactory.java b/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockResourceFactory.java index 976d0b239a..28b683e913 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockResourceFactory.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockResourceFactory.java @@ -30,7 +30,7 @@ public class EasyMockResourceFactory implements ResourceFactory { private final Map, Object> _mockMap = - new HashMap, Object>(); + new HashMap<>(); /** * @see com.linkedin.restli.server.resources.ResourceFactory#setRootResources(java.util.Map) diff --git a/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockUtils.java b/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockUtils.java index 4882f5fc1e..a792c59da2 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockUtils.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/test/EasyMockUtils.java @@ -36,7 +36,7 @@ public class EasyMockUtils /** * Static collection of custom "eq" methods, which are required when using custom * argument matchers in {@link EasyMock#expect(Object)} calls. - * + * * @author dellamag * @see IArgumentMatcher */ @@ -214,7 +214,7 @@ public boolean matches(Object obj) */ public static CollectionArgumentMatcher createSizeMatcher(Collection expected) { - return new CollectionArgumentMatcher(expected, Functions.identity(), MatchType.size); + return new CollectionArgumentMatcher<>(expected, Functions.identity(), MatchType.size); } /** @@ -222,7 +222,7 @@ public static CollectionArgumentMatcher createSizeMatcher(Collection CollectionArgumentMatcher createUnorderedExactMatcher(Collection expected) { - return new CollectionArgumentMatcher(expected, Functions.identity(), MatchType.unordered); + return new CollectionArgumentMatcher<>(expected, Functions.identity(), MatchType.unordered); } /** @@ -230,7 +230,7 @@ public static CollectionArgumentMatcher createUnorderedExactMatcher(Co */ public static CollectionArgumentMatcher createOrderedExactMatcher(Collection expected) { - return new CollectionArgumentMatcher(expected, Functions.identity(), MatchType.ordered); + return new CollectionArgumentMatcher<>(expected, Functions.identity(), MatchType.ordered); } } } diff --git a/restli-server/src/test/java/com/linkedin/restli/server/test/RestLiTestHelper.java b/restli-server/src/test/java/com/linkedin/restli/server/test/RestLiTestHelper.java index 7d64776f1e..642e1155a2 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/test/RestLiTestHelper.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/test/RestLiTestHelper.java @@ -38,7 +38,7 @@ public static M buildResourceModel(Class rootResour public static Map buildResourceModels(Class... resourceClasses) { - Set> classes = new HashSet>(Arrays.asList(resourceClasses)); + Set> classes = new HashSet<>(Arrays.asList(resourceClasses)); return RestLiApiBuilder.buildResourceModels(classes); } diff --git a/restli-server/src/test/java/com/linkedin/restli/server/test/TestResourceContext.java b/restli-server/src/test/java/com/linkedin/restli/server/test/TestResourceContext.java index 33f11df395..2be4192600 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/test/TestResourceContext.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/test/TestResourceContext.java @@ -74,7 +74,7 @@ public Object[][] projectionMask() public void testResourceContextGetProjectionMask(ProtocolVersion version, String stringUri) throws Exception { URI uri = URI.create(stringUri); - Map headers = new HashMap(1); + Map headers = new HashMap<>(1); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString()); ResourceContext context = new ResourceContextImpl(new PathKeysImpl(), @@ -120,7 +120,7 @@ public Object[][] queryParamsProjectionMaskWithSyntax() public void testResourceContextWithQueryParamsGetProjectionMaskWithMaskSyntax(ProtocolVersion version, String stringUri) throws Exception { URI uri = URI.create(stringUri); - Map headers = new HashMap(1); + Map headers = new HashMap<>(1); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString()); ResourceContext context = new ResourceContextImpl(new PathKeysImpl(), @@ -174,7 +174,7 @@ public Object[][] projectionMaskWithSyntax() public void testResourceContextGetProjectionMaskWithSyntax(ProtocolVersion version, String stringUri) throws Exception { URI uri = URI.create(stringUri); - Map headers = new HashMap(1); + Map headers = new HashMap<>(1); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString()); ResourceContext context = new ResourceContextImpl(new PathKeysImpl(), @@ -251,7 +251,7 @@ public Object[][] uriDecoding() public void testResourceContextURIDecoding(ProtocolVersion version, String stringUri) throws Exception { URI uri = URI.create(stringUri); - Map headers = new HashMap(1); + Map headers = new HashMap<>(1); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString()); ServerResourceContext context = new ResourceContextImpl(new PathKeysImpl(), @@ -347,15 +347,15 @@ public static class MockRequest implements RestRequest public MockRequest(URI uri) { _uri = uri; - _headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); - _cookies = new ArrayList(); + _headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + _cookies = new ArrayList<>(); } public MockRequest(URI uri, Map headers) { _uri = uri; _headers = headers; - _cookies = new ArrayList(); + _cookies = new ArrayList<>(); } @Override @@ -406,4 +406,4 @@ public URI getURI() return _uri; } } -} \ No newline at end of file +} diff --git a/restli-server/src/test/java/com/linkedin/restli/server/test/TestRestLiMethodInvocation.java b/restli-server/src/test/java/com/linkedin/restli/server/test/TestRestLiMethodInvocation.java index 1664985c5b..79acd75821 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/test/TestRestLiMethodInvocation.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/test/TestRestLiMethodInvocation.java @@ -627,7 +627,7 @@ public Object answer() throws Throwable { methodDescriptor = followsAssociationResourceModel.findMethod(ResourceMethod.BATCH_GET); followsResource = getMockResource(AsyncFollowsAssociativeResource.class); - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); CompoundKey key1 = new CompoundKey(); key1.append("followeeID", 1L); key1.append("followerID", 1L); @@ -1567,7 +1567,7 @@ public void testPromiseBatchGet() throws Exception methodDescriptor = followsAssociationResourceModel.findMethod(ResourceMethod.BATCH_GET); followsResource = getMockResource(PromiseFollowsAssociativeResource.class); - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); CompoundKey key1 = new CompoundKey(); key1.append("followeeID", 1L); key1.append("followerID", 1L); @@ -2182,7 +2182,7 @@ public void testAltKeyGet() throws Exception ResourceMethodDescriptor batchGetMethodDescriptor = statusResourceModel.findMethod(ResourceMethod.BATCH_GET); statusResource = getMockResource(StatusCollectionResource.class); - Set batchKeys = new HashSet(3); + Set batchKeys = new HashSet<>(3); batchKeys.add(1L); batchKeys.add(2L); batchKeys.add(3L); @@ -2409,7 +2409,7 @@ public void testBatchGet() throws Exception methodDescriptor = followsAssociationResourceModel.findMethod(ResourceMethod.BATCH_GET); followsResource = getMockResource(FollowsAssociativeResource.class); - Set expectedKeys = new HashSet(); + Set expectedKeys = new HashSet<>(); CompoundKey key1 = new CompoundKey(); key1.append("followeeID", 1L); key1.append("followerID", 1L); @@ -3228,14 +3228,14 @@ public void testActionParameterTypeCoercion() throws Exception @Test public void testHeuristicKeySyntaxDetection() throws PathSegment.PathSegmentSyntaxException { - Set keys = new HashSet(2); + Set keys = new HashSet<>(2); keys.add(new Key("foo", Integer.class)); keys.add(new Key("bar", String.class)); // heuristic key syntax detection only occurs in Protocol Version 1.0.0 ProtocolVersion v1 = AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(); - Set expectedKeys = new HashSet(Arrays.asList("foo", "bar")); + Set expectedKeys = new HashSet<>(Arrays.asList("foo", "bar")); Assert.assertEquals(expectedKeys, ArgumentUtils.parseCompoundKey("foo:42;bar:abcd", keys, v1).getPartKeys()); Assert.assertEquals(expectedKeys, ArgumentUtils.parseCompoundKey("foo:42;bar:abcd=1&efg=2", keys, v1).getPartKeys()); Assert.assertEquals(expectedKeys, ArgumentUtils.parseCompoundKey("foo=42&bar=abcd", keys, v1).getPartKeys()); @@ -3258,7 +3258,7 @@ public Object[][] dataMapToCompoundKey() dataMap1.put("foo", "1"); dataMap1.put("bar", "hello"); - Set keys1 = new HashSet(2); + Set keys1 = new HashSet<>(2); keys1.add(new Key("foo", Integer.class)); keys1.add(new Key("bar", String.class)); @@ -3270,7 +3270,7 @@ public Object[][] dataMapToCompoundKey() dataMap2.put("a", "6"); dataMap2.put("b", "3.14"); - Set keys2 = new HashSet(2); + Set keys2 = new HashSet<>(2); keys2.add(new Key("a", Long.class)); keys2.add(new Key("b", Double.class)); @@ -5106,7 +5106,7 @@ private MutablePathKeys buildPathKeys(Object... pathKeyValues) throws RestLiSynt public MutablePathKeys buildBatchPathKeys(Object... batchKeys) throws RestLiSyntaxException { MutablePathKeys result = new PathKeysImpl(); - Set keys = new HashSet(); + Set keys = new HashSet<>(); for (Object batchKey : batchKeys) { diff --git a/restli-server/src/test/java/com/linkedin/restli/server/twitter/ExceptionsResource.java b/restli-server/src/test/java/com/linkedin/restli/server/twitter/ExceptionsResource.java index 42c6a41149..7b51c7aa68 100644 --- a/restli-server/src/test/java/com/linkedin/restli/server/twitter/ExceptionsResource.java +++ b/restli-server/src/test/java/com/linkedin/restli/server/twitter/ExceptionsResource.java @@ -37,12 +37,12 @@ public class ExceptionsResource extends CollectionResourceTemplate @RestMethod.Get public GetResult getWithResult(Long key) { - return new GetResult(new Status(), HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new GetResult<>(new Status(), HttpStatus.S_500_INTERNAL_SERVER_ERROR); } @Action(name = "exception") public ActionResult actionWithResult() { - return new ActionResult(100, HttpStatus.S_500_INTERNAL_SERVER_ERROR); + return new ActionResult<>(100, HttpStatus.S_500_INTERNAL_SERVER_ERROR); } } diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/JavaRequestBuilderGenerator.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/JavaRequestBuilderGenerator.java index 7eef07c267..d8166d2067 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/JavaRequestBuilderGenerator.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/JavaRequestBuilderGenerator.java @@ -153,11 +153,11 @@ public class JavaRequestBuilderGenerator extends JavaCodeGeneratorBase private static final Map METHOD_BUILDER_SUFFIX; static { - ROOT_BUILDERS_SUFFIX = new HashMap(); + ROOT_BUILDERS_SUFFIX = new HashMap<>(); ROOT_BUILDERS_SUFFIX.put(RestliVersion.RESTLI_1_0_0, "Builders"); ROOT_BUILDERS_SUFFIX.put(RestliVersion.RESTLI_2_0_0, "RequestBuilders"); - METHOD_BUILDER_SUFFIX = new HashMap(); + METHOD_BUILDER_SUFFIX = new HashMap<>(); METHOD_BUILDER_SUFFIX.put(RestliVersion.RESTLI_1_0_0, "Builder"); METHOD_BUILDER_SUFFIX.put(RestliVersion.RESTLI_2_0_0, "RequestBuilder"); } @@ -181,7 +181,7 @@ public class JavaRequestBuilderGenerator extends JavaCodeGeneratorBase private final JClass _resourceMethodClass = getCodeModel().ref(ResourceMethod.class); private final JClass _classClass = getCodeModel().ref(Class.class); private final JClass _objectClass = getCodeModel().ref(Object.class); - private final HashSet _generatedArrayClasses = new HashSet(); + private final HashSet _generatedArrayClasses = new HashSet<>(); private final DataSchemaResolver _schemaResolver; private final TemplateSpecGenerator _specGenerator; private final JavaDataTemplateGenerator _javaDataTemplateGenerator; @@ -288,7 +288,7 @@ private static List fixOldStylePathKeys(List pathKeys, String re if (resourcePath.contains("=")) { // this is an old-style IDL. - final List newPathKeys = new ArrayList(pathKeys.size()); + final List newPathKeys = new ArrayList<>(pathKeys.size()); final Map assocToPathKeys = reverseMap(pathToAssocKeys); final Set prevRealPathKeys = new TreeSet<>(); for (String currKey : pathKeys) @@ -318,7 +318,7 @@ private static List fixOldStylePathKeys(List pathKeys, String re private static Map reverseMap(Map> toReverse) { - final Map reversed = new HashMap(); + final Map reversed = new HashMap<>(); for (Map.Entry> entry : toReverse.entrySet()) { for (String element : entry.getValue()) @@ -711,7 +711,7 @@ else if (resource.getAssociation() != null) final String keyName = getAssociationKey(resource, association); pathKeyTypes.put(keyName, keyClass); - final List assocKeys = new ArrayList(4); + final List assocKeys = new ArrayList<>(4); for (Map.Entry entry : assocKeyTypeInfos.entrySet()) { assocKeys.add(entry.getKey()); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RequestBuilderSpecGenerator.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RequestBuilderSpecGenerator.java index 15b6a0a920..41d5856e75 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RequestBuilderSpecGenerator.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RequestBuilderSpecGenerator.java @@ -93,7 +93,7 @@ public class RequestBuilderSpecGenerator private final String _customMethodBuilderSuffix; // use LinkedHashSet to keep insertion order to avoid randomness in generated code in giant root builder case. - protected final Set _builderSpecs = new LinkedHashSet(); + protected final Set _builderSpecs = new LinkedHashSet<>(); private final DataSchemaResolver _schemaResolver; private final TemplateSpecGenerator _templateSpecGenerator; @@ -105,11 +105,11 @@ public class RequestBuilderSpecGenerator static { - ROOT_BUILDERS_SUFFIX = new HashMap(); + ROOT_BUILDERS_SUFFIX = new HashMap<>(); ROOT_BUILDERS_SUFFIX.put(RestliVersion.RESTLI_1_0_0, "Builders"); ROOT_BUILDERS_SUFFIX.put(RestliVersion.RESTLI_2_0_0, "RequestBuilders"); - METHOD_BUILDER_SUFFIX = new HashMap(); + METHOD_BUILDER_SUFFIX = new HashMap<>(); METHOD_BUILDER_SUFFIX.put(RestliVersion.RESTLI_1_0_0, "Builder"); METHOD_BUILDER_SUFFIX.put(RestliVersion.RESTLI_2_0_0, "RequestBuilder"); } @@ -170,7 +170,7 @@ public void generate(ResourceSchema resource, File sourceFile) try { _currentSchemaLocation = new FileDataSchemaLocation(sourceFile); - generateRootRequestBuilder(null, resource, sourceFile.getAbsolutePath(), new HashMap()); + generateRootRequestBuilder(null, resource, sourceFile.getAbsolutePath(), new HashMap<>()); } catch (IOException e) { @@ -281,11 +281,11 @@ else if (resource.getActionsSet() != null) } } - List restMethodSpecs = new ArrayList(); - List finderSpecs = new ArrayList(); - List resourceActionSpecs = new ArrayList(); - List entityActionSpecs = new ArrayList(); - List subresourceSpecs = new ArrayList(); + List restMethodSpecs = new ArrayList<>(); + List finderSpecs = new ArrayList<>(); + List resourceActionSpecs = new ArrayList<>(); + List entityActionSpecs = new ArrayList<>(); + List subresourceSpecs = new ArrayList<>(); String schemaClass = resource.getSchema(); if (restMethods != null) @@ -351,9 +351,9 @@ private static List fixOldStylePathKeys(List pathKeys, if (resourcePath.contains("=")) { // this is an old-style IDL. - List newPathKeys = new ArrayList(pathKeys.size()); + List newPathKeys = new ArrayList<>(pathKeys.size()); Map assocToPathKeys = reverseMap(pathToAssocKeys); - Set prevRealPathKeys = new HashSet(); + Set prevRealPathKeys = new HashSet<>(); for (String currKey : pathKeys) { if (assocToPathKeys.containsKey(currKey)) @@ -381,7 +381,7 @@ private static List fixOldStylePathKeys(List pathKeys, private static Map reverseMap(Map> toReverse) { - Map reversed = new HashMap(); + Map reversed = new HashMap<>(); for (Map.Entry> entry : toReverse.entrySet()) { for (String element : entry.getValue()) @@ -406,7 +406,7 @@ private static void validateResourceMethod(ResourceSchema resourceSchema, static List getPathKeys(String basePath) { UriTemplate template = new UriTemplate(basePath); - return fixOldStylePathKeys(template.getTemplateVariables(), basePath, new HashMap>()); + return fixOldStylePathKeys(template.getTemplateVariables(), basePath, new HashMap<>()); } private List generateSubResources(String sourceFile, @@ -415,7 +415,7 @@ private List generateSubResources(String sourceFile, Map pathKeyTypes) throws IOException { - List subSpecList = new ArrayList(); + List subSpecList = new ArrayList<>(); if (subresources != null) { for (ResourceSchema resource : subresources) @@ -438,7 +438,7 @@ private List generateFinders(RootBuilderSpec rootBuilderS List pathKeys, Map pathKeyTypes) { - List finderSpecList = new ArrayList(); + List finderSpecList = new ArrayList<>(); if (finderSchemas != null) { String baseBuilderClass = getBuilderBase(ResourceMethod.FINDER); @@ -547,7 +547,7 @@ private List generateActions(RootBuilderSpec rootBuilderS List pathKeys, Map pathKeyTypes) { - List actionSpecList = new ArrayList(); + List actionSpecList = new ArrayList<>(); if (actions != null) { for (ActionSchema action : actions) @@ -598,7 +598,7 @@ private List generateBasicMethods(RootBuilderSpec rootBui List pathKeys, Map pathKeyTypes) { - final Map schemaMap = new HashMap(); + final Map schemaMap = new HashMap<>(); if (restMethods != null) { for (RestMethodSchema restMethod : restMethods) @@ -607,7 +607,7 @@ private List generateBasicMethods(RootBuilderSpec rootBui } } - List methodSpecList = new ArrayList(); + List methodSpecList = new ArrayList<>(); for (Map.Entry entry : _builderBaseMap.entrySet()) { ResourceMethod method = entry.getKey(); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RestSpecParser.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RestSpecParser.java index 80d63b32f6..ed87de5d3a 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RestSpecParser.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/RestSpecParser.java @@ -74,7 +74,7 @@ public ParseResult parseSources(String[] sourcePaths) try { final ResourceSchema resource = _codec.readResourceSchema(new FileInputStream(sourceFile)); - result._schemaAndFiles.add(new CodeUtil.Pair(resource, sourceFile)); + result._schemaAndFiles.add(new CodeUtil.Pair<>(resource, sourceFile)); result._sourceFiles.add(sourceFile); } catch (IOException e) @@ -91,8 +91,8 @@ public ParseResult parseSources(String[] sourcePaths) public static class ParseResult { // use collections to maintain order - private final Collection> _schemaAndFiles = new ArrayList>(); - private final Collection _sourceFiles = new ArrayList(); + private final Collection> _schemaAndFiles = new ArrayList<>(); + private final Collection _sourceFiles = new ArrayList<>(); private final StringBuilder _message = new StringBuilder(); /** diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionBuilderSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionBuilderSpec.java index d888977604..395544433d 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionBuilderSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionBuilderSpec.java @@ -33,7 +33,7 @@ public class ActionBuilderSpec extends RequestBuilderSpec { private String _actionName; - private List _actionParamMethods = new ArrayList(); + private List _actionParamMethods = new ArrayList<>(); public ActionBuilderSpec(String actionName) { diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionSetRootBuilderSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionSetRootBuilderSpec.java index 4336754cc7..02456ede9e 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionSetRootBuilderSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/ActionSetRootBuilderSpec.java @@ -56,7 +56,7 @@ public void setResourceActions(List resourceActions) @Override public List getMethods() { - List methods = new ArrayList(); + List methods = new ArrayList<>(); if (_resourceActions != null) { methods.addAll(_resourceActions); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/CollectionRootBuilderSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/CollectionRootBuilderSpec.java index 48ca10bf33..4415eb1d24 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/CollectionRootBuilderSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/CollectionRootBuilderSpec.java @@ -100,7 +100,7 @@ public void setSubresources(List subresources) @Override public List getMethods() { - List methods = new ArrayList(); + List methods = new ArrayList<>(); if (_restMethods != null) { methods.addAll(_restMethods); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/RequestBuilderSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/RequestBuilderSpec.java index 363a660d03..34cdb21ff4 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/RequestBuilderSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/RequestBuilderSpec.java @@ -39,8 +39,8 @@ public abstract class RequestBuilderSpec extends BuilderSpec private Map _keyPathTypes; private ClassTemplateSpec _keyClass; private ClassTemplateSpec _valueClass; - private List _pathKeyMethods = new ArrayList(); - private List _queryParamMethods = new ArrayList(); + private List _pathKeyMethods = new ArrayList<>(); + private List _queryParamMethods = new ArrayList<>(); private DataMap _annotations; public RequestBuilderSpec() diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/SimpleRootBuilderSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/SimpleRootBuilderSpec.java index 7d47360cf3..07eb1f732e 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/SimpleRootBuilderSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/builderspec/SimpleRootBuilderSpec.java @@ -78,7 +78,7 @@ public void setSubresources(List subresources) @Override public List getMethods() { - List methods = new ArrayList(); + List methods = new ArrayList<>(); if (_restMethods != null) { methods.addAll(_restMethods); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/fluentspec/SpecUtils.java b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/fluentspec/SpecUtils.java index f50968d967..1edcde63b1 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/fluentspec/SpecUtils.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/clientgen/fluentspec/SpecUtils.java @@ -37,14 +37,14 @@ */ public class SpecUtils { static final String JAVA_LANG_PREFIX = "java.lang"; - static final Set PRIMITIVE_CLASS_NAMES = new HashSet(Arrays.asList( + static final Set PRIMITIVE_CLASS_NAMES = new HashSet<>(Arrays.asList( Integer.class.getSimpleName(), Double.class.getSimpleName(), Boolean.class.getSimpleName(), String.class.getSimpleName(), Long.class.getSimpleName(), Float.class.getSimpleName() - )); + )); private SpecUtils() { diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/CompatibilityInfoMap.java b/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/CompatibilityInfoMap.java index 87e981e665..90faf83596 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/CompatibilityInfoMap.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/CompatibilityInfoMap.java @@ -35,20 +35,20 @@ public class CompatibilityInfoMap { - private Map> _restSpecMap = new HashMap>(); - private Map> _modelMap = new HashMap>(); + private Map> _restSpecMap = new HashMap<>(); + private Map> _modelMap = new HashMap<>(); private Map> _annotationMap = new HashMap<>(); public CompatibilityInfoMap() { - _restSpecMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList()); - _restSpecMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList()); + _restSpecMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList<>()); + _restSpecMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList<>()); - _modelMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList()); - _modelMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList()); + _modelMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList<>()); + _modelMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList<>()); - _annotationMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList()); - _annotationMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList()); + _annotationMap.put(CompatibilityInfo.Level.INCOMPATIBLE, new ArrayList<>()); + _annotationMap.put(CompatibilityInfo.Level.COMPATIBLE, new ArrayList<>()); } public void addRestSpecInfo(CompatibilityInfo.Type infoType, Stack path, @@ -276,7 +276,7 @@ public Collection getModelCompatibles() public Collection get(CompatibilityInfo.Level level) { - Collection infos = new ArrayList(getRestSpecInfo(level)); + Collection infos = new ArrayList<>(getRestSpecInfo(level)); infos.addAll(getModelInfo(level)); return infos; } diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/ResourceCompatibilityChecker.java b/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/ResourceCompatibilityChecker.java index aa40c731c8..6bbe4bf9ab 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/ResourceCompatibilityChecker.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/compatibility/ResourceCompatibilityChecker.java @@ -291,7 +291,7 @@ private boolean checkArrayContainment(RecordDataSchema.Field field, { if (container.size() > containee.size()) { - final Set diff = new HashSet(container); + final Set diff = new HashSet<>(container); diff.removeAll(containee); _infoMap.addRestSpecInfo(field.getName(), CompatibilityInfo.Type.SUPERSET, _infoPath, diff); } @@ -574,7 +574,7 @@ boolean checkComplexArrayField(RecordDataSchema.Field field, private > boolean checkComplexArrayField(RecordDataSchema.Field field, String keyName, T prevArray, T currArray) { - return checkComplexArrayField(field, keyName, prevArray, currArray, new HashMap(), true); + return checkComplexArrayField(field, keyName, prevArray, currArray, new HashMap<>(), true); } /** @@ -583,7 +583,7 @@ boolean checkComplexArrayField(RecordDataSchema.Field field, String keyName, T p private > boolean checkEqualComplexArrayField(RecordDataSchema.Field field, String keyName, T prevArray, T currArray) { - final HashMap currRemainder = new HashMap(); + final HashMap currRemainder = new HashMap<>(); // if prev has more than curr, array missing element // this should catch it @@ -608,7 +608,7 @@ boolean checkEqualComplexArrayField(RecordDataSchema.Field field, String keyName */ private boolean checkParameterArrayField(RecordDataSchema.Field field, ParameterSchemaArray prevArray, ParameterSchemaArray currArray) { - final HashMap currRemainder = new HashMap(); + final HashMap currRemainder = new HashMap<>(); if (!checkComplexArrayField(field, "name", prevArray, currArray, currRemainder, false)) { @@ -1029,12 +1029,12 @@ private void checkRestLiDataAnnotations(RecordDataSchema.Field field, CustomAnno for (Class annotationClass : new Class[]{ReadOnly.class, CreateOnly.class}) { String annotationName = annotationClass.getAnnotation(RestSpecAnnotation.class).name(); - Set prevPaths = new HashSet(); + Set prevPaths = new HashSet<>(); if (prevMap != null && prevMap.containsKey(annotationName)) prevPaths.addAll((DataList) prevMap.get(annotationName).data().get("value")); - Set currPaths = new HashSet(); + Set currPaths = new HashSet<>(); if (currMap != null && currMap.containsKey(annotationName)) currPaths.addAll((DataList) currMap.get(annotationName).data().get("value")); // Adding an annotation is only valid if the field was newly added to the schema. - Set addedPaths = new HashSet(currPaths); + Set addedPaths = new HashSet<>(currPaths); addedPaths.removeAll(prevPaths); for (Object path : addedPaths) { @@ -1050,7 +1050,7 @@ private void checkRestLiDataAnnotations(RecordDataSchema.Field field, CustomAnno // level incompatibilities are checked. Hence the reason that restSpecInfo is populated. Therefore we will // treat restSpec incompatibility in isolation from model incompatibility in order to provide fine grained // compatibility results. - Set removedPaths = new HashSet(prevPaths); + Set removedPaths = new HashSet<>(prevPaths); removedPaths.removeAll(currPaths); for (Object path : removedPaths) { @@ -1076,7 +1076,7 @@ private void checkRestLiDataAnnotations(RecordDataSchema.Field field, CustomAnno private void checkAnnotationsMap(RecordDataSchema.Field field, CustomAnnotationContentSchemaMap prevMap, CustomAnnotationContentSchemaMap currMap) { - Set allKeys = new HashSet(); + Set allKeys = new HashSet<>(); if (prevMap != null) allKeys.addAll(prevMap.keySet()); if (currMap != null) allKeys.addAll(currMap.keySet()); for(String key : allKeys) diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/data/PredicateExpressionParser.java b/restli-tools/src/main/java/com/linkedin/restli/tools/data/PredicateExpressionParser.java index 7b20a35fe0..6def979aad 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/data/PredicateExpressionParser.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/data/PredicateExpressionParser.java @@ -50,8 +50,8 @@ public class PredicateExpressionParser public static Predicate parse(String expression) { - final Stack predicateStack = new Stack(); - final Stack operatorStack = new Stack(); + final Stack predicateStack = new Stack<>(); + final Stack operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(trimmedExpression, OPERATORS, true); @@ -168,7 +168,7 @@ private static void evaluate(Stack predicateStack, Stack o private static Predicate evaluateMultiaryOperator(Stack predicateStack, Stack operatorStack, char operator) { - final Deque predicateOperands = new ArrayDeque(); + final Deque predicateOperands = new ArrayDeque<>(); predicateOperands.addFirst(predicateStack.pop()); predicateOperands.addFirst(predicateStack.pop()); @@ -190,7 +190,7 @@ private static Predicate evaluateMultiaryOperator(Stack predicateStac } private static final String OPERATORS = "()!&|"; - private static final Map OPERATOR_PRECEDENCE = new HashMap(); + private static final Map OPERATOR_PRECEDENCE = new HashMap<>(); static { OPERATOR_PRECEDENCE.put('(', 0); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/idlcheck/RestLiResourceModelCompatibilityChecker.java b/restli-tools/src/main/java/com/linkedin/restli/tools/idlcheck/RestLiResourceModelCompatibilityChecker.java index e916279eaa..f5f07b2e7a 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/idlcheck/RestLiResourceModelCompatibilityChecker.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/idlcheck/RestLiResourceModelCompatibilityChecker.java @@ -166,7 +166,7 @@ public boolean check(String prevRestspecPath, String currRestspecPath, Compatibi _prevRestspecPath = prevRestspecPath; _currRestspecPath = currRestspecPath; - Stack path = new Stack(); + Stack path = new Stack<>(); path.push(""); ResourceSchema prevRec = null; diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/DocletDocsProvider.java b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/DocletDocsProvider.java index 0c713ba2a4..f0cd6ecc41 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/DocletDocsProvider.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/DocletDocsProvider.java @@ -93,10 +93,10 @@ public void registerSourceFiles(Collection sourceFileNames) final PrintWriter sysoutWriter = new PrintWriter(System.out, true); final PrintWriter nullWriter = new PrintWriter(new NullWriter()); - final List javadocArgs = new ArrayList(Arrays.asList("-classpath", - flatClasspath, - "-sourcepath", - StringUtils.join(_sourcePaths, ":"))); + final List javadocArgs = new ArrayList<>(Arrays.asList("-classpath", + flatClasspath, + "-sourcepath", + StringUtils.join(_sourcePaths, ":"))); if (_resourcePackages != null) { javadocArgs.add("-subpackages"); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/MultiLanguageDocsProvider.java b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/MultiLanguageDocsProvider.java index 26aae8b930..664a77249d 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/MultiLanguageDocsProvider.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/MultiLanguageDocsProvider.java @@ -41,7 +41,7 @@ public class MultiLanguageDocsProvider implements DocsProvider public static List loadExternalProviders(List docsProviders) { - List providers = new ArrayList(); + List providers = new ArrayList<>(); for(Object provider : docsProviders) { log.info("Executing "+ provider.getClass().getSimpleName() + " tool..."); @@ -92,7 +92,7 @@ public void registerSourceFiles(Collection filenames) private static Collection filterForFileExtensions(Collection filenames, Collection extensions) { - List filenamesMatchingExtension = new ArrayList(); + List filenamesMatchingExtension = new ArrayList<>(); for(String extension : extensions) // usually just one { @@ -113,7 +113,7 @@ private static Collection filterForFileExtensions(Collection fil @Override public Set supportedFileExtensions() { - Set supportedFileExtensions = new HashSet(); + Set supportedFileExtensions = new HashSet<>(); for(DocsProvider provider : _languageSpecificProviders) { supportedFileExtensions.addAll(provider.supportedFileExtensions()); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiDoclet.java b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiDoclet.java index 5a2f5c8f79..025765a017 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiDoclet.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiDoclet.java @@ -160,15 +160,15 @@ public void setMethodDoc(MethodIdentity methodId, MethodDoc methodDoc) _methodIdToMethodDoc.put(methodId, methodDoc); } - private final Map _classNameToClassDoc = new HashMap(); - private final Map _methodIdToMethodDoc = new HashMap(); + private final Map _classNameToClassDoc = new HashMap<>(); + private final Map _methodIdToMethodDoc = new HashMap<>(); } private static class MethodIdentity { public static MethodIdentity create(Method method) { - final List parameterTypeNames = new ArrayList(); + final List parameterTypeNames = new ArrayList<>(); // type parameters are not included in identity because of differences between reflection and Doclet: // e.g. for Collection: @@ -184,7 +184,7 @@ public static MethodIdentity create(Method method) public static MethodIdentity create(MethodDoc method) { - final List parameterTypeNames = new ArrayList(); + final List parameterTypeNames = new ArrayList<>(); for (Parameter param: method.parameters()) { Type type = param.type(); diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiResourceModelExporter.java b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiResourceModelExporter.java index e117b51634..5c28fece20 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiResourceModelExporter.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/idlgen/RestLiResourceModelExporter.java @@ -138,7 +138,7 @@ public GeneratorResult export(String apiName, config.addResourcePackageNames(resourcePackages); } - final Map classFileNames = new HashMap(); + final Map classFileNames = new HashMap<>(); for (String path : sourcePaths) { classFileNames.putAll(FileClassNameScanner.scan(path)); @@ -151,7 +151,7 @@ public GeneratorResult export(String apiName, { config.addResourceClassNames(resourceClasses); - sourceFileNames = new ArrayList(resourceClasses.length); + sourceFileNames = new ArrayList<>(resourceClasses.length); for (String resourceClass : resourceClasses) { final String resourceFileName = classFileNames.get(resourceClass); @@ -261,7 +261,7 @@ private GeneratorResult generateIDLFiles(String apiName, final ResourceModelEncoder encoder = new ResourceModelEncoder(docsProvider); - final List rootResourceNodes = new ArrayList(); + final List rootResourceNodes = new ArrayList<>(); for (Entry entry: rootResourceMap.entrySet()) { final ResourceSchema rootResourceNode = encoder.buildResourceSchema(entry.getValue()); @@ -291,8 +291,8 @@ private GeneratorResult generateIDLFiles(String apiName, class Result implements GeneratorResult { - private List targetFiles = new ArrayList(); - private List modifiedFiles = new ArrayList(); + private List targetFiles = new ArrayList<>(); + private List modifiedFiles = new ArrayList<>(); public void addTargetFile(File file) { diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/AbstractSnapshot.java b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/AbstractSnapshot.java index ab3745e881..310f93b080 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/AbstractSnapshot.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/AbstractSnapshot.java @@ -30,7 +30,7 @@ public abstract class AbstractSnapshot protected Map parseModels(DataList models) throws IOException { - final Map parsedModels = new HashMap(); + final Map parsedModels = new HashMap<>(); for (Object modelObj : models) { diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestLiSnapshotCompatibilityChecker.java b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestLiSnapshotCompatibilityChecker.java index c728d2296a..c1d727e58b 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestLiSnapshotCompatibilityChecker.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestLiSnapshotCompatibilityChecker.java @@ -186,7 +186,7 @@ private CompatibilityInfoMap checkCompatibility(String prevRestModelPath, String return infoMap; } - final Stack path = new Stack(); + final Stack path = new Stack<>(); path.push(""); FileInputStream prevSnapshotFile = null; diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestSpec.java b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestSpec.java index 753c6c8d18..769ee2b7ba 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestSpec.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/check/RestSpec.java @@ -17,7 +17,7 @@ public class RestSpec extends AbstractSnapshot public RestSpec(InputStream inputStream) throws IOException { DataMap data = _dataCodec.readMap(inputStream); - _models = new HashMap(); + _models = new HashMap<>(); _resourceSchema = parseSchema(data); } } diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/RestLiSnapshotExporter.java b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/RestLiSnapshotExporter.java index 9e9c2e146a..ab23b25144 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/RestLiSnapshotExporter.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/RestLiSnapshotExporter.java @@ -88,7 +88,7 @@ public GeneratorResult export(String apiName, config.addResourcePackageNames(resourcePackages); } - final Map classFileNames = new HashMap(); + final Map classFileNames = new HashMap<>(); for (String path : sourcePaths) { classFileNames.putAll(FileClassNameScanner.scan(path)); @@ -101,7 +101,7 @@ public GeneratorResult export(String apiName, { config.addResourceClassNames(resourceClasses); - sourceFileNames = new ArrayList(resourceClasses.length); + sourceFileNames = new ArrayList<>(resourceClasses.length); for (String resourceClass : resourceClasses) { final String resourceFileName = classFileNames.get(resourceClass); @@ -181,7 +181,7 @@ private GeneratorResult generateSnapshotFiles(String apiName, final ResourceModelEncoder encoder = new ResourceModelEncoder(docsProvider); - final List rootResourceNodes = new ArrayList(); + final List rootResourceNodes = new ArrayList<>(); for (Map.Entry entry: rootResourceMap.entrySet()) { final ResourceSchema rootResourceNode = encoder.buildResourceSchema(entry.getValue()); @@ -221,8 +221,8 @@ private File writeSnapshotFile(File outdirFile, private static class SnapshotResult implements GeneratorResult { - private List targetFiles = new ArrayList(); - private List modifiedFiles = new ArrayList(); + private List targetFiles = new ArrayList<>(); + private List modifiedFiles = new ArrayList<>(); public void addTargetFile(File file) { diff --git a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/SnapshotGenerator.java b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/SnapshotGenerator.java index 768982dc36..3252c33af1 100644 --- a/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/SnapshotGenerator.java +++ b/restli-tools/src/main/java/com/linkedin/restli/tools/snapshot/gen/SnapshotGenerator.java @@ -77,8 +77,8 @@ public SnapshotGenerator(ResourceSchema resourceSchema, DataSchemaResolver schem public List generateModelList() { - List result = new ArrayList(); - Map map = new HashMap(); + List result = new ArrayList<>(); + Map map = new HashMap<>(); findModelsResource(_topLevelSchema, map, result); return result; } diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/clientgen/TestRequestBuilderSpecGenerator.java b/restli-tools/src/test/java/com/linkedin/restli/tools/clientgen/TestRequestBuilderSpecGenerator.java index fc5b25fa7f..34ee280437 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/clientgen/TestRequestBuilderSpecGenerator.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/clientgen/TestRequestBuilderSpecGenerator.java @@ -78,7 +78,7 @@ private Set generateBuilderSpec(String[] sources) final DataSchemaParser schemaParser = new DataSchemaParser(RESOLVER_DIR); final TemplateSpecGenerator specGenerator = new TemplateSpecGenerator(schemaParser.getSchemaResolver()); final RestSpecParser parser = new RestSpecParser(); - final Map builderBaseMap = new HashMap(); + final Map builderBaseMap = new HashMap<>(); builderBaseMap.put(ResourceMethod.GET, "GetRequestBuilder"); builderBaseMap.put(ResourceMethod.DELETE, "DeleteRequestBuilder"); builderBaseMap.put(ResourceMethod.UPDATE, "UpdateRequestBuilder"); @@ -115,7 +115,7 @@ public void testSimpleResource() throws Exception Set builderSpecs = generateBuilderSpec(new String[] {idl}); Assert.assertNotNull(builderSpecs); Assert.assertTrue(builderSpecs.size() == 6); - Map methodMap = new HashMap(); + Map methodMap = new HashMap<>(); methodMap.put("get", "Gets the greeting."); methodMap.put("delete","Deletes the greeting."); methodMap.put("update", "Updates the greeting."); @@ -172,12 +172,12 @@ public void testCollectionResource() throws Exception Assert.assertNotNull(builderSpecs); Assert.assertTrue(builderSpecs.size() == 15); List expectedMethods = Arrays.asList("actionAnotherAction", "actionSomeAction", "actionVoidAction", "batchGet", "create", "delete", "findBySearch", "get", "getAll", "partialUpdate", "update"); - List actualMethods = new ArrayList(); + List actualMethods = new ArrayList<>(); CollectionRootBuilderSpec rootBuilder = null; CollectionRootBuilderSpec subRootBuilder = null; FinderBuilderSpec finderBuilder = null; - List actionBuilders = new ArrayList(); - List basicMethodBuilders = new ArrayList(); + List actionBuilders = new ArrayList<>(); + List basicMethodBuilders = new ArrayList<>(); for (BuilderSpec spec : builderSpecs) { @@ -339,7 +339,7 @@ public void testActionResource() throws Exception Assert.assertEquals(builderSpecs.size(), 27); ActionSetRootBuilderSpec rootBuilder = null; - List actionBuilders = new ArrayList(); + List actionBuilders = new ArrayList<>(); for (BuilderSpec spec : builderSpecs) { @@ -372,12 +372,12 @@ else if (spec instanceof ActionBuilderSpec) Assert.assertNotNull(actionBuilders); Assert.assertEquals(actionBuilders.size(), 26); - Set actionNames = new HashSet(Arrays.asList("arrayPromise", "echo", "echoRecord", "echoRecordArray", "echoStringArray", - "echoEnumArray", "failCallbackCall", "failCallbackThrow", "failPromiseCall", "failPromiseThrow", - "failTaskCall", "failTaskThrow", "failThrowInTask", "get", "nullPromise", - "nullTask", "parseq", "parseq3", "returnBool", "returnBoolOptionalParam", - "returnInt", "returnIntOptionalParam", "returnVoid", "timeout", "timeoutCallback", - "ultimateAnswer")); + Set actionNames = new HashSet<>(Arrays.asList("arrayPromise", "echo", "echoRecord", "echoRecordArray", "echoStringArray", + "echoEnumArray", "failCallbackCall", "failCallbackThrow", "failPromiseCall", "failPromiseThrow", + "failTaskCall", "failTaskThrow", "failThrowInTask", "get", "nullPromise", + "nullTask", "parseq", "parseq3", "returnBool", "returnBoolOptionalParam", + "returnInt", "returnIntOptionalParam", "returnVoid", "timeout", "timeoutCallback", + "ultimateAnswer")); for (ActionBuilderSpec spec : actionBuilders) { Assert.assertTrue(actionNames.contains(spec.getActionName())); @@ -410,4 +410,4 @@ else if (param.getParamName().equals("c")) Assert.assertTrue(actionNames.isEmpty()); } -} \ No newline at end of file +} diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/compatibility/TestResourceCompatibilityChecker.java b/restli-tools/src/test/java/com/linkedin/restli/tools/compatibility/TestResourceCompatibilityChecker.java index c655feccc0..0dd98e4a02 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/compatibility/TestResourceCompatibilityChecker.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/compatibility/TestResourceCompatibilityChecker.java @@ -89,15 +89,15 @@ public void setUp() @Test public void testPassCollectionFile() throws IOException { - final Collection resourceTestDiffs = new HashSet(); - final Collection modelTestDiffs = new HashSet(); + final Collection resourceTestDiffs = new HashSet<>(); + final Collection modelTestDiffs = new HashSet<>(); resourceTestDiffs.add(new CompatibilityInfo(Collections.singletonList(""), CompatibilityInfo.Type.OPTIONAL_VALUE, "namespace")); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "supports"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("update")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("update")))); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "methods"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("update")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("update")))); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "methods", "batch_get"), CompatibilityInfo.Type.MAX_BATCH_SIZE_REMOVED)); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "methods", "batch_create"), @@ -123,7 +123,7 @@ public void testPassCollectionFile() throws IOException resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "actions", "oneAction", "parameters", "someString"), CompatibilityInfo.Type.OPTIONAL_PARAMETER)); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "actions", "exceptionTest", "throws"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("java.lang.NullPointerException")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("java.lang.NullPointerException")))); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "entity", "actions", "someAction", "parameters", "b", "default"), CompatibilityInfo.Type.VALUE_DIFFERENT, "default", "changed")); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "finders", "oneFinder", "annotations", "deprecated"), @@ -143,7 +143,7 @@ public void testPassCollectionFile() throws IOException Assert.assertTrue(check); final Collection resourceIncompatibles = checker.getInfoMap().getRestSpecIncompatibles(); - final Collection resourceCompatibles = new HashSet(checker.getInfoMap().getRestSpecCompatibles()); + final Collection resourceCompatibles = new HashSet<>(checker.getInfoMap().getRestSpecCompatibles()); for (CompatibilityInfo di : resourceTestDiffs) { @@ -155,7 +155,7 @@ public void testPassCollectionFile() throws IOException Assert.assertTrue(resourceCompatibles.isEmpty(), "Unexpected resource compatibilities: " + resourceCompatibles.toString()); final Collection modelIncompatibles = checker.getInfoMap().getModelIncompatibles(); - final Collection modelCompatibles = new HashSet(checker.getInfoMap().getModelCompatibles()); + final Collection modelCompatibles = new HashSet<>(checker.getInfoMap().getModelCompatibles()); for (CompatibilityInfo di : modelTestDiffs) { @@ -170,7 +170,7 @@ public void testPassCollectionFile() throws IOException @Test public void testPassAssociationFile() throws IOException { - final Collection testDiffs = new HashSet(); + final Collection testDiffs = new HashSet<>(); testDiffs.add(new CompatibilityInfo(Arrays.asList("", "association", "methods", "create", "parameters"), CompatibilityInfo.Type.PARAMETER_NEW_OPTIONAL, "type")); @@ -183,7 +183,7 @@ public void testPassAssociationFile() throws IOException Assert.assertTrue(checker.check(CompatibilityLevel.BACKWARDS)); final Collection incompatibles = checker.getInfoMap().getIncompatibles(); - final Collection compatibles = new HashSet(checker.getInfoMap().getCompatibles()); + final Collection compatibles = new HashSet<>(checker.getInfoMap().getCompatibles()); for (CompatibilityInfo di : testDiffs) { @@ -198,15 +198,15 @@ public void testPassAssociationFile() throws IOException @Test public void testPassSimpleFile() throws IOException { - final Collection resourceTestDiffs = new HashSet(); - final Collection modelTestDiffs = new HashSet(); + final Collection resourceTestDiffs = new HashSet<>(); + final Collection modelTestDiffs = new HashSet<>(); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList(""), CompatibilityInfo.Type.OPTIONAL_VALUE, "namespace")); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "simple", "supports"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("update")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("update")))); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "simple", "methods"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("update")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("update")))); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "simple", "methods", "get", "parameters", "param1", "default"), CompatibilityInfo.Type.VALUE_DIFFERENT, "abcd", "abc")); resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "simple", "actions", "oneAction", "parameters", "bitfield"), @@ -236,7 +236,7 @@ public void testPassSimpleFile() throws IOException Assert.assertTrue(check); final Collection resourceIncompatibles = checker.getInfoMap().getRestSpecIncompatibles(); - final Collection resourceCompatibles = new HashSet(checker.getInfoMap().getRestSpecCompatibles()); + final Collection resourceCompatibles = new HashSet<>(checker.getInfoMap().getRestSpecCompatibles()); for (CompatibilityInfo di : resourceTestDiffs) { @@ -248,7 +248,7 @@ public void testPassSimpleFile() throws IOException Assert.assertTrue(resourceCompatibles.isEmpty(), "Unexpected resource compatibilities: " + resourceCompatibles.toString()); final Collection modelIncompatibles = checker.getInfoMap().getModelIncompatibles(); - final Collection modelCompatibles = new HashSet(checker.getInfoMap().getModelCompatibles()); + final Collection modelCompatibles = new HashSet<>(checker.getInfoMap().getModelCompatibles()); for (CompatibilityInfo di : modelTestDiffs) { @@ -263,7 +263,7 @@ public void testPassSimpleFile() throws IOException @Test public void testPassActionsSetFile() throws IOException { - final Collection testDiffs = new HashSet(); + final Collection testDiffs = new HashSet<>(); testDiffs.add(new CompatibilityInfo(Arrays.asList("", "doc"), CompatibilityInfo.Type.DOC_NOT_EQUAL)); testDiffs.add(new CompatibilityInfo(Arrays.asList("", "actionsSet", "actions", "handshake", "parameters"), @@ -282,7 +282,7 @@ public void testPassActionsSetFile() throws IOException final Collection incompatibles = checker.getInfoMap().getIncompatibles(); Assert.assertTrue(incompatibles.isEmpty(), "Unexpected incompatibilities: " + incompatibles.toString()); - final Collection compatibles = new HashSet(checker.getInfoMap().getCompatibles()); + final Collection compatibles = new HashSet<>(checker.getInfoMap().getCompatibles()); for (CompatibilityInfo td : testDiffs) { @@ -296,8 +296,8 @@ public void testPassActionsSetFile() throws IOException @Test public void testPassServiceErrorsFile() throws IOException { - final Collection resourceTestDiffs = new HashSet(); - final Collection modelTestDiffs = new HashSet(); + final Collection resourceTestDiffs = new HashSet<>(); + final Collection modelTestDiffs = new HashSet<>(); // Compatible changes resourceTestDiffs.add(new CompatibilityInfo(Arrays.asList("", "simple", "methods", "update", "serviceErrors"), @@ -335,7 +335,7 @@ public void testPassServiceErrorsFile() throws IOException Assert.assertTrue(resourceCompatibles.isEmpty(), "Unexpected resource compatibilities: " + resourceCompatibles.toString()); final Collection modelIncompatibles = checker.getInfoMap().getModelIncompatibles(); - final Collection modelCompatibles = new HashSet(checker.getInfoMap().getModelCompatibles()); + final Collection modelCompatibles = new HashSet<>(checker.getInfoMap().getModelCompatibles()); for (CompatibilityInfo di : modelTestDiffs) { @@ -353,8 +353,8 @@ public void testFailCollectionFile() throws IOException final SchemaParser sp = new SchemaParser(); sp.parse("\"StringRef\""); - final Collection resourceTestErrors = new HashSet(); - final Collection modelTestErrors = new HashSet(); + final Collection resourceTestErrors = new HashSet<>(); + final Collection modelTestErrors = new HashSet<>(); resourceTestErrors.add( new CompatibilityInfo(Arrays.asList("", "collection", "identifier", "params"), CompatibilityInfo.Type.TYPE_ERROR, "schema type changed from string to long")); @@ -433,7 +433,7 @@ public void testFailCollectionFile() throws IOException Assert.assertFalse(checker.check(CompatibilityLevel.BACKWARDS)); - final Collection resourceIncompatibles = new HashSet(checker.getInfoMap().getRestSpecIncompatibles()); + final Collection resourceIncompatibles = new HashSet<>(checker.getInfoMap().getRestSpecIncompatibles()); for (CompatibilityInfo te : resourceTestErrors) { Assert.assertTrue(resourceIncompatibles.contains(te), "Reported resource incompatibles should contain: " + te.toString()); @@ -442,7 +442,7 @@ public void testFailCollectionFile() throws IOException Assert.assertTrue(resourceIncompatibles.isEmpty(), "Unexpected resource incompatibilities: " + resourceIncompatibles.toString()); - final Collection modelIncompatibles = new HashSet(checker.getInfoMap().getModelIncompatibles()); + final Collection modelIncompatibles = new HashSet<>(checker.getInfoMap().getModelIncompatibles()); for (CompatibilityInfo te : modelTestErrors) { Assert.assertTrue(modelIncompatibles.contains(te), "Reported model incompatibles should contain: " + te.toString()); @@ -460,7 +460,7 @@ public void testFailAssociationFile() throws IOException prevAssocKey.setName("key1"); prevAssocKey.setType("string"); - final Collection testErrors = new HashSet(); + final Collection testErrors = new HashSet<>(); testErrors.add(new CompatibilityInfo(Arrays.asList("", "association", "assocKeys"), CompatibilityInfo.Type.ARRAY_NOT_EQUAL, new AssocKeySchemaArray(prevAssocKey))); @@ -484,7 +484,7 @@ public void testFailAssociationFile() throws IOException Assert.assertFalse(checker.check(CompatibilityLevel.BACKWARDS)); - final Collection incompatibles = new HashSet(checker.getInfoMap().getIncompatibles()); + final Collection incompatibles = new HashSet<>(checker.getInfoMap().getIncompatibles()); for (CompatibilityInfo te : testErrors) { @@ -498,8 +498,8 @@ public void testFailAssociationFile() throws IOException @Test public void testFailSimpleFile() throws IOException { - final Collection resourceTestErrors = new HashSet(); - final Collection modelTestErrors = new HashSet(); + final Collection resourceTestErrors = new HashSet<>(); + final Collection modelTestErrors = new HashSet<>(); resourceTestErrors.add(new CompatibilityInfo(Arrays.asList("", "simple", "supports"), CompatibilityInfo.Type.ARRAY_NOT_CONTAIN, @@ -531,7 +531,7 @@ public void testFailSimpleFile() throws IOException Assert.assertFalse(checker.check(CompatibilityLevel.BACKWARDS)); - final Collection resourceIncompatible = new HashSet(checker.getInfoMap().getRestSpecIncompatibles()); + final Collection resourceIncompatible = new HashSet<>(checker.getInfoMap().getRestSpecIncompatibles()); for (CompatibilityInfo te : resourceTestErrors) { @@ -541,7 +541,7 @@ public void testFailSimpleFile() throws IOException Assert.assertTrue(resourceIncompatible.isEmpty(), "Unexpected resource incompatibilities: " + resourceIncompatible.toString()); - final Collection modelIncompatible = new HashSet(checker.getInfoMap().getModelIncompatibles()); + final Collection modelIncompatible = new HashSet<>(checker.getInfoMap().getModelIncompatibles()); for (CompatibilityInfo te : modelTestErrors) { @@ -557,7 +557,7 @@ public void testFailSimpleFile() throws IOException @Test public void testFailActionsSetFile() throws IOException { - final Collection testErrors = new HashSet(); + final Collection testErrors = new HashSet<>(); testErrors.add(new CompatibilityInfo(Arrays.asList(""), CompatibilityInfo.Type.VALUE_WRONG_OPTIONALITY, "actionsSet")); @@ -569,8 +569,8 @@ public void testFailActionsSetFile() throws IOException Assert.assertFalse(checker.check(CompatibilityLevel.BACKWARDS)); - final Collection incompatibles = new HashSet(checker.getInfoMap().getIncompatibles()); - final Collection compatibles = new HashSet(checker.getInfoMap().getCompatibles()); + final Collection incompatibles = new HashSet<>(checker.getInfoMap().getIncompatibles()); + final Collection compatibles = new HashSet<>(checker.getInfoMap().getCompatibles()); for (CompatibilityInfo te : testErrors) { @@ -585,7 +585,7 @@ public void testFailActionsSetFile() throws IOException @Test public void testFailUnstructuredDataFile() throws IOException { - final Collection errors = new HashSet(); + final Collection errors = new HashSet<>(); errors.add(new CompatibilityInfo(Arrays.asList("", "entityType"), CompatibilityInfo.Type.VALUE_NOT_EQUAL, ResourceEntityType.UNSTRUCTURED_DATA, ResourceEntityType.STRUCTURED_DATA)); @@ -612,8 +612,8 @@ public void testFailUnstructuredDataFile() throws IOException @Test public void testFailServiceErrorsFile() throws IOException { - final Collection resourceTestErrors = new HashSet(); - final Collection modelTestErrors = new HashSet(); + final Collection resourceTestErrors = new HashSet<>(); + final Collection modelTestErrors = new HashSet<>(); // Incompatible changes, ignore compatible changes resourceTestErrors.add(new CompatibilityInfo(Arrays.asList("", "simple", "methods", "get", "serviceErrors", "METHOD_LEVEL_ERROR", "status"), @@ -670,8 +670,8 @@ public void testFailServiceErrorsFile() throws IOException Assert.assertTrue(resourceIncompatible.isEmpty(), "Unexpected resource incompatibilities: " + resourceIncompatible.toString()); Assert.assertFalse(resourceCompatible.isEmpty(), "Expected there to be some resource compatibilities, but there were none."); - final Collection modelIncompatible = new HashSet(checker.getInfoMap().getModelIncompatibles()); - final Collection modelCompatible = new HashSet(checker.getInfoMap().getModelCompatibles()); + final Collection modelIncompatible = new HashSet<>(checker.getInfoMap().getModelIncompatibles()); + final Collection modelCompatible = new HashSet<>(checker.getInfoMap().getModelCompatibles()); for (CompatibilityInfo te : modelTestErrors) { @@ -700,7 +700,7 @@ private void bindSchemaResolvers() Name toneName = new Name("com.linkedin.greetings.api.Tone"); EnumDataSchema tone = new EnumDataSchema(toneName); - List symbols = new ArrayList(); + List symbols = new ArrayList<>(); symbols.add("FRIENDLY"); symbols.add("SINCERE"); symbols.add("INSULTING"); @@ -708,7 +708,7 @@ private void bindSchemaResolvers() Name greetingName = new Name("com.linkedin.greetings.api.Greeting"); RecordDataSchema prevGreeting = new RecordDataSchema(greetingName, RecordDataSchema.RecordType.RECORD); - List oldFields = new ArrayList(); + List oldFields = new ArrayList<>(); RecordDataSchema.Field id = new RecordDataSchema.Field(new LongDataSchema()); id.setName("id", errors); oldFields.add(id); @@ -737,7 +737,7 @@ private void bindSchemaResolvers() // compat greeting added a new optional field "newField" RecordDataSchema compatGreeting = new RecordDataSchema(greetingName, RecordDataSchema.RecordType.RECORD); - List compatFields = new ArrayList(); + List compatFields = new ArrayList<>(); compatFields.add(id); compatFields.add(message); compatFields.add(toneField); @@ -759,7 +759,7 @@ private void bindSchemaResolvers() // has changed the type of "id" to string, // and added a new non-optional field "newField" RecordDataSchema incompatGreeting = new RecordDataSchema(greetingName, RecordDataSchema.RecordType.RECORD); - List incompatFields = new ArrayList(); + List incompatFields = new ArrayList<>(); RecordDataSchema.Field incompatId = new RecordDataSchema.Field(new StringDataSchema()); incompatId.setName("id", errors); oldFields.add(incompatId); diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/idlcheck/TestRestLiResourceModelCompatibilityChecker.java b/restli-tools/src/test/java/com/linkedin/restli/tools/idlcheck/TestRestLiResourceModelCompatibilityChecker.java index 3ff5aacce0..d578603b8e 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/idlcheck/TestRestLiResourceModelCompatibilityChecker.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/idlcheck/TestRestLiResourceModelCompatibilityChecker.java @@ -32,8 +32,8 @@ public void testFileNotFound() { final String nonExistentFilename1 = "NonExistentFile1"; final String nonExistentFilename2 = "NonExistentFile2"; - final Collection testIncompatibles = new HashSet(); - final Collection testCompatibles = new HashSet(); + final Collection testIncompatibles = new HashSet<>(); + final Collection testCompatibles = new HashSet<>(); testIncompatibles.add(new CompatibilityInfo(Arrays.asList(""), CompatibilityInfo.Type.RESOURCE_MISSING, @@ -49,8 +49,8 @@ public void testFileNotFound() nonExistentFilename2, CompatibilityLevel.BACKWARDS)); - final Collection incompatibles = new HashSet(checker.getInfoMap().getIncompatibles()); - final Collection compatibles = new HashSet(checker.getInfoMap().getCompatibles()); + final Collection incompatibles = new HashSet<>(checker.getInfoMap().getIncompatibles()); + final Collection compatibles = new HashSet<>(checker.getInfoMap().getCompatibles()); for (CompatibilityInfo te : incompatibles) { diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/sample/CustomKeyAssociationResource.java b/restli-tools/src/test/java/com/linkedin/restli/tools/sample/CustomKeyAssociationResource.java index b0c9ec9693..1debdab3e5 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/sample/CustomKeyAssociationResource.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/sample/CustomKeyAssociationResource.java @@ -60,7 +60,7 @@ public SimpleGreeting get(CompoundKey key) public BatchUpdateResult batchUpdate(BatchUpdateRequest entities) { Set keys = entities.getData().keySet(); - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); for(CompoundKey key : keys) { diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestPegasusSchemaSnapshotCompatibilityChecker.java b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestPegasusSchemaSnapshotCompatibilityChecker.java index 46bf86c5ec..dae8cf2a75 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestPegasusSchemaSnapshotCompatibilityChecker.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestPegasusSchemaSnapshotCompatibilityChecker.java @@ -153,8 +153,8 @@ private Object[][] compatibleInputFiles() @DataProvider private Object[][] incompatibleInputFiles() { - final Collection incompatibilityErrors = new HashSet(); - final Collection compatibilityDiffs = new HashSet(); + final Collection incompatibilityErrors = new HashSet<>(); + final Collection compatibilityDiffs = new HashSet<>(); incompatibilityErrors.add(new CompatibilityInfo(Arrays.asList("BirthInfo"), CompatibilityInfo.Type.TYPE_BREAKS_NEW_READER, "new record added required fields name")); incompatibilityErrors.add(new CompatibilityInfo(Arrays.asList("BirthInfo"), @@ -173,4 +173,4 @@ private Object[][] incompatibleInputFiles() } }; } -} \ No newline at end of file +} diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestRestliSnapshotCompatibilityChecker.java b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestRestliSnapshotCompatibilityChecker.java index 43898964dc..d2c71419df 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestRestliSnapshotCompatibilityChecker.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestRestliSnapshotCompatibilityChecker.java @@ -49,8 +49,8 @@ public void testCompatibleRestSpecVsSnapshot() @Test public void testIncompatibleRestSpecVsSnapshot() { - final Collection restSpecErrors = new HashSet(); - final Collection restSpecDiffs = new HashSet(); + final Collection restSpecErrors = new HashSet<>(); + final Collection restSpecDiffs = new HashSet<>(); restSpecErrors.add(new CompatibilityInfo(Arrays.asList("", "collection", "identifier", "type"), CompatibilityInfo.Type.TYPE_ERROR, "schema type changed from int to long")); restSpecErrors.add(new CompatibilityInfo(Arrays.asList("", "collection", "alternativeKeys"), @@ -60,11 +60,11 @@ public void testIncompatibleRestSpecVsSnapshot() restSpecErrors.add(new CompatibilityInfo(Arrays.asList("", "collection", "alternativeKeys", "alt", "keyCoercer"), CompatibilityInfo.Type.VALUE_NOT_EQUAL, "com.linkedin.restli.tools.twitter.IntLongCoercer", "com.linkedin.restli.tools.twitter.StringLongCoercer")); restSpecDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "supports"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("create")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("create")))); restSpecDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "methods"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("create")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("create")))); restSpecDiffs.add(new CompatibilityInfo(Arrays.asList("", "collection", "alternativeKeys"), - CompatibilityInfo.Type.SUPERSET, new HashSet(Arrays.asList("newAlt")))); + CompatibilityInfo.Type.SUPERSET, new HashSet<>(Arrays.asList("newAlt")))); final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker(); final CompatibilityInfoMap incompatibleInfoMap = checker.checkRestSpecVsSnapshot(RESOURCES_DIR + FS + "idls" + FS + "twitter-statuses-incompatible.restspec.json", @@ -103,7 +103,7 @@ public void testCompatibleRestLiDataAnnotations() @Test public void testIncompatibleRestLiDataAnnotations() { - final Collection errors = new HashSet(); + final Collection errors = new HashSet<>(); errors.add(new CompatibilityInfo(Arrays.asList("", "annotations", "intB"), CompatibilityInfo.Type.ANNOTATION_CHANGE_BREAKS_OLD_CLIENT, "Cannot add ReadOnly annotation")); errors.add(new CompatibilityInfo(Arrays.asList("", "annotations", "validationDemoNext/intA"), @@ -140,8 +140,8 @@ public void testFileNotFound() { final String nonExistentFilename1 = "NonExistentFile1"; final String nonExistentFilename2 = "NonExistentFile2"; - final Collection testIncompatibles = new HashSet(); - final Collection testCompatibles = new HashSet(); + final Collection testIncompatibles = new HashSet<>(); + final Collection testCompatibles = new HashSet<>(); testIncompatibles.add(new CompatibilityInfo(Arrays.asList(""), CompatibilityInfo.Type.RESOURCE_MISSING, @@ -157,8 +157,8 @@ public void testFileNotFound() CompatibilityLevel.BACKWARDS); Assert.assertFalse(infoMap.isCompatible(CompatibilityLevel.BACKWARDS)); - final Collection incompatibles = new HashSet(infoMap.getIncompatibles()); - final Collection compatibles = new HashSet(infoMap.getCompatibles()); + final Collection incompatibles = new HashSet<>(infoMap.getIncompatibles()); + final Collection compatibles = new HashSet<>(infoMap.getCompatibles()); for (CompatibilityInfo te : incompatibles) { diff --git a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestSnapshot.java b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestSnapshot.java index bd7db0442b..1edf99e7a6 100644 --- a/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestSnapshot.java +++ b/restli-tools/src/test/java/com/linkedin/restli/tools/snapshot/check/TestSnapshot.java @@ -50,7 +50,7 @@ public void testCircularlyDependentModels() throws IOException Map models = snapshot.getModels(); Assert.assertEquals(models.size(), 4); - List expectedModelNames = new ArrayList(); + List expectedModelNames = new ArrayList<>(); expectedModelNames.add("com.linkedin.restli.tools.snapshot.circular.A"); expectedModelNames.add("com.linkedin.restli.tools.snapshot.circular.B"); expectedModelNames.add("com.linkedin.restli.tools.snapshot.circular.C");