auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void cancelPendingTransactions(final SearchCompositeDto searchCompositeDto) { final BindingResult errors = new MapBindingResult(new HashMap<String, String>(), TransactionService.class.getName()); try { lock.lock(); if (searchCompositeDto.getSearchRequestId() == null && (searchCompositeDto.getItemIds() == null || searchCompositeDto .getItemIds().isEmpty()) || (searchCompositeDto.getSearchRequestId() != null && searchCompositeDto.getItemIds() != null)) { errors.reject("transaction.selection.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } TransactionsSearchDto transactionsSearchDto; if (searchCompositeDto.getSearchRequestId() != null) { transactionsSearchDto = (TransactionsSearchDto) this.searchRequestService .getSearchRequest(searchCompositeDto.getSearchRequestId(), TransactionsSearchDto.class); } else { transactionsSearchDto = new TransactionsSearchDto(); transactionsSearchDto.setTransactionIds(new ArrayList<>(searchCompositeDto.getItemIds())); } final List<TransactionDto> transactionDtos = this.transactionService.searchTransactions(transactionsSearchDto, null); final Set<ExtendedLotDto> lotDtos = transactionDtos.stream().map(TransactionDto::getLot).collect( Collectors.toSet()); transactionInputValidator.validateAllProvidedTransactionsExists(transactionDtos, searchCompositeDto.getItemIds()); transactionInputValidator.validateEmptyList(transactionDtos); transactionInputValidator.validatePendingStatus(transactionDtos); extendedLotListValidator.validateClosedLots(lotDtos.stream().collect(Collectors.toList())); this.transactionService.cancelPendingTransactions(transactionDtos); } finally { lock.unlock(); } }

Target:
public void cancelPendingTransactions(final SearchCompositeDto searchCompositeDto) { final BindingResult errors = new MapBindingResult(new HashMap<String, String>(), TransactionService.class.getName()); try { lock.lock(); if (!searchCompositeDto.isValid()) { errors.reject("transaction.selection.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } TransactionsSearchDto transactionsSearchDto; if (searchCompositeDto.getSearchRequestId() != null) { transactionsSearchDto = (TransactionsSearchDto) this.searchRequestService .getSearchRequest(searchCompositeDto.getSearchRequestId(), TransactionsSearchDto.class); } else { transactionsSearchDto = new TransactionsSearchDto(); transactionsSearchDto.setTransactionIds(new ArrayList<>(searchCompositeDto.getItemIds())); } final List<TransactionDto> transactionDtos = this.transactionService.searchTransactions(transactionsSearchDto, null); final Set<ExtendedLotDto> lotDtos = transactionDtos.stream().map(TransactionDto::getLot).collect( Collectors.toSet()); transactionInputValidator.validateEmptyList(transactionDtos); transactionInputValidator.validateAllProvidedTransactionsExists(transactionDtos, searchCompositeDto.getItemIds()); transactionInputValidator.validatePendingStatus(transactionDtos); extendedLotListValidator.validateClosedLots(lotDtos.stream().collect(Collectors.toList())); this.transactionService.cancelPendingTransactions(transactionDtos); } finally { lock.unlock(); } }
Source:
public boolean appliesToTraceType(Class<? extends ITmfTrace> traceclass) { return !TmfExperiment.class.isAssignableFrom(traceclass); }

Target:
public boolean appliesToTraceType(Class<? extends ITmfTrace> traceclass) { return TmfTraceStub.class.isAssignableFrom(traceclass); }
Source:
protected void saveMedia(RawPacket p) { RawPacket newMedia; if (mediaPackets.size() < MEDIA_BUF_SIZE) { newMedia = new RawPacket(); newMedia.setBuffer(new byte[FECTransformEngine.INITIAL_BUFFER_SIZE]); newMedia.setOffset(0); } else { newMedia = mediaPackets.remove(mediaPackets.firstKey()); } int pLen = p.getLength(); if (pLen > newMedia.getBuffer().length) { newMedia.setBuffer(new byte[pLen]); } System.arraycopy(p.getBuffer(), p.getOffset(), newMedia.getBuffer(), 0, pLen); newMedia.setLength(pLen); mediaPackets.put(newMedia.getSequenceNumber(), newMedia); }

Target:
protected void saveMedia(RawPacket p) { RawPacket newMedia; if (mediaPackets.size() < MEDIA_BUF_SIZE) { newMedia = new RawPacket(); newMedia.setBuffer(new byte[FECTransformEngine.INITIAL_BUFFER_SIZE]); newMedia.setOffset(0); } else { newMedia = mediaPackets.remove(mediaPackets.firstKey()); } int pLen = p.getLength(); if (pLen > newMedia.getBuffer().length) { newMedia.setBuffer(new byte[pLen]); } System.arraycopy(p.getBuffer(), p.getOffset(), newMedia.getBuffer(), 0, pLen); newMedia.setLength(pLen); newMedia.setOffset(0); mediaPackets.put(newMedia.getSequenceNumber(), newMedia); }
Source:
private Document readXMLResource(Resource resource) { try { return db.parse(resource.openInputStream()); } catch (Throwable t) { return db.newDocument(); } }

Target:
private Document readXMLResource(Resource resource) { try (InputStream is = resource.openInputStream()) { return db.parse(is); } catch (Throwable t) { return db.newDocument(); } }
Source:
public MetadataCollector getMetadataCollector() { return metadataCollector; }

Target:
protected MetadataCollector getMetadataCollector() { return metadataCollector; }
Source:
public Operation exec(Prolog engine, UserIdentity userId) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); Term a2 = arg2.dereference(); Term a3 = arg3.dereference(); Term idTerm; Term nameTerm = Prolog.Nil; Term emailTerm = Prolog.Nil; Account.Id id = userId.getAccount(); if (id == null) { idTerm = anonymous; } else { idTerm = new IntegerTerm(id.get()); } String name = userId.getName(); if (name != null && !name.equals("")) { nameTerm = SymbolTerm.create(name); } String email = userId.getEmail(); if (email != null && !email.equals("")) { emailTerm = SymbolTerm.create(email); } if (!a1.unify(new StructureTerm(user, idTerm), engine.trail)) { return engine.fail(); } if (!a2.unify(nameTerm, engine.trail)) { return engine.fail(); } if (!a3.unify(emailTerm, engine.trail)) { return engine.fail(); } return cont; }

Target:
protected Operation exec(Prolog engine, UserIdentity userId) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); Term a2 = arg2.dereference(); Term a3 = arg3.dereference(); Term idTerm; Term nameTerm = Prolog.Nil; Term emailTerm = Prolog.Nil; Account.Id id = userId.getAccount(); if (id == null) { idTerm = anonymous; } else { idTerm = new IntegerTerm(id.get()); } String name = userId.getName(); if (name != null && !name.equals("")) { nameTerm = SymbolTerm.create(name); } String email = userId.getEmail(); if (email != null && !email.equals("")) { emailTerm = SymbolTerm.create(email); } if (!a1.unify(new StructureTerm(user, idTerm), engine.trail)) { return engine.fail(); } if (!a2.unify(nameTerm, engine.trail)) { return engine.fail(); } if (!a3.unify(emailTerm, engine.trail)) { return engine.fail(); } return cont; }
Source:
public Instant parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; if (value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\'') value = unquote(value); if (isLongLiteral(value)) { try { return ofEpochMilli(parseLong(value)); } catch (NumberFormatException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } } try { return Instant.from(PARSER.parse(value)); } catch (DateTimeParseException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } }

Target:
public Instant parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; if (isQuoted(value)) value = unquote(value); if (isLongLiteral(value)) { try { return ofEpochMilli(parseLong(value)); } catch (NumberFormatException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } } try { return Instant.from(PARSER.parse(value)); } catch (DateTimeParseException e) { throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value)); } }
Source:
public synchronized void write(final byte[] data, final int off, final int length) throws IOException { maybeThrowLastError(); Preconditions.checkArgument(data != null, "null data"); if (off < 0 || length < 0 || length > data.length - off) { throw new IndexOutOfBoundsException(); } if (lease != null && lease.isFreed()) { throw new IOException("Attempted to write to file without lease: " + path); } int currentOffset = off; int writableBytes = bufferSize - bufferIndex; int numberOfBytesToWrite = length; while (numberOfBytesToWrite > 0) { if (writableBytes <= numberOfBytesToWrite) { System.arraycopy(data, currentOffset, buffer, bufferIndex, writableBytes); bufferIndex += writableBytes; writeCurrentBufferToService(false, false); currentOffset += writableBytes; numberOfBytesToWrite = numberOfBytesToWrite - writableBytes; } else { System.arraycopy(data, currentOffset, buffer, bufferIndex, numberOfBytesToWrite); bufferIndex += numberOfBytesToWrite; numberOfBytesToWrite = 0; } writableBytes = bufferSize - bufferIndex; } }

Target:
public synchronized void write(final byte[] data, final int off, final int length) throws IOException { maybeThrowLastError(); Preconditions.checkArgument(data != null, "null data"); if (off < 0 || length < 0 || length > data.length - off) { throw new IndexOutOfBoundsException(); } if (lease != null && lease.isFreed()) { throw new PathIOException(path, ERR_WRITE_WITHOUT_LEASE); } int currentOffset = off; int writableBytes = bufferSize - bufferIndex; int numberOfBytesToWrite = length; while (numberOfBytesToWrite > 0) { if (writableBytes <= numberOfBytesToWrite) { System.arraycopy(data, currentOffset, buffer, bufferIndex, writableBytes); bufferIndex += writableBytes; writeCurrentBufferToService(); currentOffset += writableBytes; numberOfBytesToWrite = numberOfBytesToWrite - writableBytes; } else { System.arraycopy(data, currentOffset, buffer, bufferIndex, numberOfBytesToWrite); bufferIndex += numberOfBytesToWrite; numberOfBytesToWrite = 0; } writableBytes = bufferSize - bufferIndex; } incrementWriteOps(); }
Source:
public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PasswordEncoder passwordEncoder) { setIdAttribute(COUCH_ID); this.couchDbConnector = couchDbConnector; setAttributes(attributes); setPasswordEncoder(passwordEncoder); }

Target:
public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PasswordEncoder passwordEncoder) { setIdAttribute(COUCH_ID); objectMapper = new ObjectMapper(); this.couchDbConnector = couchDbConnector; setAttributes(attributes); setPasswordEncoder(passwordEncoder); }
Source:
public T waitForResponse() { try { boolean timeEllapsed = false; if (timeout != null) { timeEllapsed = !latch.await(timeout, TimeUnit.MILLISECONDS); } else { latch.await(); } if (timeEllapsed || coapTimeout.get()) { coapRequest.cancel(); if (exception.get() != null) { throw exception.get(); } else { if (timeout != null) throw new RequestTimeoutException(coapRequest.toString(), timeout); else throw new RequestTimeoutException(coapRequest.toString()); } } } catch (final InterruptedException e) { LOG.debug("Caught an unexpected InterruptedException during execution of CoAP request", e); } finally { coapRequest.removeMessageObserver(this); } if (exception.get() != null) { throw exception.get(); } return ref.get(); }

Target:
public T waitForResponse() { try { boolean timeElapsed = false; if (timeout != null) { timeElapsed = !latch.await(timeout, TimeUnit.MILLISECONDS); } else { latch.await(); } if (timeElapsed || coapTimeout.get()) { coapRequest.cancel(); if (exception.get() != null) { throw exception.get(); } } } catch (final InterruptedException e) { LOG.debug("Caught an unexpected InterruptedException during execution of CoAP request", e); } finally { coapRequest.removeMessageObserver(this); } if (exception.get() != null) { throw exception.get(); } return ref.get(); }
Source:
private void invalidateHashForClient(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); if (originatingClientDescriptor != null) { clientsToInvalidate.remove(originatingClientDescriptor); } InvalidationHolder invalidationHolder = null; invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }

Target:
private void invalidateHashForClient(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); if (originatingClientDescriptor != null) { clientsToInvalidate.remove(originatingClientDescriptor); } InvalidationHolder invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { throw new AssertionError("Codec error", mce); } } if (clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }
Source:
public TextureAtlasConfig(FileHandle packFile, FileHandle imagesDir){ String[] lines; try { lines = packFile.readAllLines(); } catch (IOException e) { throw new MdxException(e.toString()); } int i = 1; while (i < lines.length){ String texturePath = imagesDir.child(lines[i]).path(); textures.put(texturePath, null); i+=5; while (i < lines.length && !lines[i].isEmpty()){ int index, x, y, width, height, originalWidth, originalHeight, offsetX, offsetY; String name = lines[i]; boolean rotate = Boolean.parseBoolean(lines[i + 1].split(":")[1].trim()); int[] xyTuple = TextureAtlas.readTuple(lines[i + 2]); x = xyTuple[0]; y = xyTuple[1]; int[] whTuple = TextureAtlas.readTuple(lines[i + 3]); width = whTuple[0]; height = whTuple[1]; int[] originalWhTuple = TextureAtlas.readTuple(lines[i + 4]); originalWidth = originalWhTuple[0]; originalHeight = originalWhTuple[1]; int[] offsetTuple = TextureAtlas.readTuple(lines[i + 5]); offsetX = offsetTuple[0]; offsetY = offsetTuple[1]; index = Integer.parseInt(lines[i + 6].split(":")[1].trim()); atlasRegions.add(Mdx.graphics.newTextureAtlasRegion(texturePath, name, index, x, y, width, height, rotate, originalWidth, originalHeight, offsetX, offsetY)); i += 7; } i++; } }

Target:
public TextureAtlasConfig(FileHandle packFile, FileHandle imagesDir){ String[] lines; try { lines = packFile.readAllLines(); } catch (IOException e) { throw new MdxException(e.toString()); } int i = 1; while (i < lines.length){ String texturePath = imagesDir.child(lines[i]).path(); textures.put(texturePath, null); i+=5; while (i < lines.length && !lines[i].isEmpty()){ int index, x, y, width, height, originalWidth, originalHeight, offsetX, offsetY; String name = lines[i]; boolean rotate = Boolean.parseBoolean(lines[i + 1].split(":")[1].trim()); int[] xyTuple = readTuple(lines[i + 2]); x = xyTuple[0]; y = xyTuple[1]; int[] whTuple = readTuple(lines[i + 3]); width = whTuple[0]; height = whTuple[1]; int[] originalWhTuple = readTuple(lines[i + 4]); originalWidth = originalWhTuple[0]; originalHeight = originalWhTuple[1]; int[] offsetTuple = readTuple(lines[i + 5]); offsetX = offsetTuple[0]; offsetY = offsetTuple[1]; index = Integer.parseInt(lines[i + 6].split(":")[1].trim()); atlasRegions.add(Mdx.graphics.newTextureAtlasRegion(texturePath, name, index, x, y, width, height, rotate, originalWidth, originalHeight, offsetX, offsetY)); i += 7; } i++; } }
Source:
public void testDeleteFile_onWindows() throws Exception { Assume.assumeTrue(Functions.isWindows()); Class<?> c; try { c = Class.forName("java.nio.file.FileSystemException"); } catch (ClassNotFoundException x) { throw new AssumptionViolatedException("prior to JDK 7", x); } File d = tmp.getRoot(); try { File f = new File(d, "f"); mkfiles(f); lockFileForDeletion(f); try { Util.deleteFile(f); fail("should not have been deletable"); } catch (IOException x) { assertThat(calcExceptionHierarchy(x), hasItem(c)); assertThat(x.getMessage(), containsString(f.getPath())); } } finally { unlockFilesForDeletion(); Util.deleteRecursive(d); } }

Target:
public void testDeleteFile_onWindows() throws Exception { Assume.assumeTrue(Functions.isWindows()); Class<?> c; try { c = Class.forName("java.nio.file.FileSystemException"); } catch (ClassNotFoundException x) { throw new AssumptionViolatedException("prior to JDK 7", x); } try { File f = tmp.newFile(); mkfiles(f); lockFileForDeletion(f); try { Util.deleteFile(f); fail("should not have been deletable"); } catch (IOException x) { assertThat(calcExceptionHierarchy(x), hasItem(c)); assertThat(x.getMessage(), containsString(f.getPath())); } } finally { unlockFilesForDeletion(); } }
Source:
public void callbackOnContext(TraverserContext context, DataSchemaTraverse.Order order) { if (order == DataSchemaTraverse.Order.POST_ORDER) { return; } DataSchema schema = context.getCurrentSchema(); SchemaAnnotationHandler.ValidationMetaData metaData = new SchemaAnnotationHandler.ValidationMetaData(); metaData.setDataSchema(context.getCurrentSchema()); metaData.setPathToSchema(context.getTraversePath()); metaData.setEnclosingField(context.getEnclosingField()); AnnotationValidationResult annotationValidationResult = _useProperties ? _schemaAnnotationHandler.validate(context.getEnclosingField() != null ? context.getEnclosingField().getProperties() : schema.getProperties(), metaData) : _schemaAnnotationHandler.validate(schema.getResolvedProperties(), metaData); if (!annotationValidationResult.isValid()) { getSchemaVisitorTraversalResult().addMessages(context.getSchemaPathSpec(), annotationValidationResult.getMessages()); } }

Target:
public void callbackOnContext(TraverserContext context, DataSchemaTraverse.Order order) { if (order == DataSchemaTraverse.Order.POST_ORDER) { return; } DataSchema schema = context.getCurrentSchema(); SchemaAnnotationHandler.ValidationMetaData metaData = new SchemaAnnotationHandler.ValidationMetaData(); metaData.setDataSchema(context.getCurrentSchema()); metaData.setPathToSchema(context.getTraversePath()); AnnotationValidationResult annotationValidationResult = _schemaAnnotationHandler.validate(schema.getResolvedProperties(), metaData); if (!annotationValidationResult.isValid()) { getSchemaVisitorTraversalResult().addMessages(context.getSchemaPathSpec(), annotationValidationResult.getMessages()); } }
Source:
public String getInputStream() { return isBlank(inputStream) ? name : inputStream; }

Target:
public String getInputStream() { return defaultIfBlank(inputStream, name); }
Source:
public void copyMetaData(final DirCacheEntry src) { int origflags = NB.decodeUInt16(info, infoOffset + P_FLAGS); int newflags = NB.decodeUInt16(src.info, src.infoOffset + P_FLAGS); System.arraycopy(src.info, src.infoOffset, info, infoOffset, INFO_LEN); final int pLen = origflags & NAME_MASK; final int SHIFTED_STAGE_MASK = 0x3 << 12; final int pStageShifted = origflags & SHIFTED_STAGE_MASK; NB.encodeInt16(info, infoOffset + P_FLAGS, pStageShifted | pLen | (newflags & ~NAME_MASK & ~SHIFTED_STAGE_MASK)); }

Target:
public void copyMetaData(final DirCacheEntry src) { copyMetaData(src, false); }
Source:
public float sendNotification(String message, EntityRef notificationMessageEntity, float lastNotification) { if (time.getGameTime() - lastNotification > maxDelay || lastNotification == 0) { localPlayer.getCharacterEntity().getOwner().send(new ChatMessageEvent(message, notificationMessageEntity)); return time.getGameTime(); } return lastNotification; }

Target:
public float sendNotification(String message, EntityRef notificationMessageEntity, float lastNotification) { if (lastNotification == 0 || time.getGameTime() - lastNotification > maxDelay) { localPlayer.getCharacterEntity().getOwner().send(new ChatMessageEvent(message, notificationMessageEntity)); return time.getGameTime(); } return lastNotification; }
Source:
public ValueStack createValueStack(ValueStack stack) { String allowStaticMethodAccess = container.getInstance(String.class, XWorkConstants.ALLOW_STATIC_METHOD_ACCESS); ValueStack result = new OgnlValueStack(stack, xworkConverter, compoundRootAccessor, Boolean.valueOf(allowStaticMethodAccess)); container.inject(result); stack.getContext().put(ActionContext.CONTAINER, container); return result; }

Target:
public ValueStack createValueStack(ValueStack stack) { final boolean allowStaticMethodAccess = isAllowStaticMethodAccess(); ValueStack result = new OgnlValueStack(stack, xworkConverter, compoundRootAccessor, allowStaticMethodAccess); container.inject(result); stack.getContext().put(ActionContext.CONTAINER, container); return result; }
Source:
protected String checkType(String descriptorType) { if (!Objects.equals(descriptorType.toLowerCase(), DescriptorLanguage.CWL_STRING) && !Objects.equals(descriptorType.toLowerCase(), DescriptorLanguage.WDL_STRING) && !Objects.equals(descriptorType.toLowerCase(), DescriptorLanguage.NFL_STRING)) { throw new CustomWebApplicationException(descriptorType + " is not a valid descriptor type", HttpStatus.SC_BAD_REQUEST); } return descriptorType.toLowerCase(); }

Target:
protected DescriptorLanguage checkType(String descriptorType) { for (DescriptorLanguage descriptorLanguage : DescriptorLanguage.values()) { if (Objects.equals(descriptorLanguage.toString().toLowerCase(), descriptorType.toLowerCase())) { return descriptorLanguage; } } throw new CustomWebApplicationException(descriptorType + " is not a valid descriptor type", HttpStatus.SC_BAD_REQUEST); }
Source:
public SELF isBefore(LocalDateTime other) { Objects.instance().assertNotNull(info, actual); assertLocalDateTimeParameterIsNotNull(other); comparables.assertIsBefore(info, actual, other); return myself; }

Target:
public SELF isBefore(LocalDateTime other) { assertLocalDateTimeParameterIsNotNull(other); comparables.assertIsBefore(info, actual, other); return myself; }
Source:
public JSONObject toJSON() { JSONObject json = new JSONObject(); try { json.put("id", pageId); json.put("revision", revisionId); json.put("lastmodified", sdf.format(getLastModified())); json.put("displaytitle", displayTitleText); if (editProtectionStatus == null) { json.put("protection", new JSONArray()); } else { JSONObject protectionStatusObject = new JSONObject(); JSONArray editProtectionStatusArray = new JSONArray(); editProtectionStatusArray.put(editProtectionStatus); protectionStatusObject.put("edit", editProtectionStatusArray); json.put("protection", protectionStatusObject); } json.put("languagecount", languageCount); json.put("editable", canEdit); if (isMainPage) { json.put("mainpage", ""); } if (isDisambiguationPage) { json.put("disambiguation", ""); } if (leadImageUrl != null) { JSONObject thumbObject = new JSONObject(); thumbObject.put("url", leadImageUrl); json.put("thumb", thumbObject); } if (leadImageName != null) { JSONObject imageObject = new JSONObject(); imageObject.put("file", leadImageName); json.put("image", imageObject); } } catch (JSONException e) { throw new RuntimeException(e); } return json; }

Target:
public JSONObject toJSON() { JSONObject json = new JSONObject(); try { json.put("id", pageId); json.put("revision", revisionId); json.put("lastmodified", sdf.format(getLastModified())); json.put("displaytitle", displayTitleText); if (editProtectionStatus == null) { json.put("protection", new JSONArray()); } else { JSONObject protectionStatusObject = new JSONObject(); JSONArray editProtectionStatusArray = new JSONArray(); editProtectionStatusArray.put(editProtectionStatus); protectionStatusObject.put("edit", editProtectionStatusArray); json.put("protection", protectionStatusObject); } json.put("languagecount", languageCount); json.put("editable", canEdit); if (isMainPage) { json.put("mainpage", "true"); } if (isDisambiguationPage) { json.put("disambiguation", "true"); } if (leadImageUrl != null) { JSONObject thumbObject = new JSONObject(); thumbObject.put("url", leadImageUrl); json.put("thumb", thumbObject); } if (leadImageName != null) { JSONObject imageObject = new JSONObject(); imageObject.put("file", leadImageName); json.put("image", imageObject); } } catch (JSONException e) { throw new RuntimeException(e); } return json; }
Source:
public static void refreshRadius(IPapyrusEditPart editpart, int defaultCornerWidth, int defaultCornerHeight) { if (editpart.getPrimaryShape() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure roundedRectangleFigure = (IRoundedRectangleFigure) editpart.getPrimaryShape(); if (((GraphicalEditPart) editpart).getModel() instanceof View) { int width = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_WIDTH, defaultCornerWidth); int height = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_HEIGHT, defaultCornerHeight); if (!((width == 0) != (height == 0))) { roundedRectangleFigure.setCornerDimensions(new Dimension(width, height)); } } } }

Target:
public static void refreshRadius(IPapyrusEditPart editpart, int defaultCornerWidth, int defaultCornerHeight) { if (editpart.getPrimaryShape() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure roundedRectangleFigure = (IRoundedRectangleFigure) editpart.getPrimaryShape(); if (((GraphicalEditPart) editpart).getModel() instanceof View) { int width = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_WIDTH, defaultCornerWidth); int height = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_HEIGHT, defaultCornerHeight); if (!xor(width == 0, height == 0)) { roundedRectangleFigure.setCornerDimensions(new Dimension(width, height)); } } } }
Source:
public void shouldSyncNewConfiguration() { String configName = "newName"; Config config = configService.create(); config.setName(configName); List<Config> configList = new ArrayList<>(); configList.add(config); Configs configs = new Configs(configList); configService.setConfigs(configs); when(configService.verifyConfig(config)).thenReturn(true); configService.syncConfig(configName); verify(eventRelay).sendEventMessage(eq(prepareConfigUpdateEvent(configName, true))); }

Target:
public void shouldSyncNewConfiguration() { String configName = "newName"; Config config = configService.create(); config.setName(configName); Configs mockedConfigs = mock(Configs.class); when(mockedConfigs.getByName(configName)).thenReturn(config); configService.setConfigs(mockedConfigs); when(commCareAPIHttpClient.verifyConnection(any())).thenReturn(true); configService.syncConfig(configName); verify(mockedConfigs).getByName(configName); verify(commCareAPIHttpClient).verifyConnection(any()); verify(eventRelay).sendEventMessage(eq(prepareConfigUpdateEvent(configName, true))); }
Source:
private static void registerValidityBoundMetric(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService) { metricsManager.registerMetric( MetadataCoordinationServiceMetrics.class, LAST_VALID_BOUND, TrackerUtils.createCachingMonotonicIncreasingGauge( log, Clock.defaultClock(), LAST_VALID_BOUND, () -> metadataCoordinationService.getLastKnownLocalValue() .map(ValueAndBound::bound) .orElse(Long.MIN_VALUE))); }

Target:
private static void registerValidityBoundMetric(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService) { metricsManager.registerMetric( MetadataCoordinationServiceMetrics.class, AtlasDbMetricNames.COORDINATION_LAST_VALID_BOUND, TrackerUtils.createCachingExceptionHandlingGauge( log, Clock.defaultClock(), AtlasDbMetricNames.COORDINATION_LAST_VALID_BOUND, () -> metadataCoordinationService.getLastKnownLocalValue() .map(ValueAndBound::bound) .orElse(Long.MIN_VALUE))); }
Source:
public JSONObject createPayload() { JSONObject payload = super.createPayload(); String buildNumber = buildData.getBuildNumber("unknown"); String userId = buildData.getUserId(); String jobName = buildData.getJobName("unknown"); String buildUrl = buildData.getBuildUrl("unknown"); String hostname = buildData.getHostname("unknown"); String title = jobName + " build #" + buildNumber + " started on " + hostname; payload.put("title", title); String message = "%%% \n User " + userId + " started the [job " + jobName + " with build number #" + buildNumber + "](" + buildUrl + ") " + getFormattedDuration() + " \n %%%"; payload.put("text", message); payload.put("priority", "low"); payload.put("alert_type", "info"); return payload; }

Target:
public JSONObject createPayload() { JSONObject payload = super.createPayload(); String buildNumber = buildData.getBuildNumber("unknown"); String userId = buildData.getUserId(); String jobName = buildData.getJobName("unknown"); String buildUrl = buildData.getBuildUrl("unknown"); String hostname = buildData.getHostname("unknown"); String title = jobName + " build #" + buildNumber + " started on " + hostname; payload.put("title", title); String message = "%%% \nUser " + userId + " started the [job " + jobName + " build #" + buildNumber + "](" + buildUrl + ") " + getFormattedDuration() + " \n%%%"; payload.put("text", message); payload.put("priority", "low"); payload.put("alert_type", "info"); return payload; }
Source:
private static Repo repo() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final String keyrepo = System.getProperty("failsafe.github.repo"); Assume.assumeThat(keyrepo, Matchers.notNullValue()); return new RtGithub(key).repos().get(new Coordinates.Simple(keyrepo)); }

Target:
private static Repo repo() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final String repo = System.getProperty("failsafe.github.repo"); Assume.assumeThat(repo, Matchers.notNullValue()); return new RtGithub(key).repos().get(new Coordinates.Simple(repo)); }
Source:
public Map<Integer, Node> getFixedMapping() { if (!bucketToNode.isPresent()) { throw new IllegalArgumentException("No fixed bucket to node mapping"); } return new HashMap<>(bucketToNode.get()); }

Target:
public Map<Integer, Node> getFixedMapping() { return bucketToNode.orElseThrow(() -> new IllegalArgumentException("No fixed bucket to node mapping")); }
Source:
public void setTimeout(int timeout) { this.timeout = timeout >= 2 ? timeout : DEFAULT_TIMEOUT_MINUTES; }

Target:
public void setTimeout(int timeout) { if (timeout >= MINIMUM_TIMEOUT_MINUTES) { this.timeout = timeout; } else { LOGGER.warn( "Received a timeout of minutes, which is less than the minimum timeout allowed of {}. Defaulting to {}.", timeout, MINIMUM_TIMEOUT_MINUTES, DEFAULT_TIMEOUT_MINUTES); this.timeout = DEFAULT_TIMEOUT_MINUTES; } }
Source:
protected Path determineMountPoint() throws InvalidMountPointException { for (MountPointChooser chooser : this.choosers) { Optional<Path> chosenPath = chooser.chooseMountPoint(); if (chosenPath.isEmpty()) { continue; } this.cleanupRequired = chooser.prepare(chosenPath.get()); this.usedChooser = chooser; return chosenPath.get(); } String tried = Joiner.on(", ").join(this.choosers.stream().map((mpc) -> mpc.getClass().getTypeName()).collect(ImmutableSet.toImmutableSet())); throw new InvalidMountPointException(String.format("No feasible MountPoint found! Tried %s", tried)); }

Target:
protected Path determineMountPoint() throws InvalidMountPointException { SortedSet<MountPointChooser> checkedChoosers = new TreeSet<>(); for (MountPointChooser chooser : this.choosers) { if(!chooser.isApplicable(this)) { continue; } Optional<Path> chosenPath = chooser.chooseMountPoint(this); checkedChoosers.add(chooser); if (chosenPath.isEmpty()) { continue; } this.cleanupRequired = chooser.prepare(this, chosenPath.get()); this.usedChooser = chooser; return chosenPath.get(); } String checked = Joiner.on(", ").join(checkedChoosers.stream().map((mpc) -> mpc.getClass().getTypeName()).collect(ImmutableSet.toImmutableSet())); throw new InvalidMountPointException(String.format("No feasible MountPoint found! Checked %s", checked.isBlank() ? "<No applicable MPC>" : checked)); }
Source:
public void updateRecurringBilling(String merchantId, Boolean enable) { http.put(String.format("/merchants/%s/settings/orderSettings/recurringBilling/%b", merchantId, enable), null); }

Target:
public void updateRecurringBilling(String merchantId, Boolean enable) { http.put(String.format(MERCHANT_SETTINGS_RECURRING_BILLING, merchantId, enable), null); }
Source:
protected void addLink(LinksTreeNode linksTree, String link) { String[] linkSegments = link.split("\\."); for (String segment : linkSegments) { linksTree = updateTree(linksTree, segment); } }

Target:
private void addLink(LinksTreeNode linksTree, String link) { String[] linkSegments = link.split("\\."); for (String segment : linkSegments) { linksTree = updateTree(linksTree, segment); } }
Source:
public <V> ListenableFuture<V> createError(Request request, ErrorType errorType, Throwable throwable) { TFuture<V> future = TFuture.create(); ArgScheme argScheme = request.getArgScheme(); Response response = Response.build(argScheme, new ErrorResponse( request.getId(), errorType, throwable)); switch (argScheme) { case RAW: ((TFuture<RawResponse>)future).set((RawResponse) response); break; case JSON: ((TFuture<JsonResponse>)future).set((JsonResponse) response); break; case THRIFT: ((TFuture<ThriftResponse>)future).set((ThriftResponse) response); break; default: ((TFuture<RawResponse>)future).set((RawResponse) response); break; } return future; }

Target:
public <V> ListenableFuture<V> createError(Request request, ErrorType errorType, Throwable throwable) { TFuture<V> future = TFuture.create(); ArgScheme argScheme = request.getArgScheme(); Response response = Response.build(argScheme, new ErrorResponse( request.getId(), errorType, throwable)); ResponseRouter.setResponse(future, argScheme, response); return future; }
Source:
private void addParameter(org.sonar.plugins.python.api.tree.Parameter parameter, @Nullable String fileId, ParameterState parameterState) { Name parameterName = parameter.name(); Token starToken = parameter.starToken(); if (parameterName != null) { TypeAnnotation typeAnnotation = parameter.typeAnnotation(); InferredType declaredType = InferredTypes.anyType(); if (typeAnnotation != null) { declaredType = InferredTypes.declaredType(typeAnnotation); } boolean isVariadic = false; if (starToken != null) { hasVariadicParameter = true; isVariadic = true; } this.parameters.add(new ParameterImpl(parameterName.name(), declaredType, parameter.defaultValue() != null, isVariadic, parameterState, locationInFile(parameter, fileId))); } else if (starToken != null) { if ("*".equals(starToken.value())) { parameterState.keywordOnly = true; parameterState.positionalOnly = false; } if ("/".equals(starToken.value())) { parameterState.positionalOnly = false; } } }

Target:
private void addParameter(org.sonar.plugins.python.api.tree.Parameter parameter, @Nullable String fileId, ParameterState parameterState) { Name parameterName = parameter.name(); Token starToken = parameter.starToken(); if (parameterName != null) { TypeAnnotation typeAnnotation = parameter.typeAnnotation(); InferredType declaredType = InferredTypes.anyType(); if (typeAnnotation != null) { declaredType = InferredTypes.declaredType(typeAnnotation); } this.parameters.add(new ParameterImpl(parameterName.name(), declaredType, parameter.defaultValue() != null, starToken != null, parameterState, locationInFile(parameter, fileId))); if (starToken != null) { hasVariadicParameter = true; parameterState.keywordOnly = true; parameterState.positionalOnly = false; } } else if (starToken != null) { if ("*".equals(starToken.value())) { parameterState.keywordOnly = true; parameterState.positionalOnly = false; } if ("/".equals(starToken.value())) { parameterState.positionalOnly = false; } } }
Source:
public Blog getBlog(String blogUuid) throws BlogServiceException { if(StringUtil.isEmpty(blogUuid)){ throw new BlogServiceException(null, "null blogUuid"); } String getBlogUrl = resolveUrl(BLOG_HANDLE, FilterType.UPDATE_REMOVE_BLOG, blogUuid); Blog blog; try { blog = (Blog)getEntity(getBlogUrl, null, new BlogsFeedHandler(this)); } catch (Exception e) { throw new BlogServiceException(e, "error getting blog"); } return blog; }

Target:
public Blog getBlog(String blogUuid) throws BlogServiceException { if(StringUtil.isEmpty(blogUuid)){ throw new BlogServiceException(null, "null blogUuid"); } String getBlogUrl = resolveUrl(BLOG_HANDLE, FilterType.GET_UPDATE_REMOVE_BLOG, blogUuid); Blog blog; try { blog = (Blog)getEntity(getBlogUrl, null, new BlogsFeedHandler(this)); } catch (Exception e) { throw new BlogServiceException(e, "error getting blog"); } return blog; }
Source:
public Set<String> getInputs() { return new HashSet<String>(); }

Target:
public Set<String> getInputs() { return Collections.EMPTY_SET; }
Source:
void onErrorResponse(ReplicaId replicaId, RouterException exception) { logger.info("DC: " + replicaId.getDataNodeId().getDatacenterName() + " exception: " + exception); operationTracker.onResponse(replicaId, TrackedRequestFinalState.fromRouterErrorCodeToFinalState(exception.getErrorCode())); setOperationException(exception); routerMetrics.routerRequestErrorCount.inc(); routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).getBlobInfoRequestErrorCount.inc(); }

Target:
private void onErrorResponse(ReplicaId replicaId, RouterException exception) { operationTracker.onResponse(replicaId, TrackedRequestFinalState.fromRouterErrorCodeToFinalState(exception.getErrorCode())); setOperationException(exception); routerMetrics.routerRequestErrorCount.inc(); routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).getBlobInfoRequestErrorCount.inc(); }
Source:
public SingularityCreateResult addToPendingQueue(SingularityPendingRequest pendingRequest) { SingularityCreateResult result = create(getPendingPath(pendingRequest), pendingRequest, pendingRequestTranscoder); if (result == SingularityCreateResult.EXISTED) { SingularityPendingRequest existingPendingRequest = getPendingRequest(pendingRequest.getRequestId(), pendingRequest.getDeployId()).get(); if (existingPendingRequest.getPendingType() == PendingType.STARTUP) { set(getPendingPath(pendingRequest), pendingRequest, pendingRequestTranscoder); LOG.info("{} added to pending queue, overwriting an existing SingularityPendingRequest of type STARTUP. Previous pending request was {}", existingPendingRequest, result); return result; } } LOG.info("{} added to pending queue with result: {}", pendingRequest, result); return result; }

Target:
public SingularityCreateResult addToPendingQueue(SingularityPendingRequest pendingRequest) { SingularityCreateResult result = create(getPendingPath(pendingRequest), pendingRequest, pendingRequestTranscoder); if (result == SingularityCreateResult.EXISTED) { Optional<SingularityPendingRequest> existingPendingRequest = getPendingRequest(pendingRequest.getRequestId(), pendingRequest.getDeployId()); if (!existingPendingRequest.isPresent() || (existingPendingRequest.get().getPendingType() == PendingType.STARTUP)) { set(getPendingPath(pendingRequest), pendingRequest, pendingRequestTranscoder); LOG.info("{} added to pending queue, overwriting an existing SingularityPendingRequest of type STARTUP. Previous pending request was {}", existingPendingRequest, result); return result; } } LOG.info("{} added to pending queue with result: {}", pendingRequest, result); return result; }
Source:
private AdminSearchPageData putStudentDetailsPageLinkIntoMap(List<StudentAttributes> students, AdminSearchPageData data){ for(StudentAttributes student : students){ if(student.course == null ||student.email == null){ continue; } String curLink = Url.addParamToUrl(Const.ActionURIs.INSTRUCTOR_COURSE_STUDENT_DETAILS_PAGE, Const.ParamsNames.COURSE_ID, student.course); curLink = Url.addParamToUrl(curLink, Const.ParamsNames.STUDENT_EMAIL, student.email); InstructorAttributes instructor = logic.getInstructorsForCourse(student.course).get(0); if(instructor.googleId == null){ continue; } curLink = Url.addParamToUrl(curLink, Const.ParamsNames.USER_ID, instructor.googleId); data.studentDetailsPageLinkMap.put(student.getIdentificationString(), curLink); } return data; }

Target:
private AdminSearchPageData putStudentDetailsPageLinkIntoMap(List<StudentAttributes> students, AdminSearchPageData data){ for(StudentAttributes student : students){ if(student.course == null ||student.email == null){ continue; } String curLink = Url.addParamToUrl(Const.ActionURIs.INSTRUCTOR_COURSE_STUDENT_DETAILS_PAGE, Const.ParamsNames.COURSE_ID, student.course); curLink = Url.addParamToUrl(curLink, Const.ParamsNames.STUDENT_EMAIL, student.email); String availableGoogleId = findAvailableInstructorGoogleIdForCourse(student.course); if (!availableGoogleId.isEmpty()) { curLink = Url.addParamToUrl(curLink, Const.ParamsNames.USER_ID, availableGoogleId); data.studentDetailsPageLinkMap.put(student.getIdentificationString(), curLink); } } return data; }
Source:
public static boolean isNotContains(String str, char ch) { return isEmpty(str) || str.indexOf(ch) < 0; }

Target:
public static boolean isNotContains(String str, char ch) { return !isContains(str, ch); }
Source:
public void cancel() { this.canceled = true; }

Target:
public void cancel() { this.cancelled = true; }
Source:
private void addRecord(final String message) { if (currentStep >= this.stepStarts.length) { this.stepStarts = Arrays.copyOf(this.stepStarts, this.stepStarts.length + 10); this.stepNames = Arrays.copyOf(this.stepNames, this.stepStarts.length); } this.stepStarts[currentStep] = System.currentTimeMillis(); this.stepNames[currentStep] = message; currentStep++; }

Target:
private void addRecord(final String message) { this.stepStarts.add(System.currentTimeMillis()); this.stepNames.add(message); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_clear_all_saved_pages: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_title_clear_saved_pages); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { app.getPersister(SavedPage.class).deleteAll(); (new SaneAsyncTask<Void>(SaneAsyncTask.SINGLE_THREAD) { @Override public Void performTask() throws Throwable { Utils.delete(new File(SavedPage.getSavedPagesDir()), true); return null; } }).execute(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; default: throw new RuntimeException("Unknown menu item clicked!"); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_clear_all_saved_pages: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_title_clear_saved_pages); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { (new SaneAsyncTask<Void>(SaneAsyncTask.SINGLE_THREAD) { @Override public Void performTask() throws Throwable { app.getPersister(SavedPage.class).deleteAll(); Utils.delete(new File(SavedPage.getSavedPagesDir()), true); return null; } }).execute(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; default: throw new RuntimeException("Unknown menu item clicked!"); } }
Source:
public Comment updateComment(@PathParam("commentId") String commentId, Comment comment) { if (!getContext().getCoreSession().exists(new IdRef(commentId))) { throw new DocumentNotFoundException("The comment " + commentId + " does not exist."); } CommentManager commentManager = Framework.getService(CommentManager.class); commentManager.updateComment(getContext().getCoreSession(), commentId, comment); return comment; }

Target:
public Response updateComment(@PathParam("commentId") String commentId, Comment comment) { CommentManager commentManager = Framework.getService(CommentManager.class); Comment updatedComment = commentManager.updateComment(getContext().getCoreSession(), commentId, comment); return Response.ok(updatedComment).build(); }
Source:
private void assertMessageValues(Document msgDoc, PID expectedPid) { Element entry = msgDoc.getRootElement(); String pidString = entry.getChildText("pid", ATOM_NS);; String author = entry.getChild("author", ATOM_NS) .getChildText("name", ATOM_NS); assertEquals(collection.getPid().getURI(), pidString); assertEquals(USER_NAME, author); }

Target:
private void assertMessageValues(Document msgDoc, PID expectedPid) { Element entry = msgDoc.getRootElement(); String pidString = entry.getChild(RUN_ENHANCEMENTS.getName(), CDR_MESSAGE_NS) .getChildText("pid", CDR_MESSAGE_NS); String author = entry.getChild("author", ATOM_NS) .getChildText("name", ATOM_NS); assertEquals(collection.getPid().getURI(), pidString); assertEquals(USER_NAME, author); }
Source:
public ValidationResult diskImagesHaveNoDerivedDisks(Guid storageDomainId) { List<String> disksInfo = null; for (DiskImage diskImage : diskImages) { if (diskImage.getVmEntityType() != null && diskImage.getVmEntityType().isTemplateType()) { List<DiskImage> basedDisks = getDiskImageDAO().getAllSnapshotsForParent(diskImage.getImageId()); for (DiskImage basedDisk : basedDisks) { if (storageDomainId == null || basedDisk.getStorageIds().contains(storageDomainId)) { if (disksInfo == null) { disksInfo = new LinkedList<>(); } disksInfo.add(String.format("%s (%s) ", basedDisk.getDiskAlias(), basedDisk.getId())); } } } } if (disksInfo != null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DETECTED_DERIVED_DISKS, String.format("$disksInfo %s", String.format(StringUtils.join(disksInfo, "%n")))); } return ValidationResult.VALID; }

Target:
public ValidationResult diskImagesHaveNoDerivedDisks(Guid storageDomainId) { List<String> disksInfo = new LinkedList<>(); for (DiskImage diskImage : diskImages) { if (diskImage.getVmEntityType() != null && diskImage.getVmEntityType().isTemplateType()) { List<DiskImage> basedDisks = getDiskImageDAO().getAllSnapshotsForParent(diskImage.getImageId()); for (DiskImage basedDisk : basedDisks) { if (storageDomainId == null || basedDisk.getStorageIds().contains(storageDomainId)) { disksInfo.add(String.format("%s (%s) ", basedDisk.getDiskAlias(), basedDisk.getId())); } } } } if (!disksInfo.isEmpty()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DETECTED_DERIVED_DISKS, String.format("$disksInfo %s", String.format(StringUtils.join(disksInfo, "%n")))); } return ValidationResult.VALID; }