auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private javax.jms.Message doSendAndReceiveAsync(Destination requestDestination, javax.jms.Message jmsRequest, Session session, int priority) throws JMSException { String correlationId = null; MessageProducer messageProducer = null; try { messageProducer = session.createProducer(requestDestination); if (!this.correlationKey.equals("JMSCorrelationID*") || jmsRequest.getJMSCorrelationID() == null) { correlationId = this.gatewayCorrelation + "_" + Long.toString(this.correlationId.incrementAndGet()); if (this.correlationKey.equals("JMSCorrelationID")) { jmsRequest.setJMSCorrelationID(correlationId); } else { jmsRequest.setStringProperty(this.correlationKey, correlationId); jmsRequest.setJMSCorrelationID(null); } } else { correlationId = this.gatewayCorrelation + "_" + jmsRequest.getJMSCorrelationID(); jmsRequest.setJMSCorrelationID(correlationId); } LinkedBlockingQueue<javax.jms.Message> replyQueue = new LinkedBlockingQueue<javax.jms.Message>(1); if (logger.isDebugEnabled()) { logger.debug(this.getComponentName() + " Sending message with correlationId " + correlationId); } this.replies.put(correlationId, replyQueue); this.sendRequestMessage(jmsRequest, messageProducer, priority); return obtainReplyFromContainer(correlationId, replyQueue); } finally { JmsUtils.closeMessageProducer(messageProducer); this.replies.remove(correlationId); } }

Target:
private javax.jms.Message doSendAndReceiveAsync(Destination requestDestination, javax.jms.Message jmsRequest, Session session, int priority) throws JMSException { String correlationId = null; MessageProducer messageProducer = null; try { messageProducer = session.createProducer(requestDestination); correlationId = this.gatewayCorrelation + "_" + Long.toString(this.correlationId.incrementAndGet()); if (this.correlationKey.equals("JMSCorrelationID")) { jmsRequest.setJMSCorrelationID(correlationId); } else { jmsRequest.setStringProperty(this.correlationKey, correlationId); jmsRequest.setJMSCorrelationID(null); } LinkedBlockingQueue<javax.jms.Message> replyQueue = new LinkedBlockingQueue<javax.jms.Message>(1); if (logger.isDebugEnabled()) { logger.debug(this.getComponentName() + " Sending message with correlationId " + correlationId); } this.replies.put(correlationId, replyQueue); this.sendRequestMessage(jmsRequest, messageProducer, priority); return obtainReplyFromContainer(correlationId, replyQueue); } finally { JmsUtils.closeMessageProducer(messageProducer); this.replies.remove(correlationId); } }
Source:
public void parallelValueExtractorDefinitionsCausesException() { Validator validator = Validation.byDefaultProvider() .configure() .addValueExtractor( new IWrapper21ValueExtractor0() ) .addValueExtractor( new IWrapper211ValueExtractor0() ) .addValueExtractor( new IWrapper212ValueExtractor0() ) .addValueExtractor( new IWrapper22ValueExtractor0() ) .addValueExtractor( new IWrapper221ValueExtractor0() ) .addValueExtractor( new Wrapper2ValueExtractor1() ) .buildValidatorFactory() .getValidator(); validator.validate( new CascadingEntity2( null ) ); }

Target:
public void parallelValueExtractorDefinitionsCausesException() { Validator validator = Validation.byDefaultProvider() .configure() .addValueExtractor( new IWrapper211ValueExtractor0() ) .addValueExtractor( new IWrapper212ValueExtractor0() ) .addValueExtractor( new Wrapper2ValueExtractor1() ) .buildValidatorFactory() .getValidator(); validator.validate( new CascadingEntity2( null ) ); }
Source:
public void invokeCallbackMethods() { initCommandExecutor(); for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: try { callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { log.errorFormat("Error invoking onFailed for FAILED command {0}", cmdId.toString()); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: try { callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { log.errorFormat("Error invoking onSucceeded for SUCCEEDED command {0}", cmdId.toString()); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE_ASYNC_EXECUTED: try { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { coco.retrieveCommand(cmdId).setCommandStatus(CommandStatus.FAILED); log.errorFormat("Error invoking doPooling for active command {0}", cmdId.toString()); } break; default: break; } } }

Target:
public void invokeCallbackMethods() { initCommandExecutor(); CommandEntity cmdEntity; for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: try { callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { log.errorFormat("Error invoking onFailed for FAILED command {0}", cmdId.toString()); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: try { callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); } catch (Exception ex) { log.errorFormat("Error invoking onSucceeded for SUCCEEDED command {0}", cmdId.toString()); coco.updateCommandStatus(cmdId, CommandStatus.FAILED); } break; case ACTIVE: cmdEntity = coco.getCommandEntity(cmdId); if (cmdEntity.isExecuted() && cmdEntity.isAsync()) { try { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { coco.updateCommandStatus(cmdId, CommandStatus.FAILED); log.errorFormat("Error invoking doPolling for active command {0}", cmdId.toString()); } } break; default: break; } } }
Source:
public BindQuery getBindersForSlot(ChildSlot slot, AssociationQuery childAq) { List<Binder> binders = new ArrayList<>(); for (BoundObject bo : childAq.getFieldBindings()) { Path field = bo.getFieldInfo().getEntityRelativeFieldNameWithContext(); Path fieldAtSlot = field.mutableCopy().rewriteIndexes(slot.getLocalContainerName()).immutableCopy(); Object value; if (fieldAtSlot.nAnys() > 0) { KeyValueCursor<Path, JsonNode> cursor = doc.getAllNodes(fieldAtSlot); value=new ArrayList<Value>(); while (cursor.hasNext()) { cursor.next(); ((List)value).add(getValue(bo.getFieldInfo().getFieldMd(),cursor.getCurrentValue())); } } else { value=getValue(bo.getFieldInfo().getFieldMd(),doc.get(fieldAtSlot)); } binders.add(new Binder(bo, value)); } return new BindQuery(binders); }

Target:
public BindQuery getBindersForSlot(ChildSlot slot, AssociationQuery childAq) { List<Binder> binders = new ArrayList<>(); for (BoundObject bo : childAq.getFieldBindings()) { Path field = bo.getFieldInfo().getEntityRelativeFieldNameWithContext(); Path fieldAtSlot = field.mutableCopy().rewriteIndexes(slot.getLocalContainerName()).immutableCopy(); if (fieldAtSlot.nAnys() > 0) { KeyValueCursor<Path, JsonNode> cursor = doc.getAllNodes(fieldAtSlot); List<Value> value=new ArrayList<Value>(); while (cursor.hasNext()) { cursor.next(); ((List)value).add(getValue(bo.getFieldInfo().getFieldMd(),cursor.getCurrentValue())); } binders.add(new Binder(bo,value)); } else { binders.add(new Binder(bo,getValue(bo.getFieldInfo().getFieldMd(),doc.get(fieldAtSlot)))); } } return new BindQuery(binders); }
Source:
public <T> T evalSha(byte[] scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs) { return evalSha(JedisConverters.toString(scriptSha1), returnType, numKeys, keysAndArgs); }

Target:
public <T> T evalSha(byte[] scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs) { return evalSha(LettuceConverters.toString(scriptSha1), returnType, numKeys, keysAndArgs); }
Source:
public void notify(String message) { LOGGER.info(message); DefaultTaskExecutor.runInJavaFXThread(() -> statusLine.fireEvent(new SnackbarEvent(new JFXSnackbarLayout(message), TOAST_MESSAGE_DISPLAY_TIME, null))); }

Target:
public void notify(String message) { LOGGER.info(message); statusLine.fireEvent(new SnackbarEvent(new JFXSnackbarLayout(message), TOAST_MESSAGE_DISPLAY_TIME, null)); }
Source:
private void handleResult(StreamingRecognitionResult result) { if (result.getAlternativesList().isEmpty()) { throw new IllegalArgumentException( "The alternatives list must not be empty"); } SpeechRecognitionAlternative alternative = result.getAlternatives(0); String newStablePart = alternative.getTranscript(); if (this.stableText.equals(newStablePart)) { if (logger.isDebugEnabled()) { logger.debug( debugName + ": dropping result without any change to" + " the stable part"); } return; } this.stableText = newStablePart; TranscriptionResult transcriptionResult = new TranscriptionResult( null, this.messageID, !result.getIsFinal(), this.languageTag, result.getStability(), new TranscriptionAlternative( newStablePart, alternative.getConfidence() )); sent(transcriptionResult); }

Target:
private void handleResult(StreamingRecognitionResult result) { if (result.getAlternativesList().isEmpty()) { throw new IllegalArgumentException( "The alternatives list must not be empty"); } SpeechRecognitionAlternative alternative = result.getAlternatives(0); String newTranscript = alternative.getTranscript(); if (this.latestTranscript.equals(newTranscript)) { if (logger.isDebugEnabled()) { logger.debug( debugName + ": dropping result without any change to" + " the stable part"); } return; } this.latestTranscript = newTranscript; TranscriptionResult transcriptionResult = new TranscriptionResult( null, this.messageID, !result.getIsFinal(), this.languageTag, result.getStability(), new TranscriptionAlternative( newTranscript, alternative.getConfidence() )); sent(transcriptionResult); }
Source:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (extensionPoint.equals(EVENT_EXT_POINT)) { doRegisterEvent((EventDescriptor) contribution); } else if (extensionPoint.equals(EXTENDED_INFO_EXT_POINT)) { doRegisterExtendedInfo((ExtendedInfoDescriptor) contribution); } else if (extensionPoint.equals(ADAPTER_POINT)) { doRegisterAdapter((AdapterDescriptor) contribution); } else if (contribution instanceof AuditBackendDescriptor) { backendConfig = (AuditBackendDescriptor)contribution; } else if (contribution instanceof AuditBulkerDescriptor) { bulkerConfig = (AuditBulkerDescriptor)contribution; } else if (contribution instanceof AuditStorageDescriptor) { AuditStorageDescriptor auditStorageDesc = (AuditStorageDescriptor) contribution; auditStorageDescriptors.putIfAbsent(auditStorageDesc.getId(), auditStorageDesc); } }

Target:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (extensionPoint.equals(EVENT_EXT_POINT)) { doRegisterEvent((EventDescriptor) contribution); } else if (extensionPoint.equals(EXTENDED_INFO_EXT_POINT)) { doRegisterExtendedInfo((ExtendedInfoDescriptor) contribution); } else if (extensionPoint.equals(ADAPTER_POINT)) { doRegisterAdapter((AdapterDescriptor) contribution); } else if (contribution instanceof AuditBackendDescriptor) { backendConfig = (AuditBackendDescriptor)contribution; } else if (contribution instanceof AuditBulkerDescriptor) { bulkerConfig = (AuditBulkerDescriptor)contribution; } else if (contribution instanceof AuditStorageDescriptor) { AuditStorageDescriptor auditStorageDesc = (AuditStorageDescriptor) contribution; auditStorageDescriptors.put(auditStorageDesc.getId(), auditStorageDesc); } }
Source:
public D withChangelogStream(String changelogStream) { this.changelogStream = changelogStream; return (D) this; }

Target:
public D withChangelogStream(String changelogStream) { this.enableChangelog = true; this.changelogStream = changelogStream; return (D) this; }
Source:
public String getProductSlug() { return mProductSlug; }

Target:
public String getProductSlug() { return StringUtils.notNullStr(mProductSlug); }
Source:
public byte[] enhance(String className, byte[] originalBytes) throws EnhancementException { final String safeClassName = className.replace( '/', '.' ); classFileLocator.addNameAndBytes( safeClassName, originalBytes ); try { final TypeDescription typeDescription = typePool.describe( safeClassName ).resolve(); return byteBuddyState.rewrite( typePool, safeClassName, byteBuddy -> doEnhance( byteBuddy.ignore( isDefaultFinalizer() ).redefine( typeDescription, ClassFileLocator.Simple.of( safeClassName, originalBytes ) ), typeDescription ) ); } catch (RuntimeException e) { throw new EnhancementException( "Failed to enhance class " + className, e ); } }

Target:
public byte[] enhance(String className, byte[] originalBytes) throws EnhancementException { final String safeClassName = className.replace( '/', '.' ); classFileLocator.setClassNameAndBytes( safeClassName, originalBytes ); try { final TypeDescription typeDescription = typePool.describe( safeClassName ).resolve(); return byteBuddyState.rewrite( typePool, safeClassName, byteBuddy -> doEnhance( byteBuddy.ignore( isDefaultFinalizer() ).redefine( typeDescription, ClassFileLocator.Simple.of( safeClassName, originalBytes ) ), typeDescription ) ); } catch (RuntimeException e) { throw new EnhancementException( "Failed to enhance class " + className, e ); } }
Source:
public void onPlayerTeleports(PlayerTeleportEvent event) { if (event.getFrom().getY() > 255 || event.getFrom().getY() < 0 || event.getTo().getY() > 255 || event.getTo().getY() < 0) { return; } Location from = event.getFrom().getBlock().getLocation(); Location to = event.getTo().getBlock().getLocation(); if (from.equals(to)) { return; } int maxRad = 50 * 50; for (final NPC npc: getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { if ((to.getWorld().getName().equalsIgnoreCase(npc.getEntity().getLocation().getWorld().getName()) && npc.getEntity().getLocation().distanceSquared(to) < maxRad) && ((from.getWorld().getName().equalsIgnoreCase(npc.getEntity().getLocation().getWorld().getName()) && npc.getEntity().getLocation().distanceSquared(from) > maxRad) || !from.getWorld().getName().equalsIgnoreCase(to.getWorld().getName()))) { showNPCReset(event.getPlayer(), npc); } } } }

Target:
public void onPlayerTeleports(PlayerTeleportEvent event) { Location from = roundLocation(event.getFrom()); Location to = roundLocation(event.getTo()); if (from.equals(to)) { return; } int maxRad = 50 * 50; for (final NPC npc: getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { Location npcPos = npc.getEntity().getLocation(); if ((to.getWorld() == npcPos.getWorld() && npcPos.distanceSquared(to) < maxRad) && ((from.getWorld() == npcPos.getWorld() && npcPos.distanceSquared(from) > maxRad) || from.getWorld() != to.getWorld())) { showNPCReset(event.getPlayer(), npc); } } } }
Source:
public void testToCheckNoConfigurationsAreExecuted() { XmlSuite suite = createXmlSuite("suite"); XmlTest test = createXmlTest(suite, "test", Issue1574TestclassSample.class); test.addExcludedGroup("sometest"); TestNG testng = create(suite); testng.run(); assertThat(Issue1574TestclassSample.messages).containsExactly("anothertest","@AfterSuite"); }

Target:
public void testToCheckNoConfigurationsAreExecuted() { XmlSuite suite = createXmlSuite("suite"); XmlTest test = createXmlTest(suite, "test", Issue1574TestclassSample.class); test.addExcludedGroup("sometest"); TestNG testng = create(suite); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener((ITestNGListener) listener); testng.run(); assertThat(listener.getInvokedMethodNames()).containsExactly("anothertest", "tearDownSuite"); }
Source:
private static String normAutoRangeValue(Object objectValue) { if (objectValue == null) return null; String value = objectValue.toString(); if ("auto".equals(value)) { return value; } return normRangeValue(objectValue); }

Target:
private static String normAutoRangeValue(Object objectValue) { if ("auto".equals(objectValue)) { return objectValue.toString(); } return normRangeValue(objectValue); }
Source:
private List<Observation> resolveConceptUuidForConceptNames(Config config, List<Observation> originalObservations) { List<Observation> updatedObs = new ArrayList<>(); if (originalObservations != null) { for (Observation observation : originalObservations) { if (observation.getValue() != null && StringUtils.isNotEmpty(observation.getValue().getDisplay())) { String conceptUuid = conceptService.resolveConceptUuidFromConceptName(config.getName(), observation.getConcept().getName().getName()); if (CollectionUtils.isNotEmpty(observation.getGroupsMembers())) { resolveConceptUuidForConceptNames(config, observation.getGroupsMembers()); } observation.getConcept().setUuid(conceptUuid); updatedObs.add(observation); } } } return updatedObs; }

Target:
private List<Observation> resolveConceptUuidForConceptNames(Config config, List<Observation> originalObservations) { List<Observation> updatedObs = new ArrayList<>(); if (originalObservations != null) { for (Observation observation : originalObservations) { if (observationValueIsNotEmpty(observation)) { String conceptUuid = conceptService.resolveConceptUuidFromConceptName(config.getName(), observation.getConcept().getName().getName()); if (CollectionUtils.isNotEmpty(observation.getGroupsMembers())) { resolveConceptUuidForConceptNames(config, observation.getGroupsMembers()); } observation.getConcept().setUuid(conceptUuid); updatedObs.add(observation); } else { LOGGER.warn("Observation value is null or empty for concept: " + observation.getConcept().getName() + " and will not be created"); } } } return updatedObs; }
Source:
public boolean equals(Object a, Object b) { final boolean ret; if (a != b && a instanceof IMergeViewerItem && b instanceof IMergeViewerItem) { IMergeViewerItem itemA = (IMergeViewerItem)a; IMergeViewerItem itemB = (IMergeViewerItem)b; Diff diffA = itemA.getDiff(); Diff diffB = itemB.getDiff(); if (diffA != null && diffA.getConflict() != null && diffA.getConflict().getKind() == ConflictKind.PSEUDO && diffB != null && diffB.getConflict() != null && diffB.getConflict().getKind() == ConflictKind.PSEUDO) { ret = Objects.equal(itemA.getAncestor(), itemB.getAncestor()) && Objects.equal(diffA.getConflict(), diffB.getConflict()); } else if (diffA != null && diffB != null && itemA.getLeft() == null && itemA.getRight() == null && itemB.getLeft() == null && itemB.getRight() == null) { ret = Objects.equal(diffA, diffB); } else if ((diffA == null) != (diffB == null)) { ret = Objects.equal(itemA.getLeft(), itemB.getLeft()) && Objects.equal(itemA.getRight(), itemB.getRight()) && Objects.equal(itemA.getAncestor(), itemB.getAncestor()); } else { ret = Objects.equal(itemA.getLeft(), itemB.getLeft()) && Objects.equal(itemA.getRight(), itemB.getRight()) && Objects.equal(itemA.getAncestor(), itemB.getAncestor()) && Objects.equal(diffA, diffB); } } else { ret = Objects.equal(a, b); } return ret; }

Target:
public boolean equals(Object a, Object b) { final boolean ret; if (a != b && a instanceof IMergeViewerItem && b instanceof IMergeViewerItem) { IMergeViewerItem itemA = (IMergeViewerItem)a; IMergeViewerItem itemB = (IMergeViewerItem)b; Diff diffA = itemA.getDiff(); Diff diffB = itemB.getDiff(); if (diffA != null && diffA.getConflict() != null && diffA.getConflict().getKind() == ConflictKind.PSEUDO && diffB != null && diffB.getConflict() != null && diffB.getConflict().getKind() == ConflictKind.PSEUDO) { ret = Objects.equal(itemA.getAncestor(), itemB.getAncestor()) && Objects.equal(diffA.getConflict(), diffB.getConflict()); } else if (diffA != null && diffB != null && itemA.getLeft() == null && itemA.getRight() == null && itemB.getLeft() == null && itemB.getRight() == null) { ret = Objects.equal(diffA, diffB); } else if (diffA == null || diffB == null) { ret = Objects.equal(itemA.getLeft(), itemB.getLeft()) && Objects.equal(itemA.getRight(), itemB.getRight()) && Objects.equal(itemA.getAncestor(), itemB.getAncestor()); } else { ret = Objects.equal(itemA.getLeft(), itemB.getLeft()) && Objects.equal(itemA.getRight(), itemB.getRight()) && Objects.equal(itemA.getAncestor(), itemB.getAncestor()) && Objects.equal(diffA, diffB); } } else { ret = Objects.equal(a, b); } return ret; }
Source:
public Iterator<Widget> iterator() { return new Iterator<Widget>() { boolean hasElement = widget != null; Widget returned = null; @Override public boolean hasNext() { return hasElement; } @Override public Widget next() { if (!hasElement || (widget == null)) { throw new NoSuchElementException(); } hasElement = false; return (returned = widget); } @Override public void remove() { if (returned != null) { WidgetDecorator.this.remove(returned); } } }; }

Target:
public Iterator<Widget> iterator() { return new Iterator<Widget>() { boolean hasElement = widget != null; Widget returned = null; @Override public boolean hasNext() { return hasElement; } @Override public Widget next() { if (!hasElement || (widget == null)) { throw new NoSuchElementException(); } hasElement = false; returned = widget; return returned; } @Override public void remove() { if (returned != null) { WidgetDecorator.this.remove(returned); } } }; }
Source:
public void write (OutputStream outputStream) { DataOutputStream write = null; GZIPOutputStream gzip = null; byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { gzip = new GZIPOutputStream(outputStream); write = new DataOutputStream(gzip); write.writeInt(compressedData.capacity()); while (writtenBytes != compressedData.capacity()) { int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); compressedData.get(buffer, 0, bytesToWrite); write.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } write.close(); gzip.close(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM", e); } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); }

Target:
public void write (OutputStream outputStream) { DataOutputStream dataStream = null; GZIPOutputStream gzipStream = null; byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { gzipStream = new GZIPOutputStream(outputStream); dataStream = new DataOutputStream(gzipStream); dataStream.writeInt(compressedData.capacity()); while (writtenBytes != compressedData.capacity()) { int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); compressedData.get(buffer, 0, bytesToWrite); dataStream.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } dataStream.flush(); gzipStream.flush(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM", e); } finally { StreamUtils.closeQuietly(dataStream); StreamUtils.closeQuietly(gzipStream); } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); }
Source:
boolean doRefresh() { boolean performRefresh = false; synchronized (isRefreshing) { if (!isRefreshing.get() && getCacheState(headerCache.get()) != CacheState.Good) { isRefreshing.set(true); performRefresh = true; } } if (!performRefresh) { return false; } HeaderCacheElement cacheElement = null; try { AccessToken newToken = credentials.refreshAccessToken(); if (newToken == null) { cacheElement = new HeaderCacheElement( new IOException("Could not load the token for credentials: " + credentials)); } else { cacheElement = new HeaderCacheElement(newToken); } } catch (IOException e) { cacheElement = new HeaderCacheElement(e); } catch (Exception e) { cacheElement = new HeaderCacheElement(new IOException("Could not read headers", e)); } finally { synchronized (isRefreshing) { headerCache.set(cacheElement); isRefreshing.set(false); isRefreshing.notifyAll(); } } return true; }

Target:
boolean doRefresh() { boolean requiresRefresh = false; synchronized (isRefreshing) { if (!isRefreshing.get() && getCacheState(this.headerCache.get()) != CacheState.Good) { isRefreshing.set(true); requiresRefresh = true; } } if (!requiresRefresh) { return false; } HeaderCacheElement cacheElement = null; try { AccessToken newToken = credentials.refreshAccessToken(); if (newToken == null) { cacheElement = new HeaderCacheElement( new IOException("Could not load the token for credentials: " + credentials)); } else { cacheElement = new HeaderCacheElement(newToken); } } catch (IOException e) { cacheElement = new HeaderCacheElement(e); } catch (Exception e) { cacheElement = new HeaderCacheElement(new IOException("Could not read headers", e)); } finally { synchronized (isRefreshing) { headerCache.set(cacheElement); isRefreshing.set(false); isRefreshing.notifyAll(); } } return true; }
Source:
private VCFColumn getColumn(String token) { String lkToken = token.toLowerCase(); VCFColumn matchedColumn = null; for (VCFColumn column : VCFColumn.values()) { if (column.getName().equals(lkToken)) { matchedColumn = column; } } return matchedColumn; }

Target:
private VCFColumn getColumn(String token) { VCFColumn matchedColumn = null; for (VCFColumn column : VCFColumn.values()) { if (column.name().equalsIgnoreCase(token)) { matchedColumn = column; } } return matchedColumn; }
Source:
public LookupRuntimeProvider getLookupRuntimeProvider(LookupTableSource.Context context) { String[] keyNames = new String[context.getKeys().length]; for (int i = 0; i < keyNames.length; i++) { int index = context.getKeys()[i][0]; keyNames[i] = schema.getFieldNames()[index]; } return TableFunctionProvider.of(JdbcDynamicLookupFunction.builder() .setFieldNames(schema.getFieldNames()) .setFieldTypes(schema.getFieldDataTypes()) .setKeyNames(keyNames) .setOptions(options) .setLookupOptions(lookupOptions) .build()); }

Target:
public LookupRuntimeProvider getLookupRuntimeProvider(LookupTableSource.Context context) { String[] keyNames = new String[context.getKeys().length]; for (int i = 0; i < keyNames.length; i++) { int[] innerKeyArr = context.getKeys()[i]; Preconditions.checkArgument(innerKeyArr.length == 1, "JDBC only support non-nested look up keys"); keyNames[i] = schema.getFieldNames()[innerKeyArr[0]]; } final RowType rowType = (RowType) schema.toRowDataType().getLogicalType(); return TableFunctionProvider.of(new JdbcRowDataLookupFunction( options, lookupOptions, schema.getFieldNames(), schema.getFieldDataTypes(), keyNames, rowType)); }
Source:
public static CFGBytecode buildCFG(Symbol.MethodSymbol methodSymbol, SquidClassLoader classLoader) { InputStream is = classLoader.getResourceAsStream(Convert.bytecodeName(((JavaSymbol.TypeJavaSymbol) methodSymbol.owner()).getFullyQualifiedName()) + ".class"); try { byte[] bytes = ByteStreams.toByteArray(is); if (Java9Support.isJava9Class(bytes)) { Java9Support.setJava8MajorVersion(bytes); } ClassReader cr = new ClassReader(bytes); BytecodeCFGMethodVisitor methodVisitor = new BytecodeCFGMethodVisitor(methodSymbol); cr.accept(new ClassVisitor(Opcodes.ASM5) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (name.equals(methodSymbol.name())) { return methodVisitor; } return null; } }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return methodVisitor.cfg; } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(is); } }

Target:
public static BytecodeCFG buildCFG(Symbol.MethodSymbol methodSymbol, SquidClassLoader classLoader) { try(InputStream is = classLoader.getResourceAsStream(Convert.bytecodeName(((JavaSymbol.TypeJavaSymbol) methodSymbol.owner()).getFullyQualifiedName()) + ".class")) { byte[] bytes = ByteStreams.toByteArray(is); if (Java9Support.isJava9Class(bytes)) { Java9Support.setJava8MajorVersion(bytes); } return buildCFG(methodSymbol, bytes); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
private boolean validateAccount(String chartCode, String accountNumber) { if (StringUtils.isBlank(accountNumber)) { LOG.error("Account Number cannot be blank."); return false; } if (StringUtils.equalsIgnoreCase(accountNumber, CuFPConstants.AmazonWebServiceBillingConstants.INTERNAL_KFS_ACCOUNT_DESCRIPTION)) { return true; } Account account = accountService.getByPrimaryId(chartCode, accountNumber); if (ObjectUtils.isNull(account)) { LOG.error(String.format("Could not find Account (%s, %s).", chartCode, accountNumber)); return false; } if (!account.isActive()) { LOG.error(String.format("Invalid Account (%s, %s) is not active.", chartCode, accountNumber)); return false; } if (account.isClosed()) { LOG.error(String.format("Invalid Account (%s, %s) is closed.", chartCode, accountNumber)); return false; } if (account.isExpired()) { LOG.error(String.format("Invalid Account (%s, %s) is expired.", chartCode, accountNumber)); return false; } return true; }

Target:
private boolean validateAccount(String chartCode, String accountNumber) { if (StringUtils.isBlank(accountNumber)) { LOG.error(configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_ACCOUNT_NUMBER_BLANK)); return false; } if (StringUtils.equalsIgnoreCase(accountNumber, CuFPConstants.AmazonWebServiceBillingConstants.INTERNAL_KFS_ACCOUNT_DESCRIPTION)) { return true; } Account account = accountService.getByPrimaryId(chartCode, accountNumber); if (ObjectUtils.isNull(account)) { LOG.error(String.format(configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_ACCOUNT_NOT_FOUND), chartCode, accountNumber)); return false; } if (account.isClosed()) { LOG.error(String.format(configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_ACCOUNT_CLOSED), chartCode, accountNumber)); return false; } if (account.isExpired()) { LOG.error(String.format(configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_ACCOUNT_EXPIRED), chartCode, accountNumber)); return false; } return true; }
Source:
protected void onBindBoxItemViewHolder(BoxItemViewHolder holder, BoxItem itemToBind) { if (holder.getItem() == null || holder.getItem() == null) { return; } final BoxItem item = holder.getItem(); holder.getNameView().setText(item.getName()); holder.getMetaDescription().setText(BoxSearchListAdapter.createPath(item, File.separator)); mController.getThumbnailManager().loadThumbnail(item, holder.getThumbView()); holder.getProgressBar().setVisibility(View.GONE); holder.getMetaDescription().setVisibility(View.VISIBLE); holder.getThumbView().setVisibility(View.VISIBLE); }

Target:
protected void onBindBoxItemViewHolder(BoxItemViewHolder holder, BoxItem itemToBind) { if (itemToBind == null || itemToBind == null) { return; } holder.getNameView().setText(itemToBind.getName()); holder.getMetaDescription().setText(BoxSearchListAdapter.createPath(itemToBind, File.separator)); mController.getThumbnailManager().loadThumbnail(itemToBind, holder.getThumbView()); holder.getProgressBar().setVisibility(View.GONE); holder.getMetaDescription().setVisibility(View.VISIBLE); holder.getThumbView().setVisibility(View.VISIBLE); }
Source:
private void setDepth(N node, N parent) { if (parent == null) { depths.put(node, 0); height = Optional.of(0); } else { depths.putIfAbsent(parent, 0); int nodeDepth = Math.max(depths.get(parent) + 1, height.orElse(0)); depths.put(node, nodeDepth); height = Optional.of(nodeDepth); } }

Target:
private void setDepth(N node, N parent) { if (parent == null) { depths.put(node, 0); height = Optional.of(0); } else { depths.putIfAbsent(parent, 0); int nodeDepth = Math.max(depths.get(parent) + 1, height.orElseThrow(AssertionError::new)); depths.put(node, nodeDepth); height = Optional.of(nodeDepth); } }
Source:
public void testPathIncludeWhitelist() { OpenTracingManager.fileExtensionWhitelist.add("jsp"); OpenTracingManager.fileExtensionWhitelist.add("foo"); OpenTracingManager otm = new OpenTracingManager(null); assertTrue(otm.includePath("/foo/bar/test.jsp")); assertTrue(otm.includePath("/quux/test.foo")); assertFalse(otm.includePath("/my/image.png")); OpenTracingManager.fileExtensionWhitelist.clear(); }

Target:
public void testPathIncludeWhitelist() { OpenTracingManager.fileExtensionWhitelist.add("foo"); OpenTracingManager otm = new OpenTracingManager(null); assertTrue(otm.includePath("/quux/test.foo")); assertFalse(otm.includePath("/my/image.bar")); OpenTracingManager.fileExtensionWhitelist.clear(); }
Source:
public FilterResult apply(final Message message) { for (MessageFilter filter : messageFilters) { try { if (!filter.test(message)) { return FilterResult.failed(filter.getType(), "logical"); } } catch (Exception ex) { return FilterResult.failed(filter.getType(), ex.getMessage()); } } return FilterResult.PASS; }

Target:
public FilterResult apply(final Message message) { for (MessageFilter filter : messageFilters) { try { if (!filter.test(message)) { return FilterResult.failed(filter.getType(), "logical"); } } catch (Exception ex) { return FilterResult.failed(filter.getType(), ex); } } return FilterResult.PASS; }
Source:
private RevocableMemoryOperator setupConsumeRevocableMemory(DataSize reservedPerPage, long numberOfPages) { final AtomicReference<RevocableMemoryOperator> createOperator = new AtomicReference<>(); setUp(() -> { DriverContext driverContext = taskContext.addPipelineContext(0, false, false).addDriverContext(); OperatorContext revokableOperatorContext = driverContext.addOperatorContext( Integer.MAX_VALUE, new PlanNodeId("revokable_operator"), TableScanOperator.class.getSimpleName()); OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> { })); Operator outputOperator = outputFactory.createOutputOperator(2, new PlanNodeId("output"), ImmutableList.of(), Function.identity(), new TestingPagesSerdeFactory()).createOperator(driverContext); RevocableMemoryOperator revocableMemoryOperator = new RevocableMemoryOperator(revokableOperatorContext, reservedPerPage, numberOfPages); createOperator.set(revocableMemoryOperator); return ImmutableList.of(new Driver(driverContext, revocableMemoryOperator, outputOperator)); }); return createOperator.get(); }

Target:
private RevocableMemoryOperator setupConsumeRevocableMemory(DataSize reservedPerPage, long numberOfPages) { AtomicReference<RevocableMemoryOperator> createOperator = new AtomicReference<>(); setUp(() -> { DriverContext driverContext = taskContext.addPipelineContext(0, false, false).addDriverContext(); OperatorContext revokableOperatorContext = driverContext.addOperatorContext( Integer.MAX_VALUE, new PlanNodeId("revokable_operator"), TableScanOperator.class.getSimpleName()); OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> { })); Operator outputOperator = outputFactory.createOutputOperator(2, new PlanNodeId("output"), ImmutableList.of(), Function.identity(), new TestingPagesSerdeFactory()).createOperator(driverContext); RevocableMemoryOperator revocableMemoryOperator = new RevocableMemoryOperator(revokableOperatorContext, reservedPerPage, numberOfPages); createOperator.set(revocableMemoryOperator); return ImmutableList.of(new Driver(driverContext, revocableMemoryOperator, outputOperator)); }); return createOperator.get(); }
Source:
public RuleSetBuilder addRule(final Rule newRule) { if (newRule == null) { throw new IllegalArgumentException(MISSING_RULE); } for (Rule rule : rules) { if (rule.getName().equals(newRule.getName()) && rule.getLanguage() == newRule.getLanguage()) { LOG.warning("Duplicated rule: " + newRule.getName()); } } rules.add(newRule); return this; }

Target:
public RuleSetBuilder addRule(final Rule newRule) { if (newRule == null) { throw new IllegalArgumentException(MISSING_RULE); } for (Rule rule : rules) { if (rule.getName().equals(newRule.getName()) && rule.getLanguage() == newRule.getLanguage()) { LOG.warning("The rule with name " + newRule.getName() + " is duplicated. " + "Future versions of PMD will reject to load such rulesets."); break; } } rules.add(newRule); return this; }
Source:
public Object clone() throws CloneNotSupportedException { TimeLiteral timeLiteral = (TimeLiteral) super.clone(); timeLiteral.time = (TimeValue) timeLiteral.clone(); return timeLiteral; }

Target:
public Object clone() throws CloneNotSupportedException { TimeLiteral timeLiteral = (TimeLiteral) super.clone(); timeLiteral.time = (TimeValue) timeLiteral.time.clone(); return timeLiteral; }
Source:
public <T extends LogicalSegment> List<T> filterSegments(SegmentMetadataQuery query, List<T> segments) { SegmentMetadataQuery updatedQuery = (SegmentMetadataQuery) query.withAnalysisTypes(getFinalAnalysisTypes(query)); if (!updatedQuery.isUsingDefaultInterval()) { return segments; } if (segments.size() <= 1) { return segments; } final T max = segments.get(segments.size() - 1); DateTime targetEnd = max.getInterval().getEnd(); final Interval targetInterval = new Interval(config.getDefaultHistory(), targetEnd); return Lists.newArrayList( Iterables.filter( segments, new Predicate<T>() { @Override public boolean apply(T input) { return (input.getInterval().overlaps(targetInterval)); } } ) ); }

Target:
public <T extends LogicalSegment> List<T> filterSegments(SegmentMetadataQuery query, List<T> segments) { if (!query.isUsingDefaultInterval()) { return segments; } if (segments.size() <= 1) { return segments; } final T max = segments.get(segments.size() - 1); DateTime targetEnd = max.getInterval().getEnd(); final Interval targetInterval = new Interval(config.getDefaultHistory(), targetEnd); return Lists.newArrayList( Iterables.filter( segments, new Predicate<T>() { @Override public boolean apply(T input) { return (input.getInterval().overlaps(targetInterval)); } } ) ); }
Source:
private boolean isCheProjectNameValid(String projectName) { if (cheProjectsList != null && cheProjectsList.contains(projectName)) { view.showCheProjectNameError(locale.existingProjectNameError()); return false; } if (!NameUtils.checkProjectName(projectName)) { view.showCheProjectNameError(locale.invalidCheProjectNameError()); return false; } view.hideCheProjectNameError(); return true; }

Target:
private boolean isCheProjectNameValid(String projectName) { if (cheProjects.contains(projectName)) { view.showCheProjectNameError(locale.existingProjectNameError()); return false; } if (!NameUtils.checkProjectName(projectName)) { view.showCheProjectNameError(locale.invalidCheProjectNameError()); return false; } view.hideCheProjectNameError(); return true; }
Source:
public void testDiscoverDevice() throws Exception { String id = "id"; byte[] deviceTimeoutByteArray = new byte[]{0x50}; long deviceTimeout = ByteUtils.byteArrayToLong(deviceTimeoutByteArray) * 100; ATCommandResponsePacket packet = createPacket(1, ATCommandStatus.OK, new XBee16BitAddress("0000"), new XBee64BitAddress("0013A20040A6A0DB"), id, new XBee16BitAddress("FFFE"), (byte)0x00, (byte)0x49); ndAnswers.add(packet); PowerMockito.when(deviceMock.getParameter("NT")).thenReturn(deviceTimeoutByteArray); PowerMockito.when(deviceMock.getXBeeProtocol()).thenReturn(XBeeProtocol.ZIGBEE); long start = System.currentTimeMillis(); RemoteXBeeDevice remote = nd.discoverDevice(id); long end = System.currentTimeMillis(); assertThat("The 'discoverDevice' should not be blocked for " + deviceTimeout + " ms", end - start < deviceTimeout, is(equalTo(true))); assertThat("The discovered device should not be null", remote, is(not(equalTo(null)))); assertThat("The Node ID of the discovered device should be '" + id + "'", remote.getNodeID(), is(equalTo(id))); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(SEND_NODE_DISCOVERY_COMMAND_METHOD, Mockito.anyString()); Mockito.verify(deviceMock, Mockito.times(1)).addPacketListener(packetListener); Mockito.verify(deviceMock, Mockito.times(1)).removePacketListener(packetListener); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(DISCOVER_DEVICES_API_METHOD, null, id); Mockito.verify(networkMock, Mockito.never()).addRemoteDevices(Mockito.anyListOf(RemoteXBeeDevice.class)); }

Target:
public void testDiscoverDevice() throws Exception { String id = "id"; byte[] deviceTimeoutByteArray = new byte[]{0x50}; long deviceTimeout = ByteUtils.byteArrayToLong(deviceTimeoutByteArray) * 100; ATCommandResponsePacket packet = createPacket(1, ATCommandStatus.OK, new XBee16BitAddress("0000"), new XBee64BitAddress("0013A20040A6A0DB"), id, new XBee16BitAddress("FFFE"), (byte)0x00, (byte)0x49); ndAnswers.add(packet); PowerMockito.when(deviceMock.getParameter("NT")).thenReturn(deviceTimeoutByteArray); PowerMockito.when(deviceMock.getXBeeProtocol()).thenReturn(XBeeProtocol.ZIGBEE); long start = System.currentTimeMillis(); RemoteXBeeDevice remote = nd.discoverDevice(id); long end = System.currentTimeMillis(); assertThat("The 'discoverDevice' should not be blocked for " + deviceTimeout + " ms", end - start < deviceTimeout, is(equalTo(true))); assertThat("The discovered device should not be null", remote, is(not(equalTo(null)))); assertThat("The Node ID of the discovered device should be '" + id + "'", remote.getNodeID(), is(equalTo(id))); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(SEND_NODE_DISCOVERY_COMMAND_METHOD, Mockito.anyString()); Mockito.verify(deviceMock, Mockito.times(1)).addPacketListener(packetListener); Mockito.verify(deviceMock, Mockito.times(1)).removePacketListener(packetListener); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(DISCOVER_DEVICES_API_METHOD, null, id); Mockito.verify(networkMock, Mockito.never()).addRemoteDevices(Mockito.anyListOf(RemoteXBeeDevice.class)); Mockito.verify(networkMock, Mockito.times(1)).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class)); }
Source:
public static Optional<RuleAttribute> build(final int columnIndex, final AnalyzerConfiguration configuration, final String attribute, final DTCellValue52 realCellValue) { PortablePreconditions.checkNotNull("columnIndex", columnIndex); PortablePreconditions.checkNotNull("attribute", attribute); PortablePreconditions.checkNotNull("realCellValue", realCellValue); final Comparable value = ActionBuilder.getValue(realCellValue); if (attribute.equals(DateExpiresRuleAttribute.NAME)) { final Date date = toDate(configuration, value); if (date != null) { return Optional.of(new DateExpiresRuleAttribute(columnIndex, (Date) value)); } } else if (attribute.equals(DateEffectiveRuleAttribute.NAME)) { final Date date = toDate(configuration, value); if (date != null) { return Optional.of(new DateEffectiveRuleAttribute(columnIndex, (Date) value)); } } return Optional.empty(); }

Target:
public static Optional<RuleAttribute> build(final int columnIndex, final AnalyzerConfiguration configuration, final String attribute, final DTCellValue52 realCellValue) { PortablePreconditions.checkNotNull("columnIndex", columnIndex); PortablePreconditions.checkNotNull("attribute", attribute); PortablePreconditions.checkNotNull("realCellValue", realCellValue); final Comparable value = ActionBuilder.getValue(realCellValue); if (attribute.equals(DateExpiresRuleAttribute.NAME)) { final Date date = toDate(configuration, value); if (date != null) { return Optional.of(new DateExpiresRuleAttribute(columnIndex, date)); } } else if (attribute.equals(DateEffectiveRuleAttribute.NAME)) { final Date date = toDate(configuration, value); if (date != null) { return Optional.of(new DateEffectiveRuleAttribute(columnIndex, date)); } } return Optional.empty(); }
Source:
private CreateImageVDSCommandParameters getCreateImageVDSCommandParameters() { DiskImage diskImage = getParameters().getDiskInfo(); if (getStorageDomain().getStorageType().isBlockDomain() && diskImage.getImage().getVolumeType().equals(VolumeType.Sparse) && diskImage.getActualSizeInBytes() != 0) { return new CreateImageVDSCommandParameters(getParameters().getStoragePoolId(), getParameters() .getStorageDomainId(), getImageGroupId(), getParameters().getDiskInfo().getSize(), getParameters().getDiskInfo().getVolumeType(), getParameters().getDiskInfo() .getVolumeFormat(), getDestinationImageId(), getJsonDiskDescription(getParameters().getDiskInfo()), diskImage.getActualSizeInBytes()); } else { return new CreateImageVDSCommandParameters(getParameters().getStoragePoolId(), getParameters() .getStorageDomainId(), getImageGroupId(), getParameters().getDiskInfo().getSize(), getParameters().getDiskInfo().getVolumeType(), getParameters().getDiskInfo() .getVolumeFormat(), getDestinationImageId(), getJsonDiskDescription(getParameters().getDiskInfo())); } }

Target:
private CreateImageVDSCommandParameters getCreateImageVDSCommandParameters() { DiskImage diskImage = getParameters().getDiskInfo(); CreateImageVDSCommandParameters parameters = new CreateImageVDSCommandParameters(getParameters().getStoragePoolId(), getParameters() .getStorageDomainId(), getImageGroupId(), getParameters().getDiskInfo().getSize(), getParameters().getDiskInfo().getVolumeType(), getParameters().getDiskInfo() .getVolumeFormat(), getDestinationImageId(), getJsonDiskDescription(getParameters().getDiskInfo())); if (getStorageDomain().getStorageType().isBlockDomain() && diskImage.getImage().getVolumeType().equals(VolumeType.Sparse) && diskImage.getActualSizeInBytes() != 0) { parameters.setImageInitialSizeInBytes(diskImage.getActualSizeInBytes()); } return parameters; }
Source:
public void setDefinitions(List<Definition> definitions) { this.m_definitions = definitions; }

Target:
public void setDefinitions(List<Definition> definitions) { m_definitions = definitions; }
Source:
void unexport(MBeanExporter exporter) { for (Class<?> rule : stats.keySet()) { String name = ObjectNames.builder(PlanOptimizer.class) .withProperty("optimizer", rule.getSimpleName()) .build(); exporter.unexport(name); } }

Target:
void unexport(MBeanExporter exporter) { for (Class<?> rule : stats.keySet()) { exporter.unexport(getName(rule)); } }
Source:
public TaskExecution getLatestTaskExecutionForTaskName(String taskName) { Assert.hasText(taskName, "The task name must not be empty."); final List<TaskExecution> te = this.getLatestTaskExecutionsByTaskNames(taskName); if (te.isEmpty()) { return null; } else if (te.size() == 1) { return te.get(0); } else { throw new IllegalStateException("Only expected a single TaskExecution but received " + te.size()); } }

Target:
public TaskExecution getLatestTaskExecutionForTaskName(String taskName) { Assert.hasText(taskName, "The task name must not be empty."); final List<TaskExecution> taskExecutions = this.getLatestTaskExecutionsByTaskNames(taskName); if (taskExecutions.isEmpty()) { return null; } else if (taskExecutions.size() == 1) { return taskExecutions.get(0); } else { throw new IllegalStateException("Only expected a single TaskExecution but received " + taskExecutions.size()); } }
Source:
protected void copyToResponse(InputStream is, HttpServletResponse response) throws IOException { try (OutputStream os = response.getOutputStream()) { long totalBytes = 0L; int readLength; byte[] bytes = new byte[4096]; while ((readLength = is.read(bytes, 0, bytes.length)) != -1) { try { os.write(bytes, 0, readLength); os.flush(); } catch (EOFException e) { if (e.getCause().getMessage().equals("Connection reset by peer")) { logger.debug("Socket has been closed. Possibly, user cancelled download."); response.setStatus(202); break; } } totalBytes += readLength; } response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(totalBytes)); response.flushBuffer(); } }

Target:
protected void copyToResponse(InputStream is, HttpServletResponse response) throws IOException { try (OutputStream os = new ExceptionHandlingOutputStream(response.getOutputStream())) { long totalBytes = 0L; int readLength; byte[] bytes = new byte[4096]; while ((readLength = is.read(bytes, 0, bytes.length)) != -1) { os.write(bytes, 0, readLength); os.flush(); totalBytes += readLength; } response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(totalBytes)); response.flushBuffer(); } }