auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void executeCommand() { Map<Boolean, List<VM>> vms = vmDao.getForDisk(getParameters().getImageGroupId(), true); boolean attachedToVms = vms.computeIfAbsent(Boolean.TRUE, b -> new ArrayList<>()) .stream() .anyMatch(VM::isDown); if (!vms.isEmpty() && attachedToVms && storageDomainDao.get(getParameters().getStorageDomainId()).getStorageType().isBlockDomain()) { if (!executeWithHost(getParameters().getVdsRunningOn(), host -> imagesHandler.prepareImage(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupId(), getParameters().getImageId(), host).getSucceeded())) { log.error("Failed to prepare image '{}/{}'", getParameters().getImageGroupId(), getParameters().getImageId()); return; } getParameters().setShouldTeardown(true); } long volumeSize = (long) vdsCommandsHelper.runVdsCommandWithFailover( VDSCommandType.MeasureVolume, new MeasureVolumeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupId(), getParameters().getImageId(), getParameters().getDstVolFormat()), getParameters().getStoragePoolId(), null) .getReturnValue(); persistCommandIfNeeded(); setActionReturnValue(volumeSize); setSucceeded(true); }

Target:
protected void executeCommand() { Map<Boolean, List<VM>> vms = vmDao.getForDisk(getParameters().getImageGroupId(), true); if (!vms.isEmpty() && !isAttachedToRunningVMs(vms) && storageDomainDao.get(getParameters().getStorageDomainId()).getStorageType().isBlockDomain()) { if (!executeWithHost(getParameters().getVdsRunningOn(), host -> imagesHandler.prepareImage(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupId(), getParameters().getImageId(), host).getSucceeded())) { log.error("Failed to prepare image '{}/{}'", getParameters().getImageGroupId(), getParameters().getImageId()); return; } getParameters().setShouldTeardown(true); } long volumeSize = (long) vdsCommandsHelper.runVdsCommandWithFailover( VDSCommandType.MeasureVolume, new MeasureVolumeVDSCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupId(), getParameters().getImageId(), getParameters().getDstVolFormat()), getParameters().getStoragePoolId(), null) .getReturnValue(); persistCommandIfNeeded(); setActionReturnValue(volumeSize); setSucceeded(true); }
Source:
public void test() { connect(); sleep(600); Assert.assertTrue(jq(".z-tab").eq(16).hasClass("z-tab-selected")); Assert.assertEquals("true", getZKLog()); }

Target:
public void test() { connect(); waitResponse(); Assert.assertTrue(jq(".z-tab").eq(16).hasClass("z-tab-selected")); Assert.assertEquals("true", getZKLog()); }
Source:
private void executeFirstChunkedQuery() throws SQLException { boolean checkpointsSaved = _chunkingKeys.values().iterator().next() != null; if (checkpointsSaved) { prepareChunkedQuery(_queryStmt, new ArrayList<>(_chunkingKeys.values())); executeChunkedQuery(_queryStmt); } else { executeChunkedQuery(_firstStmt); } }

Target:
private void executeFirstChunkedQuery() throws SQLException { boolean checkpointsSaved = _chunkingKeys.values().iterator().next() != null; if (checkpointsSaved) { executeNextChunkedQuery(); } else { executeChunkedQuery(_firstStmt); } }
Source:
private void setFatalError(HL7InQueue hl7InQueue, String error, Throwable cause) { HL7InError hl7InError = new HL7InError(hl7InQueue); hl7InError.setError(error); if (cause == null) { hl7InError.setErrorDetails(""); } else { StringWriter sw = new StringWriter(); log.error(cause); sw.flush(); hl7InError.setErrorDetails(OpenmrsUtil.shortenedStackTrace(sw.toString())); } Context.getHL7Service().saveHL7InError(hl7InError); Context.getHL7Service().purgeHL7InQueue(hl7InQueue); log.info(error, cause); }

Target:
private void setFatalError(HL7InQueue hl7InQueue, String error, Throwable cause) { HL7InError hl7InError = new HL7InError(hl7InQueue); hl7InError.setError(error); if (cause == null) { hl7InError.setErrorDetails(""); } else { log.error(cause); hl7InError.setErrorDetails(ExceptionUtils.getStackTrace(cause)); } Context.getHL7Service().saveHL7InError(hl7InError); Context.getHL7Service().purgeHL7InQueue(hl7InQueue); log.info(error, cause); }
Source:
public String toString() { StringBuilder buf= new StringBuilder(); buf.append("Id: ").append(getErrorCode(fId)).append('\n'); buf.append('[').append(fOffset).append(", ").append(fLength).append(']').append('\n'); for (String a : fArguments) { buf.append(a); buf.append('\n'); } return buf.toString(); }

Target:
public String toString() { StringBuilder buf= new StringBuilder(); buf.append("Id: ").append(getErrorCode(fId)).append('\n'); buf.append('[').append(fOffset).append(", ").append(fLength).append(']').append('\n'); for (String arg : fArguments) { buf.append(arg); buf.append('\n'); } return buf.toString(); }
Source:
private void addSequencesFromCache( final List<Sequence<T>> listOfSequences, final List<Pair<Interval, byte[]>> cachedResults ) { if (strategy == null) { return; } final Function<Object, T> pullFromCacheFunction = strategy.pullFromCache(); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); for (Pair<Interval, byte[]> cachedResultPair : cachedResults) { final byte[] cachedResult = cachedResultPair.rhs; Sequence<Object> cachedSequence = new BaseSequence<>( new BaseSequence.IteratorMaker<Object, Iterator<Object>>() { @Override public Iterator<Object> make() { try { if (cachedResult.length == 0) { return Iterators.emptyIterator(); } return ((List<Object>) objectMapper.readValue( objectMapper.getFactory().createParser(cachedResult), cacheObjectClazz )).iterator(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void cleanup(Iterator<Object> iterFromMake) { } } ); listOfSequences.add(Sequences.map(cachedSequence, pullFromCacheFunction)); } }

Target:
private void addSequencesFromCache( final List<Sequence<T>> listOfSequences, final List<Pair<Interval, byte[]>> cachedResults ) { if (strategy == null) { return; } final Function<Object, T> pullFromCacheFunction = strategy.pullFromCache(); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); for (Pair<Interval, byte[]> cachedResultPair : cachedResults) { final byte[] cachedResult = cachedResultPair.rhs; Sequence<Object> cachedSequence = new BaseSequence<>( new BaseSequence.IteratorMaker<Object, Iterator<Object>>() { @Override public Iterator<Object> make() { try { if (cachedResult.length == 0) { return Iterators.emptyIterator(); } return objectMapper.readValues( objectMapper.getFactory().createParser(cachedResult), cacheObjectClazz ); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void cleanup(Iterator<Object> iterFromMake) { } } ); listOfSequences.add(Sequences.map(cachedSequence, pullFromCacheFunction)); } }
Source:
private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } } else { getLogger().error("Field has no tagger provider and cannot be tagged - [Gamma: %s]", gamma); } } catch (Exception ex) { getLogger().error(ex, "Unable to tag - [%s]", gamma); } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } return tagCollector.getTotalTags(); }

Target:
private long createTags(OseeConnection connection, Collection<IndexedResource> sources) throws OseeCoreException { SearchTagCollector tagCollector = new SearchTagCollector(); Set<Long> processed = new HashSet<Long>(); Map<Long, Collection<Long>> toStore = new HashMap<Long, Collection<Long>>(); for (IndexedResource source : sources) { long startItemTime = System.currentTimeMillis(); Long gamma = source.getGammaId(); if (processed.add(gamma)) { Set<Long> tags = new HashSet<Long>(); toStore.put(gamma, tags); tagCollector.setCurrentTag(gamma, tags); try { long typeUuid = source.getTypeUuid(); String taggerId = getTaggerIdByTypeUuid(typeUuid); if (taggingEngine.hasTagger(taggerId)) { Tagger tagger = taggingEngine.getTagger(taggerId); tagger.tagIt(source, tagCollector); if (isStorageAllowed(toStore)) { getLogger().debug("Stored a - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } } else { getLogger().error("Field has invalid tagger[%s] provider and cannot be tagged - [Gamma: %s]", taggerId, gamma); } } catch (Exception ex) { getLogger().error(ex, "Unable to tag - [%s]", gamma); } finally { long endItemTime = System.currentTimeMillis() - startItemTime; notifyOnIndexItemComplete(gamma, tags.size(), endItemTime); } } } if (!toStore.isEmpty()) { getLogger().debug("Stored b - [%s] - connectionId[%s] - [%s]", getTagQueueQueryId(), connection, toStore); storeTags(connection, toStore); } return tagCollector.getTotalTags(); }
Source:
public void resolve(List<Material> materials) { materials.stream() .filter((material) -> material instanceof SecretParamAware && ((SecretParamAware) material).hasSecretParams()) .forEach((material) -> { if (material instanceof ScmMaterial) { this.resolve((ScmMaterial) material); } else if (material instanceof PluggableSCMMaterial) { this.resolve((PluggableSCMMaterial) material); } }); }

Target:
public void resolve(List<Material> materials) { materials.stream() .filter((material) -> material instanceof SecretParamAware) .forEach(this::resolve); }
Source:
public void terminationProperties() { contextRunner .withPropertyValues("optaplanner.solver.termination.spent-limit=PT4H") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(Duration.ofHours(4), terminationConfig.getSpentLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); contextRunner .withPropertyValues("optaplanner.solver.termination.unimproved-spent-limit=PT5H") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(Duration.ofHours(5), terminationConfig.getUnimprovedSpentLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); contextRunner .withPropertyValues("optaplanner.solver.termination.best-score-limit=6") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(SimpleScore.of(6).toString(), terminationConfig.getBestScoreLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); }

Target:
public void terminationProperties() { contextRunner .withPropertyValues("optaplanner.solver.termination.spent-limit=4h") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(Duration.ofHours(4), terminationConfig.getSpentLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); contextRunner .withPropertyValues("optaplanner.solver.termination.unimproved-spent-limit=5h") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(Duration.ofHours(5), terminationConfig.getUnimprovedSpentLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); contextRunner .withPropertyValues("optaplanner.solver.termination.best-score-limit=6") .run(context -> { TerminationConfig terminationConfig = context.getBean(SolverConfig.class).getTerminationConfig(); assertEquals(SimpleScore.of(6).toString(), terminationConfig.getBestScoreLimit()); assertNotNull(context.getBean(SolverFactory.class)); }); }
Source:
private void validateAndSetNewDesignation(final int desigColumn, final Row xlsRow, final MeasurementRow measurementRow) throws WorkbookParserException { final String newDesig = this.getDesignation(xlsRow, desigColumn); setNewDesignation(measurementRow, newDesig); }

Target:
private void validateAndSetNewDesignation(final int desigColumn, final Row xlsRow, final MeasurementRow measurementRow) throws WorkbookParserException { final String newDesig = this.getDesignation(xlsRow, desigColumn); this.setNewDesignation(measurementRow, newDesig); }
Source:
public Member createSponsoredAccount(PerunSession sess, Map<String, String> params, String namespace, ExtSource extSource, String extSourcePostfix, Vo vo, int loa) throws InternalErrorException, PrivilegeException, UserNotExistsException, ExtSourceNotExistsException, UserExtSourceNotExistsException, WrongReferenceAttributeValueException, LoginNotExistsException, PasswordCreationFailedException, ExtendMembershipException, AlreadyMemberException, GroupOperationsException, PasswordStrengthFailedException, PasswordOperationTimeoutException, WrongAttributeValueException { Utils.checkPerunSession(sess); Utils.notNull(extSource, "extSource"); Utils.notNull(namespace, "namespace"); Utils.notNull(vo, "vo"); Utils.notNull(extSourcePostfix, "extSourcePostfix"); if (!AuthzResolver.isAuthorized(sess, Role.REGISTRAR, vo)) { throw new PrivilegeException(sess, "createSponsoredAccount"); } if(params.containsKey("sponsor")) { String sponsorLogin = params.get("sponsor"); User owner = getPerunBl().getUsersManager().getUserByExtSourceNameAndExtLogin(sess, extSource.getName(), sponsorLogin + extSourcePostfix); return getPerunBl().getMembersManagerBl().createSponsoredAccount(sess, params, namespace, extSource, extSourcePostfix, owner, vo, loa); } else { throw new InternalErrorException("sponsor cannot be null"); } }

Target:
public Member createSponsoredAccount(PerunSession sess, Map<String, String> params, String namespace, ExtSource extSource, String extSourcePostfix, Vo vo, int loa) throws InternalErrorException, PrivilegeException, UserNotExistsException, ExtSourceNotExistsException, UserExtSourceNotExistsException, WrongReferenceAttributeValueException, LoginNotExistsException, PasswordCreationFailedException, ExtendMembershipException, AlreadyMemberException, GroupOperationsException, PasswordStrengthFailedException, PasswordOperationTimeoutException, WrongAttributeValueException { Utils.checkPerunSession(sess); Utils.notNull(extSource, "extSource"); Utils.notNull(namespace, "namespace"); Utils.notNull(vo, "vo"); Utils.notNull(extSourcePostfix, "extSourcePostfix"); if (!AuthzResolver.isAuthorized(sess, Role.REGISTRAR)) { throw new PrivilegeException(sess, "createSponsoredAccount"); } if(params.containsKey("sponsor")) { String sponsorLogin = params.get("sponsor"); User owner = getPerunBl().getUsersManager().getUserByExtSourceNameAndExtLogin(sess, extSource.getName(), sponsorLogin + extSourcePostfix); return getPerunBl().getMembersManagerBl().createSponsoredAccount(sess, params, namespace, extSource, extSourcePostfix, owner, vo, loa); } else { throw new InternalErrorException("sponsor cannot be null"); } }
Source:
private void loadPathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (FileInputStream is = new FileInputStream(depFH)) { consoleLog.info("Loading Path configuration from " + depFH.getAbsolutePath()); m_pathList.load(is); is.close(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to read configuration path destination", false, e); } }

Target:
private void loadPathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (FileInputStream is = new FileInputStream(depFH)) { consoleLog.info("Loading Path configuration from " + depFH.getAbsolutePath()); m_pathList.load(is); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to read configuration path destination", false, e); } }
Source:
public SslContext getSslContext() { return sslContext; }

Target:
public SSLContext getSslContext() { return sslContext; }
Source:
public void listen(EntriesRemovedEvent entriesRemovedEvent) { citationStyleCache.invalidateAll(entriesRemovedEvent.getBibEntries()); }

Target:
public void listen(EntriesRemovedEvent entriesRemovedEvent) { for (BibEntry entry : entriesRemovedEvent.getBibEntries()) { citationStyleCache.invalidate(entry); } }
Source:
public static Number numeric(byte bytes, int pos, int numBytes) { if (numBytes < 8) { throw new IllegalArgumentException("number of bytes should be at-least 8"); } short len = ByteConverter.int2(bytes, pos); short weight = ByteConverter.int2(bytes, pos + 2); short sign = ByteConverter.int2(bytes, pos + 4); short scale = ByteConverter.int2(bytes, pos + 6); if (numBytes != (len * Short.BYTES) + 8) { throw new IllegalArgumentException("invalid length of bytes \"numeric\" value"); } if (!(sign == NUMERIC_POS || sign == NUMERIC_NEG || sign == NUMERIC_NAN)) { throw new IllegalArgumentException("invalid sign in \"numeric\" value"); } if (sign == NUMERIC_NAN) { return Double.NaN; } if ((scale & NUMERIC_DSCALE_MASK) != scale) { throw new IllegalArgumentException("invalid scale in \"numeric\" value"); } short[] digits = new short[len]; int idx = pos + 8; for (int i = 0; i < len; i++) { short d = ByteConverter.int2(bytes, idx); idx += 2; if (d < 0 || d >= NBASE) { throw new IllegalArgumentException("invalid digit in \"numeric\" value"); } digits[i] = d; } String numString = numberBytesToString(digits, scale, weight, sign); return new BigDecimal(numString); }

Target:
public static Number numeric(byte bytes, int pos, int numBytes) { if (numBytes < 8) { throw new IllegalArgumentException("number of bytes should be at-least 8"); } short len = ByteConverter.int2(bytes, pos); short weight = ByteConverter.int2(bytes, pos + 2); short sign = ByteConverter.int2(bytes, pos + 4); short scale = ByteConverter.int2(bytes, pos + 6); if (numBytes != (len * SHORT_BYTES + 8)) { throw new IllegalArgumentException("invalid length of bytes \"numeric\" value"); } if (!(sign == NUMERIC_POS || sign == NUMERIC_NEG || sign == NUMERIC_NAN)) { throw new IllegalArgumentException("invalid sign in \"numeric\" value"); } if (sign == NUMERIC_NAN) { return Double.NaN; } if ((scale & NUMERIC_DSCALE_MASK) != scale) { throw new IllegalArgumentException("invalid scale in \"numeric\" value"); } short[] digits = new short[len]; int idx = pos + 8; for (int i = 0; i < len; i++) { short d = ByteConverter.int2(bytes, idx); idx += 2; if (d < 0 || d >= NBASE) { throw new IllegalArgumentException("invalid digit in \"numeric\" value"); } digits[i] = d; } String numString = numberBytesToString(digits, scale, weight, sign); return new BigDecimal(numString); }
Source:
public void setState(boolean bold, boolean italic, boolean underlined, String text, int textSize, String font) { boldToggleButton.setChecked(bold); italicToggleButton.setChecked(italic); underlinedToggleButton.setChecked(underlined); textEditText.setText(text); fontSpinner.setSelection(fonts.indexOf(font)); textSizeSpinner.setSelection(sizes.indexOf(localeNumberFormat.format(textSize))); }

Target:
public void setState(boolean bold, boolean italic, boolean underlined, String text, int textSize, String font) { boldToggleButton.setChecked(bold); italicToggleButton.setChecked(italic); underlinedToggleButton.setChecked(underlined); textEditText.setText(text); fontSpinner.setSelection(fonts.indexOf(font)); }
Source:
public void coreLoggerBridge() { TestHelper.TestLogger testLogger = new TestHelper.TestLogger(); RealmLog.setLevel(LogLevel.INFO); RealmLog.add(testLogger); long ptr = RealmLog.nativeCreateCoreLoggerBridge("TEST"); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.INFO, "42"); assertTrue(testLogger.message.equals("42")); RealmLog.setLevel(LogLevel.FATAL); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.INFO, "44"); assertFalse(testLogger.message.equals("44")); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.FATAL, "45"); assertTrue(testLogger.message.equals("45")); RealmLog.nativeCloseCoreLoggerBridge(ptr); }

Target:
public void coreLoggerBridge() { TestHelper.TestLogger testLogger = new TestHelper.TestLogger(); RealmLog.setLevel(LogLevel.INFO); RealmLog.add(testLogger); long ptr = RealmLog.nativeCreateCoreLoggerBridge("TEST"); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.INFO, "42"); assertTrue(testLogger.message.equals("42")); RealmLog.setLevel(LogLevel.FATAL); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.INFO, "44"); assertTrue(testLogger.message.equals("42")); assertFalse(testLogger.message.equals("44")); RealmLog.nativeLogToCoreLoggerBridge(ptr, LogLevel.FATAL, "45"); assertTrue(testLogger.message.equals("45")); RealmLog.nativeCloseCoreLoggerBridge(ptr); }
Source:
private void registerPostModelsForMedia(List<MediaModel> mediaList, boolean isRetry) { if (mediaList != null && !mediaList.isEmpty()) { Set<PostModel> postsToRefresh = PostUtils.getPostsThatIncludeThisMedia(mPostStore, mediaList); for (PostModel post : postsToRefresh) { mUploadStore.registerPostModel(post, mediaList); if (isThisPostTotallyNewOrFailed(post)) { mPostUploadNotifier.addPostInfoToForegroundNotification(post, null); } } if (isRetry) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_UPLOAD_MEDIA_ERROR_RETRY); EventBus.getDefault().post(new UploadService.UploadMediaRetryEvent(mediaList)); } } }

Target:
private void registerPostModelsForMedia(List<MediaModel> mediaList, boolean isRetry) { if (mediaList != null && !mediaList.isEmpty()) { Set<PostModel> postsToRefresh = PostUtils.getPostsThatIncludeAnyOfTheseMedia(mPostStore, mediaList); for (PostModel post : postsToRefresh) { if (!mUploadStore.isRegisteredPostModel(post)) { mUploadStore.registerPostModel(post, mediaList); } } if (isRetry) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_UPLOAD_MEDIA_ERROR_RETRY); EventBus.getDefault().post(new UploadService.UploadMediaRetryEvent(mediaList)); } } }
Source:
public Span createSpan() { final Tracer.SpanBuilder spanBuilder; final Span activeSpan = tracer.scopeManager().activeSpan(); if (activeSpan != null) { spanBuilder = tracer.buildSpan(operationName) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); } else { spanBuilder = tracer.buildSpan(operationName) .withTag(Tags.SAMPLING_PRIORITY.getKey(), 0) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); } if (trackMetricsPerOperationName()) { spanBuilder.withTag(MetricsSpanEventListener.ENABLE_TRACKING_METRICS_TAG, true); } spanBuilder.withTag(SpanUtils.OPERATION_TYPE, getType()); Span span = spanBuilder.start(); return span; }

Target:
public Span createSpan() { final Tracer.SpanBuilder spanBuilder; final Span activeSpan = tracer.scopeManager().activeSpan(); if (activeSpan != null) { spanBuilder = tracer.buildSpan(operationName) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); } else { spanBuilder = tracer.buildSpan(operationName) .withTag(Tags.SAMPLING_PRIORITY.getKey(), 0) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); } if (trackMetricsPerOperationName()) { spanBuilder.withTag(MetricsSpanEventListener.ENABLE_TRACKING_METRICS_TAG, true); } spanBuilder.withTag(SpanUtils.OPERATION_TYPE, getType()); return spanBuilder.start(); }
Source:
synchronized Map<Long, CacheContinuousQueryEntry> flushCurrentEntries( BiFunction<Long, Long, CacheContinuousQueryEntry> filteredFactory ) { Map<Long, CacheContinuousQueryEntry> res = new HashMap<>(); if (entries == null || filteredFactory == null) return res; long filtered = this.filtered; long cntr = startCntr; for (int i = 0; i < entries.length; i++) { CacheContinuousQueryEntry e = entries[i]; CacheContinuousQueryEntry flushEntry = null; if (e == null) { if (filtered != 0) { flushEntry = filteredFactory.apply(cntr - 1, filtered - 1); filtered = 0; } } else { if (e.isFiltered()) filtered++; else { flushEntry = new CacheContinuousQueryEntry(e.cacheId(), e.eventType(), e.key(), e.value(), e.oldValue(), e.isKeepBinary(), e.partition(), e.updateCounter(), e.topologyVersion(), e.flags()); flushEntry.filteredCount(filtered); filtered = 0; } } if (flushEntry != null) res.put(flushEntry.updateCounter(), flushEntry); cntr++; } if (filtered != 0L) { CacheContinuousQueryEntry flushEntry = filteredFactory.apply(cntr - 1, filtered - 1); res.put(flushEntry.updateCounter(), flushEntry); } return res; }

Target:
synchronized Map<Long, CacheContinuousQueryEntry> flushCurrentEntries( BiFunction<Long, Long, CacheContinuousQueryEntry> filteredFactory ) { if (entries == null || filteredFactory == null) return Collections.emptyMap(); Map<Long, CacheContinuousQueryEntry> res = new HashMap<>(); long filtered = this.filtered; long cntr = startCntr; for (int i = 0; i < entries.length; i++) { CacheContinuousQueryEntry e = entries[i]; CacheContinuousQueryEntry flushEntry = null; if (e == null) { if (filtered != 0) { flushEntry = filteredFactory.apply(cntr - 1, filtered - 1); filtered = 0; } } else { if (e.isFiltered()) filtered++; else { flushEntry = new CacheContinuousQueryEntry(e.cacheId(), e.eventType(), e.key(), e.value(), e.oldValue(), e.isKeepBinary(), e.partition(), e.updateCounter(), e.topologyVersion(), e.flags()); flushEntry.filteredCount(filtered); filtered = 0; } } if (flushEntry != null) res.put(flushEntry.updateCounter(), flushEntry); cntr++; } if (filtered != 0L) { CacheContinuousQueryEntry flushEntry = filteredFactory.apply(cntr - 1, filtered - 1); res.put(flushEntry.updateCounter(), flushEntry); } return res; }
Source:
public static ServerResponseWrapper invoke(HttpMethod method) throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS); final String proxyHost = System.getProperty("http.proxyHost"); final String proxyPort = System.getProperty("http.proxyPort"); final String nonProxyHosts = System.getProperty("http.nonProxyHosts"); httpClient.getHostConfiguration().setProxyHost( ProxyConfigurator.create(method, proxyHost, proxyPort, nonProxyHosts)); try { final int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_NOT_FOUND) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("Return Code: " + status); out.println("Few Possible Causes: "); out.println("1. Your Go Server is down or not accessible."); out.println("2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent."); out.close(); throw new Exception(sw.toString()); } if (status != HttpStatus.SC_OK) { throw new Exception("Got status " + status + " " + method.getStatusText() + " from server"); } for (Header header : method.getResponseHeaders()) { headers.put(header.getName(), header.getValue()); } return new ServerResponseWrapper(headers, method.getResponseBodyAsStream()); } catch (Exception e) { String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString(); LOG.error(message); throw new Exception(message, e); } finally { method.releaseConnection(); } }

Target:
public static ServerResponseWrapper invoke(HttpMethod method) throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS); httpClient.getHostConfiguration().setProxyHost( ProxyConfigurator.create(method, System.getProperties())); try { final int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_NOT_FOUND) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("Return Code: " + status); out.println("Few Possible Causes: "); out.println("1. Your Go Server is down or not accessible."); out.println("2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent."); out.close(); throw new Exception(sw.toString()); } if (status != HttpStatus.SC_OK) { throw new Exception("Got status " + status + " " + method.getStatusText() + " from server"); } for (Header header : method.getResponseHeaders()) { headers.put(header.getName(), header.getValue()); } return new ServerResponseWrapper(headers, method.getResponseBodyAsStream()); } catch (Exception e) { String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString(); LOG.error(message); throw new Exception(message, e); } finally { method.releaseConnection(); } }
Source:
public int getDispenseSlot() { Inventory inv = getInventory(); boolean allAir = true; if (inv.getItem(0).getType() != Material.AIR) allAir = false; if (inv.getItem(1).getType() != Material.AIR) allAir = false; if (inv.getItem(2).getType() != Material.AIR) allAir = false; if (inv.getItem(3).getType() != Material.AIR) allAir = false; if (inv.getItem(4).getType() != Material.AIR) allAir = false; if (inv.getItem(5).getType() != Material.AIR) allAir = false; if (inv.getItem(6).getType() != Material.AIR) allAir = false; if (inv.getItem(7).getType() != Material.AIR) allAir = false; if (inv.getItem(8).getType() != Material.AIR) allAir = false; if (allAir) { return 0; } else { int slot = 0; int tries = 0; while (true) { slot = random.nextInt(9); if (inv.getItem(slot).getType() != Material.AIR) break; tries += 1; if (tries == 20) { int i = 0; while (i < 9) { if (inv.getItem(i).getType() != Material.AIR) { slot = i; break; } } break; } } return slot; } }

Target:
public int getDispenseSlot() { return InventoryUtil.getRandomSlot(random, getInventory(), true); }
Source:
public String getProgress() { if (getHealth() == HealthType.Running) { if (numCycles != null && callCycle != null) { if (numCycles != 0) { return String.format("%d/%d", callCycle, numCycles); } } return "Running"; } return ""; }

Target:
public String getProgress() { if (getHealth() == HealthType.Running) { if (numCycles != null && callCycle != null) { if (numCycles != 0) { return String.format("Cycle %d of %d", callCycle, numCycles); } } return "Running"; } return ""; }
Source:
public Response add(ImageTransfer imageTransfer) { TransferDiskImageParameters params = new TransferDiskImageParameters(); if (imageTransfer.getDirection() != null && imageTransfer.getDirection().equals(ImageTransferDirection.DOWNLOAD)) { params.setIsDownloading(true); } params.setImageId(GuidUtils.asGuid(imageTransfer.getImage().getId())); params.setKeepaliveInterval(ConfigurationValues.UploadImageUiInactivityTimeoutInSeconds.getValue()); return performCreate(VdcActionType.TransferDiskImage, params, new QueryIdResolver<Guid>(VdcQueryType.GetImageTransferById, IdQueryParameters.class)); }

Target:
public Response add(ImageTransfer imageTransfer) { TransferDiskImageParameters params = new TransferDiskImageParameters(); if (imageTransfer.isSetDirection() && imageTransfer.getDirection().equals(ImageTransferDirection.DOWNLOAD)) { params.setTransferType(TransferType.Download); } params.setImageId(GuidUtils.asGuid(imageTransfer.getImage().getId())); params.setKeepaliveInterval(ConfigurationValues.UploadImageUiInactivityTimeoutInSeconds.getValue()); return performCreate(VdcActionType.TransferDiskImage, params, new QueryIdResolver<Guid>(VdcQueryType.GetImageTransferById, IdQueryParameters.class)); }
Source:
private static String encodeEntry(Entry<Object, Object> e) { String key = e.getKey().toString(); String value = e.getValue() == null ? "" : e.getValue().toString(); return urlEncode(key) + ">" + urlEncode(value); }

Target:
private static String encodeEntry(Entry<Object, Object> e) { String key = e.getKey().toString(); String value = e.getValue() == null ? "" : e.getValue().toString(); return urlEncode(key) + PROPERTIES_KV_SEPARATOR + urlEncode(value); }
Source:
public Boolean getMakeredundant() { if (makeredundant != null) { return makeredundant; } return false; }

Target:
public Boolean getMakeredundant() { return makeredundant; }
Source:
private void checkForCharactersBeforeProlog(FileSystem fileSystem) { try { int lineNb = 1; Pattern firstTagPattern = Pattern.compile("<[a-zA-Z?]+"); for (String line : Files.readLines(inputFile.file(), fileSystem.encoding())) { if (lineNb == 1 && line.length() > 0 && line.charAt(0) == '\ufeff') { characterDeltaForHighlight = -1; } Matcher m = firstTagPattern.matcher(line); if (m.find()) { int groupIndex = line.indexOf(m.group()); if (XML_PROLOG_START_TAG.equals(m.group()) && (groupIndex > 0 || lineNb > 1)) { hasCharsBeforeProlog = true; } break; } lineNb++; } if (hasCharsBeforeProlog) { processCharBeforePrologInFile(fileSystem, lineNb); } } catch (IOException e) { LOG.warn("Unable to analyse file {}", inputFile.absolutePath(), e); } }

Target:
private void checkForCharactersBeforeProlog(FileSystem fileSystem) { try { int lineNb = 1; Pattern firstTagPattern = Pattern.compile("<[a-zA-Z?]+"); for (String line : Files.readLines(inputFile.file(), fileSystem.encoding())) { if (lineNb == 1) { checkBOM(line); } Matcher m = firstTagPattern.matcher(line); if (m.find()) { int groupIndex = line.indexOf(m.group()); if (XML_PROLOG_START_TAG.equals(m.group()) && (groupIndex > 0 || lineNb > 1)) { hasCharsBeforeProlog = true; } break; } lineNb++; } if (hasCharsBeforeProlog) { processCharBeforePrologInFile(fileSystem, lineNb); } } catch (IOException e) { LOG.warn("Unable to analyse file {}", inputFile.absolutePath(), e); } }
Source:
private static byte[] getRandomSeed(SecureRandom random, int bits) { byte[] seed = new byte[bits / 8]; random.nextBytes(seed); return seed; }

Target:
private static byte[] getRandomSeed(SecureRandom random, int bits) { Preconditions.checkArgument(bits >= DEFAULT_SEED_BITS, "requested seed size too small"); Preconditions.checkArgument(bits <= MAX_SEED_BITS, "requested seed size too large"); Preconditions.checkArgument(bits % 8 == 0, "requested seed size not an even number of bytes"); byte[] seed = new byte[bits / 8]; random.nextBytes(seed); return seed; }
Source:
public String verifiedSources(@ApiParam(value = "Tool id", required = true) @PathParam("containerId") Long containerId) { Tool tool = toolDAO.findById(containerId); Helper.checkEntry(tool); Set<String> verifiedSourcesArray = new HashSet<>(); for (Tag tag : tool.getTags()) { if (tag.isVerified()) { verifiedSourcesArray.add(tag.getVerifiedSource()); } } JSONArray jsonArray = new JSONArray(); try { jsonArray = new JSONArray(verifiedSourcesArray.toArray()); } catch (JSONException ex) { ex.printStackTrace(); } return jsonArray.toString(); }

Target:
public String verifiedSources(@ApiParam(value = "Tool id", required = true) @PathParam("containerId") Long containerId) { Tool tool = toolDAO.findById(containerId); Helper.checkEntry(tool); Set<String> verifiedSourcesArray = new HashSet<>(); tool.getTags() .stream() .filter((Tag u) -> u.isVerified()) .forEach((Tag v) -> verifiedSourcesArray.add(v.getVerifiedSource())); JSONArray jsonArray; try { jsonArray = new JSONArray(verifiedSourcesArray.toArray()); } catch (JSONException ex) { throw new CustomWebApplicationException("There was an error converting the array of verified sources to a JSON array.", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return jsonArray.toString(); }
Source:
public Map<String, String> getExternalMetadata() { return externalMetadata; }

Target:
public Map<String, String> getExternalMetadata() { return ImmutableMap.copyOf(externalMetadata); }
Source:
private static boolean attributeValuesAreNonNull(Attribute attribute) { return !attribute.getValues().stream().allMatch(Objects::isNull); }

Target:
private static boolean attributeValuesAreNonNull(Attribute attribute) { return attribute.getValues().stream().noneMatch(Objects::isNull); }
Source:
private boolean handlePositiveEnforcingAffinityGroup(Guid vdsId, List<VM> runningVms) { List<AffinityGroup> affinityGroups = affinityGroupDao.getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId(vdsId); if (!affinityGroups.isEmpty()) { List<Object> items = new ArrayList<>(); affinityGroups.stream() .filter(ag -> (!ag.getVdsIds().isEmpty()) || affinityGroupContainsRunningVMs(ag, runningVms) ) .forEach(affinityGroup -> { items.add(String.format("%1$s (%2$s)", affinityGroup.getName(), StringUtils.join(affinityGroup.getVmEntityNames(), " ,"))); }); if (!items.isEmpty()) { addValidationMessage(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_HAS_AFFINITY_VMS); getReturnValue().getValidationMessages() .addAll(ReplacementUtils.replaceWith("AFFINITY_GROUPS_VMS", items)); return false; } } return true; }

Target:
private boolean handlePositiveEnforcingAffinityGroup(Guid vdsId, List<VM> runningVms) { List<AffinityGroup> affinityGroups = affinityGroupDao.getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId(vdsId); if (!affinityGroups.isEmpty()) { List<Object> items = new ArrayList<>(); affinityGroups.stream() .filter(ag -> !ag.getVdsIds().isEmpty() || affinityGroupContainsRunningVMs(ag, runningVms) ) .forEach(affinityGroup -> { items.add(String.format("%1$s (%2$s)", affinityGroup.getName(), StringUtils.join(affinityGroup.getVmEntityNames(), " ,"))); }); if (!items.isEmpty()) { addValidationMessage(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_HAS_AFFINITY_VMS); getReturnValue().getValidationMessages() .addAll(ReplacementUtils.replaceWith("AFFINITY_GROUPS_VMS", items)); return false; } } return true; }
Source:
synchronized OptionalLong reheat() throws IOException { long pagesLoaded = 0; List<PagedFile> files = pageCache.listExistingMappings(); for ( PagedFile file : files ) { try { pagesLoaded += reheat( file ); } catch ( FileIsNotMappedException ignore ) { } } return stopped ? OptionalLong.empty() : OptionalLong.of( pagesLoaded ); }

Target:
synchronized OptionalLong reheat() throws IOException { if ( stopOngoingWarming ) { return OptionalLong.empty(); } long pagesLoaded = 0; List<PagedFile> files = pageCache.listExistingMappings(); for ( PagedFile file : files ) { try { pagesLoaded += reheat( file ); } catch ( FileIsNotMappedException ignore ) { } } return OptionalLong.of( pagesLoaded ); }
Source:
private Map<Partition, SystemStreamPartitionMetadata> getPartitionMetadata(String streamName, String[] partitionIds) { EventHubClientWrapper eventHubClientWrapper = getStreamEventHubClient(streamName); Map<Partition, SystemStreamPartitionMetadata> sspMetadataMap = new HashMap<>(); Map<String, CompletableFuture<EventHubPartitionRuntimeInformation>> ehRuntimeInfos = new HashMap<>(); for (String partition : partitionIds) { ehRuntimeInfos.put(partition, eventHubClientWrapper.getEventHubClient() .getPartitionRuntimeInformation(partition)); } ehRuntimeInfos.forEach((partitionId, ehPartitionRuntimeInfo) -> { try { EventHubPartitionRuntimeInformation ehPartitionInfo = ehPartitionRuntimeInfo .get(eventHubConfig.getRuntimeInfoWaitTimeMS(), TimeUnit.MILLISECONDS); sspMetadataMap.put(new Partition(Integer.parseInt(partitionId)), new SystemStreamPartitionMetadata(EventHubSystemConsumer.START_OF_STREAM, ehPartitionInfo.getLastEnqueuedOffset(), EventHubSystemConsumer.END_OF_STREAM)); } catch (InterruptedException | ExecutionException e) { String msg = String.format( "Error while fetching EventHubPartitionRuntimeInfo for System:%s, Stream:%s, Partition:%s", systemName, streamName, partitionId); LOG.error(msg, e); throw new SamzaException(msg); } catch (TimeoutException e) { String msg = String.format( "Timed out while fetching EventHubRuntimeInfo for System:%s, Stream:%s, , Partition:%s", systemName, streamName, partitionId); LOG.error(msg, e); throw new SamzaException(msg); } }); return sspMetadataMap; }

Target:
private Map<Partition, SystemStreamPartitionMetadata> getPartitionMetadata(String streamName, String[] partitionIds) { EventHubClientManager eventHubClientManager = getOrCreateStreamEventHubClient(streamName); Map<Partition, SystemStreamPartitionMetadata> sspMetadataMap = new HashMap<>(); Map<String, CompletableFuture<EventHubPartitionRuntimeInformation>> ehRuntimeInfos = new HashMap<>(); for (String partition : partitionIds) { CompletableFuture<EventHubPartitionRuntimeInformation> partitionRuntimeInfo = eventHubClientManager .getEventHubClient() .getPartitionRuntimeInformation(partition); ehRuntimeInfos.put(partition, partitionRuntimeInfo); } ehRuntimeInfos.forEach((partitionId, ehPartitionRuntimeInfo) -> { try { long timeoutMs = eventHubConfig.getRuntimeInfoWaitTimeMS(systemName); EventHubPartitionRuntimeInformation ehPartitionInfo = ehPartitionRuntimeInfo.get(timeoutMs, TimeUnit.MILLISECONDS); String startingOffset = EventHubSystemConsumer.START_OF_STREAM; String newestOffset = ehPartitionInfo.getLastEnqueuedOffset(); String upcomingOffset = getNextOffset(newestOffset); SystemStreamPartitionMetadata sspMetadata = new SystemStreamPartitionMetadata(startingOffset, newestOffset, upcomingOffset); Partition partition = new Partition(Integer.parseInt(partitionId)); sspMetadataMap.put(partition, sspMetadata); } catch (InterruptedException | ExecutionException | TimeoutException e) { String msg = String.format( "Error while fetching EventHubPartitionRuntimeInfo for System:%s, Stream:%s, Partition:%s", systemName, streamName, partitionId); throw new SamzaException(msg); } }); return sspMetadataMap; }
Source:
public boolean contains(int element) { if (element < 0) throw new UnsupportedOperationException("Negative values are not supported!"); return bitSet.get(element); }

Target:
@Override public boolean contains(int element) { if (element < 0) return false; return bitSet.get(element); }
Source:
private String toPattern(String tableName) throws MalformedObjectNameException { if (!tableName.contains("*")) { return new ObjectName(tableName).getCanonicalName(); } String pattern = Pattern.compile("\\*").splitAsStream(tableName) .map(Pattern::quote) .collect(Collectors.joining(".*")); if (tableName.startsWith("*")) { pattern = ".*" + pattern; } if (tableName.endsWith("*")) { pattern += ".*"; } return pattern; }

Target:
private String toPattern(String tableName) throws MalformedObjectNameException { if (!tableName.contains("*")) { return Pattern.quote(new ObjectName(tableName).getCanonicalName()); } return Streams.stream(Splitter.on('*').split(tableName)) .map(Pattern::quote) .collect(Collectors.joining(".*")); }
Source:
public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); try { payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return Mono.just(new AccessToken(msiToken.getToken(), msiToken.getExpiresAt().plusMinutes(2).minus(options.getRefreshBeforeExpiry()))); } catch (IOException e) { return Mono.error(e); } finally { if (connection != null) { connection.disconnect(); } } }

Target:
public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); }
Source:
public void close() { isOpen = false; wrappedIterator.close(); for (final Map.Entry<String, UmiMetrics> metric : umiMetricsMap.entrySet()) { metric.getValue().calculateDerivedFields(); } }

Target:
public void close() { isOpen = false; wrappedIterator.close(); for (final UmiMetrics metrics : umiMetricsMap.values()) { metrics.calculateDerivedFields(); } }
Source:
private void copyDocument(ElementNodeBuilder enb, DictionaryBuilder db, NodeTreePointable ntp, DocumentNodePointable dnp) throws IOException, SystemException { SequencePointable seqp = ppool.takeOne(SequencePointable.class); AttributeNodePointable anp = ppool.takeOne(AttributeNodePointable.class); TaggedValuePointable tvp = ppool.takeOne(TaggedValuePointable.class); ElementNodePointable cenp = ppool.takeOne(ElementNodePointable.class); try { dnp.getContent(ntp, seqp); for (int i = 0; i < seqp.getEntryCount(); ++i) { seqp.getEntry(i, tvp); if (tvp.getTag() == ValueTag.ELEMENT_NODE_TAG) { tvp.getValue(cenp); copyElement(enb, db, ntp, cenp); break; } } } finally { ppool.giveBack(cenp); ppool.giveBack(tvp); ppool.giveBack(anp); ppool.giveBack(seqp); } }

Target:
private void copyDocument(ElementNodeBuilder enb, DictionaryBuilder db, NodeTreePointable ntp, DocumentNodePointable dnp) throws IOException { SequencePointable seqp = ppool.takeOne(SequencePointable.class); AttributeNodePointable anp = ppool.takeOne(AttributeNodePointable.class); TaggedValuePointable tvp = ppool.takeOne(TaggedValuePointable.class); ElementNodePointable cenp = ppool.takeOne(ElementNodePointable.class); try { dnp.getContent(ntp, seqp); for (int i = 0; i < seqp.getEntryCount(); ++i) { seqp.getEntry(i, tvp); if (tvp.getTag() == ValueTag.ELEMENT_NODE_TAG) { tvp.getValue(cenp); copyElement(enb, db, ntp, cenp); break; } } } finally { ppool.giveBack(cenp); ppool.giveBack(tvp); ppool.giveBack(anp); ppool.giveBack(seqp); } }