auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AuthenticationResult acquireTokenSilentSync(String resource, String clientId, String userId) throws InterruptedException, ExecutionException { Future<AuthenticationResult> futureResult = acquireTokenSilent(resource, clientId, userId, null); return futureResult.get(); }

Target:
public AuthenticationResult acquireTokenSilentSync(String resource, String clientId, String userId) { Future<AuthenticationResult> futureResult = acquireTokenSilent(resource, clientId, userId, null); try { return futureResult.get(); } catch (InterruptedException e) { convertExceptionForSync(e); } catch (ExecutionException e) { convertExceptionForSync(e); } return null; }
Source:
public Long getEarliestSequenceNumber(StreamPartition<Integer> partition) { seekToEarliest(Collections.singleton(partition)); return consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); }

Target:
public Long getEarliestSequenceNumber(StreamPartition<Integer> partition) { Long currPos = consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); seekToEarliest(Collections.singleton(partition)); Long nextPos = consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); seek(partition, currPos); return nextPos; }
Source:
public void setUp() throws Exception { omMetadataManager = initializeNewOmMetadataManager(); File tempDir = temporaryFolder.newFolder(); AbstractSqlDatabaseTest.DataSourceConfigurationProvider configurationProvider = new AbstractSqlDatabaseTest.DataSourceConfigurationProvider(tempDir); JooqPersistenceModule jooqPersistenceModule = new JooqPersistenceModule(configurationProvider); injector = Guice.createInjector(jooqPersistenceModule, new AbstractModule() { @Override protected void configure() { try { bind(DataSourceConfiguration.class) .toProvider(configurationProvider); bind(OzoneConfiguration.class).toInstance( getTestOzoneConfiguration()); reconOMMetadataManager = getTestMetadataManager(omMetadataManager); bind(ReconOMMetadataManager.class) .toInstance(reconOMMetadataManager); ozoneManagerServiceProvider = new OzoneManagerServiceProviderImpl( getTestOzoneConfiguration()); bind(OzoneManagerServiceProvider.class) .toInstance(ozoneManagerServiceProvider); bind(DBStore.class).toProvider(ReconContainerDBProvider.class). in(Singleton.class); bind(ContainerDBServiceProvider.class).to( ContainerDBServiceProviderImpl.class).in(Singleton.class); } catch (IOException e) { Assert.fail(); } } }); if (!setUpIsDone) { DSL.using(new DefaultConfiguration().set( injector.getInstance(DataSource.class))); containerDbServiceProvider = injector.getInstance( ContainerDBServiceProvider.class); StatsSchemaDefinition schemaDefinition = getInjector().getInstance( StatsSchemaDefinition.class); schemaDefinition.initializeSchema(); setUpIsDone = true; } containerDbServiceProvider = injector.getInstance( ContainerDBServiceProvider.class); }

Target:
public void setUp() throws Exception { if (!setUpIsDone) { initializeInjector(); DSL.using(new DefaultConfiguration().set( injector.getInstance(DataSource.class))); containerDbServiceProvider = injector.getInstance( ContainerDBServiceProvider.class); StatsSchemaDefinition schemaDefinition = getInjector().getInstance( StatsSchemaDefinition.class); schemaDefinition.initializeSchema(); setUpIsDone = true; } containerDbServiceProvider = injector.getInstance( ContainerDBServiceProvider.class); }
Source:
public void discoverNetworks() { ArrayList<Provider<?>> items = new ArrayList<Provider<?>>(); items.add(provider); getProviders().setItems(items); getProviders().setSelectedItem(provider); }

Target:
public void discoverNetworks() { Collection<Provider<?>> items = new ArrayList<Provider<?>>(); items.add(provider); getProviders().setItems(items); getProviders().setSelectedItem(provider); }
Source:
protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr) throws IOException { SSLServerSocketFactory serverSocketFactory = null; try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(ServerKeyStoreManager.getInstance().getKeyManagerFactory().getKeyManagers(), null, null); serverSocketFactory = context.getServerSocketFactory(); } catch (final NoSuchAlgorithmException exception) { shutdown(serverSocketFactory, exception); } catch (final KeyManagementException exception) { shutdown(serverSocketFactory, exception); } catch (final ServerKeyStoreException exception) { shutdown(serverSocketFactory, exception); } return disableSSLv3AndReturn(serverSocketFactory.createServerSocket(pPort, backlog, addr)); }

Target:
protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr) throws IOException { SSLServerSocketFactory serverSocketFactory = null; try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(ServerKeyStoreManager.getInstance().getKeyManagerFactory().getKeyManagers(), null, null); serverSocketFactory = context.getServerSocketFactory(); } catch (final NoSuchAlgorithmException exception) { shutdown(serverSocketFactory, exception); } catch (final KeyManagementException exception) { shutdown(serverSocketFactory, exception); } catch (final ServerKeyStoreException exception) { shutdown(serverSocketFactory, exception); } try { return disableSSLv3AndReturn(serverSocketFactory.createServerSocket(pPort, backlog, addr)); } catch (final FatalSocketException ex) { shutdown(serverSocketFactory, ex); throw new IOException(ex.getMessage()); } }
Source:
public void init() throws CarbonToolsIntegrationTestException, IOException, XPathExpressionException { context = new AutomationContext("CARBON", "carbon002", ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.ADMIN); authenticatorClient = new LoginLogoutUtil(context); carbonHome = CarbonCommandToolsUtil.getCarbonHome(context); log.info("replacing the master-datasources.xml file"); File sourceFile = new File(TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "CARBON" + File.separator + "carbontools" + File.separator + "master-datasources.xml"); File targetFile = new File(carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator + "datasources" + File.separator + "master-datasources.xml"); copyFile(sourceFile,targetFile); }

Target:
public void init() throws CarbonToolsIntegrationTestException, XPathExpressionException, MalformedURLException, AxisFault { context = new AutomationContext("CARBON", "carbon002", ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.ADMIN); authenticatorClient = new LoginLogoutUtil(context); carbonHome = CarbonCommandToolsUtil.getCarbonHome(context); log.info("replacing the master-datasources.xml file"); File sourceFile = new File(TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "CARBON" + File.separator + "carbontools" + File.separator + "master-datasources.xml"); File targetFile = new File(carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator + "datasources" + File.separator + "master-datasources.xml"); super.copyFolder(sourceFile, targetFile); }
Source:
public static EventSourceType getEventSourceType(Bundle bundle) { if(bundle == null) { return null; } if(bundle.containsKey(CAMPAIGN.getEventSourceKeyPrefix()+CAMPAIGN.getEventSourceIdAttributeKey())) { return CAMPAIGN; } else { return JOURNEY; } }

Target:
static EventSourceType getEventSourceType(Bundle bundle) { if (bundle == null) { return UNKNOWN; } String campaignKey = CAMPAIGN.getEventSourceKeyPrefix() + CAMPAIGN.getEventSourceIdAttributeKey(); if (bundle.containsKey(campaignKey)) { return CAMPAIGN; } else if (bundle.containsKey(PINPOINT_ATTRIBUTE_KEY) && bundle.getString(PINPOINT_ATTRIBUTE_KEY).matches(".*\"journey_id\".*")) { return JOURNEY; } else { return UNKNOWN; } }
Source:
public void testUserMessageSerdeException() { IntermediateMessageSerde imserde = new IntermediateMessageSerde(new ObjectSerde()); IntermediateMessageSerde imserde2 = new IntermediateMessageSerde(new JsonSerdeV2<>()); String msg = "this is a test message"; TestUserMessage userMessage = new TestUserMessage(msg, 0, System.currentTimeMillis()); byte[] bytes = imserde.toBytes(userMessage); imserde2.fromBytes(bytes); }

Target:
public void testUserMessageSerdeException() { Serde<?> mockUserMessageSerde = mock(Serde.class); when(mockUserMessageSerde.fromBytes(anyObject())).then(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { byte[] bytes = invocation.getArgumentAt(0, byte[].class); if (Arrays.equals(bytes, new byte[]{1, 2})) { throw new IllegalArgumentException("User message serde failed to deserialize this message."); } else { Assert.fail(); return null; } } }); IntermediateMessageSerde imserde = new IntermediateMessageSerde(mockUserMessageSerde); byte[] bytes = new byte[]{0, 1, 2}; imserde.fromBytes(bytes); }
Source:
public String getAnswerString() { if (answer == -1) { return "Invalid response"; } return Integer.toString(answer); }

Target:
public String getAnswerString() { return Integer.toString(answer); }
Source:
public void should_load_profile_in_sonar_lint_context() { ProfileDefinition sonarWay = new JavaSonarWayProfile(ruleFinder(true)); ValidationMessages validation = ValidationMessages.create(); RulesProfile profile = sonarWay.createProfile(validation); assertThat(profile.getActiveRules()).onProperty("repositoryKey").containsOnly(CheckList.REPOSITORY_KEY); assertThat(profile.getActiveRulesByRepository("common-abap")).isEmpty(); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY).size()).isGreaterThanOrEqualTo(269); assertThat(profile.getName()).isEqualTo("Sonar way"); assertThat(validation.hasErrors()).isFalse(); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY).get(0).getSeverity()).isSameAs(RulePriority.MINOR); }

Target:
public void should_load_profile_in_sonar_lint_context() { ProfileDefinition sonarWay = new JavaSonarWayProfile(ruleFinder(true)); ValidationMessages validation = ValidationMessages.create(); RulesProfile profile = sonarWay.createProfile(validation); assertThat(profile.getActiveRules()).onProperty("repositoryKey").containsOnly(CheckList.REPOSITORY_KEY); assertThat(profile.getActiveRulesByRepository("common-java")).isEmpty(); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY).size()).isGreaterThanOrEqualTo(269); assertThat(profile.getName()).isEqualTo("Sonar way"); assertThat(validation.hasErrors()).isFalse(); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY).get(0).getSeverity()).isSameAs(RulePriority.MINOR); }
Source:
public void addAll(Collection<? extends RMEvent> toAdd) { for (RMEvent rmEvent : toAdd) { events.add(rmEvent); } latestCounter.set(Math.max(latestCounter.get(), findLargestCounter(events.getSortedItems()))); }

Target:
public void addAll(Collection<? extends RMEvent> toAdd) { toAdd.forEach(rmEvent -> events.add(rmEvent)); latestCounter.set(Math.max(latestCounter.get(), findLargestCounter(events.getSortedItems()))); }
Source:
public void testENG11935() throws Exception { Client client = getClient(); client.callProcedure("ENG11935.insert", "0", "abc", 1486148453, "def", "ghi", "jkl", "mno0", 35094, 30847, 27285, 36335, 59247, 50750, "0"); client.callProcedure("ENG11935.insert", "0", "abc", 1486148453, "def", "ghi", "jkl", "mno1", 35094, 30847, 27285, 36335, 59247, 50750, "1"); client.callProcedure("@AdHoc", "DELETE FROM ENG11935 WHERE VAR1=0 AND PRIMKEY=1;"); }

Target:
public void testENG11935() throws Exception { if (isHSQL()) { return; } Client client = getClient(); client.callProcedure("ENG11935.insert", "0", "abc", 1486148453, "def", "ghi", "jkl", "mno0", 35094, 30847, 27285, 36335, 59247, 50750, "0"); client.callProcedure("ENG11935.insert", "0", "abc", 1486148453, "def", "ghi", "jkl", "mno1", 35094, 30847, 27285, 36335, 59247, 50750, "1"); TimestampType timestamp = new TimestampType("1970-01-18 04:50:00.000000"); VoltTable vt = client.callProcedure("@AdHoc", "SELECT * FROM V_ENG11935;").getResults()[0]; Object[][] expectedAnswer = new Object[][] { {"0", "abc", "def", "ghi", "jkl", timestamp, 1486200, 2, "mno1", new BigDecimal("1403760.000000000000"), new BigDecimal("1233880.000000000000"), 1091400, 1453400, 64662175800L, 73760050000L} }; assertContentOfTable(expectedAnswer, vt); client.callProcedure("@AdHoc", "DELETE FROM ENG11935 WHERE VAR1 = '0' AND PRIMKEY = '1';"); vt = client.callProcedure("@AdHoc", "SELECT * FROM V_ENG11935;").getResults()[0]; expectedAnswer = new Object[][] { {"0", "abc", "def", "ghi", "jkl", timestamp, 1486200, 1, "mno0", new BigDecimal("701880.000000000000"), new BigDecimal("616940.000000000000"), 545700, 726700, 32331087900L, 36880025000L} }; assertContentOfTable(expectedAnswer, vt); }
Source:
public String visitCall(CallExpression node, Void context) { if (standardFunctionResolution.isArithmeticFunction(node.getFunctionHandle()) || standardFunctionResolution.isComparisonFunction(node.getFunctionHandle())) { String operation = functionManager.getFunctionMetadata(node.getFunctionHandle()).getOperatorType().get().getOperator(); return String.join(" " + operation + " ", formatRowExpressions(node.getArguments()).stream().map(e -> "(" + e + ")").collect(toList())); } else { return node.getDisplayName() + "(" + String.join(", ", formatRowExpressions(node.getArguments())) + ")"; } }

Target:
public String visitCall(CallExpression node, Void context) { if (standardFunctionResolution.isArithmeticFunction(node.getFunctionHandle()) || standardFunctionResolution.isComparisonFunction(node.getFunctionHandle())) { String operation = functionMetadataManager.getFunctionMetadata(node.getFunctionHandle()).getOperatorType().get().getOperator(); return String.join(" " + operation + " ", formatRowExpressions(node.getArguments()).stream().map(e -> "(" + e + ")").collect(toImmutableList())); } else if (standardFunctionResolution.isCastFunction(node.getFunctionHandle())) { return String.format("CAST(%s AS %s)", formatRowExpression(node.getArguments().get(0)), node.getType().getDisplayName()); } else if (standardFunctionResolution.isNegateFunction(node.getFunctionHandle())) { return "-(" + formatRowExpression(node.getArguments().get(0)) + ")"; } else if (standardFunctionResolution.isSubscriptFunction(node.getFunctionHandle())) { return formatRowExpression(node.getArguments().get(0)) + "[" + formatRowExpression(node.getArguments().get(1)) + "]"; } else if (standardFunctionResolution.isBetweenFunction(node.getFunctionHandle())) { List<String> formattedExpresions = formatRowExpressions(node.getArguments()); return String.format("%s BETWEEN (%s) AND (%s)", formattedExpresions.get(0), formattedExpresions.get(1), formattedExpresions.get(2)); } return node.getDisplayName() + "(" + String.join(", ", formatRowExpressions(node.getArguments())) + ")"; }
Source:
public Span getSpan(String tenantId, String id) { GetResponse response = client.getClient() .prepareGet(client.getIndex(tenantId), SPAN_TYPE, id) .setRouting(id) .execute() .actionGet(); Span span = null; if (!response.isSourceEmpty()) { try { span = deserialize(response.getSourceAsString(), Span.class); } catch (IOException ex) { msgLog.errorFailedToParse(ex); } } msgLog.tracef("Get span with id[%s] is: %s", id, span); return span; }

Target:
public Span getSpan(String tenantId, String id) { GetResponse response = null; try { response = client.getClient() .prepareGet(client.getIndex(tenantId), SPAN_TYPE, id) .setRouting(id) .execute() .actionGet(); } catch (IndexMissingException ex) { log.errorf("Missing span index %s", tenantId); return null; } Span span = null; if (!response.isSourceEmpty()) { try { span = deserialize(response.getSourceAsString(), Span.class); } catch (IOException ex) { log.errorFailedToParse(ex); throw new IllegalStateException("Failed to deserialize span", ex); } } log.tracef("Get span with id[%s] is: %s", id, span); return span; }
Source:
private void getRunId(){ Boolean isAppModeBatch = new ApplicationConfig(appDesc.getConfig()).getAppMode() == ApplicationConfig.ApplicationMode.BATCH; if(coordinationUtils == null || !isAppModeBatch) { return; } runIdLock = coordinationUtils.getReadWriteLock(RUNID_LOCK_ID); if(runIdLock == null) { LOG.warn("Processor failed to create the lock for run.id generation", uid); return; } runIdAccess = coordinationUtils.getDataAccess(new LocalDistributedDataStateListener()); if(runIdAccess == null) { LOG.warn("Processor failed to create data access utils for run.id generation", uid); return; } try { DistributedReadWriteLock.AccessType lockAccess = runIdLock.lock(LOCK_TIMEOUT, LOCK_TIMEOUT_UNIT); if(lockAccess == DistributedReadWriteLock.AccessType.WRITE) { LOG.info("write lock acquired for run.id generation by Processor " + uid); runId = String.valueOf(System.currentTimeMillis()) + "-" + UUID.randomUUID().toString().substring(0, 8); LOG.info("The run id for this run is {}", runId); runIdAccess.writeData(RUNID_PATH,runId, new LocalDistributedDataWatcher()); runIdLock.unlock(); return; } else if(lockAccess == DistributedReadWriteLock.AccessType.READ) { LOG.info("read lock acquired for run.id by Processor " + uid); runId = (String) runIdAccess.readData(RUNID_PATH, new LocalDistributedDataWatcher()); runIdLock.unlock(); return; } else { String msg = String.format("Processor failed to get the lock for run.id", uid); throw new SamzaException(msg); } } catch (TimeoutException e) { String msg = String.format("Processor failed to get the lock for run.id generation", uid); throw new SamzaException(msg, e); } }

Target:
public Optional<String> getRunId() { return this.runId; }
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultClusteredCacheConfig = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); defaultClusteredCacheConfig.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); defaultClusteredCacheConfig.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(defaultClusteredCacheConfig); createHotRodServers(NUM_NODES, cfgBuilder); waitForClusterToForm(); RemoteCache<String, String> metadataCache = client(0).getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("sample_bank_account/bank.proto", Util.getResourceAsString("/sample_bank_account/bank.proto", getClass().getClassLoader())); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); for (int i = 0; i < NUM_NODES; i++) { server(i).addCacheEventFilterFactory("custom-filter-factory", new CustomCacheEventFilterFactory()); ProtobufMetadataManagerImpl metadataManager = ProtobufMetadataManagerImpl.getProtobufMetadataManager(server(i).getCacheManager()); MarshallerRegistration.getMarshallers().forEach(metadataManager::registerMarshaller); } MarshallerRegistration.registerMarshallers(ProtoStreamMarshaller.getSerializationContext(client(0))); remoteCache = client(0).getCache(); }

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultClusteredCacheConfig = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); defaultClusteredCacheConfig.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); defaultClusteredCacheConfig.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(defaultClusteredCacheConfig); createHotRodServers(NUM_NODES, cfgBuilder); waitForClusterToForm(); for (int i = 0; i < NUM_NODES; i++) { server(i).addCacheEventFilterFactory("custom-filter-factory", new CustomCacheEventFilterFactory()); MarshallerRegistration.registerMarshallers(ProtobufMetadataManagerImpl.getSerializationContextInternal(server(i).getCacheManager())); assertFalse(client(i).getCache(PROTOBUF_METADATA_CACHE_NAME).containsKey(ERRORS_KEY_SUFFIX)); } MarshallerRegistration.registerMarshallers(ProtoStreamMarshaller.getSerializationContext(client(0))); remoteCache = client(0).getCache(); }
Source:
Call<RbGallery> request(@NonNull Service service, @NonNull String title, @NonNull Callback cb, @NonNull String...types) { Call<RbGallery> call = service.fetch(title); call.enqueue(new retrofit2.Callback<RbGallery>() { @Override public void onResponse(@NonNull Call<RbGallery> call, @NonNull Response<RbGallery> response) { if (response.body() != null && response.body().success()) { cb.success(call, types.length == 0 ? response.body().getAllItems() : response.body().getItems(types)); } else if (response.body().hasError()) { cb.failure(call, new Throwable(response.body().getErrorMessage())); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } @Override public void onFailure(@NonNull Call<RbGallery> call, @NonNull Throwable t) { cb.failure(call, t); } }); return call; }

Target:
Call<RbGallery> request(@NonNull Service service, @NonNull String title, @NonNull Callback cb, @NonNull String...types) { Call<RbGallery> call = service.fetch(title); call.enqueue(new retrofit2.Callback<RbGallery>() { @Override public void onResponse(@NonNull Call<RbGallery> call, @NonNull Response<RbGallery> response) { if (response.body() != null && response.body().getAllItems() != null) { cb.success(call, types.length == 0 ? response.body().getAllItems() : response.body().getItems(types)); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } @Override public void onFailure(@NonNull Call<RbGallery> call, @NonNull Throwable t) { cb.failure(call, t); } }); return call; }
Source:
public ResponseEntity<ListWorkflowInstanceResponse> fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathVariable("id") int id, @RequestParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include, @RequestParam("maxActions") @ApiParam("Maximum number of actions returned for each workflow instance") Long maxActions) { try { return ResponseEntity.ok().body(super.fetchWorkflowInstance(id, include, maxActions, this.workflowInstances, this.listWorkflowConverter)); } catch (EmptyResultDataAccessException e) { return ResponseEntity.notFound().build(); } }

Target:
public ResponseEntity<ListWorkflowInstanceResponse> fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathVariable("id") int id, @RequestParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include, @RequestParam("maxActions") @ApiParam("Maximum number of actions returned for each workflow instance") Long maxActions) { try { return ResponseEntity.ok().body(super.fetchWorkflowInstance(id, include, maxActions, this.workflowInstances, this.listWorkflowConverter)); } catch (@SuppressWarnings("unused") EmptyResultDataAccessException e) { return ResponseEntity.notFound().build(); } }
Source:
static RuntimeException andLog(UnsupportedOperationException exception) { StackTraceElement[] stackTrace = exception.getStackTrace(); StringBuilder buffer = new StringBuilder(255); buffer.append(stackTrace[1].getClassName()); buffer.append('.'); buffer.append(stackTrace[1].getMethodName()); buffer.append("()"); if (stackTrace[1].getLineNumber() > -1) { buffer.append(" line "); buffer.append(stackTrace[1].getLineNumber()); } buffer.append(" unexpectedly called unimplemented "); buffer.append(stackTrace[0].getMethodName()); buffer.append("()"); if (exception.getMessage() != null) { buffer.append(": "); buffer.append(exception.getMessage()); } logger.error(buffer.toString()); return exception; }

Target:
static UnsupportedOperationException andLog(UnsupportedOperationException exception) { StackTraceElement[] stackTrace = exception.getStackTrace(); StringBuilder buffer = new StringBuilder(255); buffer.append(stackTrace[1].getClassName()); buffer.append('.'); buffer.append(stackTrace[1].getMethodName()); buffer.append("()"); if (stackTrace[1].getLineNumber() > -1) { buffer.append(" line "); buffer.append(stackTrace[1].getLineNumber()); } buffer.append(" unexpectedly called unimplemented "); buffer.append(stackTrace[0].getMethodName()); buffer.append("()"); if (exception.getMessage() != null) { buffer.append(": "); buffer.append(exception.getMessage()); } logger.error(buffer.toString()); return exception; }
Source:
KafkaConsumerProxy(Consumer<K, V> kafkaConsumer, String systemName, String clientId, KafkaSystemConsumer.KafkaConsumerMessageSink messageSink, KafkaSystemConsumerMetrics samzaConsumerMetrics, String metricName) { this.kafkaConsumer = kafkaConsumer; this.systemName = systemName; this.sink = messageSink; this.kafkaConsumerMetrics = samzaConsumerMetrics; this.metricName = metricName; this.clientId = clientId; this.kafkaConsumerMetrics.registerClientProxy(metricName); consumerPollThread = new Thread(createProxyThreadRunnable()); consumerPollThread.setDaemon(true); consumerPollThread.setName( "Samza KafkaConsumerProxy Poll " + consumerPollThread.getName() + " - " + systemName); LOG.info("Creating KafkaConsumerProxy with sn={}, clientId={}, metricsName={}", systemName, clientId, metricName); }

Target:
KafkaConsumerProxy(Consumer<K, V> kafkaConsumer, String systemName, String clientId, KafkaSystemConsumer.KafkaConsumerMessageSink messageSink, KafkaSystemConsumerMetrics samzaConsumerMetrics, String metricName) { this.kafkaConsumer = kafkaConsumer; this.systemName = systemName; this.sink = messageSink; this.kafkaConsumerMetrics = samzaConsumerMetrics; this.metricName = metricName; this.clientId = clientId; this.kafkaConsumerMetrics.registerClientProxy(metricName); consumerPollThread = new Thread(createProxyThreadRunnable()); consumerPollThread.setDaemon(true); consumerPollThread.setName( "Samza KafkaConsumerProxy Poll " + consumerPollThread.getName() + " - " + systemName); LOG.info("Creating KafkaConsumerProxy with systeName={}, clientId={}, metricsName={}", systemName, clientId, metricName); }
Source:
public Archive startArchive(String sessionId, ArchiveProperties properties) throws OpenTokException { if (sessionId == null || sessionId == "") { throw new InvalidArgumentException("Session not valid"); } Boolean hasResolution = properties != null && properties.resolution() != null && !properties.resolution().isEmpty(); if(properties != null && properties.outputMode().equals(Archive.OutputMode.INDIVIDUAL) && hasResolution) { throw new InvalidArgumentException("Resolution must not be specified in individual output mode."); } String archive = this.client.startArchive(sessionId, properties); try { return archiveReader.readValue(archive); } catch (Exception e) { throw new RequestException("Exception mapping json: " + e.getMessage()); } }

Target:
public Archive startArchive(String sessionId, ArchiveProperties properties) throws OpenTokException { if (sessionId == null || sessionId == "") { throw new InvalidArgumentException("Session not valid"); } Boolean hasResolution = properties != null && properties.resolution() != null && !properties.resolution().isEmpty(); if(properties != null && properties.outputMode().equals(Archive.OutputMode.INDIVIDUAL) && hasResolution) { throw new InvalidArgumentException("The resolution cannot be specified for individual output mode."); } String archive = this.client.startArchive(sessionId, properties); try { return archiveReader.readValue(archive); } catch (Exception e) { throw new RequestException("Exception mapping json: " + e.getMessage()); } }
Source:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { drive(toteDistance.get()); QuasarHelios.autoLoader.set(true); drive(autoZoneDistance.get()); drive(-returnDistance.get()); }

Target:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { collectTote(); turn(90); drive(autoZoneDistance.get()); drive(-returnDistance.get()); }
Source:
public ExternalDocumentation getExternalDocs(ObjectNode node, String location, ParseResult result) { ExternalDocumentation externalDocs = null; if (node != null) { externalDocs = new ExternalDocumentation(); Set<String> keys = getKeys(node); String value = getString("description", node, false, location, result); externalDocs.description(value); value = getString("url", node, true, location, result); externalDocs.url(value); externalDocs.setExtensions(new LinkedHashMap<>()); for (String key : keys) { if (key.startsWith("x-")) { externalDocs.getExtensions().put(key, Json.mapper().convertValue(node.get(key), Object.class)); } else if (!EXTERNAL_DOCS_KEYS.contains(key)) { result.extra(location + ".externalDocs", key, node.get(key)); } } } return externalDocs; }

Target:
public ExternalDocumentation getExternalDocs(ObjectNode node, String location, ParseResult result) { ExternalDocumentation externalDocs = null; if (node != null) { externalDocs = new ExternalDocumentation(); String value = getString("description", node, false, location, result); if(StringUtils.isNotBlank(value)) { externalDocs.description(value); } value = getString("url", node, true, location, result); if(StringUtils.isNotBlank(value)) { externalDocs.url(value); } Map <String,Object> extensions = getExtensions(node,location,result); if(extensions != null && extensions.size() > 0) { externalDocs.setExtensions(extensions); } } return externalDocs; }
Source:
private static SBIIndex readIndex(final InputStream in) { BinaryCodec binaryCodec = new BinaryCodec(in); Header header = readHeader(binaryCodec); long numOffsetsLong = binaryCodec.readLong(); if (numOffsetsLong > Integer.MAX_VALUE) { throw new RuntimeException(String.format("Cannot read SBI with more than %s offsets.", Integer.MAX_VALUE)); } int numOffsets = (int) numOffsetsLong; long[] virtualOffsets = new long[numOffsets]; long prev = -1; for (int i = 0; i < numOffsets; i++) { long cur = binaryCodec.readLong(); if (prev > cur) { throw new RuntimeException(String.format( "Invalid SBI; offsets not in order: %#x > %#x", prev, cur)); } virtualOffsets[i] = cur; prev = cur; } return new SBIIndex(header, virtualOffsets); }

Target:
private static SBIIndex readIndex(final InputStream in) { final BinaryCodec binaryCodec = new BinaryCodec(in); final Header header = readHeader(binaryCodec); final long numOffsetsLong = binaryCodec.readLong(); if (numOffsetsLong > Integer.MAX_VALUE) { throw new RuntimeException(String.format("Cannot read SBI with more than %s offsets.", Integer.MAX_VALUE)); } final int numOffsets = (int) numOffsetsLong; final long[] virtualOffsets = new long[numOffsets]; long prev = -1; for (int i = 0; i < numOffsets; i++) { final long cur = binaryCodec.readLong(); if (prev > cur) { throw new RuntimeException(String.format( "Invalid SBI; offsets not in order: %#x > %#x", prev, cur)); } virtualOffsets[i] = cur; prev = cur; } return new SBIIndex(header, virtualOffsets); }
Source:
public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired && nullsAllowed && presentStream != null) { nulls = ensureCapacity(nulls, positionCount); } if (!nullsAllowed || !nonNullsAllowed) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; outputPositionsReadOnly = true; } if (presentStream == null) { readNoNulls(offset, positions, positionCount); } else if (keyCount == 0) { readAllNulls(offset, positions, positionCount); } else { readWithNulls(offset, positions, positionCount); } localMemoryContext.setBytes(getRetainedSizeInBytes()); return outputPositionCount; }

Target:
public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired && nullsAllowed && presentStream != null) { nulls = ensureCapacity(nulls, positionCount); } if (!nullsAllowed || !nonNullsAllowed) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; outputPositionsReadOnly = true; } if (presentStream != null && keyCount == 0) { readAllNulls(positions, positionCount); } else { readNotAllNulls(offset, positions, positionCount); } localMemoryContext.setBytes(getRetainedSizeInBytes()); return outputPositionCount; }
Source:
public void testLoadingEmptyMetacards() { cmd = new SearchFormsManageCommand() { @Override protected List<Metacard> retrieveSystemMetacards() { return Collections.emptyList(); } }; cmd.massDeletion = true; cmd.executeWithSubject(); assertThat(this.getOutput(), containsString("No system forms exist.")); }

Target:
public void testLoadingEmptyMetacards() { when(endpointUtil.getMetacardListByTag(SYSTEM_TEMPLATE)).thenReturn(Collections.emptyList()); cmd.massDeletion = true; cmd.executeWithSubject(); assertThat(this.getOutput(), containsString("No system forms exist.")); }
Source:
public static SimpleResourceDefinition forDomain(final DelegatingConfigurableAuthorizer authorizer) { return forDomain(authorizer, null); }

Target:
public static SimpleResourceDefinition forDomain(final DelegatingConfigurableAuthorizer authorizer) { List<ResourceDefinition> interfaces = Collections.emptyList(); return new CoreManagementResourceDefinition(Environment.DOMAIN, authorizer, null, null, null, interfaces, null); }
Source:
for (int codePoint = 0; codePoint < MAX_CODE_POINT; codePoint++) { int type = Character.getType(codePoint); if (type != Character.UNASSIGNED && type != Character.SURROGATE) { LOWER_CODE_POINTS[codePoint] = Character.toLowerCase(codePoint); UPPER_CODE_POINTS[codePoint] = Character.toUpperCase(codePoint); WHITESPACE_CODE_POINTS[codePoint] = Character.isWhitespace(codePoint); } else { LOWER_CODE_POINTS[codePoint] = 0xFFFD; UPPER_CODE_POINTS[codePoint] = 0xFFFD; WHITESPACE_CODE_POINTS[codePoint] = false; } }

Target:
for (int codePoint = 0; codePoint < MAX_CODE_POINT; codePoint++) { int type = Character.getType(codePoint); if (type != Character.SURROGATE) { LOWER_CODE_POINTS[codePoint] = Character.toLowerCase(codePoint); UPPER_CODE_POINTS[codePoint] = Character.toUpperCase(codePoint); WHITESPACE_CODE_POINTS[codePoint] = Character.isWhitespace(codePoint); } else { LOWER_CODE_POINTS[codePoint] = REPLACEMENT_CODE_POINT; UPPER_CODE_POINTS[codePoint] = REPLACEMENT_CODE_POINT; WHITESPACE_CODE_POINTS[codePoint] = false; } }
Source:
private ConfigPersistenceService retrieveAndConfigureRuleCorePersistenceService() throws IOException { return getOsgiService(ConfigPersistenceService.class, "(configuration.id=RULE)", 30000L); }

Target:
private ConfigPersistenceService retrieveAndConfigureRuleCorePersistenceService() throws IOException { return getOsgiService(ConfigPersistenceService.class, String.format("(%s=%s)", Constants.CONFIGURATION_ID, RuleConfiguration.TYPE_ID), 30000L); }
Source:
public static void copyVmDevices(Guid srcId, Guid dstId) { Guid id; VmBase vmBase = DbFacade.getInstance().getVmStaticDAO().get(dstId); List<DiskImage> disks = DbFacade.getInstance().getDiskImageDAO().getAllForVm(dstId); List<VmNetworkInterface> ifaces; int diskCount=0; int ifaceCount=0; boolean isVm = (vmBase != null); if (isVm) { ifaces = DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForVm(dstId); } else { vmBase = DbFacade.getInstance().getVmTemplateDAO().get(dstId); ifaces = DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForTemplate(dstId); } List<VmDevice> devices = dao.getVmDeviceByVmId(srcId); for (VmDevice device : devices) { id = Guid.NewGuid(); String specParams = ""; if (srcId.equals(Guid.Empty)) { if (vmBase.getvm_type() == VmType.Desktop) { updateNumOfMonitorsInVmDevice(null, vmBase); } continue; } if (device.getType().equalsIgnoreCase(VmDeviceType.DISK.name()) && device.getDevice().equalsIgnoreCase(VmDeviceType.DISK.name())) { if (diskCount < disks.size()) { id = (disks.get(diskCount++)).getimage_group_id(); } } else if (device.getType().equalsIgnoreCase(VmDeviceType.INTERFACE.name())) { if (ifaceCount < ifaces.size()) { id = ifaces.get(ifaceCount++).getId(); } } else if (device.getType().equalsIgnoreCase(VmDeviceType.VIDEO.name())) { specParams = getMemExpr(vmBase.getnum_of_monitors()); } device.setId(new VmDeviceId(id, dstId)); device.setSpecParams(appendDeviceIdToSpecParams(id, specParams)); dao.save(device); } if (isVm) { updateBootOrderInVmDevice(vmBase); } }

Target:
public static void copyVmDevices(Guid srcId, Guid dstId) { Guid id; VmBase vmBase = DbFacade.getInstance().getVmStaticDAO().get(dstId); List<DiskImage> disks = DbFacade.getInstance().getDiskImageDAO().getAllForVm(dstId); List<VmNetworkInterface> ifaces; int diskCount = 0; int ifaceCount = 0; boolean isVm = (vmBase != null); if (isVm) { ifaces = DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForVm(dstId); } else { vmBase = DbFacade.getInstance().getVmTemplateDAO().get(dstId); ifaces = DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForTemplate(dstId); } List<VmDevice> devices = dao.getVmDeviceByVmId(srcId); for (VmDevice device : devices) { id = Guid.NewGuid(); String specParams = ""; if (srcId.equals(Guid.Empty)) { if (vmBase.getvm_type() == VmType.Desktop) { updateNumOfMonitorsInVmDevice(null, vmBase); } continue; } if (VmDeviceType.DISK.getName().equals(device.getType()) && VmDeviceType.DISK.getName().equals(device.getDevice())) { if (diskCount < disks.size()) { id = (disks.get(diskCount++)).getimage_group_id(); } } else if (VmDeviceType.INTERFACE.getName().equals(device.getType())) { if (ifaceCount < ifaces.size()) { id = ifaces.get(ifaceCount++).getId(); } } else if (VmDeviceType.VIDEO.getName().equals(device.getType())) { specParams = getMemExpr(vmBase.getnum_of_monitors()); } device.setId(new VmDeviceId(id, dstId)); device.setSpecParams(appendDeviceIdToSpecParams(id, specParams)); dao.save(device); } if (isVm) { updateBootOrderInVmDevice(vmBase); } }
Source:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { System.err.println(ERROR_PREFIX + "Failed getting user GUID"); return null; } }

Target:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { log.error(ERROR_PREFIX + "Failed getting user GUID"); return null; } }
Source:
public Map<String, Map<Partition, Map<String, Long>>> getStartTimeMap(String stateType) { return Collections .unmodifiableMap(_startTimeMap.getOrDefault(stateType, Collections.emptyMap())); }

Target:
private Map<String, Map<Partition, Map<String, Long>>> getStartTimeMap(String stateType) { return _startTimeMap.getOrDefault(stateType, Collections.emptyMap()); }
Source:
public List<Conflict> call() { final URL repoUrl = getCommandLocator().command(ResolveGeogitDir.class).call(); if (repoUrl == null) { return Collections.emptyList(); } else { getIndex().getDatabase().open(); return getIndex().getDatabase().getConflicts(null, null); } }

Target:
public List<Conflict> call() { final URL repoUrl = getCommandLocator().command(ResolveGeogitDir.class).call(); if (repoUrl == null) { return ImmutableList.of(); } else { return getIndex().getDatabase().getConflicts(null, null); } }
Source:
private static boolean typeIsByte(ExpressionTree expression) { if (expression.symbolType().isSubtypeOf("byte")) { return true; } if (expression.is(Tree.Kind.AND)) { BinaryExpressionTree and = (BinaryExpressionTree) expression; return isFFLiteral(and.rightOperand()) || isFFLiteral(and.leftOperand()); } return false; }

Target:
private static boolean typeIsByte(ExpressionTree expression) { return expression.symbolType().isSubtypeOf("byte") || ExpressionUtils.isSecuringByte(expression); }
Source:
public String persistenceId() { return "com.arpnetworking.metrics.portal.scheduling.JobCoordinator:" + "repositoryType=" + _repositoryType + "; " + "organizationId=" + _organization.getId(); }

Target:
public String persistenceId() { return String.format( "job-coordinator-%s", _repositoryType.getCanonicalName()); }
Source:
private void configureLoadListener() { JavaFxUtil.addListener(engine.getLoadWorker().stateProperty(), (observable, oldValue, newValue) -> { if (Worker.State.SUCCEEDED == newValue) { synchronized (waitingMessages) { waitingMessages.forEach(AbstractChatTabController.this::addMessage); waitingMessages.clear(); isChatReady = true; onWebViewLoaded(); } } }); }

Target:
private void configureLoadListener() { JavaFxUtil.addListener(engine.getLoadWorker().stateProperty(), (observable, oldValue, newValue) -> { if (newValue != Worker.State.SUCCEEDED) { return; } synchronized (waitingMessages) { waitingMessages.forEach(AbstractChatTabController.this::addMessage); waitingMessages.clear(); isChatReady = true; onWebViewLoaded(); } }); }
Source:
public ImmutableStaticScriptResourcesBuilder add(Collection<StaticScriptResource> toAdd) throws DuplicateResourceKeyException { for (Iterator<StaticScriptResource> it = toAdd.iterator(); it.hasNext();) { StaticScriptResource staticScriptResource = it.next(); String resourcePath = staticScriptResource.getResourcePath(); StaticScriptResource availableValue = staticScriptResources.get(resourcePath); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring " + StaticScriptResource.class.getSimpleName() + " " + staticScriptResource + " because the given resource path was already provided by " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding " + staticScriptResource); } staticScriptResources.put(resourcePath, staticScriptResource); } } return this; }

Target:
public ImmutableStaticScriptResourcesBuilder add(Collection<StaticScriptResource> toAdd) throws DuplicateResourceKeyException { for (StaticScriptResource staticScriptResource : toAdd) { String resourcePath = staticScriptResource.getResourcePath(); StaticScriptResource availableValue = staticScriptResources.get(resourcePath); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring " + StaticScriptResource.class.getSimpleName() + " " + staticScriptResource + " because the given resource path was already provided by " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding " + staticScriptResource); } staticScriptResources.put(resourcePath, staticScriptResource); } } return this; }
Source:
public static String validateTopic(String topic) { if (VALID_TOPIC_REGEXP.matcher(topic).matches()) { return topic; } String err = "Topic validation error: \"" + topic + "\" must be an alpha-numeric, colon-delimited string"; LOG.error(err); throw new IllegalArgumentException(err); }

Target:
public static String validateTopic(String topic) { if (VALID_TOPIC_REGEXP.matcher(topic).matches()) { return topic; } RuntimeException e = new IllegalArgumentException("\"" + topic + "\" must be an alpha-numeric, colon-delimited string"); LOG.error("Topic validation error:", e); throw e; }
Source:
public void testHostSwiftcopt() throws Exception { scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def swift_binary_impl(ctx):", " copts = ctx.fragments.swift.copts()", " return struct(", " copts=copts,", " )", "swift_binary = rule(", " implementation = swift_binary_impl,", " fragments = ['swift']", ")"); scratch.file("examples/swift_skylark/a.m"); scratch.file( "examples/swift_skylark/BUILD", "package(default_visibility = [' "load(' "swift_binary(", " name='my_target',", ")"); useConfiguration("--swiftcopt=foo", "--host_swiftcopt=bar", "--host_swiftcopt=baz"); ConfiguredTarget target = getConfiguredTarget(" @SuppressWarnings("unchecked") List<String> copts = (List<String>) target.get("copts"); assertThat(copts).doesNotContain("foo"); assertThat(copts).containsAllOf("bar", "baz"); }

Target:
public void testHostSwiftcopt() throws Exception { scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def swift_binary_impl(ctx):", " copts = ctx.fragments.swift.copts()", " return struct(", " copts=copts,", " )", "swift_binary = rule(", " implementation = swift_binary_impl,", " fragments = ['swift']", ")"); scratch.file( "examples/swift_skylark/BUILD", "load(' "swift_binary(", " name='my_target',", ")"); useConfiguration("--swiftcopt=foo", "--host_swiftcopt=bar", "--host_swiftcopt=baz"); ConfiguredTarget target = getConfiguredTarget(" @SuppressWarnings("unchecked") List<String> copts = (List<String>) target.get("copts"); assertThat(copts).doesNotContain("foo"); assertThat(copts).containsAllOf("bar", "baz"); }
Source:
@Override public void viewCreated(final boolean isTablet) { List<UiShowDetailItem> items = new ArrayList<>(); if (isTablet) { view.displayAboutData(show); } else { items.add(new UiShowDetailAbout()); } ArrayList<Integer> availableSeasons = getAvailableSeasons(); for (int season : availableSeasons) { items.add(new UiShowDetailSeason(season)); } view.displayData(show, items); }

Target:
@Override public void viewCreated(final boolean isTablet) { List<UiShowDetailItem> items = new ArrayList<>(); if (isTablet) { view.displayAboutData(show); } else { items.add(new UiShowDetailAbout()); } List<Integer> availableSeasons = getAvailableSeasons(); for (int season : availableSeasons) { items.add(new UiShowDetailSeason(season)); } view.displayData(show, items); }
Source:
private URI getFinalURI(final URI uri, final URI initialURI) { URI result = initialURI; if (null != uri && null != uri.fileExtension() && uri.fileExtension().equals("properties")) { final String lastSegment = initialURI.lastSegment(); final String withoutLocalization = LocaleUtil.trimLocalization(lastSegment); if (!lastSegment.equals(withoutLocalization)) { result = initialURI.trimSegments(1); result = result.appendSegment(withoutLocalization); } } return result; }

Target:
private URI getFinalURI(final URI uri, final URI initialURI) { URI result = initialURI; if (null != uri && null != uri.fileExtension() && uri.fileExtension().equals(PropertiesFilesUtils.PROPERTIES_FILE_EXTENSION)) { final String lastSegment = initialURI.lastSegment(); final String withoutLocalization = LocaleUtil.trimLocalization(lastSegment); if (!lastSegment.equals(withoutLocalization)) { result = initialURI.trimSegments(1); result = result.appendSegment(withoutLocalization); } } return result; }
Source:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup groupUUID : groupsToDelete) { preferences.remove( PREFS_GROUP_PREFIX + groupUUID.getUuid().toString()); groupMap.remove(groupUUID.getUuid()); } savePreferences(); }

Target:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup group : groupsToDelete) { preferences .remove(PREFS_GROUP_PREFIX + group.getGroupId().toString()); groupMap.remove(group.getGroupId()); } savePreferences(); }
Source:
public ZooKeeper connect(String host, int timeoutMillis) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Watcher w = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connected = true; latch.countDown(); } } }; try { zoo = new ZooKeeper(host, timeoutMillis, w, new HashSet<Long>()); latch.await(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (connected) { return zoo; } else { throw new RuntimeException("Could not connect to Zookeeper at host:" + host); } }

Target:
public ZooKeeper connect(String host, int timeoutMillis) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Watcher w = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connected = true; latch.countDown(); } } }; try { zk = new ZooKeeper(host, timeoutMillis, w, new HashSet<Long>()); latch.await(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (!connected) { throw new RuntimeException("Could not connect to Zookeeper at host:" + host); } return zk; }
Source:
public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, Objects.requireNonNull(name, "name == null"), null); }

Target:
public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, requireNonNull(name, "name == null"), null); }