auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static <S> S createService(Class<S> serviceClass, String username, String password) { if (username != null && password != null) { String credentials = username + ":" + password; final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); httpClient.addInterceptor(chain -> { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .header("Authorization", basic) .header("Accept", "application/json") .method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); }); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(new SnooperInterceptor()); httpClient.addInterceptor(logging); } OkHttpClient client = httpClient.build(); Retrofit retrofit = builder.client(client).build(); return retrofit.create(serviceClass); }

Target:
public static <S> S createService(Class<S> serviceClass, String username, String password) { if (username != null && password != null) { String credentials = username + ":" + password; final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); httpClient.addNetworkInterceptor(chain -> { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .header("Authorization", basic) .header("Accept", "application/json") .method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); }); httpClient.addNetworkInterceptor(new ChuckInterceptor(OpenMRS.getInstance())); } OkHttpClient client = httpClient.build(); Retrofit retrofit = builder.client(client).build(); return retrofit.create(serviceClass); }
Source:
private void cleanupExpiredInflightRequests() { Iterator<Map.Entry<Integer, DeleteRequestInfo>> itr = deleteRequestInfos.entrySet().iterator(); while (itr.hasNext()) { DeleteRequestInfo deleteRequestInfo = itr.next().getValue(); if (time.milliseconds() - deleteRequestInfo.startTimeMs > routerConfig.routerRequestTimeoutMs) { itr.remove(); ReplicaId replica = deleteRequestInfo.replica; DataNodeId dataNodeId = replica.getDataNodeId(); NonBlockingRouterMetrics.NodeLevelMetrics dataNodeBasedMetrics = routerMetrics.getDataNodeBasedMetrics(dataNodeId); dataNodeBasedMetrics.deleteRequestTimeoutCount.inc(); dataNodeBasedMetrics.deleteRequestErrorCount.inc(); dataNodeBasedMetrics.countError(RouterErrorCode.OperationTimedOut); updateOperationState(deleteRequestInfo.replica, RouterErrorCode.OperationTimedOut); } } }

Target:
private void cleanupExpiredInflightRequests() { Iterator<Map.Entry<Integer, DeleteRequestInfo>> itr = deleteRequestInfos.entrySet().iterator(); while (itr.hasNext()) { DeleteRequestInfo deleteRequestInfo = itr.next().getValue(); if (time.milliseconds() - deleteRequestInfo.startTimeMs > routerConfig.routerRequestTimeoutMs) { itr.remove(); NonBlockingRouterMetrics.NodeLevelMetrics dataNodeBasedMetrics = routerMetrics.getDataNodeBasedMetrics(deleteRequestInfo.replica.getDataNodeId()); dataNodeBasedMetrics.deleteRequestErrorCount.inc(); updateOperationState(deleteRequestInfo.replica, RouterErrorCode.OperationTimedOut); } } }
Source:
private void logDataspacesStatus(String message, DataspacesStatusLevel level) { final String eol = System.lineSeparator(); final boolean hasEol = message.endsWith(eol); if (taskLogger != null && level == DataspacesStatusLevel.ERROR) { taskLogger.getErrorSink().println("[DATASPACES-ERROR] " + message + (hasEol ? "" : eol)); } else if (taskLogger != null && level == DataspacesStatusLevel.WARNING) { taskLogger.getErrorSink().println("[DATASPACES-WARNING] " + message + (hasEol ? "" : eol)); } else if (taskLogger != null && level == DataspacesStatusLevel.INFO) { taskLogger.getOutputSink().println("[DATASPACES-INFO] " + message + (hasEol ? "" : eol)); } }

Target:
private void logDataspacesStatus(String message, DataspacesStatusLevel level) { final String eol = System.lineSeparator(); final boolean hasEol = message.endsWith(eol); if (taskLogger != null) { switch (level) { case ERROR: taskLogger.getErrorSink().print("[DATASPACES-ERROR] " + message + (hasEol ? "" : eol)); taskLogger.getErrorSink().flush(); break; case WARNING: taskLogger.getErrorSink().print("[DATASPACES-WARNING] " + message + (hasEol ? "" : eol)); taskLogger.getErrorSink().flush(); break; case INFO: taskLogger.getOutputSink().print("[DATASPACES-INFO] " + message + (hasEol ? "" : eol)); taskLogger.getOutputSink().flush(); break; } } }
Source:
public void coordinateByHitIndex() { final Comparator<SAMRecord> comparator = Comparator.comparing( record -> record.getIntegerAttribute(SAMTag.HI.name()), Comparator.nullsLast(Comparator.naturalOrder()) ); firstOfPairOrFragment.sort(comparator); secondOfPair.sort(comparator); for (int i = 0; i < Math.min(firstOfPairOrFragment.size(), secondOfPair.size()); ++i) { final Integer hiTagValueOfFirst = firstOfPairOrFragment.get(i).getIntegerAttribute(SAMTag.HI.name()); final Integer hiTagValueOfSecond = secondOfPair.get(i).getIntegerAttribute(SAMTag.HI.name()); if (nonNull(hiTagValueOfFirst) && nonNull(hiTagValueOfSecond)) { if (hiTagValueOfFirst < hiTagValueOfSecond) secondOfPair.add(i, null); else if (hiTagValueOfSecond < hiTagValueOfFirst) firstOfPairOrFragment.add(i, null); } if (isNull(hiTagValueOfFirst) && nonNull(hiTagValueOfSecond)) firstOfPairOrFragment.add(i, null); if (isNull(hiTagValueOfFirst) && isNull(hiTagValueOfSecond)) secondOfPair.add(i, null); } renumberHitIndex(); }

Target:
public void coordinateByHitIndex() { final Comparator<SAMRecord> comparator = Comparator.comparing( record -> record.getIntegerAttribute(SAMTag.HI.name()), Comparator.nullsLast(Comparator.naturalOrder()) ); firstOfPairOrFragment.sort(comparator); secondOfPair.sort(comparator); for (int i = 0; i < Math.min(firstOfPairOrFragment.size(), secondOfPair.size()); ++i) { final Integer leftHi = firstOfPairOrFragment.get(i).getIntegerAttribute(SAMTag.HI.name()); final Integer rightHi = secondOfPair.get(i).getIntegerAttribute(SAMTag.HI.name()); if (leftHi != null) { if (rightHi != null) { if (leftHi < rightHi) secondOfPair.add(i, null); else if (rightHi < leftHi) firstOfPairOrFragment.add(i, null); } } else if (rightHi != null) { firstOfPairOrFragment.add(i, null); } else { secondOfPair.add(i, null); } } }
Source:
public void should_successfully_build_city_if_user_has_enough_resources_in_main_stage() { startNewGame(12, 1); playPreparationStage(); giveResourcesToFirstPlayerForCityBuilding() .nextRandomDiceValues(asList(6, 6)) .THROW_DICE(1) .getGameDetails(1).gameUser(1).check("resources.wheat", is(2)) .getGameDetails(1).gameUser(1).check("resources.stone", is(3)) .BUILD_CITY(1).atNode(1, -1, "top").successfully() .getGameDetails(1).gameUser(1).check("resources.wheat", is(0)) .getGameDetails(1).gameUser(1).check("resources.stone", is(0)); }

Target:
public void should_successfully_build_city_if_user_has_enough_resources_in_main_stage() { startNewGame(12, 1); playPreparationStage(); giveResourcesToFirstPlayerForCityBuilding() .nextRandomDiceValues(asList(6, 6)) .THROW_DICE(1) .getGameDetails(1).gameUser(1).check("resources.wheat", greaterThanOrEqualTo(2)) .getGameDetails(1).gameUser(1).check("resources.stone", greaterThanOrEqualTo(3)) .BUILD_CITY(1).atNode(1, -1, "top").successfully(); }
Source:
Object getScript(ImplementationArtifact artifact, Operation op) { Optional<RelationshipTemplate> optionalRelationshipTemplate = Optional.fromNullable(toscaApplication.getNodeTemplate(nodeId).getRelationships().get(relationship.getRelationshipId())); if (!optionalRelationshipTemplate.isPresent()) { LOG.warn("Unsupported operation implementation for " + op.getDescription() + ": no relationship template"); return null; } this.relationshipTemplate = optionalRelationshipTemplate.get(); String script = getScript(artifact); return Optional.of(buildExportStatements(op, script).or(script)); }

Target:
Object getScript(ImplementationArtifact artifact, Operation op) { Optional<RelationshipTemplate> optionalRelationshipTemplate = Optional.fromNullable(toscaApplication.getNodeTemplate(nodeId).getRelationships().get(relationship.getRelationshipId())); if (!optionalRelationshipTemplate.isPresent()) { LOG.warn("Unsupported operation implementation for " + op.getDescription() + ": no relationship template"); return null; } this.relationshipTemplate = optionalRelationshipTemplate.get(); String script = getScript(artifact); return buildExportStatements(op, script).or(script); }
Source:
public void shouldRemoveEmptyTagsRecursively_asPartOfMigration78() throws Exception { String configXml = "<cruise schemaVersion='77'>" +" <pipelines group='first'>" +" <authorization>" +" <view>" +" <user></user>" +" </view>" +" </authorization>" +" <pipeline name='Test' template='test_template'>" +" <materials>" +" <hg url='../manual-testing/ant_hg/dummy' />" +" </materials>" +" </pipeline>" +" </pipelines>" +"</cruise>"; String migratedXml = migrateXmlString(configXml, 77); assertThat(migratedXml, not(containsString("user"))); assertThat(migratedXml, not(containsString("view"))); assertThat(migratedXml, not(containsString("authorization"))); }

Target:
public void shouldRemoveEmptyTagsRecursively_asPartOfMigration78() throws Exception { String configXml = "<cruise schemaVersion='77'>" +" <pipelines group='first'>" +" <authorization>" +" <view>" +" <user></user>" +" </view>" +" </authorization>" +" <pipeline name='Test' template='test_template'>" +" <materials>" +" <hg url='../manual-testing/ant_hg/dummy' />" +" </materials>" +" </pipeline>" +" </pipelines>" +"</cruise>"; String migratedXml = migrateXmlString(configXml, 77); assertThat(migratedXml, not(containsString("<user>"))); assertThat(migratedXml, not(containsString("<view>"))); assertThat(migratedXml, not(containsString("<authorization>"))); }
Source:
public static ModuleDeploymentProperties createModuleDeploymentProperties( Map<String, String> deploymentProperties, ModuleDescriptor descriptor) { ModuleDeploymentProperties moduleDeploymentProperties = new ModuleDeploymentProperties(); String wildcardPrefix = "module.*."; for (String key : deploymentProperties.keySet()) { if (key.startsWith(wildcardPrefix)) { moduleDeploymentProperties.put(key.substring(wildcardPrefix.length()), deploymentProperties.get(key)); } } String modulePrefix = String.format("module.%s.", descriptor.getModuleName()); for (String key : deploymentProperties.keySet()) { if (key.startsWith(modulePrefix)) { moduleDeploymentProperties.put(key.substring(modulePrefix.length()), deploymentProperties.get(key)); } } return moduleDeploymentProperties; }

Target:
public static ModuleDeploymentProperties createModuleDeploymentProperties( Map<String, String> deploymentProperties, ModuleDescriptor descriptor) { ModuleDeploymentProperties moduleDeploymentProperties = new ModuleDeploymentProperties(); String wildcardPrefix = "module.*."; for (Map.Entry<String, String> prop : deploymentProperties.entrySet()) { String key = prop.getKey(); if (key.startsWith(wildcardPrefix)) { moduleDeploymentProperties.put(key.substring(wildcardPrefix.length()), prop.getValue()); } } String modulePrefix = String.format("module.%s.", descriptor.getModuleName()); for (Map.Entry<String, String> prop : deploymentProperties.entrySet()) { String key = prop.getKey(); if (key.startsWith(modulePrefix)) { moduleDeploymentProperties.put(key.substring(modulePrefix.length()), prop.getValue()); } } return moduleDeploymentProperties; }
Source:
protected void shutdownNodeSourceServices(Client initiator) { logger.info("[" + this.name + "] Shutdown finalization"); this.activePolicy.shutdown(initiator); this.infrastructureManager.internalShutDown(); this.rmcore.disconnect(Client.getId(PAActiveObject.getStubOnThis())); this.finishNodeSourceShutdown(initiator); }

Target:
protected void shutdownNodeSourceServices(Client initiator) { logger.info("[" + this.name + "] Shutdown finalization"); this.activePolicy.shutdown(initiator); this.infrastructureManager.internalShutDown(); this.finishNodeSourceShutdown(initiator); }
Source:
private void refresh() { NetworkUtils.checkConnection(new WeakReference<>(getContext()), new NetworkUtils.NetworkStateReceiverListener() { @Override public void networkAvailable() { if (AuthUtil.isUserLoggedIn()) { downloadFeedbacks(); } else { redirectToLogin(); if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(false); } } @Override public void networkUnavailable() { onFeedbacksDownloadDone(false); } }); }

Target:
private void refresh() { if (NetworkUtils.haveNetworkConnection(getContext())) { if (AuthUtil.isUserLoggedIn()) { downloadFeedbacks(); } else { if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(true); } } } else { onFeedbacksDownloadDone(false); } }
Source:
public void testNoExceptionThrownOnCallingResetLookData() { LookData lookData = new LookData(); boolean isExceptionThrown = false; try { lookData.resetLookData(); } catch (Exception error) { isExceptionThrown = true; } assertFalse(isExceptionThrown); }

Target:
public void testNoExceptionThrownOnCallingResetLookData() { LookData lookData = new LookData(); try { lookData.resetLookData(); } catch (Exception error) { fail(); } }
Source:
private void doAddToIndex() throws IOException { if (trace) { log.trace(String.format("Indexing object [%s]", scratchPad)); } if (enableParentChildIndex){ String parentId = this.getParentId(scratchPad.bytes(), this.settings.getParentIdPath()); indexFiledWithParentValue = ("{\"index\":{ \"_parent\" : \"" + parentId + "\"}}\n").getBytes(StringUtils.UTF_8); } int entrySize = enableParentChildIndex ? indexFiledWithParentValue.length + CARRIER_RETURN.length + scratchPad.size() : INDEX_DIRECTIVE.length + CARRIER_RETURN.length + scratchPad.size(); if (entrySize + bufferSize > buffer.length) { flushBatch(); } if (enableParentChildIndex) copyIntoBuffer(indexFiledWithParentValue, indexFiledWithParentValue.length); else copyIntoBuffer(INDEX_DIRECTIVE, INDEX_DIRECTIVE.length); copyIntoBuffer(scratchPad.bytes(), scratchPad.size()); copyIntoBuffer(CARRIER_RETURN, CARRIER_RETURN.length); bufferEntries++; if (bufferEntriesThreshold > 0 && bufferEntries >= bufferEntriesThreshold) { flushBatch(); } }

Target:
private void doAddToIndex() throws IOException { if (trace) { log.trace(String.format("Indexing object [%s]", scratchPad)); } if (enableParentChildIndex){ String parentId = this.getParentId(scratchPad.bytes(), this.settings.getParentIdPath()); indexFiledWithParentValue = ("{\"index\":{ \"_parent\" : \"" + parentId + "\"}}\n").getBytes(StringUtils.UTF_8); } int entrySize = enableParentChildIndex ? indexFiledWithParentValue.length + CARRIER_RETURN.length + scratchPad.size() : INDEX_DIRECTIVE.length + CARRIER_RETURN.length + scratchPad.size(); if (entrySize + bufferSize > buffer.length) { flushBatch(); } if (enableParentChildIndex){ copyIntoBuffer(indexFiledWithParentValue, indexFiledWithParentValue.length); }else{ copyIntoBuffer(INDEX_DIRECTIVE, INDEX_DIRECTIVE.length); } copyIntoBuffer(scratchPad.bytes(), scratchPad.size()); copyIntoBuffer(CARRIER_RETURN, CARRIER_RETURN.length); bufferEntries++; if (bufferEntriesThreshold > 0 && bufferEntries >= bufferEntriesThreshold) { flushBatch(); } }
Source:
public void run() { while (!interrupted) { try { semaphore.acquire(); } catch (InterruptedException e) { return; } semaphore.drainPermits(); for (Iterator<BlockingRunnable> iterator = blockedTasks.iterator(); iterator.hasNext(); ) { BlockingRunnable runnable = iterator.next(); if (runnable.isReady()) { iterator.remove(); readyList.add(runnable); } } if (log.isTraceEnabled()) { log.tracef("Tasks to be executed=%s, still pending=%s", readyList.size(), blockedTasks.size()); } while (!readyList.isEmpty()) { doExecute(readyList.pop()); } } }

Target:
public void run() { while (!interrupted) { try { semaphore.acquire(); } catch (InterruptedException e) { return; } semaphore.drainPermits(); int size = blockedTasks.size(); if (size == 0) { continue; } ArrayDeque<BlockingRunnable> readyList = new ArrayDeque<>(size); for (Iterator<BlockingRunnable> iterator = blockedTasks.iterator(); iterator.hasNext(); ) { BlockingRunnable runnable = iterator.next(); if (runnable.isReady()) { iterator.remove(); readyList.addLast(runnable); } } if (log.isTraceEnabled()) { log.tracef("Tasks to be executed=%s, still pending=~%s", readyList.size(), size); } BlockingRunnable runnable; while ((runnable = readyList.pollFirst()) != null) { doExecute(runnable); } } }
Source:
@Override public void close() throws Exception { socket.close(); ctx.close(); zeroMqExSrv.shutdown(); timeout = 1; zeroMqExSrv.awaitTermination(timeout, TimeUnit.MINUTES); isStarted = false; }

Target:
@Override public void close() throws Exception { isStarted = false; if (ctx != null) ctx.close(); if (zeroMqExSrv != null) { zeroMqExSrv.shutdown(); try { if (!zeroMqExSrv.awaitTermination(timeout, TimeUnit.MILLISECONDS)) log.warning("Timed out waiting for consumer threads to shut down, exiting uncleanly."); } catch (InterruptedException ignored) { zeroMqExSrv.shutdownNow(); log.error("Interrupted during shutdown, exiting uncleanly."); } } }
Source:
protected void publishResults(CharSequence constraint, FilterResults results) { clear(); TextView tvStats = (TextView) findViewById(R.id.tvStats); TextView tvState = (TextView) findViewById(R.id.tvState); ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter); pbFilter.setVisibility(ProgressBar.GONE); tvStats.setVisibility(TextView.VISIBLE); tvStats.setText(results.count + "/" + AppListAdapter.this.mListApp.size()); RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams(); tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.tvStats); if (mProgressDialog != null) { try { mProgressDialog.dismiss(); mProgressDialog = null; } catch (Throwable ex) { Util.bug(null, ex); } } if (results.values == null) notifyDataSetInvalidated(); else { addAll((ArrayList<ApplicationInfoEx>) results.values); notifyDataSetChanged(); } }

Target:
protected void publishResults(CharSequence constraint, FilterResults results) { clear(); TextView tvStats = (TextView) findViewById(R.id.tvStats); TextView tvState = (TextView) findViewById(R.id.tvState); ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter); pbFilter.setVisibility(ProgressBar.GONE); tvStats.setVisibility(TextView.VISIBLE); tvStats.setText(results.count + "/" + AppListAdapter.this.mListApp.size()); setProgress(getString(R.string.title_restrict), 0, 1); RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams(); tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.tvStats); if (results.values == null) notifyDataSetInvalidated(); else { addAll((ArrayList<ApplicationInfoEx>) results.values); notifyDataSetChanged(); } }
Source:
public FileHeader createFileHeader(DiffEntry ent) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buf, true, "UTF-8"); EditList editList = new EditList(); writeDiffHeader(ps, ent); if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) { if (ent.getOldMode() == GITLINK) { ps.write(encodeASCII("-Subproject commit " + ent.getOldId().name() + "\n")); } if (ent.getNewMode() == GITLINK) { ps.write(encodeASCII("+Subproject commit " + ent.getNewId().name() + "\n")); } } else { byte[] aRaw = open(ent.getOldMode(), ent.getOldId()); byte[] bRaw = open(ent.getNewMode(), ent.getNewId()); if (RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) { ps.write(encodeASCII("Binary files differ\n")); } else { RawText a = rawTextFactory.create(aRaw); RawText b = rawTextFactory.create(bRaw); editList = new MyersDiff(a, b).getEdits(); } } ps.flush(); return new FileHeader(buf.toByteArray(), editList); }

Target:
public FileHeader createFileHeader(DiffEntry ent) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buf, true, Constants.CHARSET.name()); final EditList editList; writeDiffHeader(ps, ent); if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) { writeGitLinkDiffText(ps, ent); editList = new EditList(); } else { byte[] aRaw = open(ent.getOldMode(), ent.getOldId()); byte[] bRaw = open(ent.getNewMode(), ent.getNewId()); if (RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) { ps.write(encodeASCII("Binary files differ\n")); editList = new EditList(); } else { RawText a = rawTextFactory.create(aRaw); RawText b = rawTextFactory.create(bRaw); editList = new MyersDiff(a, b).getEdits(); } } ps.flush(); return new FileHeader(buf.toByteArray(), editList); }
Source:
private void parseCommandLine(final boolean isRootParse) throws ParseException, BadArgumentException { final CommandLineParser parser = new DefaultParser(); if (isRootParse) { String[] roots = rootArgumentsOnly(); this.cmd = parser.parse(this.options, roots); } else { this.cmd = parser.parse(this.options, this.args); } }

Target:
private void parseCommandLine(final boolean isRootParse) throws ParseException, BadArgumentException { final CommandLineParser parser = new DefaultParser(); if (isRootParse) { final String[] roots = rootArgumentsOnly(); this.cmd = parser.parse(this.options, roots); } else { this.cmd = parser.parse(this.options, this.args); } }
Source:
private static void persistTopology(VDS vds) { InterfaceDao interfaceDAO = DbFacade.getInstance().getInterfaceDao(); List<VdsNetworkInterface> dbIfaces = interfaceDAO.getAllInterfacesForVds(vds.getId()); List<String> updatedIfaces = new ArrayList<String>(); List<VdsNetworkInterface> dbIfacesToBatch = new ArrayList<>(); for (VdsNetworkInterface dbIface : dbIfaces) { boolean found = false; for (VdsNetworkInterface vdsIface : vds.getInterfaces()) { if (dbIface.getName().equals(vdsIface.getName())) { vdsIface.setId(dbIface.getId()); dbIfacesToBatch.add(vdsIface); updatedIfaces.add(vdsIface.getName()); found = true; break; } } if (!found) { interfaceDAO.removeInterfaceFromVds(dbIface.getId()); interfaceDAO.removeStatisticsForVds(dbIface.getId()); } } if (dbIfacesToBatch.size() > 0) { interfaceDAO.massUpdateInterfacesForVds(dbIfacesToBatch); } for (VdsNetworkInterface vdsIface : vds.getInterfaces()) { if (!updatedIfaces.contains(vdsIface.getName())) { interfaceDAO.saveInterfaceForVds(vdsIface); interfaceDAO.saveStatisticsForVds(vdsIface.getStatistics()); } } }

Target:
private static void persistTopology(VDS vds) { InterfaceDao interfaceDAO = DbFacade.getInstance().getInterfaceDao(); List<VdsNetworkInterface> dbIfaces = interfaceDAO.getAllInterfacesForVds(vds.getId()); List<String> updatedIfaces = new ArrayList<String>(); List<VdsNetworkInterface> dbIfacesToBatch = new ArrayList<>(); for (VdsNetworkInterface dbIface : dbIfaces) { boolean found = false; for (VdsNetworkInterface vdsIface : vds.getInterfaces()) { if (dbIface.getName().equals(vdsIface.getName())) { vdsIface.setId(dbIface.getId()); dbIfacesToBatch.add(vdsIface); updatedIfaces.add(vdsIface.getName()); found = true; break; } } if (!found) { interfaceDAO.removeInterfaceFromVds(dbIface.getId()); interfaceDAO.removeStatisticsForVds(dbIface.getId()); } } if (!dbIfacesToBatch.isEmpty()) { interfaceDAO.massUpdateInterfacesForVds(dbIfacesToBatch); } for (VdsNetworkInterface vdsIface : vds.getInterfaces()) { if (!updatedIfaces.contains(vdsIface.getName())) { interfaceDAO.saveInterfaceForVds(vdsIface); interfaceDAO.saveStatisticsForVds(vdsIface.getStatistics()); } } }
Source:
public void deliverMessagesFrom(ShardIndex index) { NodeId currentNode = ServerEnvironment.instance() .nodeId(); Optional<ShardProcessingSession> picked = workRegistry.pickUp(index, currentNode); if (!picked.isPresent()) { return; } ShardProcessingSession session = picked.get(); try { int deliveredMsgCount; do { deliveredMsgCount = doDeliver(session); } while (deliveredMsgCount > 0); } catch (DeliveryStoppedByMonitorException ignored) { } finally { session.complete(); } }

Target:
public void deliverMessagesFrom(ShardIndex index) { NodeId currentNode = ServerEnvironment.instance() .nodeId(); Optional<ShardProcessingSession> picked = workRegistry.pickUp(index, currentNode); if (!picked.isPresent()) { return; } ShardProcessingSession session = picked.get(); try { RunResult runResult; do { runResult = doDeliver(session); } while (runResult.shouldRunAgain()); } finally { session.complete(); } }
Source:
public void doesNotUpdatesChangeTransactionStatusIfChargeTransactionDoesNotExist() throws Exception { PaymentRequestEntity paymentRequest = mock(PaymentRequestEntity.class); when(mockPaymentRequestDao.findByExternalId(someExternalId)).thenReturn(Optional.of(paymentRequest)); when(paymentRequest.hasChargeTransaction()).thenReturn(false); ChargeStatus newChargeStatus = ChargeStatus.ENTERING_CARD_DETAILS; new StatusUpdater(mockPaymentRequestDao).updateChargeTransactionStatus(someExternalId, newChargeStatus); verify(paymentRequest).hasChargeTransaction(); verifyNoMoreInteractions(paymentRequest); }

Target:
public void doesNotUpdatesChangeTransactionStatusIfChargeTransactionDoesNotExist() throws Exception { PaymentRequestEntity paymentRequest = mock(PaymentRequestEntity.class); when(mockPaymentRequestDao.findByExternalId(SOME_EXTERNAL_ID)).thenReturn(Optional.of(paymentRequest)); when(paymentRequest.hasChargeTransaction()).thenReturn(false); new StatusUpdater(mockPaymentRequestDao).updateChargeTransactionStatus(SOME_EXTERNAL_ID, ENTERING_CARD_DETAILS); verify(paymentRequest).hasChargeTransaction(); verifyNoMoreInteractions(paymentRequest); }
Source:
private Rectangle getPreferredInternalLocation(Rectangle proposedLocation) { Rectangle realLocation = new Rectangle(proposedLocation); IFigure compartment = getCompositeCompartmentFigure(parentFigure); Rectangle compartmentBounds; if (null != compartment) { compartmentBounds = compartment.getBounds().getCopy(); int xMin = compartmentBounds.x + borderItemOffset; int xMax = compartmentBounds.x + compartmentBounds.width - borderItemOffset - realLocation.width; int yMin = compartmentBounds.y + borderItemOffset; int yMax = compartmentBounds.y + compartmentBounds.height - borderItemOffset - realLocation.height; if (realLocation.x < xMin) { realLocation.x = xMin; } if (realLocation.x > xMax) { realLocation.x = xMax; } if (realLocation.y < yMin) { realLocation.y = yMin; } if (realLocation.y > yMax) { realLocation.y = yMax; } } System.err.println("proposed: " + proposedLocation); System.err.println("real: " + realLocation); return realLocation; }

Target:
private Rectangle getPreferredInternalLocation(Rectangle proposedLocation) { Rectangle realLocation = new Rectangle(proposedLocation); IFigure compartment = getCompositeCompartmentFigure(parentFigure); Rectangle compartmentBounds; if (null != compartment) { compartmentBounds = compartment.getBounds().getCopy(); int xMin = compartmentBounds.x + borderItemOffset; int xMax = compartmentBounds.x + compartmentBounds.width - borderItemOffset - realLocation.width; int yMin = compartmentBounds.y + borderItemOffset; int yMax = compartmentBounds.y + compartmentBounds.height - borderItemOffset - realLocation.height; if (realLocation.x < xMin) { realLocation.x = xMin; } if (realLocation.x > xMax) { realLocation.x = xMax; } if (realLocation.y < yMin) { realLocation.y = yMin; } if (realLocation.y > yMax) { realLocation.y = yMax; } } return realLocation; }
Source:
private static String getResponseAsString(HttpResponse response) { StringBuilder builder = new StringBuilder(); builder.append(response.getStatusLine().toString()); builder.append("\r\n"); for (Header header : response.getAllHeaders()) { builder.append(header.getName()); builder.append("="); builder.append(header.getValue()); builder.append("\r\n"); } builder.append("\r\n"); if (response.getEntity() != null) { try { builder.append(EntityUtils.toString(response.getEntity())); } catch (IOException ignore) { } } return builder.toString(); }

Target:
private static String getResponseAsString(HttpResponse response) { StringBuilder builder = new StringBuilder(); builder.append(response.getStatusLine().toString()); try { builder.append(StringUtils.fixLineSeparator("\r\n")); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } for (Header header : response.getAllHeaders()) { builder.append(header.getName()); builder.append("="); builder.append(header.getValue()); builder.append("\r\n"); } builder.append("\r\n"); if (response.getEntity() != null) { try { builder.append(EntityUtils.toString(response.getEntity())); } catch (IOException ignore) { } } return builder.toString(); }
Source:
public void completeResourceConfigurationUpdate(ConfigurationUpdateResponse response) { if (LOG.isDebugEnabled()) { LOG.debug("Received a configuration-update-completed message: " + response); } ResourceConfigurationUpdate update = entityManager.find(ResourceConfigurationUpdate.class, response.getConfigurationUpdateId()); if (update == null) { throw new IllegalStateException( "The completed request passed in does not match any request for any resource in inventory: " + response); } if (response.getStatus() == ConfigurationUpdateStatus.FAILURE) { if (response.getConfiguration() != null) { Configuration failedConfiguration = response.getConfiguration(); failedConfiguration = entityManager.merge(failedConfiguration); update.setConfiguration(failedConfiguration); } } else if (response.getStatus() == ConfigurationUpdateStatus.SUCCESS) { Resource resource = update.getResource(); Configuration oldResourceConfig = resource.getResourceConfiguration(); resource.setResourceConfiguration(update.getConfiguration().deepCopyWithoutProxies()); entityManager.remove(oldResourceConfig); notifyAlertConditionCacheManager("completeResourceConfigurationUpdate", update); } update.setStatus(response.getStatus()); update.setErrorMessage(response.getErrorMessage()); return; }

Target:
public void completeResourceConfigurationUpdate(ConfigurationUpdateResponse response) { if (LOG.isDebugEnabled()) { LOG.debug("Received a configuration-update-completed message: " + response); } ResourceConfigurationUpdate update = entityManager.find(ResourceConfigurationUpdate.class, response.getConfigurationUpdateId()); if (update == null) { throw new IllegalStateException( "The completed request passed in does not match any request for any resource in inventory: " + response); } if (response.getStatus() == ConfigurationUpdateStatus.FAILURE) { if (response.getConfiguration() != null) { Configuration failedConfiguration = response.getConfiguration(); failedConfiguration = entityManager.merge(failedConfiguration); update.setConfiguration(failedConfiguration); } } else if (response.getStatus() == ConfigurationUpdateStatus.SUCCESS) { Resource resource = update.getResource(); entityManager.remove(resource.getResourceConfiguration()); resource.setResourceConfiguration(update.getConfiguration().deepCopyWithoutProxies()); notifyAlertConditionCacheManager("completeResourceConfigurationUpdate", update); } update.setStatus(response.getStatus()); update.setErrorMessage(response.getErrorMessage()); return; }
Source:
public void init(ComputationContext context) { super.init(context); try { temp = Files.createTempDirectory(metadata().name()); temp.toFile().deleteOnExit(); } catch (IOException e) { throw new IllegalStateException("Cannot create temp directory for " + this); } }

Target:
public void init(ComputationContext context) { super.init(context); try { temp = Files.createTempDirectory(metadata().name()); Framework.trackFile(temp.toFile(), temp); } catch (IOException e) { throw new IllegalStateException("Cannot create temp directory for " + this); } }
Source:
public IdentityPoolCredentialSource(Map<String, Object> credentialSourceMap) { super(credentialSourceMap); if (credentialSourceMap.containsKey("file")) { credentialLocation = (String) credentialSourceMap.get("file"); credentialSourceType = IdentityPoolCredentialSourceType.FILE; } else if (credentialSourceMap.containsKey("url")) { credentialLocation = (String) credentialSourceMap.get("url"); credentialSourceType = IdentityPoolCredentialSourceType.URL; } else { throw new IllegalArgumentException( "Missing credential source file location or URL. At least one must be specified."); } Map<String, String> headersMap = (Map<String, String>) credentialSourceMap.get("headers"); if (headersMap != null && !headersMap.isEmpty()) { headers = new HashMap<>(); headers.putAll(headersMap); } credentialFormatType = CredentialFormatType.TEXT; Map<String, String> formatMap = (Map<String, String>) credentialSourceMap.get("format"); if (formatMap != null && formatMap.containsKey("type")) { String type = formatMap.get("type"); if (!type.equals("text") && !type.equals("json")) { throw new IllegalArgumentException( String.format("Invalid credential source format type: %s.", type)); } credentialFormatType = type.equals("text") ? CredentialFormatType.TEXT : CredentialFormatType.JSON; if (!formatMap.containsKey("subject_token_field_name")) { throw new IllegalArgumentException( "When specifying a JSON credential type, the subject_token_field_name must be set."); } subjectTokenFieldName = formatMap.get("subject_token_field_name"); } }

Target:
public IdentityPoolCredentialSource(Map<String, Object> credentialSourceMap) { super(credentialSourceMap); if (credentialSourceMap.containsKey("file")) { credentialLocation = (String) credentialSourceMap.get("file"); credentialSourceType = IdentityPoolCredentialSourceType.FILE; } else if (credentialSourceMap.containsKey("url")) { credentialLocation = (String) credentialSourceMap.get("url"); credentialSourceType = IdentityPoolCredentialSourceType.URL; } else { throw new IllegalArgumentException( "Missing credential source file location or URL. At least one must be specified."); } Map<String, String> headersMap = (Map<String, String>) credentialSourceMap.get("headers"); if (headersMap != null && !headersMap.isEmpty()) { headers = new HashMap<>(); headers.putAll(headersMap); } credentialFormatType = CredentialFormatType.TEXT; Map<String, String> formatMap = (Map<String, String>) credentialSourceMap.get("format"); if (formatMap != null && formatMap.containsKey("type")) { String type = formatMap.get("type"); if (type == null || (!type.equals("text") && !type.equals("json"))) { throw new IllegalArgumentException( String.format("Invalid credential source format type: %s.", type)); } credentialFormatType = type.equals("text") ? CredentialFormatType.TEXT : CredentialFormatType.JSON; if (!formatMap.containsKey("subject_token_field_name")) { throw new IllegalArgumentException( "When specifying a JSON credential type, the subject_token_field_name must be set."); } subjectTokenFieldName = formatMap.get("subject_token_field_name"); } }
Source:
public static StringBuffer getIntialWebviewBuffer(Context context, Logger logger) { StringBuffer buff = new StringBuffer(); buff.append("<head>"); buff.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); try { String cssFileContent = FileUtil.loadTextFileFromAssets(context , "css/render-html-in-webview.css"); buff.append("<style>"); buff.append(cssFileContent); buff.append("</style>"); } catch (IOException e) { logger.error(e); } buff.append("</head>"); return buff; }

Target:
public static StringBuilder getIntialWebviewBuffer(Context context, Logger logger) { StringBuilder buff = new StringBuilder(); buff.append("<head>"); buff.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); try { String cssFileContent = FileUtil.loadTextFileFromAssets(context, "css/render-html-in-webview.css"); buff.append("<style>"); buff.append(cssFileContent); buff.append("</style>"); } catch (IOException e) { logger.error(e); } buff.append("</head>"); return buff; }
Source:
private Transaction getOngoingTransaction() { try { Transaction transaction = null; if (transactionManager != null) { transaction = transactionManager.getTransaction(); if (transaction == null && batchContainer != null) { transaction = batchContainer.getBatchTransaction(); } } return transaction; } catch (SystemException e) { throw new CacheException("Unable to get transaction", e); } }

Target:
private Transaction getOngoingTransaction() { try { Transaction transaction = transactionManager.getTransaction(); if (transaction == null && batchContainer != null) { transaction = batchContainer.getBatchTransaction(); } return transaction; } catch (SystemException e) { throw new CacheException("Unable to get transaction", e); } }
Source:
public static List<OVirtNodeInfo> get() { final String delimiter = ":"; final String[] path = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String regex[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); log.debugFormat("NodeInfo: regex length {0} minimum length {1} path length {2}", regex.length, minimumVersion.length, path.length); if (regex.length != minimumVersion.length || regex.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } for (int i=0; i < regex.length; i++) { log.debugFormat("NodeInfo: regex {0} path {1}, minimumVersion {2}", regex[i], path[i], minimumVersion[i]); info.add(new OVirtNodeInfo(Pattern.compile(regex[i]), new File(path[i]), minimumVersion[i])); } return info; }

Target:
public List<Entry> get() { return info; }
Source:
private final int[] decodeInts(final String string) { final int nValues = ParsingUtils.split(string, INT_DECODE_ARRAY, ','); if ( nValues > LARGE_SIZE ) log.warn("Decoding " + nValues + " integers in " + name); final int[] values = new int[nValues]; try { for ( int i = 0; i < nValues; i++ ) values[i] = Integer.valueOf(INT_DECODE_ARRAY[i]); } catch (final NumberFormatException e) { return null; } return values; }

Target:
private final int[] decodeInts(final String string) { int numItems = StringUtils.countMatches(string, ",") + 1; String[] intDecodeArray = new String[numItems]; final int nValues = ParsingUtils.split(string, intDecodeArray, ','); final int[] values = new int[nValues]; try { for ( int i = 0; i < nValues; i++ ) values[i] = Integer.valueOf(intDecodeArray[i]); } catch (final NumberFormatException e) { return null; } return values; }
Source:
public static void writeEntryHeader(CRC32 crc, ByteBuffer headerBuf, ByteBuffer destBuf, int size, int flag) { crc.update(size); crc.update(flag); crc.update(destBuf); headerBuf.clear(); headerBuf.order(ByteOrder.LITTLE_ENDIAN); headerBuf.putLong(crc.getValue()); headerBuf.putInt(size); headerBuf.putInt(flag); headerBuf.order(ByteOrder.BIG_ENDIAN); }

Target:
public static void writeEntryHeader(CRC32 crc, ByteBuffer headerBuf, ByteBuffer destBuf, int size, int flag) { crc.update(size); crc.update(flag); crc.update(destBuf); headerBuf.putInt((int)crc.getValue()); headerBuf.putInt(size); headerBuf.putInt(flag); }
Source:
public void test_Servlet16() throws Exception { Servlet servlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Part part = req.getPart("file"); Assert.assertNotNull(part); String submittedFileName = part.getSubmittedFileName(); String contentType = part.getContentType(); long size = part.getSize(); PrintWriter writer = resp.getWriter(); writer.write(submittedFileName); writer.write("|"); writer.write(contentType); writer.write("|" + size); } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16"); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*"); props.put("osgi.http.whiteboard.servlet.multipart.enabled", Boolean.TRUE); registrations.add(getBundleContext().registerService(Servlet.class, servlet, props)); Map<String, List<Object>> map = new HashMap<String, List<Object>>(); map.put("file", Arrays.<Object>asList(getClass().getResource("resource1.txt"))); Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map); Assert.assertEquals("200", result.get("responseCode").get(0)); Assert.assertEquals("resource1.txt|text/plain|1", result.get("responseBody").get(0)); }

Target:
public void test_Servlet16() throws Exception { Servlet servlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Part part = req.getPart("file"); Assert.assertNotNull(part); String submittedFileName = part.getSubmittedFileName(); String contentType = part.getContentType(); long size = part.getSize(); PrintWriter writer = resp.getWriter(); writer.write(submittedFileName); writer.write("|"); writer.write(contentType); writer.write("|" + size); } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16"); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*"); props.put("equinox.http.multipartSupported", Boolean.TRUE); registrations.add(getBundleContext().registerService(Servlet.class, servlet, props)); Map<String, List<Object>> map = new HashMap<String, List<Object>>(); map.put("file", Arrays.<Object>asList(getClass().getResource("resource1.txt"))); Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map); Assert.assertEquals("200", result.get("responseCode").get(0)); Assert.assertEquals("resource1.txt|text/plain|1", result.get("responseBody").get(0)); }
Source:
public final void update() { removeAllChildren(); add(new JSources(this, wrapper)); List<JResource> resList = getHierarchyResources(wrapper.getResources()); for (JResource jRes : resList) { jRes.update(); add(jRes); } ApkSignature signature = ApkSignature.getApkSignature(wrapper.getOpenFile()); if (signature!=null) { add(signature); } JCertificate certificate = getCertificate(wrapper.getResources()); if (certificate != null) { add(certificate); } }

Target:
public final void update() { removeAllChildren(); add(new JSources(this, wrapper)); List<JResource> resList = getHierarchyResources(wrapper.getResources()); for (JResource jRes : resList) { jRes.update(); add(jRes); } ApkSignature signature = ApkSignature.getApkSignature(wrapper); if (signature != null) { add(signature); } JCertificate certificate = getCertificate(wrapper.getResources()); if (certificate != null) { add(certificate); } }
Source:
public void testLongDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", 1); assertTrue(field.hasDefaultValue()); assertEquals(1L, field.defaultVal()); assertEquals(1L, GenericData.get().getDefaultValue(field)); field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", Long.MIN_VALUE); assertTrue(field.hasDefaultValue()); assertEquals(Long.MIN_VALUE, field.defaultVal()); assertEquals(Long.MIN_VALUE, GenericData.get().getDefaultValue(field)); field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", Long.MAX_VALUE); assertTrue(field.hasDefaultValue()); assertEquals(Long.MAX_VALUE, field.defaultVal()); assertEquals(Long.MAX_VALUE, GenericData.get().getDefaultValue(field)); }

Target:
public void testLongDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", 1L); assertTrue(field.hasDefaultValue()); assertEquals(1L, field.defaultVal()); assertEquals(1L, GenericData.get().getDefaultValue(field)); field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", Long.MIN_VALUE); assertTrue(field.hasDefaultValue()); assertEquals(Long.MIN_VALUE, field.defaultVal()); assertEquals(Long.MIN_VALUE, GenericData.get().getDefaultValue(field)); field = new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", Long.MAX_VALUE); assertTrue(field.hasDefaultValue()); assertEquals(Long.MAX_VALUE, field.defaultVal()); assertEquals(Long.MAX_VALUE, GenericData.get().getDefaultValue(field)); }
Source:
public List<ResponseExceptionMapper<?>> createResponseExceptionMapper(Message m, Class<?> paramType) { if (responseExceptionMappers.isEmpty()) { return Collections.emptyList(); } List<ResponseExceptionMapper<?>> candidates = responseExceptionMappers.stream().map(ProviderInfo::getProvider).collect(Collectors.toList()); candidates.sort(new ResponseExceptionMapperComparator()); return Collections.unmodifiableList(candidates); }

Target:
public List<ResponseExceptionMapper<?>> createResponseExceptionMapper(Message m, Class<?> paramType) { if (responseExceptionMappers.isEmpty()) { return Collections.emptyList(); } return Collections.unmodifiableList(responseExceptionMappers .stream() .map(ProviderInfo::getProvider) .sorted(new ResponseExceptionMapperComparator()) .collect(Collectors.toList())); }
Source:
public void sendResultMsg(final boolean success, final String operationId, final TraceInfo parentTraceInfo) { try (final TraceScope sendResultMsgScope = Trace.startSpan(SEND_RESULT_MSG, parentTraceInfo)) { LOG.entering(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendResultMsg", new Object[]{}); final ResultMsg resultMsg = ResultMsg.newBuilder() .setResult(success ? Result.SUCCESS : Result.FAILURE) .build(); send(driverId, AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setSrcId(emNetworkSetup.getMyId().toString()) .setDestId(driverId) .setOperationId(operationId) .setTraceInfo(HTraceUtils.toAvro(parentTraceInfo)) .setResultMsg(resultMsg) .build()); LOG.exiting(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendResultMsg", new Object[]{}); } }

Target:
public void sendResultMsg(final boolean success, final String operationId, final TraceInfo parentTraceInfo) { try (final TraceScope sendResultMsgScope = Trace.startSpan(SEND_RESULT_MSG, parentTraceInfo)) { LOG.entering(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendResultMsg", new Object[]{success, operationId}); final ResultMsg resultMsg = ResultMsg.newBuilder() .setResult(success ? Result.SUCCESS : Result.FAILURE) .build(); send(driverId, AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setSrcId(emNetworkSetup.getMyId().toString()) .setDestId(driverId) .setOperationId(operationId) .setTraceInfo(HTraceUtils.toAvro(parentTraceInfo)) .setResultMsg(resultMsg) .build()); LOG.exiting(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendResultMsg", new Object[]{success, operationId}); } }
Source:
public void testParseNoLocalWrite() { DistCpOptions options = OptionsParser.parse(new String[] { "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertEquals(options.shouldNoLocalWrite(), false); options = OptionsParser.parse(new String[] { "-noLocalWrite", "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertEquals(options.shouldNoLocalWrite(), true); }

Target:
public void testParseNoLocalWrite() { DistCpOptions options = OptionsParser.parse(new String[] { "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertFalse("Failed to parse option -noLocalWrite correctly.", options.shouldNoLocalWrite()); options = OptionsParser.parse(new String[] { "-noLocalWrite", "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertTrue("Failed to parse option -noLocalWrite correctly.", options.shouldNoLocalWrite()); }
Source:
private List<String> validateMacraMeasuresAreUniqueForCertificationResult(List<PendingCertificationResultMacraMeasureDTO> macraMeasures, String certNumber, String messageCode) { List<String> messages = new ArrayList<String>(); Map<String, String> uniqueMacras = new HashMap<String, String>(); for (PendingCertificationResultMacraMeasureDTO macraMeasure : macraMeasures) { if (macraMeasure != null) { if (uniqueMacras.containsKey(macraMeasure.getEnteredValue())) { messages.add(msgUtil.getMessage(messageCode, certNumber, macraMeasure.getEnteredValue())); } else { uniqueMacras.put(macraMeasure.getEnteredValue(), macraMeasure.getEnteredValue()); } } } return messages; }

Target:
private List<String> validateMacraMeasuresAreUniqueForCertificationResult(List<PendingCertificationResultMacraMeasureDTO> macraMeasures, String certNumber, String messageCode) { List<String> messages = new ArrayList<String>(); Set<String> uniqueMacras = new HashSet<String>(); for (PendingCertificationResultMacraMeasureDTO macraMeasure : macraMeasures) { if (uniqueMacras.contains(macraMeasure.getEnteredValue())) { messages.add(msgUtil.getMessage(messageCode, certNumber, macraMeasure.getEnteredValue())); } else { uniqueMacras.add(macraMeasure.getEnteredValue()); } } return messages; }