auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public DSpaceCSVLine resolveEntityRefs(DSpaceCSVLine line) throws MetadataImportException { DSpaceCSVLine newLine = new DSpaceCSVLine(line.getID()); for (String key : line.keys()) { if (key.split("\\.")[0].equalsIgnoreCase("relation")) { if (line.get(key).size() > 0) { for (String val : line.get(key)) { String uuid = resolveEntityRef(c, val).toString(); newLine.add(key, uuid); } } } else { if (line.get(key).size() > 1) { for (String value : line.get(key)) { newLine.add(key, value); } } else { <START> newLine.add(key, line.get(key).get(0)); <END> } } } return newLine; }</code><technical_language>While testing new codebase, error occurred. I check if (!line.get(key).isEmpty()) {</technical_language>

Target:
public DSpaceCSVLine resolveEntityRefs(DSpaceCSVLine line) throws MetadataImportException { DSpaceCSVLine newLine = new DSpaceCSVLine(line.getID()); for (String key : line.keys()) { if (key.split("\\.")[0].equalsIgnoreCase("relation")) { if (line.get(key).size() > 0) { for (String val : line.get(key)) { String uuid = resolveEntityRef(c, val).toString(); newLine.add(key, uuid); } } } else { if (line.get(key).size() > 1) { for (String value : line.get(key)) { newLine.add(key, value); } } else { if (line.get(key).size() > 0) { newLine.add(key, line.get(key).get(0)); } } } } return newLine; }
Source:
<code>protected DockerResponse request(String method, String path, String query, List<Pair<String, ?>> headers, Entity entity) throws IOException { final String requestUri = path + (Strings.isNullOrEmpty(query) ? "" : "?" + query); final URL url = baseUri.resolve(requestUri).toURL(); final String protocol = url.getProtocol(); connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); if ("https".equals(protocol)) { ((HttpsURLConnection)connection).setSSLSocketFactory(certificates.getSslContext().getSocketFactory()); } connection.setRequestMethod(method); connection.setRequestProperty("Connection", "close"); for (Pair<String, ?> header : headers) { connection.setRequestProperty(header.first, String.valueOf(header.second)); } <START> connection.setRequestProperty("Host", url.toString()); <END> if (entity != null) { connection.setDoOutput(true); try (OutputStream output = connection.getOutputStream()) { entity.writeTo(output); } } return new TcpDockerResponse(connection); }</code><technical_language>In case host put in header host + path +query. @l0rd Do is OK host+port put in header</technical_language>

Target:
protected DockerResponse request(String method, String path, String query, List<Pair<String, ?>> headers, Entity entity) throws IOException { final String requestUri = path + (Strings.isNullOrEmpty(query) ? "" : "?" + query); final URL url = baseUri.resolve(requestUri).toURL(); final String protocol = url.getProtocol(); connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); if ("https".equals(protocol)) { ((HttpsURLConnection)connection).setSSLSocketFactory(certificates.getSslContext().getSocketFactory()); } connection.setRequestMethod(method); connection.setRequestProperty("Connection", "close"); for (Pair<String, ?> header : headers) { connection.setRequestProperty(header.first, String.valueOf(header.second)); } String host = url.getHost(); if (url.getPort() != -1) { host += ":" + Integer.toString(url.getPort()); } connection.setRequestProperty("Host", host); if (entity != null) { connection.setDoOutput(true); try (OutputStream output = connection.getOutputStream()) { entity.writeTo(output); } } return new TcpDockerResponse(connection); }
Source:
<code>public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { <START> this.prefix = Strings.isNullOrEmpty(prefix) ? "" : prefix + "/"; <END> this.layers = layers; }</code><technical_language>I dislike this confuses things. of /s in templates, this special slash is added here. This is a good opportunity for future mistakes. this is a case for changing String.format() templates do essentially for varying numbers of parameters String.join()</technical_language>

Target:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { this.prefix = prefix; this.layers = layers; }
Source:
<code>public static <T> Set<T> of(T e1, T e2, T e3, T e4, T e5) { final Set<T> set = new HashSet<>(5); set.add(e1); set.add(e2); set.add(e3); set.add(e4); set.add(e5); <START> return set; <END> }</code><technical_language>a style suggestion for methods: java Set<T> set = Stream.of(e1, e2, e3, e4, e5).collect(Collectors.toSet());</technical_language>

Target:
public static <T> Set<T> of(T e1, T e2, T e3, T e4, T e5) { final Set<T> set = new HashSet<>(5); set.add(e1); set.add(e2); set.add(e3); set.add(e4); set.add(e5); return unmodifiableSet(set); }
Source:
<code>public void close() { <START> cancelTimer.cancel(); <END> protoConnection.close(); openStackTrace = null; }</code><technical_language>I pulled this private repo ran tests failed NPE here. curious Travis-CI passes this is another issue</technical_language>

Target:
public void close() { protoConnection.close(); openStackTrace = null; timerLoan.release(); }
Source:
<code>public void setSecurityProvider(SecurityProvider securityProvider) { if (securityProvider != null) { this.securityProvider = securityProvider; } else { <START> this.securityProvider = (keyId) -> Security.getProvider("SunRsaSign"); <END> } }</code><technical_language>default Objects.requireNonNull? logic of setter is a bit unexpected</technical_language>

Target:
public final void setSecurityProvider(SecurityProvider securityProvider) { this.securityProvider = Objects.requireNonNull(securityProvider, "security provider cannot be null"); }
Source:
<code>public void run() { final Tile tile = tileQueue.remove(); int remainingAttempts = 3; while (!tile.isLoaded() && remainingAttempts > 0) { remainingAttempts--; try { URI uri = getURI(tile); BufferedImage img = cache.get(uri); if (img == null) { img = getImage(uri); } if (img != null) { addImageToTile(tile, img); } } catch (OutOfMemoryError memErr) { <START> cache.needMoreMemory(); <END> } catch (Exception ex) { if (remainingAttempts == 0) { logger.log(Level.SEVERE, String.format("Failed to load a tile at URL: %s, stopping", tile.getURL()), ex); } else { logger.log(Level.WARNING, "Failed to load a tile at URL: " + tile.getURL() + ", retrying", ex); } } } tile.setLoading(false); }</code><technical_language>Please log out of memory exception a WARNING</technical_language>

Target:
public void run() { final Tile tile = tileQueue.remove(); int remainingAttempts = 3; while (!tile.isLoaded() && remainingAttempts > 0) { remainingAttempts--; try { URI uri = getURI(tile); BufferedImage img = cache.get(uri); if (img == null) { img = getImage(uri); } if (img != null) { addImageToTile(tile, img); } } catch (OutOfMemoryError memErr) { cache.needMoreMemory(); } catch (IOException | GeoLocationDataException | InterruptedException | InvocationTargetException | URISyntaxException ex) { if (remainingAttempts == 0) { logger.log(Level.SEVERE, String.format("Failed to load a tile at URL: %s, stopping", tile.getURL()), ex); } else { logger.log(Level.WARNING, "Failed to load a tile at URL: " + tile.getURL() + ", retrying", ex); } } } tile.setLoading(false); }
Source:
<code>private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); if ((content.getField(TcpEventStrings.SEQ) != null) && <START> (content.getField(TcpEventStrings.ACKSEQ) != null) && <END> (content.getField(TcpEventStrings.FLAGS) != null)) { return true; } return false; }</code><technical_language>Indeed, this point do need verify type, getEventKey() throws exception if type is wrong, check return false if is right. correct this class is call this method, getEventKey() if this is true, exception thrown</technical_language>

Target:
private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); if ((content.getFieldValue(Long.class, TcpEventStrings.SEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) == null)) { return false; } return true; }
Source:
<code>private <V> ListenableFuture<V> runAsyncInternal(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { retryStatus.nextAttempt(); ListenableFuture<V> resultFuture; try { resultFuture = callable.call(); <START> Futures.addCallback(resultFuture, new FutureCallback() <END> { @Override public void onSuccess(@Nullable Object result) { stats.addSuccess(); stats.addAttemptsBeforeSuccess(retryStatus.getAttempts()); stats.addSuccessLatency(retryStatus.getDuration()); } @Override public void onFailure(Throwable t) { } }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw propagate(retryStatus, stats, ie); } catch (Exception e) { resultFuture = immediateFailedFuture(e); } return Futures.catchingAsync(resultFuture, Exception.class, e -> { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw propagate(retryStatus, stats, e); } else if (retryStatus.shouldStopRetry(e)) { throw propagate(retryStatus, stats, e); } log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts()); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, stats, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS)); }); }</code><technical_language>IDE gave warning generics correctly. Address warning</technical_language>

Target:
private <V> ListenableFuture<V> runAsyncInternal(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { retryStatus.nextAttempt(); ListenableFuture<V> resultFuture; try { resultFuture = callable.call(); Futures.addCallback(resultFuture, new FutureCallback<V>() { @Override public void onSuccess(@Nullable V result) { stats.addSuccess(); stats.addAttemptsBeforeSuccess(retryStatus.getAttempts()); stats.addSuccessLatency(retryStatus.getDuration()); } @Override public void onFailure(Throwable t) }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); recordFailure(retryStatus, stats); throw propagate(ie); } catch (Exception e) { resultFuture = immediateFailedFuture(e); } return Futures.catchingAsync(resultFuture, Exception.class, e -> { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); recordFailure(retryStatus, stats); throw propagate(e); } else if (retryStatus.shouldStopRetry(e)) { recordFailure(retryStatus, stats); throw propagate(e); } log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts()); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, stats, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS)); }); }
Source:
<code>public void testFLTRepeatability() { TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); <START> long deltaMax = getPrivateFieldLong(fast, "fDeltaMax"); <END> long timestamp = ts - (ts % deltaMax); fast.transform(timestamp); long tsMiss = timestamp + deltaMax; long tsNoMiss = timestamp + deltaMax - 1; long tsTNoMiss = fast.transform(tsNoMiss); assertEquals(1, fast.getCacheMisses()); fast.transform(tsMiss); assertEquals(2, fast.getCacheMisses()); long tsTAfterMiss = fast.transform(tsNoMiss); assertEquals(tsTNoMiss, tsTAfterMiss); }</code><technical_language>fDeltaMax exposed a getter? a final field too, super-seekrit. part of class only, interface, need a reference specific class get (which here)</technical_language>

Target:
public void testFLTRepeatability() { TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); long deltaMax = fast.getDeltaMax(); long timestamp = ts - (ts % deltaMax); fast.transform(timestamp); long tsMiss = timestamp + deltaMax; long tsNoMiss = timestamp + deltaMax - 1; long tsTNoMiss = fast.transform(tsNoMiss); assertEquals(1, fast.getCacheMisses()); fast.transform(tsMiss); assertEquals(2, fast.getCacheMisses()); long tsTAfterMiss = fast.transform(tsNoMiss); assertEquals(tsTNoMiss, tsTAfterMiss); }
Source:
<code>public synchronized void setDDFName(DDF ddf, String name) throws DDFException { <START> synchronized (ddf) { <END> if (!Strings.isNullOrEmpty(name)) { if (!Strings.isNullOrEmpty(ddf.getName())) { this.mUris.remove(ddf.getUri()); } ddf.setName(name); mDDFCache.invalidate(ddf.getUUID()); mDDFwithNameCache.put(ddf.getUUID(), ddf); this.mUris.put(ddf.getUri(), ddf.getUUID()); } else { throw new DDFException(String.format("DDF's name cannot be null or empty")); } } }</code><technical_language>do need this block method synchronized</technical_language>

Target:
public void setDDFName(DDF ddf, String name) throws DDFException { Lock lock = uuidLocks.get(ddf.getUUID()); try { if(lock.tryLock(120, TimeUnit.SECONDS)) { try { if (!Strings.isNullOrEmpty(name)) { if (!Strings.isNullOrEmpty(ddf.getName())) { this.mUris.remove(ddf.getUri()); } ddf.setName(name); mDDFCache.invalidate(ddf.getUUID()); mDDFwithNameCache.put(ddf.getUUID(), ddf); this.mUris.put(ddf.getUri(), ddf.getUUID()); } else { throw new DDFException(String.format("DDF's name cannot be null or empty")); } } finally { lock.unlock(); } } else { throw new DDFException("Timeout setting DDF name"); } } catch (Exception e) { throw new DDFException(e); } }
Source:
<code>protected void addValue(int val) throws IOException { if (!endBuffer.hasRemaining()) { endBuffer.rewind(); flattener.write(StupidResourceHolder.create(endBuffer)); <START> endBuffer.rewind(); <END> } endBuffer.put(val); numInserted++; }</code><technical_language>New IntBuffer reuse, write switch GenericIndexedWriter sort correct</technical_language>

Target:
protected void addValue(int val) throws IOException { if (!endBuffer.hasRemaining()) { endBuffer.rewind(); flattener.write(StupidResourceHolder.create(endBuffer)); endBuffer = IntBuffer.allocate(chunkFactor); } endBuffer.put(val); numInserted++; }
Source:
<code>@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); <START> fail("remove should not permit concurrent modifications."); <END> } catch (ConcurrentModificationException ignored) { } }</code><technical_language>switch import org.junit.Assert.fail remove messages? If this fails reason is clear I forced provide a redundant message</technical_language>

Target:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); fail(); } catch (ConcurrentModificationException ignored) { } }
Source:
<code>public static String setUserSessionBaseUrl(final HttpSession session) { String resultBaseUrl; <START> final String hashedBaseUrl = (String) session.getAttribute("BASE_URL"); <END> if (hashedBaseUrl == null) { resultBaseUrl = JiraTimetrackerAnalytics.getBaseUrl(); session.setAttribute("BASE_URL", resultBaseUrl); } else { resultBaseUrl = hashedBaseUrl; } return resultBaseUrl; }</code><technical_language>Extract "BASE_URL" a constant more unique. For example: "org.everit.jira.timetracker.plugin.base.url.hash"</technical_language>

Target:
public static String setUserSessionBaseUrl(final HttpSession session) { String resultBaseUrl; String hashedBaseUrl = (String) session.getAttribute(BASE_URL); if (hashedBaseUrl == null) { resultBaseUrl = JiraTimetrackerAnalytics.getBaseUrl(); session.setAttribute(BASE_URL, resultBaseUrl); } else { resultBaseUrl = hashedBaseUrl; } return resultBaseUrl; }
Source:
<code><START> protected static void closeStmt(Statement stmt) { <END> try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { LOG.warn("Failed to close statement " + e.getMessage()); } }</code><technical_language>Access private for close methods. Also, merge method</technical_language>

Target:
private static void closeStmt(Statement stmt) { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { LOG.warn("Failed to close statement " + e.getMessage()); } }
Source:
<code>private void unindicatePanelLoading(RepoOpenedEvent e) { togglePanelLoading(e.isPrimaryRepo, e.repoId, false); <START> } <END></code><technical_language>For methods, a structure is: java private void indicatePanelLoading(RepoOpeningEvent e) { if(isIndicatorApplicable(e.isPrimaryRepo, e.repoId){ showLoadingIndicator(); } } In current code, abstracted wrong action. checking applicability is common, toggling</technical_language>

Target:
private void unindicatePanelLoading(RepoOpenedEvent e) { if (isIndicatorApplicable(e.isPrimaryRepo)) { removePanelLoadingIndication(); } }
Source:
<code>public void add(VObject aVobj) { if (aVobj instanceof VSpan) { add((VSpan) aVobj); } else if (aVobj instanceof VArc) { add((VArc) aVobj); <START> } <END> }</code><technical_language>This method additional else block IllegalArgumentException is thrown object is a span arc</technical_language>

Target:
public void add(VObject aVobj) { if (aVobj instanceof VSpan) { add((VSpan) aVobj); } else if (aVobj instanceof VArc) { add((VArc) aVobj); } else { throw new IllegalArgumentException("VObject is neither VSpan nor VArc."); } }
Source:
<code>private UUID mapType(int type, int val) throws SQLException { if (type == Constants.COMMUNITY) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (type == Constants.COLLECTION) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (type == Constants.ITEM) { <START> Item item = itemService.findByLegacyId(context, val); <END> return item == null ? null : item.getID(); } if (type == Constants.BITSTREAM) { Bitstream bit = bitstreamService.findByLegacyId(context, val); return bit == null ? null : bit.getID(); } return null; }</code><technical_language>logic applies here, I uncache item</technical_language>

Target:
private UUID mapType(int type, int val) throws SQLException { if (type == Constants.COMMUNITY) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (type == Constants.COLLECTION) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (type == Constants.ITEM) { Item item = itemService.findByLegacyId(context, val); checkLastItem(item); return item == null ? null : item.getID(); } if (type == Constants.BITSTREAM) { Bitstream bit = bitstreamService.findByLegacyId(context, val); UUID uuid = bit == null ? null : bit.getID(); checkLastBitstream(bit); return uuid; } return null; }
Source:
<code>public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); <START> if (numberOfBytes != maxNumberOfBytes) { <END> return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }</code><technical_language>write '<' here, '!='. a bit clearer imho</technical_language>

Target:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); if (numberOfBytes < maxNumberOfBytes) { return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }
Source:
<code>public GlusterVolumeGlobalOptionsInfoReturn(Map<String, Object> innerMap) { super(innerMap); if (getStatus().code != GlusterConstants.CODE_SUCCESS) { return; } Map<String, Object> globalOptions = (Map<String, Object>) innerMap.get(OPTION_MAP); if (globalOptions != null && !globalOptions.isEmpty()) { for (String s : globalOptions.keySet()) { <START> if (!"".equals(s) && !StringUtils.isEmpty(s)) { <END> globalOptionList.add(s); } } } }</code><technical_language>is "".equals check needed StringUtils.isEmpty</technical_language>

Target:
public GlusterVolumeGlobalOptionsInfoReturn(Map<String, Object> innerMap) { super(innerMap); if (getStatus().code != GlusterConstants.CODE_SUCCESS) { return; } Map<String, Object> globalOptions = (Map<String, Object>) innerMap.get(OPTION_MAP); if (globalOptions != null && !globalOptions.isEmpty()) { for (String s : globalOptions.keySet()) { if (!StringUtils.isEmpty(s)) { globalOptionList.add(s); } } } }
Source:
<code>public void testForEachDict() throws Throwable { String schemeInputString = "(begin " + "(def x 0)" + "(foreach y " + " (let " + " ( " + " ($key " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 1) '(list number) \"select list item\" " + " ) " + " ) " + " ($value " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 2) '(list number) \"select list item\" " + " ) " + " ) " + " ) " + " (set-var! x " + " (call-yail-primitive + " + " (*list-for-runtime* (get-var x) (lexical-value $key) (lexical-value $value) )" + " '(number number number ) \"+\"" + " ) " + " ) " + " ) " + " (call-yail-primitive make-yail-dictionary " + " (*list-for-runtime* " + <START> " (call-yail-primitive make-ke-dictionary-pair " + <END> " (*list-for-runtime* 1 2 ) '(key any) \"make a pair\" " + " ) " + " (call-yail-primitive make-ke-dictionary-pair " + " (*list-for-runtime* 3 4 ) '(key any) \"make a pair\" " + " ) " + " )" + " ) '(pair pair ) \"make a dictionary\"" + " ) " + ") "; String schemeResultString = "10"; assertEquals(schemeResultString, scheme.eval(schemeInputString).toString()); }</code><technical_language>Bad symbol here: make-ke-dictionary-pair</technical_language>

Target:
public void testForEachDict() throws Throwable { String schemeInputString = "(begin " + "(def x 0) " + "(foreach y " + " (let " + " ( " + " ($key " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 1) '(list number) \"select list item\" " + " ) " + " ) " + " ($value " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 2) '(list number) \"select list item\" " + " ) " + " ) " + " ) " + " (set-var! x " + " (call-yail-primitive + " + " (*list-for-runtime* (get-var x) (lexical-value $key) (lexical-value $value) )" + " '(number number number ) \"+\"" + " ) " + " ) " + " ) " + " (call-yail-primitive make-yail-dictionary " + " (*list-for-runtime* " + " (call-yail-primitive make-dictionary-pair " + " (*list-for-runtime* 1 2 ) '(key any) \"make a pair\" " + " ) " + " (call-yail-primitive make-dictionary-pair " + " (*list-for-runtime* 3 4 ) '(key any) \"make a pair\" " + " ) " + " ) '(pair pair ) \"make a dictionary\"" + " ) " + " ) " + " (get-var x) " + ") "; String schemeResultString = "10"; assertEquals(schemeResultString, scheme.eval(schemeInputString).toString()); }
Source:
<code>InMemorySpanStore(InMemoryStorage.Builder builder) { this.strictTraceId = builder.strictTraceId; <START> this.metrics = builder.metrics == null ? StorageMetrics.NOOP_METRICS : builder.metrics; <END> this.maxSpans = builder.maxSpans; }</code><technical_language>nix this</technical_language>

Target:
InMemorySpanStore(InMemoryStorage.Builder builder) { this.strictTraceId = builder.strictTraceId; this.maxSpanCount = builder.maxSpanCount; }
Source:
<code>private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) { IndexedTypeSet selectionAsSet = IndexedTypeSets.fromClasses( selection ); <START> Set<Class<?>> entities = extendedIntegrator.getIndexedTypesPolymorphic( selectionAsSet ).toPojosSet(); <END> if ( entities.size() == 0 ) { IndexedTypeSet configuredTargetEntities = extendedIntegrator.getConfiguredTypesPolymorphic( selectionAsSet ); if ( configuredTargetEntities.isEmpty() ) { throw log.targetedEntityTypesNotConfigured( StringHelper.join( selection, "," ) ); } else { throw log.targetedEntityTypesNotIndexed( StringHelper.join( selection, "," ) ); } } Set<Class<?>> cleaned = new HashSet<Class<?>>(); Set<Class<?>> toRemove = new HashSet<Class<?>>(); for ( Class<?> type : entities ) { boolean typeIsOk = true; for ( Class<?> existing : cleaned ) { if ( existing.isAssignableFrom( type ) ) { typeIsOk = false; break; } if ( type.isAssignableFrom( existing ) ) { toRemove.add( existing ); } } if ( typeIsOk ) { cleaned.add( type ); } } cleaned.removeAll( toRemove ); log.debugf( "Targets for indexing job: %s", cleaned ); return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) ); }</code><technical_language>This refactoring semantically equivalent. intentional</technical_language>

Target:
private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) { Set<Class<?>> entities = new HashSet<>(); Set<Class<?>> nonIndexedEntities = new HashSet<>(); for ( Class<?> entityType : selection ) { IndexedTypeSet entityTypeAsSet = IndexedTypeSets.fromClass( entityType ); IndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( entityTypeAsSet ); if ( targetedClasses.isEmpty() ) { nonIndexedEntities.add( entityType ); } else { entities.addAll( targetedClasses.toPojosSet() ); } } if ( !nonIndexedEntities.isEmpty() ) { IndexedTypeSet nonIndexedEntitiesAsSet = IndexedTypeSets.fromClasses( nonIndexedEntities ); IndexedTypeSet configuredTargetEntities = extendedIntegrator.getConfiguredTypesPolymorphic( nonIndexedEntitiesAsSet ); if ( configuredTargetEntities.isEmpty() ) { throw log.someTargetedEntityTypesNotConfigured( StringHelper.join( nonIndexedEntities, "," ) ); } else { throw log.someTargetedEntityTypesNotIndexed( StringHelper.join( nonIndexedEntities, "," ) ); } } Set<Class<?>> cleaned = new HashSet<Class<?>>(); Set<Class<?>> toRemove = new HashSet<Class<?>>(); for ( Class<?> type : entities ) { boolean typeIsOk = true; for ( Class<?> existing : cleaned ) { if ( existing.isAssignableFrom( type ) ) { typeIsOk = false; break; } if ( type.isAssignableFrom( existing ) ) { toRemove.add( existing ); } } if ( typeIsOk ) { cleaned.add( type ); } } cleaned.removeAll( toRemove ); log.debugf( "Targets for indexing job: %s", cleaned ); return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) ); }
Source:
<code>AmbryBlobStorageService(FrontendConfig frontendConfig, FrontendMetrics frontendMetrics, RestResponseHandler responseHandler, Router router, ClusterMap clusterMap, IdConverterFactory idConverterFactory, SecurityServiceFactory securityServiceFactory, AccountService accountService) { this.frontendConfig = frontendConfig; <START> this.frontendMetrics = frontendMetrics; <END> this.responseHandler = responseHandler; this.router = router; this.clusterMap = clusterMap; this.idConverterFactory = idConverterFactory; this.securityServiceFactory = securityServiceFactory; this.accountService = accountService; getReplicasHandler = new GetReplicasHandler(frontendMetrics, clusterMap); logger.trace("Instantiated AmbryBlobStorageService"); }</code><technical_language>doc for extra param (accountService)</technical_language>

Target:
AmbryBlobStorageService(FrontendConfig frontendConfig, FrontendMetrics frontendMetrics, RestResponseHandler responseHandler, Router router, ClusterMap clusterMap, IdConverterFactory idConverterFactory, SecurityServiceFactory securityServiceFactory, AccountService accountService) { this.accountService = Objects.requireNonNull(accountService, "accountService cannot be null."); this.frontendConfig = frontendConfig; this.frontendMetrics = frontendMetrics; this.responseHandler = responseHandler; this.router = router; this.clusterMap = clusterMap; this.idConverterFactory = idConverterFactory; this.securityServiceFactory = securityServiceFactory; getReplicasHandler = new GetReplicasHandler(frontendMetrics, clusterMap); logger.trace("Instantiated AmbryBlobStorageService"); }
Source:
<code>private Response mockResponse(int code) { Response mockResponse = mock(Response.class); <START> when(mockResponse.isSuccessful()).thenReturn(code < 400); <END> when(mockResponse.code()).thenReturn(code); when(mockResponse.body()).thenReturn(ResponseBody.create(MediaType.get("application/json"), "")); return mockResponse; }</code><technical_language>nit, HttpUrlConnection for status codes: suggestion when(mockResponse.isSuccessful()).thenReturn(code < HttpURLConnection.HTTP_BAD_REQUEST);</technical_language>

Target:
private Response mockResponse(int code) { return new Response.Builder() .request(new Request.Builder().url("http://mock").build()) .protocol(Protocol.HTTP_1_1) .code(code) .body(ResponseBody.create(MediaType.get("application/json"), "")) .message("mock") .build(); }
Source:
<code>public LcmEntityFilter withDataProduct(final String dataProduct) { <START> params.put("dataProduct", singletonList(notEmpty(dataProduct, "dataProduct"))); <END> return this; }</code><technical_language>constants for key strings</technical_language>

Target:
public LcmEntityFilter withDataProduct(final String dataProduct) { if (isNotBlank(dataProduct)) { this.dataProduct = dataProduct; } return this; }
Source:
<code>public Event<Object> event() { checkState(); if (event == null) { <START> synchronized (this) { <END> if (event == null) { event = beanManager().event(); } } } return event; }</code><technical_language>I - do want this in sync block</technical_language>

Target:
public Event<Object> event() { checkIsRunning(); if (event == null) { synchronized (this) { if (event == null) { event = beanManager().event(); } } } return event; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; <START> if (getClass() != obj.getClass()) <END> return false; if (InternalTask.class.isAssignableFrom(obj.getClass())) { return ((InternalTask) obj).getId().equals(getId()); } else { return false; } }</code><technical_language>I this contradicts check isAssignableFrom</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (InternalTask.class.isAssignableFrom(obj.getClass())) { return ((InternalTask) obj).getId().equals(getId()); } else { return false; } }
Source:
<code>public Organisation getOrganisationByName(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation name.", required = true) @PathParam("name") String name) { if (!user.isPresent()) { Organisation organisation = organisationDAO.findApprovedByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } return organisation; } else { <START> boolean doesOrgExist = doesOrganisationByNameExistToUser(name, user.get().getId()) || user.get().getIsAdmin() || user.get().isCurator(); <END> if (!doesOrgExist) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } Organisation organisation = organisationDAO.findByName(name); return organisation; } }</code><technical_language>prematurely optimizing here, this code flow is database accesses in happy path, doesOrganisationByNameExistToUser line 131. do line 131 beginning of this else, if admin curator, if belong org, getUserOrgRole method if user belongs org, return organization</technical_language>

Target:
public Organisation getOrganisationByName(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation name.", required = true) @PathParam("name") String name) { if (!user.isPresent()) { Organisation organisation = organisationDAO.findApprovedByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } return organisation; } else { Organisation organisation = organisationDAO.findByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } OrganisationUser role = getUserOrgRole(organisation, user.get().getId()); if (user.get().getIsAdmin() || user.get().isCurator() || role != null) { return organisation; } else { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } } }
Source:
<code>public void onReceive(Context context, Intent intent) { if (conMgr == null) { return; } final NetworkInfo activeInfo = conMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo != null && wifiInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); <START> if (mobileInfo == null || mobileInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) { <END> setHasNetwork(false); return; } }</code><technical_language>pattern above, change this block follows: if (mobileInfo != null && mobileInfo.isConnected()) { setHasNetwork(true); return; } setHasNetwork(false); return; }</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if (conMgr == null) { return; } final NetworkInfo activeInfo = conMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo != null && wifiInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mobileInfo != null && mobileInfo.isConnected()) { setHasNetwork(true); return; } setHasNetwork(false); return; }
Source:
<code>public void incrementCounter(String name, String hostname, JSONArray tags) { ConcurrentMetricCounters.lock.lock(); try { ConcurrentMetricCounters countersInstance = ConcurrentMetricCounters.getInstance(); <START> ConcurrentMap<CounterMetric, Integer> counters = countersInstance.get(); CounterMetric counterMetric = new CounterMetric(tags, name, hostname); Integer previousValue = counters.putIfAbsent(counterMetric, 1); if (previousValue != null){ boolean ok = counters.replace(counterMetric, previousValue, previousValue + 1); while(!ok) { logger.warning("Couldn't increment counter " + name + " with value " + (previousValue + 1) + " previousValue = " + previousValue); previousValue = counters.get(counterMetric); ok = counters.replace(counterMetric, previousValue, previousValue + 1); } } previousValue = previousValue == null ? 0 : previousValue; logger.fine("Counter " + name + " updated from previousValue " + previousValue + " to " + (previousValue + 1)); <END> } finally { ConcurrentMetricCounters.lock.unlock(); } }</code><technical_language>this a synchronized method of ConcurrentMetricCounters object , remove manual lock</technical_language>

Target:
public void incrementCounter(String name, String hostname, JSONArray tags) { ConcurrentMetricCounters.getInstance().increment(name, hostname, tags); }
Source:
<code>public void submitFrame() { if (vrCompositor == null) { return; } if (vrCompositor.Submit == null) { return; <START> } <END> for (int nEye = 0; nEye < 2; nEye++) { vrCompositor.Submit.apply( nEye, texType[nEye], null, JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default); } if (vrCompositor.PostPresentHandoff != null) { vrCompositor.PostPresentHandoff.apply(); } }</code><technical_language>previous IF blocks: checks? time submitFrame() is called, needed? This applies PostPresentHandOff IF block below</technical_language>

Target:
public void submitFrame() { for (int nEye = 0; nEye < 2; nEye++) { vrCompositor.Submit.apply( nEye, texType[nEye], null, JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default); } if (vrCompositor.PostPresentHandoff != null) { vrCompositor.PostPresentHandoff.apply(); } }
Source:
<code>LogEventHandler(int eventCount, boolean isSlowLogTableEnabled, Configuration conf) { this.configuration = conf; EvictingQueue<SlowLogPayload> evictingQueue = EvictingQueue.create(eventCount); queueForRingBuffer = Queues.synchronizedQueue(evictingQueue); this.isSlowLogTableEnabled = isSlowLogTableEnabled; if (isSlowLogTableEnabled) { <START> EvictingQueue<SlowLogPayload> evictingQueueForTable = EvictingQueue.create( <END> SYS_TABLE_QUEUE_SIZE); queueForSysTable = Queues.synchronizedQueue(evictingQueueForTable); } else { queueForSysTable = null; } }</code><technical_language>system table logging is enabled, 2 queue. This new 1000 max size 'queueForRingBuffer' a default of 256 only. occupy more heap memory upto 1000 messages. reduce max numbers in queueForRingBuffer</technical_language>

Target:
LogEventHandler(int eventCount, boolean isSlowLogTableEnabled, Configuration conf) { this.configuration = conf; EvictingQueue<SlowLogPayload> evictingQueue = EvictingQueue.create(eventCount); queueForRingBuffer = Queues.synchronizedQueue(evictingQueue); this.isSlowLogTableEnabled = isSlowLogTableEnabled; if (isSlowLogTableEnabled) { int sysTableQueueSize = conf.getInt(SYS_TABLE_QUEUE_SIZE, DEFAULT_SYS_TABLE_QUEUE_SIZE); EvictingQueue<SlowLogPayload> evictingQueueForTable = EvictingQueue.create(sysTableQueueSize); queueForSysTable = Queues.synchronizedQueue(evictingQueueForTable); } else { queueForSysTable = null; } }
Source:
<code>public void getSegmentPoint(final int i) { final int mulLength = 3, offset = 2; if (splinePoints[i].getY() < splinePoints[i + 1].getY()) { final Vector3f vecNew = new Vector3f().add(splinePoints[i + 1]); vecNew.setY(splinePoints[i].getY()); meshStructurePoints[splinePoints.length * mulLength + offset * i] = splinePoints[i]; <START> meshStructurePoints[splinePoints.length * mulLength + offset * i + 1] = vecNew; <END> } else { final Vector3f vecNew = new Vector3f().add(splinePoints[i]); vecNew.setY(splinePoints[i + 1].getY()); meshStructurePoints[splinePoints.length * mulLength + offset * i] = vecNew; meshStructurePoints[splinePoints.length * mulLength + offset * i + 1] = splinePoints[i + 1]; } }</code><technical_language>clean, add parenthesis kind of more clear</technical_language>

Target:
public void getSegmentPoint(final int i) { final int mulLength = 3, offset = 2; if (splinePoints[i].getY() < splinePoints[i + 1].getY()) { final Vector3f vecNew = new Vector3f().add(splinePoints[i + 1]); vecNew.setY(splinePoints[i].getY()); meshStructurePoints[(splinePoints.length * mulLength) + (offset * i)] = splinePoints[i]; meshStructurePoints[(splinePoints.length * mulLength) + (offset * i) + 1] = vecNew; } else { final Vector3f vecNew = new Vector3f().add(splinePoints[i]); vecNew.setY(splinePoints[i + 1].getY()); meshStructurePoints[(splinePoints.length * mulLength) + (offset * i)] = vecNew; meshStructurePoints[(splinePoints.length * mulLength) + (offset * i) + 1] = splinePoints[i + 1]; } }
Source:
<code>public Post scrollToBottom(WebDriver driver) { <START> ((JavascriptExecutor) driver) <END> .executeScript("window.scrollTo(0, document.body.scrollHeight)"); return this; }</code><technical_language>need cast JavascripExecutor</technical_language>

Target:
public Post scrollToBottom(WebDriver driver) { jsActions.scrollToBottom(driver); return this; }
Source:
<code>private void setCacheHeaders(boolean isPrivate, RestResponseChannel restResponseChannel) throws RestServiceException { if (isPrivate) { <START> restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(0)); <END> restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "private, no-cache, no-store, proxy-revalidate"); restResponseChannel.setHeader(RestUtils.Headers.PRAGMA, "no-cache"); } else { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(System.currentTimeMillis() + adminConfig.adminCacheValiditySeconds * Time.MsPerSec)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "max-age=" + adminConfig.adminCacheValiditySeconds); } }</code><technical_language>I understand this is code, private blobs handled differently EXPIRES is concerned, is implication of setting EXPIRES a time in past</technical_language>

Target:
private void setCacheHeaders(boolean isPrivate, RestResponseChannel restResponseChannel) throws RestServiceException { if (isPrivate) { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, restResponseChannel.getHeader(RestUtils.Headers.DATE)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "private, no-cache, no-store, proxy-revalidate"); restResponseChannel.setHeader(RestUtils.Headers.PRAGMA, "no-cache"); } else { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(System.currentTimeMillis() + adminConfig.adminCacheValiditySeconds * Time.MsPerSec)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "max-age=" + adminConfig.adminCacheValiditySeconds); } }
Source:
<code>public void lockTask(TaskExecution taskExecution) { if(this.lockRegistry == null ) { this.lockRegistry = getDefaultLockRegistry(taskExecution.getExecutionId()); } this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator( this.lockRegistry, new DefaultCandidate(String.valueOf(taskExecution.getExecutionId()), taskNameResolver.getTaskName())); this.lockRegistryLeaderInitiator.setApplicationEventPublisher(this.applicationEventPublisher); this.lockRegistryLeaderInitiator.setPublishFailedEvents(true); this.lockRegistryLeaderInitiator.start(); while (!this.lockReady) { try { <START> Thread.sleep(500); <END> } catch (InterruptedException ex) { logger.warn("Thread Sleep Failed", ex); } if (this.lockFailed) { String errorMessage = String.format( "Task with name \"%s\" is already running.", this.taskNameResolver.getTaskName()); try { this.lockRegistryLeaderInitiator.destroy(); } catch (Exception exception) { throw new TaskExecutionException("Failed to destroy lock.", exception); } throw new TaskExecutionException(errorMessage); } } }</code><technical_language>Is a reason this configurable</technical_language>

Target:
public void lockTask(TaskExecution taskExecution) { if(this.lockRegistry == null ) { this.lockRegistry = getDefaultLockRegistry(taskExecution.getExecutionId()); } this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator( this.lockRegistry, new DefaultCandidate(String.valueOf(taskExecution.getExecutionId()), taskNameResolver.getTaskName())); this.lockRegistryLeaderInitiator.setApplicationEventPublisher(this.applicationEventPublisher); this.lockRegistryLeaderInitiator.setPublishFailedEvents(true); this.lockRegistryLeaderInitiator.start(); while (!this.lockReady) { try { Thread.sleep(this.taskProperties.getSingleInstanceLockCheckInterval()); } catch (InterruptedException ex) { logger.warn("Thread Sleep Failed", ex); } if (this.lockFailed) { String errorMessage = String.format( "Task with name \"%s\" is already running.", this.taskNameResolver.getTaskName()); try { this.lockRegistryLeaderInitiator.destroy(); } catch (Exception exception) { throw new TaskExecutionException("Failed to destroy lock.", exception); } throw new TaskExecutionException(errorMessage); } } }
Source:
<code>private void setAndCreateWebViewsStyleSheet(String styleSheetUrl) { Path cacheDirectory = preferencesService.getCacheDirectory(); noCatch(() -> { Files.createDirectories(cacheDirectory); Path newTempStyleSheet = Files.createTempFile(cacheDirectory, "style-webview", ".css"); Files.delete(newTempStyleSheet); try (InputStream inputStream = new URL(styleSheetUrl).openStream()) { Files.copy(inputStream, newTempStyleSheet); } String newStyleSheetUrl = newTempStyleSheet.toUri().toURL().toString(); webViews.forEach(webView -> Platform.runLater(() -> webView.getEngine().setUserStyleSheetLocation(newStyleSheetUrl))); logger.debug("{} created and applied to all web views", newTempStyleSheet.getFileName()); if (currentTempStyleSheet != null) { <START> Files.delete(currentTempStyleSheet); <END> } currentTempStyleSheet = newTempStyleSheet; }); }</code><technical_language>This delete style sheet client launch, it</technical_language>

Target:
private void setAndCreateWebViewsStyleSheet(String styleSheetUrl) { Path stylesheetsCacheDirectory = preferencesService.getCacheStylesheetsDirectory(); noCatch(() -> { Files.createDirectories(stylesheetsCacheDirectory); Path newTempStyleSheet = Files.createTempFile(stylesheetsCacheDirectory, "style-webview", ".css"); try (InputStream inputStream = new URL(styleSheetUrl).openStream()) { Files.copy(inputStream, newTempStyleSheet, StandardCopyOption.REPLACE_EXISTING); } String newStyleSheetUrl = newTempStyleSheet.toUri().toURL().toString(); webViews.forEach(webView -> Platform.runLater(() -> webView.getEngine().setUserStyleSheetLocation(newStyleSheetUrl))); logger.debug("{} created and applied to all web views", newTempStyleSheet.getFileName()); if (currentTempStyleSheet != null) { Files.delete(currentTempStyleSheet); } currentTempStyleSheet = newTempStyleSheet; }); }
Source:
<code>private void checkAnnotators() { synchronized (observedRequests) { long waitingTime; long currentTime = System.currentTimeMillis(); ObservedHttpRequest observedRequest; for (Entry<ObservedHttpRequest, Long> e : observedRequests.entrySet()) { waitingTime = currentTime - e.getValue(); if (waitingTime > maxWaitingTime) { observedRequest = e.getKey(); if (observedRequest.request.isAborted()) { LOGGER.warn( "Observing an HTTP request that is already aborted. This could be mean that the HTTP management does not have been informed about the termination of a request."); <START> observedRequests.remove(observedRequest); <END> } else { LOGGER.info("The HTTP request emitter \"{}\" already runs for ms. Trying to interrupt it.", observedRequest.emitter.getName(), waitingTime); try { observedRequest.emitter.interrupt(observedRequest.request); } catch (UnsupportedOperationException ex) { LOGGER.error("Couldn't interrupt request of HTTP request emitter \"" + observedRequest.emitter.getName() + "\" that is already running for " + waitingTime + " ms."); } } } } } }</code><technical_language>I this throw a ConcurrentModificationException. iterator of entrySet() remove method of iterator</technical_language>

Target:
private void checkAnnotators() { synchronized (observedRequests) { long waitingTime; long currentTime = System.currentTimeMillis(); ObservedHttpRequest observedRequest; Iterator<Entry<ObservedHttpRequest, Long>> iterator = observedRequests.entrySet().iterator(); while (iterator.hasNext()) { Entry<ObservedHttpRequest, Long> entry = iterator.next(); waitingTime = currentTime - entry.getValue(); if (waitingTime > maxWaitingTime) { observedRequest = entry.getKey(); if (observedRequest.request.isAborted()) { LOGGER.warn( "Observing an HTTP request that is already aborted. This could be mean that the HTTP management does not have been informed about the termination of a request."); iterator.remove(); } else { LOGGER.info("The HTTP request emitter \"{}\" already runs for ms. Trying to interrupt it.", observedRequest.emitter.getName(), waitingTime); try { observedRequest.emitter.interrupt(observedRequest.request); } catch (UnsupportedOperationException ex) { LOGGER.error("Couldn't interrupt request of HTTP request emitter \"" + observedRequest.emitter.getName() + "\" that is already running for " + waitingTime + " ms."); } } } } } }