auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<String, String> toPartitionParameters() { ImmutableMap.Builder<String, String> properties = ImmutableMap.builder(); fileCount.ifPresent(fileCount -> properties.put(NUM_FILES, Long.toString(fileCount))); rowCount.ifPresent(fileCount -> properties.put(NUM_ROWS, Long.toString(fileCount))); rawDataSize.ifPresent(fileCount -> properties.put(RAW_DATA_SIZE, Long.toString(fileCount))); totalSize.ifPresent(fileCount -> properties.put(TOTAL_SIZE, Long.toString(fileCount))); return properties.build(); }

Target:
public Map<String, String> toPartitionParameters() { ImmutableMap.Builder<String, String> properties = ImmutableMap.builder(); fileCount.ifPresent(count -> properties.put(NUM_FILES, Long.toString(count))); rowCount.ifPresent(count -> properties.put(NUM_ROWS, Long.toString(count))); inMemoryDataSizeInBytes.ifPresent(size -> properties.put(RAW_DATA_SIZE, Long.toString(size))); onDiskDataSizeInBytes.ifPresent(size -> properties.put(TOTAL_SIZE, Long.toString(size))); return properties.build(); }
Source:
private static List<AuthMethod> getAuthMethods(AgentProxy agent) throws Exception { Identity[] identities = agent.getIdentities(); List<AuthMethod> result = Lists.newArrayList(); for (Identity identity : identities) { result.add(new AuthAgent(agent, identity)); } return result; }

Target:
private static List<AuthMethod> getAuthMethods(AgentProxy agent) throws BufferException { ImmutableList.Builder<AuthMethod> identities = ImmutableList.builder(); for (Identity identity : agent.getIdentities()) { identities.add(new AuthAgent(agent, identity)); } return identities.build(); }
Source:
public void setValue(String content) { this.content = Optional.fromNullable(content); }

Target:
public void setValue(String content) { this.content = content; }
Source:
private AllSensorSampleList adjustTimeSeriesAllSensors (final AllSensorSampleList allSensorSampleList, final String senseId) { if (!this.hasDustSmoothEnabled(senseId)) { return allSensorSampleList; } final AllSensorSampleList adjustedAllSensorSampleList = new AllSensorSampleList(); adjustedAllSensorSampleList.add(Sensor.LIGHT, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.HUMIDITY, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.SOUND, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.TEMPERATURE, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.LIGHT, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.WAVE_COUNT, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.HOLD_COUNT, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.SOUND_NUM_DISTURBANCES, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.SOUND_PEAK_DISTURBANCE, allSensorSampleList.get(Sensor.LIGHT)); adjustedAllSensorSampleList.add(Sensor.PARTICULATES, SmoothSample.convert(allSensorSampleList.get(Sensor.PARTICULATES))); return adjustedAllSensorSampleList; }

Target:
private AllSensorSampleList adjustTimeSeriesAllSensors (final AllSensorSampleList allSensorSampleList, final String senseId) { if (!this.hasDustSmoothEnabled(senseId)) { return allSensorSampleList; } allSensorSampleList.update(Sensor.PARTICULATES, SmoothSample.convert(allSensorSampleList.get(Sensor.PARTICULATES))); return allSensorSampleList; }
Source:
private void preloadEventTypes(final EventTypeRepository eventTypeRepository, final TimelineDbRepository timelineRepository) { final long start = System.currentTimeMillis(); rwLock.writeLock().lock(); try { final Map<String, List<Timeline>> eventTypeTimelines = timelineRepository.listTimelines().stream() .collect(Collectors.groupingBy(Timeline::getEventType)); final List<Timeline> emptyList = Collections.unmodifiableList(new ArrayList<>()); final Map<String, CachedValue> preloaded = eventTypeRepository.list().stream().collect(Collectors.toMap( EventType::getName, et -> new CachedValue( et, EventValidation.forType(et), eventTypeTimelines.getOrDefault(et.getName(), emptyList)) )); final Iterator<Map.Entry<String, CachedValue>> it = preloaded.entrySet().iterator(); while (it.hasNext()) { String eventTypeName = null; try { eventTypeName = it.next().getKey(); created(eventTypeName); } catch (final Exception e) { LOG.error("Failed to create node for {}", eventTypeName, e); it.remove(); } } this.eventTypeCache.putAll(preloaded); LOG.info("Cache preload complete, load event types within ms", preloaded.size(), System.currentTimeMillis() - start); } finally { rwLock.writeLock().unlock(); } }

Target:
private void preloadEventTypes(final EventTypeRepository eventTypeRepository, final TimelineDbRepository timelineRepository) { final long start = System.currentTimeMillis(); rwLock.writeLock().lock(); try { final Map<String, List<Timeline>> eventTypeTimelines = timelineRepository.listTimelinesOrdered().stream() .collect(Collectors.groupingBy(Timeline::getEventType)); final List<Timeline> emptyList = ImmutableList.of(); final Map<String, CachedValue> preloaded = eventTypeRepository.list().stream().collect(Collectors.toMap( EventType::getName, et -> new CachedValue( et, EventValidation.forType(et), eventTypeTimelines.getOrDefault(et.getName(), emptyList)) )); final Iterator<Map.Entry<String, CachedValue>> it = preloaded.entrySet().iterator(); while (it.hasNext()) { String eventTypeName = null; try { eventTypeName = it.next().getKey(); created(eventTypeName); } catch (final Exception e) { LOG.error("Failed to create node for {}", eventTypeName, e); it.remove(); } } this.eventTypeCache.putAll(preloaded); LOG.info("Cache preload complete, load event types within ms", preloaded.size(), System.currentTimeMillis() - start); } finally { rwLock.writeLock().unlock(); } }
Source:
public static boolean processIsRunning(String hostname, int vmPid) throws ToolsCoreException { Object host = Tools.getInstance().invokeGetMonitoredHost(hostname); Object vmId = Tools.getInstance().invokeVmIdentifier(String.format(IToolsConstants.VM_IDENTIFIRER, vmPid)); try { Object monitoredVm = Tools.getInstance().invokeGetMonitoredVm(host, vmId); return monitoredVm != null; } catch(ToolsCoreException tce) { return false; } }

Target:
public static boolean processIsRunning(String hostname, int vmPid) throws ToolsCoreException { return processIsMonitorable(hostname, vmPid); }
Source:
public MockSerializationResult(Proxifier proxifier, XStreamBuilder xstreambuilder, GsonSerializerBuilder gsonBuilder) { super(proxifier); this.response = new MockHttpServletResponse(); this.extractor = new DefaultTypeNameExtractor(); this.xstreambuilder = xstreambuilder; this.gsonBuilder = gsonBuilder; this.environment = new NullEnvironment(); }

Target:
public MockSerializationResult(Proxifier proxifier, XStreamBuilder xstreambuilder, GsonSerializerBuilder gsonBuilder) { this(proxifier, xstreambuilder, gsonBuilder, new NullEnvironment()); }
Source:
public void onLinkClicked(QBAttachment qbAttachment, int position) { if (!TextUtils.isEmpty(qbAttachment.getUrl())) { AttachmentImageActivity.start(ChatActivity.this, qbAttachment.getUrl()); } else { String url = QBFile.getPrivateUrlForUID(qbAttachment.getId()); AttachmentImageActivity.start(ChatActivity.this, url); } }

Target:
public void onLinkClicked(QBAttachment qbAttachment, int position) { if (qbAttachment != null) { String url = QBFile.getPrivateUrlForUID(qbAttachment.getId()); AttachmentImageActivity.start(ChatActivity.this, url); } }
Source:
public boolean isSubtypeOf(Type superType) { if (((JavaType) superType).isTagged(TYPEVAR)) { return false; } if(erasure() == superType.erasure()) { if (((JavaType) superType).isParameterized()) { return checkSubstitutedTypesCompatibility((ParametrizedTypeJavaType) superType); } return true; } for (ClassJavaType classJavaType : symbol.superTypes()) { JavaType javaType = typeSubstitutionSolver.applySubstitution(classJavaType, this.typeSubstitution); if(javaType.isSubtypeOf(superType)) { return true; } } if (((JavaType) superType).isTagged(WILDCARD)) { return ((WildCardType) superType).isSubtypeOfBound(this); } return false; }

Target:
public boolean isSubtypeOf(Type superType) { if (((JavaType) superType).isTagged(TYPEVAR)) { return false; } if(erasure() == superType.erasure()) { if (((JavaType) superType).isParameterized()) { return checkSubstitutedTypesCompatibility((ParametrizedTypeJavaType) superType); } return true; } JavaType superclass = symbol.getSuperclass(); if(superclass != null) { superclass = typeSubstitutionSolver.applySubstitution(superclass, this.typeSubstitution); if(superclass.isSubtypeOf(superType)) { return true; } } for (JavaType superInterface : symbol.getInterfaces()) { superclass = typeSubstitutionSolver.applySubstitution(superInterface, this.typeSubstitution); if(superclass.isSubtypeOf(superType)) { return true; } } if (((JavaType) superType).isTagged(WILDCARD)) { return ((WildCardType) superType).isSubtypeOfBound(this); } return false; }
Source:
public void getExecutionLog(ProcessExecutionDetail executionDetail, OutputStream outputStream) { notNull(executionDetail, "executionDetail"); try { final File tempFile = createTempFile("execution", ".log"); tempFile.deleteOnExit(); InputStream response = restTemplate.execute(executionDetail.getLogLink(), HttpMethod.GET, noopRequestCallback, new FileResponseExtractor(tempFile)); FileCopyUtils.copy(response, outputStream); } catch (IOException | GoodDataException | RestClientException e) { throw new GoodDataException("Unable to get process execution log " + executionDetail.getLogLink(), e); } }

Target:
public void getExecutionLog(ProcessExecutionDetail executionDetail, OutputStream outputStream) { notNull(executionDetail, "executionDetail"); notNull(outputStream, "outputStream"); try { restTemplate.execute(executionDetail.getLogLink(), HttpMethod.GET, noopRequestCallback, new OutputStreamResponseExtractor(outputStream)); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to get process execution log " + executionDetail.getLogLink(), e); } }
Source:
public boolean equals(Object other) { EventListenerWrapper l2 = (EventListenerWrapper)other; return listener.equals(l2.listener); }

Target:
public boolean equals(Object other) { if (!(other instanceof EventListenerWrapper)) { return false; } EventListenerWrapper l2 = (EventListenerWrapper)other; return listener.equals(l2.listener); }
Source:
public void testWildcard(String tenantId, String unit) throws Exception { SearchResult entry; List<SearchResult> results; results = elasticIO.search(tenantId, "one.two.*"); List<Locator> locators = locatorMap.get(tenantId); assertEquals(locators.size(), results.size()); for (Locator locator : locators) { entry = new SearchResult(tenantId, locator.getMetricName(), unit); boolean isFound = false; for(SearchResult item : results){ if((StringUtils.isNotEmpty(item.getMetricName()) && item.getMetricName().equalsIgnoreCase(entry.getMetricName())) && (StringUtils.isNotEmpty(item.getTenantId()) && item.getTenantId().equalsIgnoreCase(entry.getTenantId()))){ isFound = true; break; } } Assert.assertTrue(isFound); } results = elasticIO.search(tenantId, "*.fourA.*"); assertEquals(NUM_PARENT_ELEMENTS * NUM_GRANDCHILD_ELEMENTS, results.size()); for (int x = 0; x < NUM_PARENT_ELEMENTS; x++) { for (int z = 0; z < NUM_GRANDCHILD_ELEMENTS; z++) { entry = createExpectedResult(tenantId, x, "A", z, unit); Assert.assertTrue(results.contains(entry)); } } results = elasticIO.search(tenantId, "*.three1*.four*.five2"); assertEquals(10 * CHILD_ELEMENTS.size(), results.size()); for (int x = 10; x < 20; x++) { for (String y : CHILD_ELEMENTS) { entry = createExpectedResult(tenantId, x, y, 2, unit); Assert.assertTrue(results.contains(entry)); } } }

Target:
public void testWildcard(String tenantId, String unit) throws Exception { SearchResult entry; List<SearchResult> results; results = elasticIO.search(tenantId, "one.two.*"); List<Locator> locators = locatorMap.get(tenantId); assertEquals(locators.size(), results.size()); for (Locator locator : locators) { entry = new SearchResult(tenantId, locator.getMetricName(), unit); Assert.assertTrue((results.contains(entry))); } results = elasticIO.search(tenantId, "*.fourA.*"); assertEquals(NUM_PARENT_ELEMENTS * NUM_GRANDCHILD_ELEMENTS, results.size()); for (int x = 0; x < NUM_PARENT_ELEMENTS; x++) { for (int z = 0; z < NUM_GRANDCHILD_ELEMENTS; z++) { entry = createExpectedResult(tenantId, x, "A", z, unit); Assert.assertTrue(results.contains(entry)); } } results = elasticIO.search(tenantId, "*.three1*.four*.five2"); assertEquals(10 * CHILD_ELEMENTS.size(), results.size()); for (int x = 10; x < 20; x++) { for (String y : CHILD_ELEMENTS) { entry = createExpectedResult(tenantId, x, y, 2, unit); Assert.assertTrue(results.contains(entry)); } } }
Source:
public static DirectoryEntry createDirectoryEntry(String directoryName, Map<String, String> properties) { DirectoryEntry entry = new DirectoryEntry(); entry.setProperties(properties); entry = CLIENT.directoryManager().directory(directoryName).createEntry(entry); addDirectoryEntryToDelete(directoryName, entry.getId()); return entry; }

Target:
public static String createDirectoryEntry(String directoryName, Map<String, String> properties) { DirectoryEntry entry = new DirectoryEntry(); entry.setProperties(properties); entry = CLIENT.directoryManager().directory(directoryName).createEntry(entry); String entryId = entry.getId(); addDirectoryEntryToDelete(directoryName, entryId); return entryId; }
Source:
public void testOverride() throws Exception { deployContrib("org.nuxeo.ecm.platform.usermanager.tests", "test-userservice-override-config.xml"); applyInlineDeployments(); postSetUp(); FakeUserManagerImpl fum = (FakeUserManagerImpl) userManager; assertEquals(Arrays.asList("tehroot", "bob", "bobette"), fum.defaultAdministratorIds); assertEquals(Arrays.asList("myAdministrators"), fum.administratorsGroups); assertEquals("id", userManager.getUserSortField()); assertEquals("search_only", userManager.getUserListingMode()); assertEquals("search_oh_yeah", userManager.getGroupListingMode()); assertEquals("defgr", userManager.getDefaultGroup()); assertEquals("sn", fum.groupSortField); assertNull(fum.anonymousUser); assertTrue(fum.virtualUsers.containsKey("MyCustomAdministrator")); VirtualUser customAdmin = fum.virtualUsers.get("MyCustomAdministrator"); assertNotNull(customAdmin); assertEquals("MyCustomAdministrator", customAdmin.getId()); assertEquals(1, customAdmin.getGroups().size()); assertTrue(customAdmin.getGroups().contains("administrators2")); assertEquals("secret2", customAdmin.getPassword()); Map<String, Serializable> props = new HashMap<String, Serializable>(); props.put("first", "My Custom 2"); props.put("last", "Administrator 2"); assertEquals(props, customAdmin.getProperties()); assertFalse(fum.virtualUsers.containsKey("MyCustomMember")); assertNull(fum.virtualUsers.get("MyCustomMember")); }

Target:
public void testOverride() throws Exception { pushInlineDeployments("org.nuxeo.ecm.platform.usermanager.tests:test-userservice-override-config.xml"); FakeUserManagerImpl fum = (FakeUserManagerImpl) userManager; assertEquals(Arrays.asList("tehroot", "bob", "bobette"), fum.defaultAdministratorIds); assertEquals(Arrays.asList("myAdministrators"), fum.administratorsGroups); assertEquals("id", userManager.getUserSortField()); assertEquals("search_only", userManager.getUserListingMode()); assertEquals("search_oh_yeah", userManager.getGroupListingMode()); assertEquals("defgr", userManager.getDefaultGroup()); assertEquals("sn", fum.groupSortField); assertNull(fum.anonymousUser); assertTrue(fum.virtualUsers.containsKey("MyCustomAdministrator")); VirtualUser customAdmin = fum.virtualUsers.get("MyCustomAdministrator"); assertNotNull(customAdmin); assertEquals("MyCustomAdministrator", customAdmin.getId()); assertEquals(1, customAdmin.getGroups().size()); assertTrue(customAdmin.getGroups().contains("administrators2")); assertEquals("secret2", customAdmin.getPassword()); Map<String, Serializable> props = new HashMap<>(); props.put("first", "My Custom 2"); props.put("last", "Administrator 2"); assertEquals(props, customAdmin.getProperties()); assertFalse(fum.virtualUsers.containsKey("MyCustomMember")); assertNull(fum.virtualUsers.get("MyCustomMember")); }
Source:
public static void setupTest() throws Exception { if (startCount++ > 0) { return; } addAppArtifact(APP_ARTIFACT_ID, ETLBatchApplication.class, BatchSource.class.getPackage().getName(), PipelineConfigurable.class.getPackage().getName(), "org.apache.avro.mapred", "org.apache.avro", "org.apache.avro.generic", "org.apache.avro.io", "parquet.hadoop.api", "parquet.hadoop", "parquet.schema", "parquet.io.api"); addPluginArtifact(Id.Artifact.from(Id.Namespace.DEFAULT, "batch-plugins", "1.0.0"), APP_ARTIFACT_ID, KVTableSource.class, StreamBatchSource.class, TableSource.class, TimePartitionedFileSetDatasetAvroSource.class, TimePartitionedFileSetDatasetParquetSource.class, AvroParquetInputFormat.class, BatchCubeSink.class, KVTableSink.class, TableSink.class, TimePartitionedFileSetDatasetAvroSink.class, AvroKeyOutputFormat.class, AvroKey.class, TimePartitionedFileSetDatasetParquetSink.class, AvroParquetOutputFormat.class, SnapshotFileBatchAvroSink.class, SnapshotFileBatchParquetSink.class, SnapshotFileBatchAvroSource.class, SnapshotFileBatchParquetSource.class, S3AvroBatchSink.class, S3ParquetBatchSink.class); addPluginArtifact(Id.Artifact.from(Id.Namespace.DEFAULT, "transforms", "1.0.0"), APP_ARTIFACT_ID, ProjectionTransform.class, ScriptFilterTransform.class, ValidatorTransform.class, CoreValidator.class, StructuredRecordToGenericRecordTransform.class, JavaScriptTransform.class, PythonEvaluator.class, PythonInterpreter.class); }

Target:
public static void setupTest() throws Exception { if (startCount++ > 0) { return; } addAppArtifact(APP_ARTIFACT_ID, ETLBatchApplication.class, BatchSource.class.getPackage().getName(), PipelineConfigurable.class.getPackage().getName(), "org.apache.avro.mapred", "org.apache.avro", "org.apache.avro.generic", "org.apache.avro.io", "parquet.hadoop.api", "parquet.hadoop", "parquet.schema", "parquet.io.api"); addPluginArtifact(Id.Artifact.from(Id.Namespace.DEFAULT, "batch-plugins", "1.0.0"), APP_ARTIFACT_ID, KVTableSource.class, StreamBatchSource.class, TableSource.class, TimePartitionedFileSetDatasetAvroSource.class, TimePartitionedFileSetDatasetParquetSource.class, AvroParquetInputFormat.class, BatchCubeSink.class, KVTableSink.class, TableSink.class, TimePartitionedFileSetDatasetAvroSink.class, AvroKeyOutputFormat.class, AvroKey.class, TimePartitionedFileSetDatasetParquetSink.class, AvroParquetOutputFormat.class, SnapshotFileBatchAvroSink.class, SnapshotFileBatchParquetSink.class, SnapshotFileBatchAvroSource.class, SnapshotFileBatchParquetSource.class, S3AvroBatchSink.class, S3ParquetBatchSink.class); addPluginArtifact(Id.Artifact.from(Id.Namespace.DEFAULT, "transforms", "1.0.0"), APP_ARTIFACT_ID, ProjectionTransform.class, ScriptFilterTransform.class, ValidatorTransform.class, CoreValidator.class, StructuredRecordToGenericRecordTransform.class, JavaScriptTransform.class, PythonEvaluator.class); }
Source:
public static final boolean isArrayAllZeros(final byte[] array) { int sum = 0; for (byte b : array) { sum |= b; } return sum == 0; }

Target:
public static final boolean isArrayAllZeros(final byte[] array) { return PlatformDependent.isZero(array, 0, array.length); }
Source:
void unsetSuccessAndSendWriteRequest(int bookieIndex) { if (toSend == null) { return; } DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId); try { if (!writeSet.contains(bookieIndex)) { lh.sendAddSuccessCallbacks(); return; } } finally { writeSet.recycle(); } if (callbackTriggered) { return; } LOG.info("Unsetting success for ledger: " + lh.ledgerId + " entry: " + entryId + " bookie index: " + bookieIndex); if (!ackSet.removeBookieAndCheck(bookieIndex)) { completed = false; } sendWriteRequest(bookieIndex); }

Target:
void unsetSuccessAndSendWriteRequest(int bookieIndex) { if (toSend == null) { return; } DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId); try { if (!writeSet.contains(bookieIndex)) { lh.sendAddSuccessCallbacks(); return; } } finally { writeSet.recycle(); } if (callbackTriggered) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Unsetting success for ledger: " + lh.ledgerId + " entry: " + entryId + " bookie index: " + bookieIndex); } if (!ackSet.removeBookieAndCheck(bookieIndex)) { completed = false; } sendWriteRequest(bookieIndex); }
Source:
public void testQueryParamAsFormParamDisabled() throws Exception { createServer(binder -> jaxrsBinder(binder).bind(FormParamResource.class), false); Request request = Request.builder() .setUri(uriBuilderFrom(server.getBaseUrl().resolve("/test")).addParameter("testParam", "foo").build()) .setMethod("POST") .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .build(); StringResponse response = client.execute(request, createStringResponseHandler()); assertEquals(response.getStatusCode(), Status.BAD_REQUEST.getStatusCode()); }

Target:
public void testQueryParamAsFormParamDisabled() throws Exception { createServer(binder -> jaxrsBinder(binder).bind(FormParamResource.class), false); Request request = Request.builder() .setUri(uriBuilderFrom(server.getBaseUrl().resolve("/test")).addParameter("testParam", "foo").build()) .setMethod("POST") .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .build(); StringResponse response = client.execute(request, createStringResponseHandler()); assertEquals(response.getStatusCode(), Status.OK.getStatusCode()); assertEquals(response.getBody(), "Empty param"); }
Source:
public List<Description> getTestRunsStarted() { return fTestRunsStarted; }

Target:
public List<Description> getTestRunsStarted() { return unmodifiableList(testRunsStarted); }
Source:
void initialize(SpellingService spellingService, WorkbenchListManager workbenchListManager, UIPrefs uiPrefs) { userDictionary_ = workbenchListManager.getUserDictionaryList(); uiPrefs_ = uiPrefs; ExternalJavaScriptLoader.Callback loadTypoCallback = () -> typoNative = new TypoNative("en_US"); new ExternalJavaScriptLoader(TypoResources.INSTANCE.typojs().getSafeUri().asString()).addCallback(loadTypoCallback); }

Target:
void initialize(SpellingService spellingService, WorkbenchListManager workbenchListManager, UIPrefs uiPrefs) { userDictionary_ = workbenchListManager.getUserDictionaryList(); uiPrefs_ = uiPrefs; loadDictionary(); }
Source:
private void onNewTemplate() { UnitVmModel model = (UnitVmModel) getWindow(); VM vm = getSelectedItem(); if (vm == null) { cancel(); return; } if (model.getProgress() != null) { return; } if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(); } else { String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmListModel<Void> vmListModel = (VmListModel<Void>) target; boolean isNameUnique = (Boolean) returnValue; if (!isNameUnique) { UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow(); VmModel.getInvalidityReasons().clear(); VmModel.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); VmModel.getName().setIsValid(false); VmModel.setIsValid(false); } else { vmListModel.postNameUniqueCheck(); } } }), name, model.getDataCenterWithClustersList().getSelectedItem().getDataCenter().getId()); } }

Target:
private void onNewTemplate() { UnitVmModel model = (UnitVmModel) getWindow(); VM vm = getSelectedItem(); if (vm == null) { cancel(); return; } if (model.getProgress() != null) { return; } if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(); } else { String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmListModel<Void> vmListModel = (VmListModel<Void>) target; boolean isNameUnique = (Boolean) returnValue; if (!isNameUnique) { UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow(); VmModel.getInvalidityReasons().clear(); VmModel.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); VmModel.getName().setIsValid(false); VmModel.setIsValid(false); } else { vmListModel.postNameUniqueCheck(); } } }), name, model.getSelectedDataCenter().getId()); } }
Source:
public int readDataBlocking(byte[] buffer) throws IOException { int readBytes = 0; if (getInputStream() != null) readBytes = getInputStream().read(buffer); return readBytes; }

Target:
public int readDataBlocking(byte[] buffer) throws IOException { if (buffer == null) throw new NullPointerException("Buffer cannot be null."); int readBytes = 0; if (getInputStream() != null) readBytes = getInputStream().read(buffer); return readBytes; }
Source:
public void onGetSmeltingExperience(ItemStack stack, CallbackInfoReturnable<Float> cir) { ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack); Optional<SmeltingResult> result = getCustomResult(ingredient); if (result.isPresent()) { float nativeResult = (float) result.get().getExperience(); cir.setReturnValue(nativeResult); } }

Target:
private void onGetSmeltingExperience(ItemStack stack, CallbackInfoReturnable<Float> cir) { ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack); Optional<SmeltingResult> result = getCustomResult(ingredient); if (result.isPresent()) { float nativeResult = (float) result.get().getExperience(); cir.setReturnValue(nativeResult); } }
Source:
protected void performDefaults() { IPreferenceStore store = getPreferenceStore(); saveInterval.loadDefault(); stickyCycleButton.setSelection(store.getBoolean(IPreferenceConstants.STICKY_CYCLE)); openOnSingleClick = store.getDefaultBoolean(IPreferenceConstants.OPEN_ON_SINGLE_CLICK); selectOnHover = store.getDefaultBoolean(IPreferenceConstants.SELECT_ON_HOVER); openAfterDelay = store.getDefaultBoolean(IPreferenceConstants.OPEN_AFTER_DELAY); singleClickButton.setSelection(openOnSingleClick); doubleClickButton.setSelection(!openOnSingleClick); selectOnHoverButton.setSelection(selectOnHover); openAfterDelayButton.setSelection(openAfterDelay); selectOnHoverButton.setEnabled(openOnSingleClick); openAfterDelayButton.setEnabled(openOnSingleClick); stickyCycleButton.setSelection(store.getDefaultBoolean(IPreferenceConstants.STICKY_CYCLE)); showUserDialogButton.setSelection(store.getDefaultBoolean(IPreferenceConstants.RUN_IN_BACKGROUND)); showHeapStatusButton.setSelection( PrefUtil.getAPIPreferenceStore().getDefaultBoolean(IWorkbenchPreferenceConstants.SHOW_MEMORY_MONITOR)); renameModeInline = true; renameModeInlineButton.setSelection(renameModeInline); renameModeDialogButton.setSelection(!renameModeInline); super.performDefaults(); }

Target:
protected void performDefaults() { IPreferenceStore store = getPreferenceStore(); saveInterval.loadDefault(); stickyCycleButton.setSelection(store.getBoolean(IPreferenceConstants.STICKY_CYCLE)); openOnSingleClick = store.getDefaultBoolean(IPreferenceConstants.OPEN_ON_SINGLE_CLICK); selectOnHover = store.getDefaultBoolean(IPreferenceConstants.SELECT_ON_HOVER); openAfterDelay = store.getDefaultBoolean(IPreferenceConstants.OPEN_AFTER_DELAY); singleClickButton.setSelection(openOnSingleClick); doubleClickButton.setSelection(!openOnSingleClick); selectOnHoverButton.setSelection(selectOnHover); openAfterDelayButton.setSelection(openAfterDelay); selectOnHoverButton.setEnabled(openOnSingleClick); openAfterDelayButton.setEnabled(openOnSingleClick); stickyCycleButton.setSelection(store.getDefaultBoolean(IPreferenceConstants.STICKY_CYCLE)); showUserDialogButton.setSelection(store.getDefaultBoolean(IPreferenceConstants.RUN_IN_BACKGROUND)); showHeapStatusButton.setSelection( PrefUtil.getAPIPreferenceStore().getDefaultBoolean(IWorkbenchPreferenceConstants.SHOW_MEMORY_MONITOR)); String defaultRenameMode = store.getDefaultString(IWorkbenchPreferenceConstants.RESOURCE_RENAME_MODE); renameModeInline = !IWorkbenchPreferenceConstants.RESOURCE_RENAME_MODE_DIALOG.equals(defaultRenameMode); renameModeInlineButton.setSelection(renameModeInline); renameModeDialogButton.setSelection(!renameModeInline); super.performDefaults(); }
Source:
private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().replacePath("/v1/statement").path(queryId.toString()).path(String.valueOf(resultId.incrementAndGet())).replaceQuery("").scheme(scheme).build(); }

Target:
private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo) { return uriInfo.getBaseUriBuilder() .scheme(scheme) .replacePath("/v1/statement") .path(queryId.toString()) .path(String.valueOf(resultId.incrementAndGet())) .replaceQuery("") .build(); }
Source:
public void logCurrentState() { bareLockRpcClient.currentTimeMillis(); }

Target:
public void logCurrentState() { namespaceAgnosticLockRpcClient.logCurrentState(); }
Source:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); for (TableColumn viewColumn : fTable.getColumns()) { TmfEventTableColumn column = columns.get((int) viewColumn.getData(Key.INDEX)); ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } } return itemStrings.toArray(new String[itemStrings.size()]); } }

Target:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { Map<TmfEventTableColumn , String> itemStrings = new HashMap<>(); for (TableColumn viewColumn : fTable.getColumns()) { TmfEventTableColumn column = columns.get((int) viewColumn.getData(Key.INDEX)); ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.put(column ,EMPTY_STRING); } else { itemStrings.put(column ,column.getItemString(passedEvent)); } } String[] displayStrings = new String[columns.size()]; int i = 0; for (TmfEventTableColumn column : columns) { displayStrings[i] = itemStrings.get(column); i++; } return displayStrings; } }
Source:
public void testDeleteLoadBalancer() throws SerializationException, StateAccessException, MappingStatusException, Rule.RuleIndexOutOfBoundsException { String path = pb.getPoolHealthMonitorMappingsPath(pool.id, healthMonitor.id); Assert.assertTrue(this.zk.exists(path)); UUID lbId = this.dataClient.loadBalancersGetAll().get(0).getId(); this.dataClient.loadBalancerDelete(lbId); Assert.assertFalse(this.zk.exists(path)); }

Target:
public void testDeleteLoadBalancer() throws SerializationException, StateAccessException, MappingStatusException, Rule.RuleIndexOutOfBoundsException { String path = pb.getPoolHealthMonitorMappingsPath(pool.id, healthMonitor.id); Assert.assertTrue(zk.exists(path)); Assert.assertTrue(dataClient.loadBalancersGetAll().size() == 1); UUID lbId = dataClient.poolGet(pool.id).getLoadBalancerId(); dataClient.loadBalancerDelete(lbId); Assert.assertFalse(zk.exists(path)); Assert.assertNull(dataClient.poolGet(pool.id)); Assert.assertNull(dataClient.healthMonitorGet(healthMonitor.id)); }
Source:
public final Response createFolders(@Context final HttpServletRequest httpServletRequest, @Context final HttpServletResponse httpServletResponse, final List<String> paths, @PathParam("siteName") final String siteName) { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(httpServletRequest, httpServletResponse) .init(); final User user = initData.getUser(); try { final List<Map<String, Object>> createdFolders = folderHelper.createFolders(paths, siteName, user); return Response.ok(new ResponseEntityView(createdFolders)).build(); } catch (Exception e) { Logger.error(this.getClass(),"Exception saving/creating folders.", e); return ResponseUtil.mapExceptionResponse(e); } }

Target:
public final Response createFolders(@Context final HttpServletRequest httpServletRequest, @Context final HttpServletResponse httpServletResponse, final List<String> paths, @PathParam("siteName") final String siteName) throws DotSecurityException, DotDataException { final InitDataObject initData = new WebResource.InitBuilder(webResource) .requiredBackendUser(true) .requiredFrontendUser(false) .requestAndResponse(httpServletRequest, httpServletResponse) .init(); final User user = initData.getUser(); final List<Map<String, Object>> createdFolders = folderHelper.createFolders(paths, siteName, user); return Response.ok(new ResponseEntityView(createdFolders)).build(); }
Source:
private void checkAndHandleChannelOnGateway(final SmartMeter gateway, final MbusChannelElementsResponseDto mbusChannelElementsResponseDto) throws FunctionalException { final List<SmartMeter> alreadyCoupled = this.smartMeteringDeviceRepository .getMbusDevicesForGateway(gateway.getId()); for (final SmartMeter coupledDevice : alreadyCoupled) { if (this.allReadyCoupledWithOtherDevice(gateway, coupledDevice, mbusChannelElementsResponseDto)) { LOGGER.info("There is already an M-bus device coupled to gateway on channel {}", coupledDevice.getDeviceIdentification(), gateway.getDeviceIdentification(), coupledDevice.getChannel()); throw new FunctionalException(FunctionalExceptionType.CHANNEL_ON_DEVICE_ALREADY_COUPLED, ComponentType.DOMAIN_SMART_METERING, new ChannelAlreadyOccupiedException(coupledDevice.getChannel())); } } }

Target:
private void checkAndHandleChannelOnGateway(final SmartMeter gateway, final MbusChannelElementsResponseDto mbusChannelElementsResponseDto) throws FunctionalException { final List<SmartMeter> alreadyCoupled = this.smartMeteringDeviceRepository .getMbusDevicesForGateway(gateway.getId()); for (final SmartMeter coupledDevice : alreadyCoupled) { if (this.allReadyCoupledWithOtherDevice(coupledDevice, mbusChannelElementsResponseDto)) { LOGGER.warn("There is already an M-bus device coupled to gateway on channel {}, handling {}", coupledDevice.getDeviceIdentification(), gateway.getDeviceIdentification(), coupledDevice.getChannel(), mbusChannelElementsResponseDto); throw new FunctionalException(FunctionalExceptionType.CHANNEL_ON_DEVICE_ALREADY_COUPLED, ComponentType.DOMAIN_SMART_METERING, new ChannelAlreadyOccupiedException(coupledDevice.getChannel())); } } }
Source:
public TwitterDocument next() { TwitterDocument doc = new TwitterDocument(); String raw = null; try { raw = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (raw == null) { atEOF = true; return null; } try { doc = (TwitterDocument) doc.readNextRecord(raw); if (doc == null) { return null; } } catch (IOException e) { e.printStackTrace(); } return doc; }

Target:
public TwitterDocument next() { TwitterDocument doc = new TwitterDocument(); String raw = null; try { raw = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); doc = null; } if (raw == null) { atEOF = true; return null; } try { doc = (TwitterDocument) doc.readNextRecord(raw, keepRetweets); if (doc == null) { return null; } } catch (IOException e) { e.printStackTrace(); doc = null; } return doc; }
Source:
public void handleGET(CoapExchange exchange) { StringBuilder payload = new StringBuilder(); Request request = exchange.advanced().getRequest(); payload.append(String.format("Type: %d (%s)\nCode: %d (%s)\nMID: %d", request.getType().value, request.getType(), request.getCode().value, request.getCode(), request.getMID())); if (request.getToken() != null) { payload.append("\nToken: "); if (request.hasEmptyToken()) { payload.append("[]"); } else { for (byte b : request.getTokenBytes()) payload.append(String.format("%02x", b & 0xff)); } } if (payload.length() > 64) { payload.delete(62, payload.length()); payload.append('»'); } exchange.setMaxAge(30); exchange.respond(CONTENT, payload.toString(), TEXT_PLAIN); }

Target:
public void handleGET(CoapExchange exchange) { StringBuilder payload = new StringBuilder(); Request request = exchange.advanced().getRequest(); payload.append(String.format("Type: %d (%s)\nCode: %d (%s)\nMID: %d", request.getType().value, request.getType(), request.getCode().value, request.getCode(), request.getMID())); if (request.getToken() != null) { payload.append("\nToken: "); payload.append(request.getTokenString()); } if (payload.length() > 64) { payload.delete(62, payload.length()); payload.append('»'); } exchange.setMaxAge(30); exchange.respond(CONTENT, payload.toString(), TEXT_PLAIN); }
Source:
public Response getContentTypeFieldById(@PathParam("typeId") final String typeId, @PathParam("fieldId") final String fieldId, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { Response response = null; try { Field field = fieldAPI.find(fieldId); response = Response.ok(new ResponseEntityView(new JsonFieldTransformer(field).mapObject())).build(); } catch (Exception e) { response = ResponseUtil.mapExceptionResponse(e); } return response; }

Target:
public Response getContentTypeFieldById(@PathParam("typeId") final String typeId, @PathParam("fieldId") final String fieldId, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { this.webResource.init(null, false, req, false, null); Response response = null; try { final Field field = fieldAPI.find(fieldId); response = Response.ok(new ResponseEntityView(new JsonFieldTransformer(field).mapObject())).build(); } catch (Exception e) { response = ResponseUtil.mapExceptionResponse(e); } return response; }
Source:
public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { RemoveAllPRMessage message = spy(new RemoveAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); try { message.doLocalRemoveAll(partitionedRegion, mock(InternalDistributedMember.class), true); fail("Expect PrimaryBucketException"); } catch (Exception e) { assertThat(e instanceof PrimaryBucketException); } InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }

Target:
public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { RemoveAllPRMessage message = spy(new RemoveAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); assertThatThrownBy(() -> message.doLocalRemoveAll(partitionedRegion, mock(InternalDistributedMember.class), true)).isInstanceOf(PrimaryBucketException.class); InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }
Source:
public String toString() { if (parameters != null) { String parity = "N"; String flowControl = "N"; if (parameters.parity == 1) parity = "O"; else if (parameters.parity == 2) parity = "E"; else if (parameters.parity == 3) parity = "M"; else if (parameters.parity == 4) parity = "S"; if (parameters.flowControl == 1 || parameters.flowControl == 2 || parameters.flowControl == 3) flowControl = "H"; else if (parameters.flowControl == 4 || parameters.flowControl == 8 || parameters.flowControl == 12) flowControl = "S"; return port.toString() + " - " + baudRate + "/" + parameters.dataBits + "/" + parity + "/" + parameters.stopBits + "/" + flowControl; } else return port.toString() + " - " + baudRate + "/8/N/1/N"; }

Target:
public String toString() { if (parameters != null) { String parity = "N"; String flowControl = "N"; if (parameters.parity == 1) parity = "O"; else if (parameters.parity == 2) parity = "E"; else if (parameters.parity == 3) parity = "M"; else if (parameters.parity == 4) parity = "S"; if (parameters.flowControl == 1 || parameters.flowControl == 2 || parameters.flowControl == 3) flowControl = "H"; else if (parameters.flowControl == 4 || parameters.flowControl == 8 || parameters.flowControl == 12) flowControl = "S"; return port + " - " + baudRate + "/" + parameters.dataBits + "/" + parity + "/" + parameters.stopBits + "/" + flowControl; } else return port + " - " + baudRate + "/8/N/1/N"; }
Source:
public RiakResponse head(String bucket, String key, FetchMeta fm) throws IOException { if(fm != null) { fm = new FetchMeta(fm.getR(), fm.getPr(), fm.getNotFoundOK(), fm.getBasicQuorum(), true, fm.getReturnDeletedVClock(), fm.getIfModifiedSince(), fm.getIfModifiedVClock()); } else { fm = FetchMeta.head(); } return fetch(bucket, key, fm); }

Target:
public RiakResponse head(String bucket, String key, FetchMeta fm) throws IOException { if(fm != null) { fm = FetchMeta.Builder.from(fm).headOnly(true).build(); } else { fm = FetchMeta.head(); } return fetch(bucket, key, fm); }
Source:
public void assertEmptyErrorListConstructorFailure() throws Exception { try { new MultipleFailureException(Collections.<Throwable>emptyList()); fail(); } catch (Exception expected) { assertThat(expected, instanceOf(IllegalArgumentException.class)); assertTrue(expected.getMessage().equals("Argument error list cannot be empty")); } }

Target:
public void assertEmptyErrorListConstructorFailure() throws Exception { try { new MultipleFailureException(Collections.<Throwable>emptyList()); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), containsString("Argument error list cannot be empty")); } }
Source:
private CompletableFuture<Boolean> addRepository() { TextInputDialog dialog = new TextInputDialog(); dialog.setHeaderText("Add a new repository"); dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> { String repositoryId = Utility.removeAllWhitespace(newValue); if (!repositoryId.equals(newValue)) { dialog.getEditor().setText(repositoryId); return; } }); Optional<String> userInput = dialog.showAndWait(); if (!userInput.isPresent()) { return Futures.unit(false); } String repoId = userInput.get(); return repoValidator.apply(repoId) .thenCompose(valid -> { if (!valid) { Platform.runLater(() -> DialogMessage.showErrorDialog("Cannot add to repository list", repoId + " is not a valid GitHub repository.")); return Futures.unit(false); } Platform.runLater(() -> addRepositoryToState(repoId)); return Futures.unit(true); }).exceptionally(e -> { Platform.runLater(() -> DialogMessage.showErrorDialog("Error checking the validity of " + repoId, "Please try again.")); return withResult(false).apply(e); }); }

Target:
private CompletableFuture<Boolean> addRepository() { TextInputDialog dialog = new TextInputDialog(); dialog.setHeaderText("Add a new repository"); dialog.getEditor().textProperty().addListener((observable, oldValue, newValue) -> { String repositoryId = Utility.removeAllWhitespace(newValue); if (!repositoryId.equals(newValue)) { dialog.getEditor().setText(repositoryId); return; } }); Optional<String> userInput = dialog.showAndWait(); if (!userInput.isPresent()) { return CompletableFuture.completedFuture(false); } String repoId = userInput.get(); return repoValidator.apply(repoId) .thenCompose(valid -> { if (!valid) { Platform.runLater(() -> DialogMessage.showErrorDialog("Cannot add to repository list", repoId + " is not a valid GitHub repository.")); return Futures.unit(false); } Platform.runLater(() -> addRepositoryToState(repoId)); return CompletableFuture.completedFuture(true); }).exceptionally(e -> { Platform.runLater(() -> DialogMessage.showErrorDialog("Error checking the validity of " + repoId, "Please try again.")); return withResult(false).apply(e); }); }
Source:
public Configuration getWorkerServiceConfiguration(final String contextId) { return Tang.Factory.getTang() .newConfigurationBuilder(ServiceConfiguration.CONF .set(ServiceConfiguration.SERVICES, staleness > 0 ? SSPParameterWorkerImpl.class : ParameterWorkerImpl.class) .set(ServiceConfiguration.ON_TASK_STARTED, TaskStartHandler.class) .set(ServiceConfiguration.ON_TASK_STOP, TaskStopHandler.class) .build()) .bindImplementation(ParameterWorker.class, staleness > 0 ? SSPParameterWorkerImpl.class : ParameterWorkerImpl.class) .bindImplementation(AsyncWorkerHandler.class, AsyncWorkerHandlerImpl.class) .bindImplementation(ServerResolver.class, DynamicServerResolver.class) .bindNamedParameter(NumServers.class, Integer.toString(numServers)) .bindNamedParameter(NumPartitions.class, Integer.toString(numPartitions)) .bindNamedParameter(EndpointId.class, contextId) .bindNamedParameter(ParameterWorkerNumThreads.class, Integer.toString(workerNumThreads)) .bindNamedParameter(WorkerQueueSize.class, Integer.toString(workerQueueSize)) .bindNamedParameter(WorkerExpireTimeout.class, Long.toString(workerExpireTimeout)) .bindNamedParameter(WorkerKeyCacheSize.class, Integer.toString(workerKeyCacheSize)) .bindNamedParameter(WorkerLogPeriod.class, Long.toString(workerLogPeriod)) .build(); }

Target:
public Configuration getWorkerServiceConfiguration(final String contextId) { return Tang.Factory.getTang() .newConfigurationBuilder(ServiceConfiguration.CONF .set(ServiceConfiguration.SERVICES, staleness < 0 ? ParameterWorkerImpl.class : SSPParameterWorkerImpl.class) .set(ServiceConfiguration.ON_TASK_STARTED, TaskStartHandler.class) .set(ServiceConfiguration.ON_TASK_STOP, TaskStopHandler.class) .build()) .bindImplementation(ParameterAccessor.class, SSPParameterAccessorImpl.class) .bindImplementation(ParameterWorker.class, staleness < 0 ? ParameterWorkerImpl.class : SSPParameterWorkerImpl.class) .bindImplementation(AsyncWorkerHandler.class, AsyncWorkerHandlerImpl.class) .bindImplementation(ServerResolver.class, DynamicServerResolver.class) .bindNamedParameter(NumServers.class, Integer.toString(numServers)) .bindNamedParameter(NumPartitions.class, Integer.toString(numPartitions)) .bindNamedParameter(EndpointId.class, contextId) .bindNamedParameter(ParameterWorkerNumThreads.class, Integer.toString(workerNumThreads)) .bindNamedParameter(WorkerQueueSize.class, Integer.toString(workerQueueSize)) .bindNamedParameter(WorkerExpireTimeout.class, Long.toString(workerExpireTimeout)) .bindNamedParameter(PullRetryTimeoutMs.class, Long.toString(pullRetryTimeoutMs)) .bindNamedParameter(WorkerKeyCacheSize.class, Integer.toString(workerKeyCacheSize)) .bindNamedParameter(WorkerLogPeriod.class, Long.toString(workerLogPeriod)) .build(); }