auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Map<String, String>> process(String targetHost) throws AmbariException { KerberosServerAction.KerberosCommandParameters kerberosCommandParameters = new KerberosServerAction.KerberosCommandParameters(executionCommand); try { Map<String, Collection<String>> serviceComponentFilter = getServiceComponentFilter(kerberosCommandParameters.getServiceComponentFilter()); Set<ResolvedKerberosKeytab> keytabsToInject = kerberosKeytabController.getFilteredKeytabs(serviceComponentFilter, kerberosCommandParameters.getHostFilter(), kerberosCommandParameters.getIdentityFilter()); if (serviceComponentFilter != null) { keytabsToInject.addAll(kerberosKeytabController.findKeytabsForServiceIdentities(executionCommand.getClusterName(), serviceComponentFilter)); } for (ResolvedKerberosKeytab resolvedKeytab : keytabsToInject) { for (ResolvedKerberosPrincipal resolvedPrincipal : resolvedKeytab.getPrincipals()) { String hostName = resolvedPrincipal.getHostName(); if (targetHost.equalsIgnoreCase(hostName)) { process(targetHost, resolvedKeytab, resolvedPrincipal, serviceComponentFilter); } } } } catch (IOException e) { throw new AmbariException("Could not inject keytabs to enable kerberos"); } return kcp; }

Target:
public List<Map<String, String>> process(String targetHost) throws AmbariException { KerberosServerAction.KerberosCommandParameters kerberosCommandParameters = new KerberosServerAction.KerberosCommandParameters(executionCommand); try { Map<String, ? extends Collection<String>> serviceComponentFilter = getServiceComponentFilter(kerberosCommandParameters.getServiceComponentFilter()); final Collection<KerberosIdentityDescriptor> serviceIdentities = serviceComponentFilter == null ? null : kerberosKeytabController.getServiceIdentities(executionCommand.getClusterName(), serviceComponentFilter.keySet()); final Set<ResolvedKerberosKeytab> keytabsToInject = kerberosKeytabController.getFilteredKeytabs(serviceIdentities, kerberosCommandParameters.getHostFilter(), kerberosCommandParameters.getIdentityFilter()); for (ResolvedKerberosKeytab resolvedKeytab : keytabsToInject) { for (ResolvedKerberosPrincipal resolvedPrincipal : resolvedKeytab.getPrincipals()) { String hostName = resolvedPrincipal.getHostName(); if (targetHost.equalsIgnoreCase(hostName)) { process(targetHost, resolvedKeytab, resolvedPrincipal, serviceComponentFilter); } } } } catch (IOException e) { throw new AmbariException("Could not inject keytabs to enable kerberos"); } return kcp; }
Source:
public void onNext(final AggregationMessage msg) { LOG.entering(DriverSideMetricsMsgHandler.class.getSimpleName(), "onNext"); final MetricsMessage metricsMessage = metricsMessageCodec.decode(msg.getData().array()); final SrcType srcType = metricsMessage.getSrcType(); if (SrcType.Worker.equals(srcType)) { final String workerId = msg.getSourceId().toString(); final WorkerMsg workerMsg = metricsMessage.getWorkerMsg(); final Map<String, Double> workerMetrics = getMetricsFromAvro(metricsMessage.getMetrics()); LOG.log(Level.FINE, "Metric from worker: {0}, iteration: {1}, metrics: {2}", new Object[]{workerId, workerMsg.getIteration(), workerMetrics}); metricsHub.storeWorkerMetrics(workerId, workerMsg.getNumDataBlocks(), workerMetrics); } else if (SrcType.Server.equals(srcType)) { final String serverId = msg.getSourceId().toString(); final ServerMsg serverMsg = metricsMessage.getServerMsg(); final Map<String, Double> serverMetrics = getMetricsFromAvro(metricsMessage.getMetrics()); LOG.log(Level.INFO, "Metric from server: {0}, window: {1}, metrics: {2}", new Object[]{serverId, serverMsg.getWindow(), serverMetrics}); metricsHub.storeServerMetrics(serverId, serverMsg.getNumPartitionBlocks(), serverMetrics); } else { throw new RuntimeException("Unknown SrcType " + srcType); } LOG.exiting(DriverSideMetricsMsgHandler.class.getSimpleName(), "onNext"); }

Target:
public void onNext(final AggregationMessage msg) { LOG.entering(DriverSideMetricsMsgHandler.class.getSimpleName(), "onNext"); final MetricsMessage metricsMessage = metricsMessageCodec.decode(msg.getData().array()); final SrcType srcType = metricsMessage.getSrcType(); if (SrcType.Worker.equals(srcType)) { final String workerId = msg.getSourceId().toString(); final WorkerMsg workerMsg = metricsMessage.getWorkerMsg(); final Map<String, Double> workerMetrics = getMetricsFromAvro(metricsMessage.getMetrics()); LOG.log(Level.FINE, "Metric from worker: {0}, iteration: {1}, metrics: {2}", new Object[]{workerId, workerMsg.getIteration(), workerMetrics}); metricsHub.storeWorkerMetrics(workerId, workerMsg.getNumDataBlocks(), workerMetrics); } else if (SrcType.Server.equals(srcType)) { final String serverId = msg.getSourceId().toString(); final ServerMsg serverMsg = metricsMessage.getServerMsg(); final Map<String, Double> serverMetrics = getMetricsFromAvro(metricsMessage.getMetrics()); LOG.log(Level.FINE, "Metric from server: {0}, window: {1}, metrics: {2}", new Object[]{serverId, serverMsg.getWindow(), serverMetrics}); metricsHub.storeServerMetrics(serverId, serverMsg.getNumPartitionBlocks(), serverMetrics); } else { throw new RuntimeException("Unknown SrcType " + srcType); } LOG.exiting(DriverSideMetricsMsgHandler.class.getSimpleName(), "onNext"); }
Source:
public void endWindow() { multiMap.endWindow(); windowToCount.put(windowId, countInWindow); windowToCount.endWindow(); store.endWindow(); if (windowId % 10 == 0) { long startTime = System.currentTimeMillis(); checkData(); logger.info("checkData() took millis.", System.currentTimeMillis() - startTime); } }

Target:
public void endWindow() { multiMap.endWindow(); windowToCount.put(windowId, countInWindow); windowToCount.endWindow(); store.endWindow(); if (windowId % 10 == 0) { checkData(); } }
Source:
private Map<String, Serde<Object>> getSerdes() { Map<String, Serde<Object>> retVal = new HashMap<>(); JavaConverters.asJavaCollectionConverter(new SerializerConfig(jobConfig).getSerdeNames()) .asJavaCollection() .stream() .forEach(serdeName -> { Option<String> serdeClassName = new SerializerConfig(jobConfig).getSerdeClass(serdeName); if (serdeClassName.isEmpty()) { serdeClassName = Option.apply(SerializerConfig.getSerdeFactoryName(serdeName)); } Serde serde = Util.getObj(serdeClassName.get(), SerdeFactory.class) .getSerde(serdeName, new SerializerConfig(jobConfig)); retVal.put(serdeName, serde); }); return retVal; }

Target:
private Map<String, Serde<Object>> getSerdes() { Map<String, Serde<Object>> serdeMap = new HashMap<>(); SerializerConfig serializerConfig = new SerializerConfig(jobConfig); ScalaJavaUtil.toJavaCollection(serializerConfig.getSerdeNames()) .stream() .forEach(serdeName -> { Option<String> serdeClassName = serializerConfig.getSerdeClass(serdeName); if (serdeClassName.isEmpty()) { serdeClassName = Option.apply(SerializerConfig.getSerdeFactoryName(serdeName)); } Serde serde = Util.getObj(serdeClassName.get(), SerdeFactory.class).getSerde(serdeName, serializerConfig); serdeMap.put(serdeName, serde); }); return serdeMap; }
Source:
public boolean schedule() { if (scheduled.get()) { return false; } boolean res = scheduled.compareAndSet(false, true); if (res) { fragmentPool.submit(this); } return res; }

Target:
public boolean schedule() { boolean res = !scheduled.get() && scheduled.compareAndSet(false, true); if (res) { submit(); } return res; }
Source:
public synchronized <T> T newMonitor( Class<T> monitorClass, String... tags ) { requireInterface( monitorClass ); ClassLoader classLoader = monitorClass.getClassLoader(); MonitorInvocationHandler monitorInvocationHandler = new MonitorInvocationHandler( tags ); return monitorClass.cast( Proxy.newProxyInstance( classLoader, new Class<?>[]{monitorClass}, monitorInvocationHandler ) ); }

Target:
public <T> T newMonitor( Class<T> monitorClass, String... tags ) { requireInterface( monitorClass ); ClassLoader classLoader = monitorClass.getClassLoader(); MonitorInvocationHandler monitorInvocationHandler = new MonitorInvocationHandler( tags ); return monitorClass.cast( Proxy.newProxyInstance( classLoader, new Class<?>[]{monitorClass}, monitorInvocationHandler ) ); }
Source:
public void reset(OutputStream out) throws IOException { this.out = out; }

Target:
public void reset(OutputStream out) throws IOException { this.out.close(); this.out = out; }
Source:
public Collection<Tuple> get(Tuple signature) { Object bucket = matchings.get(signature); if (bucket instanceof MarkedSet<?>) { return (Collection<Tuple>) bucket; } else { if (bucket == null) return null; return Collections.singleton((Tuple)bucket); } }

Target:
public Collection<Tuple> get(Tuple signature) { Object bucket = matchings.get(signature); if (bucket instanceof MarkedSet<?>) { return (MarkedSet<Tuple>) bucket; } else { if (bucket == null) return null; return Collections.singleton((Tuple)bucket); } }
Source:
public Selector(NetworkMetrics metrics, Time time, SSLFactory sslFactory) throws IOException { this.nioSelector = java.nio.channels.Selector.open(); this.time = time; this.keyMap = new HashMap<String, SelectionKey>(); this.completedSends = new ArrayList<NetworkSend>(); this.completedReceives = new ArrayList<NetworkReceive>(); this.connected = new ArrayList<String>(); this.disconnected = new ArrayList<String>(); this.pendingSslTrans = new HashMap<>(); this.metrics = metrics; this.IdGenerator = new AtomicLong(0); this.activeConnections = new AtomicLong(0); this.connectionsPendingHandshakeCount = new AtomicLong(0); this.metrics.initializeSelectorMetricsIfRequired(activeConnections, connectionsPendingHandshakeCount); this.sslFactory = sslFactory; }

Target:
public Selector(NetworkMetrics metrics, Time time, SSLFactory sslFactory) throws IOException { this.nioSelector = java.nio.channels.Selector.open(); this.time = time; this.keyMap = new HashMap<String, SelectionKey>(); this.completedSends = new ArrayList<NetworkSend>(); this.completedReceives = new ArrayList<NetworkReceive>(); this.connected = new ArrayList<String>(); this.disconnected = new ArrayList<String>(); this.metrics = metrics; this.IdGenerator = new AtomicLong(0); numActiveConnections = new AtomicLong(0); unreadyConnections = new HashSet<>(); metrics.initializeSelectorMetrics(numActiveConnections); this.sslFactory = sslFactory; }
Source:
public GlowArmorStand(Location location) { super(location); setMaxHealth(2); setHealth(2); for (int i = 0; i < 2; i++) { pose[i] = EulerAngle.ZERO; } double ten = Math.toRadians(10); double fifteen = Math.toRadians(15); double one = Math.toRadians(1); pose[2] = new EulerAngle(-ten, 0, -ten); pose[3] = new EulerAngle(-fifteen, 0, ten); pose[4] = new EulerAngle(-one, 0, -one); pose[5] = new EulerAngle(one, 0, one); for (int i = 0; i < 5; i++) { changedEquip[i] = false; } }

Target:
public GlowArmorStand(Location location) { super(location, 2); System.arraycopy(defaultPose, 0, pose, 0, 6); for (int i = 0; i < 5; i++) { changedEquip[i] = false; } }
Source:
public void httpProxyIsConfigurableOnClientRequests() { TestResource clientWithHttpProxy = AtlasDbHttpClients.createProxyWithFailover( new MetricRegistry(), ImmutableServerListConfig.builder() .addServers(getUriForPort(availablePort)) .proxyConfiguration(ProxyConfiguration.of(getHostAndPort(proxyPort))) .build(), TestResource.class, AUXILIARY_REMOTING_PARAMETERS_NO_PAYLOAD_LIMIT); clientWithHttpProxy.getTestNumber(); proxyServer.verify(getRequestedFor(urlMatching(GET_ENDPOINT)) .withHeader(AtlasDbInterceptors.USER_AGENT_HEADER, WireMock.equalTo(DEFAULT_USER_AGENT_STRING))); availableServer.verify(0, getRequestedFor(urlMatching(GET_ENDPOINT))); }

Target:
public void httpProxyIsConfigurableOnClientRequests() { TestResource clientWithHttpProxy = AtlasDbHttpClients.createProxyWithFailover( new MetricRegistry(), ImmutableServerListConfig.builder() .addServers(getUriForPort(availablePort1)) .proxyConfiguration(ProxyConfiguration.of(getHostAndPort(proxyPort))) .build(), TestResource.class, AUXILIARY_REMOTING_PARAMETERS_NO_PAYLOAD_LIMIT); clientWithHttpProxy.getTestNumber(); proxyServer.verify(getRequestedFor(urlMatching(GET_ENDPOINT)) .withHeader(AtlasDbInterceptors.USER_AGENT_HEADER, WireMock.equalTo(LEGACY_USER_AGENT_STRING))); availableServer1.verify(0, getRequestedFor(urlMatching(GET_ENDPOINT))); }
Source:
private void setArticleCategories(Article article, List<WeightedTerm> categories) { categories.sort(WeightedTerm.BY_DESCENDING_WEIGHT); List<WeightedTerm> results = new ArrayList<>(categories.size()); Set<String> uniqueLeafs = new HashSet<>(); for (WeightedTerm s : categories) { if (s.getTerm().charAt(0) != '/') { throw new IllegalArgumentException("Bad category: " + s); } if (uniqueLeafs.size() == 8 && !uniqueLeafs.contains(s.getLeafTerm()) ) { break; } else { uniqueLeafs.add(s.getLeafTerm()); results.add(s); } } Map<Category, Integer> categoryEntities = resolveIntoCategoryEntities(results); article.setCategories(categoryEntities); }

Target:
private void setArticleCategories(Article article, List<WeightedTerm> categories) { categories = WeightedTerm.BY_DESCENDING_WEIGHT.immutableSortedCopy(categories); List<WeightedTerm> results = new ArrayList<>(categories.size()); Set<String> uniqueLeafs = new HashSet<>(); for (WeightedTerm s : categories) { if (s.getPath().charAt(0) != '/') { throw new IllegalArgumentException("Bad category: " + s); } if (uniqueLeafs.size() == CATEGORY_COUNT && !uniqueLeafs.contains(s.getLeafTerm())) { break; } else { uniqueLeafs.add(s.getLeafTerm()); results.add(s); } } Map<Category, Integer> categoryEntities = resolveIntoCategoryEntities(results); article.setCategories(categoryEntities); }
Source:
public void onDestroy() { mMediaUploadHandler.cancelInProgressUploads(); mPostUploadHandler.cancelInProgressUploads(); for (Integer postId : sCompletedMediaByPost.keySet()) { PostModel updatedPost = updatePostWithCurrentlyCompletedUploads(mPostStore.getPostByLocalPostId(postId)); mDispatcher.dispatch(PostActionBuilder.newUpdatePostAction(updatedPost)); } mDispatcher.unregister(this); mMediaUploadHandler.unregister(); mPostUploadHandler.unregister(); AppLog.i(T.MAIN, "UploadService > Destroyed"); super.onDestroy(); }

Target:
public void onDestroy() { if (mMediaUploadHandler != null) { mMediaUploadHandler.cancelInProgressUploads(); mMediaUploadHandler.unregister(); } if (mPostUploadHandler != null) { mPostUploadHandler.cancelInProgressUploads(); mPostUploadHandler.unregister(); } for (Integer postId : sCompletedMediaByPost.keySet()) { PostModel updatedPost = updatePostWithCurrentlyCompletedUploads(mPostStore.getPostByLocalPostId(postId)); mDispatcher.dispatch(PostActionBuilder.newUpdatePostAction(updatedPost)); } mDispatcher.unregister(this); AppLog.i(T.MAIN, "UploadService > Destroyed"); super.onDestroy(); }
Source:
public void mucDestroyTest() throws TimeoutException, Exception { EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-join-leave-" + randomString), mucService.getDomain()); MultiUserChat muc = mucManagerOne.getMultiUserChat(mucAddress); muc.join(Resourcepart.from("nick-one")); final SimpleResultSyncPoint mucDestroyed = new SimpleResultSyncPoint(); UserStatusListener userStatusListener = new UserStatusListener() { @Override public void voiceRevoked() { } @Override public void voiceGranted() { } @Override public void roomDestroyed(MultiUserChat alternateMUC, String reason) { mucDestroyed.signal(); } @Override public void ownershipRevoked() { } @Override public void ownershipGranted() { } @Override public void moderatorRevoked() { } @Override public void moderatorGranted() { } @Override public void membershipRevoked() { } @Override public void membershipGranted() { } @Override public void kicked(Jid actor, String reason) { } @Override public void banned(Jid actor, String reason) { } @Override public void adminRevoked() { } @Override public void adminGranted() { } }; muc.addUserStatusListener(userStatusListener); assertTrue(mucManagerOne.getJoinedRooms().size() == 1); assertTrue(muc.getOccupantsCount() == 1); assertTrue(muc.getNickname() != null); try { muc.destroy("Dummy reason", null); mucDestroyed.waitForResult(timeout); } finally { muc.removeUserStatusListener(userStatusListener); } assertTrue(mucManagerOne.getJoinedRooms().size() == 0); assertTrue(muc.getOccupantsCount() == 0); assertTrue(muc.getNickname() == null); }

Target:
public void mucDestroyTest() throws TimeoutException, Exception { EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-join-leave-" + randomString), mucService.getDomain()); MultiUserChat muc = mucManagerOne.getMultiUserChat(mucAddress); muc.join(Resourcepart.from("nick-one")); final SimpleResultSyncPoint mucDestroyed = new SimpleResultSyncPoint(); @SuppressWarnings("deprecation") DefaultUserStatusListener userStatusListener = new DefaultUserStatusListener() { @Override public void roomDestroyed(MultiUserChat alternateMUC, String reason) { mucDestroyed.signal(); } }; muc.addUserStatusListener(userStatusListener); assertTrue(mucManagerOne.getJoinedRooms().size() == 1); assertTrue(muc.getOccupantsCount() == 1); assertTrue(muc.getNickname() != null); try { muc.destroy("Dummy reason", null); mucDestroyed.waitForResult(timeout); } finally { muc.removeUserStatusListener(userStatusListener); } assertTrue(mucManagerOne.getJoinedRooms().size() == 0); assertTrue(muc.getOccupantsCount() == 0); assertTrue(muc.getNickname() == null); }
Source:
public void testApplyBlockUpdatesToTrainingDataDuringEpoch() { final int numTotalInstances = MINI_BATCH_SIZE * 10; createTrainingData(numTotalInstances); trainingDataProvider.prepareDataForEpoch(); final List <Pair<Integer, Map<Long, Integer>>> addedBlockList = testGetNextTrainingDataWithBlockAdditions(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingDataWithBlockRemovals(addedBlockList); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }

Target:
public void testApplyBlockUpdatesToTrainingDataDuringEpoch() { final int numMiniBatches = 10; final int numTotalInstances = MINI_BATCH_SIZE * numMiniBatches; createTrainingData(numTotalInstances); trainingDataProvider.prepareDataForEpoch(); final List <Pair<Integer, Map<Long, Integer>>> addedBlockList = testGetNextTrainingDataWithBlockAdditions(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingDataWithBlockRemovals(addedBlockList); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }
Source:
public void euqal_shouldPreventAddingTwoEqualObjectsToACollection() { Set<CohortMembership> cohortMembershipSet = new LinkedHashSet<>(); final int PATIENT_ID = 12; CohortMembership cohortMembershipOne = new CohortMembership(PATIENT_ID); CohortMembership cohortMembershipTwo = new CohortMembership(PATIENT_ID); final int TIMESTAMP_START_DATE = 1545140935; final int TIMESTAMP_END_DATE = 1577836801; Date startDate1 = new Date(TIMESTAMP_START_DATE); Date endDate1 = new Date(TIMESTAMP_END_DATE); Date startDate2 = new Date(TIMESTAMP_START_DATE); Date endDate2 = new Date(TIMESTAMP_END_DATE); cohortMembershipOne.setEndDate(endDate1); cohortMembershipOne.setStartDate(startDate1); cohortMembershipTwo.setStartDate(startDate2); cohortMembershipTwo.setEndDate(endDate2); cohortMembershipSet.add(cohortMembershipOne); cohortMembershipSet.add(cohortMembershipTwo); assertEquals(cohortMembershipSet.size(), 1); }

Target:
public void euqal_shouldPreventAddingTwoEqualObjectsToACollection() { Set<CohortMembership> cohortMembershipSet = new LinkedHashSet<>(); final int PATIENT_ID = 12; CohortMembership cohortMembershipOne = new CohortMembership(PATIENT_ID); CohortMembership cohortMembershipTwo = new CohortMembership(PATIENT_ID); Date startDate1 = new Date(TIMESTAMP_START_DATE); Date endDate1 = new Date(TIMESTAMP_END_DATE); Date startDate2 = new Date(TIMESTAMP_START_DATE); Date endDate2 = new Date(TIMESTAMP_END_DATE); cohortMembershipOne.setEndDate(endDate1); cohortMembershipOne.setStartDate(startDate1); cohortMembershipTwo.setStartDate(startDate2); cohortMembershipTwo.setEndDate(endDate2); cohortMembershipSet.add(cohortMembershipOne); cohortMembershipSet.add(cohortMembershipTwo); assertEquals(cohortMembershipSet.size(), 1); }
Source:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { if (Iterables.contains(allModules(getTrace()), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); resetView(trace); } break; } } } } }

Target:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { if (Iterables.contains(allModules(getTrace()), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); getDataProvider().startedAnalysisSignalHandler((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); resetView(trace); } break; } } } } }
Source:
public void setHeight(int height) { int oldHeight = this.fHeight; this.fHeight = height; if (oldHeight != height) { getParent().layout(new Control[] { this }); } }

Target:
public void setHeight(int height) { if (fHeight != height) { fHeight = height; getParent().layout(new Control[] { this }); } }
Source:
public void onSave() { boolean isInternal = (Boolean) getIsInternal().getEntity(); if (isInternal) { DiskImage diskImage = getDiskImage(); if (getQuota().getIsAvailable() && getQuota().getSelectedItem() != null) { diskImage.setQuotaId(((Quota) getQuota().getSelectedItem()).getId()); } long sizeToAddInGigabytes = Long.valueOf((String) getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } setDisk(diskImage); } else { LunDisk lunDisk = getLunDisk(); DiskInterface diskInterface = (DiskInterface) getDiskInterface().getSelectedItem(); if (DiskInterface.VirtIO_SCSI.equals(diskInterface)) { lunDisk.setSgio(Boolean.TRUE.equals((Boolean) getIsSgIoUnfiltered().getEntity()) ? ScsiGenericIO.UNFILTERED : ScsiGenericIO.FILTERED); } setDisk(lunDisk); } getDisk().setDiskAlias((String) getAlias().getEntity()); getDisk().setDiskDescription((String) getDescription().getEntity()); getDisk().setDiskInterface((DiskInterface) getDiskInterface().getSelectedItem()); getDisk().setWipeAfterDelete((Boolean) getIsWipeAfterDelete().getEntity()); getDisk().setBoot((Boolean) getIsBootable().getEntity()); getDisk().setShareable((Boolean) getIsShareable().getEntity()); getDisk().setPlugged((Boolean) getIsPlugged().getEntity()); getDisk().setPropagateErrors(PropagateErrors.Off); if (getIsReadOnly().getIsAvailable()) { getDisk().setReadOnly((Boolean) getIsReadOnly().getEntity()); } else { getDisk().setReadOnly(false); } }

Target:
public void onSave() { boolean isInternal = (Boolean) getIsInternal().getEntity(); if (isInternal) { DiskImage diskImage = getDiskImage(); if (getQuota().getIsAvailable() && getQuota().getSelectedItem() != null) { diskImage.setQuotaId(((Quota) getQuota().getSelectedItem()).getId()); } long sizeToAddInGigabytes = Long.valueOf((String) getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } setDisk(diskImage); } else { LunDisk lunDisk = getLunDisk(); DiskInterface diskInterface = (DiskInterface) getDiskInterface().getSelectedItem(); if (DiskInterface.VirtIO_SCSI.equals(diskInterface)) { lunDisk.setSgio(Boolean.TRUE.equals((Boolean) getIsSgIoUnfiltered().getEntity()) ? ScsiGenericIO.UNFILTERED : ScsiGenericIO.FILTERED); } setDisk(lunDisk); } getDisk().setDiskAlias((String) getAlias().getEntity()); getDisk().setDiskDescription((String) getDescription().getEntity()); getDisk().setDiskInterface((DiskInterface) getDiskInterface().getSelectedItem()); getDisk().setWipeAfterDelete((Boolean) getIsWipeAfterDelete().getEntity()); getDisk().setBoot((Boolean) getIsBootable().getEntity()); getDisk().setShareable((Boolean) getIsShareable().getEntity()); getDisk().setPlugged((Boolean) getIsPlugged().getEntity()); getDisk().setPropagateErrors(PropagateErrors.Off); getDisk().setReadOnly(getIsReadOnly().getIsAvailable() ? (Boolean) getIsReadOnly().getEntity() : null); }
Source:
public Consumer createConsumer(Processor processor) throws Exception { throw new NoSuchEndpointException("Workday producer is not implemented."); }

Target:
public Consumer createConsumer(Processor processor) throws Exception { throw new NoSuchEndpointException("Workday consumer is not implemented."); }
Source:
public void onEvent(final PushLinkReceivedEvent event) { if (!isInForeground) { return; } showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.view_button_text), (dialog, which) -> PushLinkManager.INSTANCE.userGrantedPushLinkAction(this, event.getPushLink()), getString(R.string.label_cancel), null ); }

Target:
public void onEvent(final PushLinkReceivedEvent event) { if (event.getPushLink().isDeepLink()) { showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.view_button_text), (dialog, which) -> PushLinkManager.INSTANCE.onPushLinkActionGranted(this, event.getPushLink()), getString(R.string.label_cancel), null ); } else { showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.label_ok), null, getString(R.string.label_cancel), null ); } }
Source:
protected void runTask() { telescopeReporter = OwlTelescopeReporterFactory.getInstance() .getTelescopeReporter( OwlTelescopeReporters.RADIO_TIMES_INGESTER, Event.Type.INGEST); telescopeReporter.startReporting(); String requestUri = feedUrl; if (doCompleteUpdate) { requestUri += "/since?lastUpdated=" + UrlEncoding.encode(dateFormat.print(START_DATE)); } else { requestUri += "/since?lastUpdated=" + UrlEncoding .encode(dateFormat.print(new DateTime(DateTimeZone.UTC).minusDays(3))); } try { reportStatus("Started..."); getAndTransform(feedUrl); } catch (Exception e) { AdapterLogEntry errorRecord = errorEntry() .withCause(e) .withSource(getClass()) .withUri(requestUri) .withDescription("Exception while fetching film feed"); log.record(errorRecord); reportStatus("Failed: " + errorRecord.id()); telescopeReporter.reportFailedEvent("Failed with exception. Ingest stopped abruptly. " + e.getMessage(), EntityType.FILM, requestUri, errorRecord); Throwables.propagate(e); } finally { telescopeReporter.endReporting(); } }

Target:
protected void runTask() { telescopeReporter = OwlTelescopeReporterFactory.getInstance() .getTelescopeReporter( OwlTelescopeReporters.RADIO_TIMES_INGESTER, Event.Type.INGEST); telescopeReporter.startReporting(); String requestUri = feedUrl; if (doCompleteUpdate) { requestUri += "/since?lastUpdated=" + UrlEncoding.encode(dateFormat.print(START_DATE)); } else { requestUri += "/since?lastUpdated=" + UrlEncoding .encode(dateFormat.print(new DateTime(DateTimeZone.UTC).minusDays(3))); } try { reportStatus("Started..."); getAndTransform(requestUri); } catch (Exception e) { AdapterLogEntry errorRecord = errorEntry() .withCause(e) .withSource(getClass()) .withUri(requestUri) .withDescription("Exception while fetching film feed"); log.record(errorRecord); reportStatus("Failed: " + errorRecord.id()); telescopeReporter.reportFailedEvent("Failed with exception. Ingest stopped abruptly. " + e.getMessage(), EntityType.FILM, requestUri, errorRecord); Throwables.propagate(e); } finally { telescopeReporter.endReporting(); } }
Source:
public long getCurrentUidValidity() throws MessagingException { if (isOpen()) { close(); } store.releaseConnection(connection); try { synchronized (this) { connection = store.getConnection(); } String openCommand = "EXAMINE"; String encodedFolderName = folderNameCodec.encode(getPrefixedName()); String escapedFolderName = ImapUtility.encodeString(encodedFolderName); String command = String.format("%s %s", openCommand, escapedFolderName); List<ImapResponse> responses = executeSimpleCommand(command); return SelectOrExamineResponse.extractUidValidity(responses); } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to open connection for " + getLogId(), me); throw me; } }

Target:
public long getCurrentUidValidity() throws MessagingException { if (isOpen()) { close(); } try { List<ImapResponse> responses = internalOpen(OPEN_MODE_RO); return SelectOrExamineResponse.extractUidValidity(responses); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to open connection for " + getLogId(), me); throw me; } }
Source:
public void testSamFileVersion1pt5() throws Exception { final SamReader samReader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(new File(TEST_DATA_DIR, "test_samfile_version_1pt5.bam")); final Histogram<String> results = executeValidation(samReader, null, IndexValidationStringency.EXHAUSTIVE); Assert.assertFalse(results.isEmpty()); }

Target:
public void testSamFileVersion1pt5() throws Exception { final SamReader samReader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(new File(TEST_DATA_DIR, "test_samfile_version_1pt5.bam")); final Histogram<String> results = executeValidation(samReader, null, IndexValidationStringency.EXHAUSTIVE); Assert.assertEquals(results.getCount(),2.0); }
Source:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; final boolean shouldPerformOpOnVmSnapshots = !diskImage.isShareable(); try { if (shouldPerformOpOnVmSnapshots) { VM vm = getVmForNonShareableDiskImage(diskImage); lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { updatedSnapshots = null; } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); if (updatedSnapshots != null) { for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } } return null; } }); } finally { if (shouldPerformOpOnVmSnapshots){ freeVmSnapshotsLock(); } } }

Target:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; final boolean shouldPerformOpOnVmSnapshots = !diskImage.isShareable(); try { if (shouldPerformOpOnVmSnapshots) { VM vm = getVmForNonShareableDiskImage(diskImage); lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { updatedSnapshots = Collections.emptyList(); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } return null; } }); } finally { if (shouldPerformOpOnVmSnapshots) { freeVmSnapshotsLock(); } } }
Source:
protected Map<String, String> getInternalAddressesAndPorts(ContainerInfo containerInfo, String internalHost) { String internalAddressContainer = containerInfo.getNetworkSettings().getIpAddress(); String internalAddress; boolean useExposedPorts = true; if (internalAddressContainer != null && !internalAddressContainer.isEmpty()) { internalAddress = internalAddressContainer; } else { internalAddress = internalHost; useExposedPorts = false; } Map<String, List<PortBinding>> portBindings = containerInfo.getNetworkSettings().getPorts(); Map<String, String> addressesAndPorts = new HashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : portBindings.entrySet()) { String exposedPort = portEntry.getKey().split("/")[0]; String ephemeralPort = portEntry.getValue().get(0).getHostPort(); if (useExposedPorts) { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + exposedPort); } else { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + ephemeralPort); } } return addressesAndPorts; }

Target:
protected Map<String, String> getInternalAddressesAndPorts(ContainerInfo containerInfo, String internalHost) { String internalAddressContainer = containerInfo.getNetworkSettings().getIpAddress(); String internalAddress; boolean useExposedPorts = true; if (!isNullOrEmpty(internalAddressContainer)) { internalAddress = internalAddressContainer; } else { internalAddress = internalHost; useExposedPorts = false; } Map<String, List<PortBinding>> portBindings = containerInfo.getNetworkSettings().getPorts(); Map<String, String> addressesAndPorts = new HashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : portBindings.entrySet()) { String exposedPort = portEntry.getKey().split("/")[0]; String ephemeralPort = portEntry.getValue().get(0).getHostPort(); if (useExposedPorts) { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + exposedPort); } else { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + ephemeralPort); } } return addressesAndPorts; }
Source:
private boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) { String requestResource = request.uri().substring(1); if (requestResource.isEmpty()) { requestResource = "index.html"; } URL resourceUrl = getClass().getResource(requestResource); if (resourceUrl == null) { return false; } RandomAccessFile raf; long fileLength; try { raf = new RandomAccessFile(resourceUrl.getFile(), "r"); fileLength = raf.length(); } catch (IOException io) { System.out.println("File not found " + io.getMessage()); return false; } HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK); HttpUtil.setContentLength(response, fileLength); String contentType = "application/octet-stream"; if (requestResource.endsWith("html")) { contentType = "text/html; charset=UTF-8"; } else if (requestResource.endsWith("css")) { contentType = "text/css; charset=UTF-8"; } else if (requestResource.endsWith("js")) { contentType = "application/javascript"; } response.headers().set(CONTENT_TYPE, contentType); sendResponse(response, ctx, false); ctx.writeAndFlush(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); return true; }

Target:
private static boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) { if (request.uri().isEmpty() || !request.uri().startsWith("/")) { return false; } String requestResource = request.uri().substring(1); if (requestResource.isEmpty()) { requestResource = "index.html"; } URL resourceUrl = INSTANCE.getClass().getResource(requestResource); if (resourceUrl == null) { return false; } RandomAccessFile raf = null; long fileLength = -1L; try { raf = new RandomAccessFile(resourceUrl.getFile(), "r"); fileLength = raf.length(); } catch (FileNotFoundException fne) { System.out.println("File not found " + fne.getMessage()); return false; } catch (IOException io) { System.out.println("Cannot read file length " + io.getMessage()); return false; } finally { if (fileLength < 0 && raf != null) { try { raf.close(); } catch (IOException io) { } } } HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK); HttpUtil.setContentLength(response, fileLength); String contentType = "application/octet-stream"; if (requestResource.endsWith("html")) { contentType = "text/html; charset=UTF-8"; } else if (requestResource.endsWith("css")) { contentType = "text/css; charset=UTF-8"; } else if (requestResource.endsWith("js")) { contentType = "application/javascript"; } response.headers().set(CONTENT_TYPE, contentType); sendResponse(response, ctx, false); ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); return true; }
Source:
public void storeToken(String tokenHash, String randomTokenLink, String accountId, String description) { Integer rowsUpdated = jdbi.withHandle(handle -> handle.insert("INSERT INTO tokens(token_hash, token_link, description, account_id) VALUES (?,?,?,?)", tokenHash, randomTokenLink, description, accountId) ); if (rowsUpdated != 1) { log.error("Unable to store new token for account {}", accountId); throw new RuntimeException(String.format("Unable to store new token for account %s}", accountId)); } }

Target:
public void storeToken(String tokenHash, String randomTokenLink, String accountId, String description) { Integer rowsUpdated = jdbi.withHandle(handle -> handle.insert("INSERT INTO tokens(token_hash, token_link, description, account_id) VALUES (?,?,?,?)", tokenHash, randomTokenLink, description, accountId) ); if (rowsUpdated != 1) { log.error("Unable to store new token for account '{}'. '{}' rows were updated", accountId, rowsUpdated); throw new RuntimeException(String.format("Unable to store new token for account %s}", accountId)); } }
Source:
public final void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); wasCustomHandlerInvoked = false; }

Target:
public void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); }
Source:
public ComponentRef<BackupSender> getBackupSender() { return basicComponentRegistry.getComponent(BackupSender.class); }

Target:
public ComponentRef<BackupSender> getBackupSender() { return backupSender; }
Source:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); kind = ( "desc".equalsIgnoreCase( order ) ) ? Order.DESC : Order.ASC; }

Target:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; }
Source:
public boolean update(String path, DataUpdater<T> updater, int options) { T newRecord = null; boolean exceptionDuringUpdater = false; try { newRecord = updater.update(pathToRecords.get(path)); } catch (Exception e) { exceptionDuringUpdater = true; } if (exceptionDuringUpdater) { return false; } else { System.out.println("Updating to store path: " + path + ", record: " + newRecord.toString()); return setAndNotify(path, newRecord); } }

Target:
public boolean update(String path, DataUpdater<T> updater, int options) { T newRecord = null; boolean exceptionDuringUpdater = false; try { newRecord = updater.update(pathToRecords.get(path)); } catch (Exception e) { exceptionDuringUpdater = true; } if (exceptionDuringUpdater) { return false; } else { return setAndNotify(path, newRecord); } }
Source:
private Signature createSignature(String encodedHeader, String encodedClaims) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, RealmUnavailableException { Signature signature = Signature.getInstance(resolveAlgorithm(encodedHeader)); Iterator<PemEntry<?>> pemEntryIterator = Pem.parsePemContent(CodePointIterator.ofUtf8Bytes(this.publicKey)); PublicKey publicKey = (PublicKey) pemEntryIterator.next().getEntry(); signature.initVerify(publicKey); signature.update((encodedHeader + "." + encodedClaims).getBytes()); return signature; }

Target:
private Signature createSignature(String encodedHeader, String encodedClaims) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, RealmUnavailableException { Signature signature = Signature.getInstance(resolveAlgorithm(encodedHeader)); signature.initVerify(this.publicKey); signature.update((encodedHeader + "." + encodedClaims).getBytes()); return signature; }
Source:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { return targetTierPrice.multiply(new BigDecimal(targetQuantity)); }

Target:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { return targetTierPrice.multiply(BigDecimal.valueOf(targetQuantity)); }
Source:
private boolean suggestionEqualsUserEntry(List<String> candidates, String chunk, int suggestionOffset) { if (chunk == null) { return false; } if (suggestionOffset > 0) { return candidates.size() == 1 && chunk.substring(suggestionOffset).equals(candidates.get(0)); } else { return candidates.size() == 1 && chunk.equals(candidates.get(0)); } }

Target:
private boolean suggestionEqualsUserEntry(List<String> candidates, String chunk, int suggestionOffset) { if (chunk == null || candidates.size() != 1) { return false; } if (suggestionOffset > 0) { return chunk.substring(suggestionOffset).equals(candidates.get(0)); } else { return chunk.equals(candidates.get(0)); } }
Source:
public IMetaStoreClient getMSC() { connectionStats.incrementMetastoreCalls(); return msClient; }

Target:
IMetaStoreClient getMSC() { connectionStats.incrementMetastoreCalls(); return msClient; }
Source:
public void testCanvasCommandUndoWithRows() { relation.getRow().add(new List()); relation.getRow().get(0).getExpression().add(new LiteralExpression()); ((LiteralExpression) relation.getRow().get(0).getExpression().get(0)).setText("value"); uiModel.appendRow(new DMNGridRow()); uiModelMapper.fromDMNModel(0, 1); makeCommand(); final Command<AbstractCanvasHandler, CanvasViolation> cc = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.execute(handler)); reset(command, canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.undo(handler)); assertEquals(2, uiModel.getColumnCount()); assertEquals(uiRowNumberColumn, uiModel.getColumns().get(0)); assertEquals(uiModelColumn, uiModel.getColumns().get(1)); assertEquals(1, uiModel.getRowCount()); assertEquals(1, uiModel.getRows().get(0).getCells().size()); assertEquals("value", uiModel.getCell(0, 1).getValue().getValue()); verify(command).updateParentInformation(); verify(canvasOperation).execute(); }

Target:
public void testCanvasCommandUndoWithRows() { relation.getRow().add(new List()); final LiteralExpression literalExpression = new LiteralExpression(); literalExpression.setText(VALUE); relation.getRow().get(0).getExpression().add(literalExpression); uiModel.appendRow(new DMNGridRow()); uiModelMapper.fromDMNModel(0, 1); makeCommand(); final Command<AbstractCanvasHandler, CanvasViolation> cc = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.execute(handler)); reset(command, canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.undo(handler)); assertEquals(2, uiModel.getColumnCount()); assertEquals(uiRowNumberColumn, uiModel.getColumns().get(0)); assertEquals(uiModelColumn, uiModel.getColumns().get(1)); assertEquals(1, uiModel.getRowCount()); assertEquals(1, uiModel.getRows().get(0).getCells().size()); assertEquals(VALUE, uiModel.getCell(0, 1).getValue().getValue()); verify(command).updateParentInformation(); verify(canvasOperation).execute(); }
Source:
public JsonNode getJson() { if (json == null || json.toString().isEmpty()) { ObjectNode root = JsonNodeFactory.instance.objectNode(); ArrayNode resps = JsonNodeFactory.instance.arrayNode(); for (LightblueResponse resp : responses) { ObjectNode seqNode = JsonNodeFactory.instance.objectNode(); seqNode.set("seq", JsonNodeFactory.instance.numberNode(responses.indexOf(resp))); seqNode.set("response", resp.getJson()); resps.add(seqNode); } root.set("responsess", resps); json = root; } return json; }

Target:
public JsonNode getJson() { if (json == null) { ObjectNode root = JsonNodeFactory.instance.objectNode(); ArrayNode resps = JsonNodeFactory.instance.arrayNode(); for (Entry<Integer, LightblueResponse> resp : responses.entrySet()) { ObjectNode seqNode = JsonNodeFactory.instance.objectNode(); seqNode.set("seq", JsonNodeFactory.instance.numberNode(resp.getKey())); seqNode.set("response", resp.getValue().getJson()); resps.add(seqNode); } root.set("responsess", resps); json = root; } return json; }
Source:
private void submitMergePlan(final MergeNormalizationPlan plan) { final int totalSizeMb; try { final long totalSizeMbLong = plan.getNormalizationTargets() .stream() .mapToLong(NormalizationTarget::getRegionSizeMb) .reduce(0, Math::addExact); totalSizeMb = Math.toIntExact(totalSizeMbLong); } catch (ArithmeticException e) { LOG.debug("Sum of merge request size overflows rate limiter data type. {}", plan); planSkipped(plan.getType()); return; } final RegionInfo[] infos = plan.getNormalizationTargets() .stream() .map(NormalizationTarget::getRegionInfo) .toArray(RegionInfo[]::new); final long rateLimitedSecs = Math.round(rateLimiter.acquire(Math.max(1, totalSizeMb))); LOG.debug("Rate limiting delayed this operation by {}", Duration.ofSeconds(rateLimitedSecs)); final long pid; try { pid = masterServices.mergeRegions( infos, false, HConstants.NO_NONCE, HConstants.NO_NONCE); } catch (IOException e) { LOG.debug("failed to submit plan {}.", plan, e); planSkipped(plan.getType()); return; } mergePlanCount++; LOG.debug("Submitted resulting in pid {}", plan, pid); }

Target:
private void submitMergePlan(final MergeNormalizationPlan plan) { final int totalSizeMb; try { final long totalSizeMbLong = plan.getNormalizationTargets() .stream() .mapToLong(NormalizationTarget::getRegionSizeMb) .reduce(0, Math::addExact); totalSizeMb = Math.toIntExact(totalSizeMbLong); } catch (ArithmeticException e) { LOG.debug("Sum of merge request size overflows rate limiter data type. {}", plan); planSkipped(plan.getType()); return; } final RegionInfo[] infos = plan.getNormalizationTargets() .stream() .map(NormalizationTarget::getRegionInfo) .toArray(RegionInfo[]::new); final long pid; try { pid = masterServices.mergeRegions( infos, false, HConstants.NO_NONCE, HConstants.NO_NONCE); } catch (IOException e) { LOG.info("failed to submit plan {}.", plan, e); planSkipped(plan.getType()); return; } mergePlanCount++; LOG.info("Submitted resulting in pid {}", plan, pid); final long rateLimitedSecs = Math.round(rateLimiter.acquire(Math.max(1, totalSizeMb))); LOG.debug("Rate limiting delayed the worker by {}", Duration.ofSeconds(rateLimitedSecs)); }