auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean accept(File file) { boolean accept = false; if (!file.isDirectory() && file.canRead()) { String fileName = file.getName(); <START> if (isDescriptorFile(fileName) || isXmlTypeDescriptorFile(fileName)) { <END> accept = true; } } return accept; }</code><technical_language>I thought a separate monitor for this CM integration descriptor, handling of contained in cm-integration module</technical_language>

Target:
public boolean accept(File file) { boolean accept = false; if (!file.isDirectory() && file.canRead()) { String extension = FilenameUtils.getExtension(file.getName()); if (SUPPORTED_EXTENSIONS.contains(extension)) { accept = true; } } return accept; }
Source:
<code>protected boolean validateInputs() { if (!super.validateInputs()) { return false; } VdcQueryReturnValue returnValue = getQueryReturnValue(); returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); return false; } List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); return false; } if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); return false; } Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); return false; } } } catch (RuntimeException ex) { <START> log.error("RegisterVdsQuery::CanDoAction: An exception has been thrown.", ex); <END> returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); return false; } return true; }</code><technical_language>RegisterVdsQuery::CanDoAction is redundant, I simply remove them</technical_language>

Target:
protected boolean validateInputs() { if (!super.validateInputs()) { return false; } VdcQueryReturnValue returnValue = getQueryReturnValue(); returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); return false; } List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); return false; } if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); return false; } Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); return false; } } } catch (RuntimeException ex) { log.error(ex); returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); return false; } return true; }
Source:
<code>private Set<Guid> getDisksNotInPreviousCheckpoint() { List<DiskImage> checkpointDisks = vmCheckpointDao.getDisksByCheckpointId(getParameters().getVmBackup().getFromCheckpointId()); Set<Guid> vmCheckpointDisksIds = checkpointDisks .stream() .map(DiskImage::getId) <START> .collect(Collectors.toCollection(LinkedHashSet::new)); <END> return getDiskIds().stream() .distinct() .filter(diskId -> !vmCheckpointDisksIds.contains(diskId)) .collect(Collectors.toSet()); }</code><technical_language>IMHO "HashSet". I iteration features of "LinkedHashSet"</technical_language>

Target:
public Set<Guid> getDisksNotInPreviousCheckpoint() { List<DiskImage> checkpointDisks = vmCheckpointDao.getDisksByCheckpointId(getParameters().getVmBackup().getFromCheckpointId()); Set<Guid> vmCheckpointDisksIds = checkpointDisks .stream() .map(DiskImage::getId) .collect(Collectors.toCollection(HashSet::new)); return getDiskIds().stream() .distinct() .filter(diskId -> !vmCheckpointDisksIds.contains(diskId)) .collect(Collectors.toSet()); }
Source:
<code>protected List<SegmentTimelineElement> parseSegmentTimeline(XmlPullParser xpp,long timescale, long periodDurationMs) throws XmlPullParserException, IOException { List<SegmentTimelineElement> segmentTimeline = new ArrayList<>(); long elapsedTime = 0; do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "S")) { elapsedTime = parseLong(xpp, "t", elapsedTime); long duration = parseLong(xpp, "d", C.TIME_UNSET); int repeat = parseInt(xpp,"r",0); <START> int count = repeat != -1? 1 + repeat : (int) (((periodDurationMs / 1000) * timescale) / duration); <END> for (int i = 0; i < count; i++) { segmentTimeline.add(buildSegmentTimelineElement(elapsedTime, duration)); elapsedTime += duration; } } else { maybeSkipTag(xpp); } } while (!XmlPullParserUtil.isEndTag(xpp, "SegmentTimeline")); return segmentTimeline; }</code><technical_language>is mention in DASH IOP this needs -1 specifically. "if @r is greater equal zero" for case "else" for other (=this) case. check for < 0 instead</technical_language>

Target:
protected List<SegmentTimelineElement> parseSegmentTimeline(XmlPullParser xpp,long timescale, long periodDurationMs) throws XmlPullParserException, IOException { List<SegmentTimelineElement> segmentTimeline = new ArrayList<>(); long elapsedTime = 0; do { xpp.next(); if (XmlPullParserUtil.isStartTag(xpp, "S")) { elapsedTime = parseLong(xpp, "t", elapsedTime); long duration = parseLong(xpp, "d", C.TIME_UNSET); int repeat = parseInt(xpp,"r",0); int count = repeat >= 0? 1 + repeat : (int) (((periodDurationMs / 1000) * timescale) / duration); for (int i = 0; i < count; i++) { segmentTimeline.add(buildSegmentTimelineElement(elapsedTime, duration)); elapsedTime += duration; } } else { maybeSkipTag(xpp); } } while (!XmlPullParserUtil.isEndTag(xpp, "SegmentTimeline")); return segmentTimeline; }
Source:
<code>static void checkModule(ModuleResolver resolver, GenContext ctx, ModuleDeclaration moduleDecl, List<TypedModuleSpec> dependencies) { TypedAST typedAST = moduleDecl.getInner(); if (moduleDecl.isAnnotated()) { List<ImportDeclaration> imports = moduleDecl.getImports(); Set<Module> liftedModules = new HashSet<>(); for (ImportDeclaration decl : imports) { if (decl.isLifted()) { String moduleName = decl.getUri().getSchemeSpecificPart(); Module m = resolver.resolveModule(moduleName, false, true); liftedModules.add(m); } } for (TypedModuleSpec spec : dependencies) { <START> if (spec.getIsAnnotated() != null && !spec.getIsAnnotated()) { <END> if (!liftedModules.contains(spec.getModule())) { ToolError.reportError(ErrorMessage.EFFECT_ANNOTATION_SEPARATION, FileLocation.UNKNOWN); } } } typedAST.acceptVisitor(new AnnotatedEffectVisitor(), ctx); } }</code><technical_language>null case getIsAnnotated() returns a boolean</technical_language>

Target:
static void checkModule(ModuleResolver resolver, GenContext ctx, ModuleDeclaration moduleDecl, List<TypedModuleSpec> dependencies) { TypedAST typedAST = moduleDecl.getInner(); if (moduleDecl.isAnnotated()) { List<ImportDeclaration> imports = moduleDecl.getImports(); Set<Module> liftedModules = new HashSet<>(); for (ImportDeclaration decl : imports) { if (decl.isLifted()) { String moduleName = decl.getUri().getSchemeSpecificPart(); Module m = resolver.resolveModule(moduleName, false, true); liftedModules.add(m); } } for (TypedModuleSpec spec : dependencies) { if (!spec.getIsAnnotated()) { if (!liftedModules.contains(spec.getModule())) { ToolError.reportError(ErrorMessage.EFFECT_ANNOTATION_SEPARATION, FileLocation.UNKNOWN); } } } typedAST.acceptVisitor(new AnnotatedEffectVisitor(), ctx); } }
Source:
<code>public void testIterator() { final DependentInstanceTestBean testBean = getBeanManager().lookupBean(DependentInstanceTestBean.class).getInstance(); final Instance<DependentBeanA> injectedBean = testBean.getInjectDependentBeanA(); <START> assertTrue(injectedBean.iterator().hasNext()); <END> }</code><technical_language>Glad test coverage, this test is missing some assertions more robust. In particular, call Iterator#next() verify returned is a DependentBeanA. This sufficient reproduce issue I above</technical_language>

Target:
public void testIterator() { final DependentInstanceTestBean testBean = getBeanManager().lookupBean(DependentInstanceTestBean.class).getInstance(); final Instance<DependentBeanA> injectedBean = testBean.getInjectDependentBeanA(); assertTrue(injectedBean.iterator().hasNext()); assertEquals(DependentBeanA.class, injectedBean.iterator().next().getClass()); }
Source:
<code><START> public void mbusDeviceIsNotCoupledWithDevice(String mbusDeviceId, String deviceId) throws Throwable { <END> this.coupleDeviceHooks.deCoupleDevices(deviceId, mbusDeviceId); }</code><technical_language>remove "throws Throwable"</technical_language>

Target:
public void mbusDeviceIsNotCoupledWithDevice(String mbusDeviceId, String deviceId) { this.coupleDeviceHooks.decoupleDevices(deviceId, mbusDeviceId); }
Source:
<code>public final void unsafeSubscribe(CompletableSubscriber s) { requireNonNull(s); try { onSubscribe.call(s); } catch (NullPointerException ex) { throw ex; } catch (Throwable ex) { Exceptions.throwIfFatal(ex); <START> ERROR_HANDLER.handleError(ex); <END> throw toNpe(ex); } }</code><technical_language>unsafeSubscribe call ERROR_HANDLER</technical_language>

Target:
public final void unsafeSubscribe(CompletableSubscriber s) { requireNonNull(s); try { CompletableOnSubscribe onSubscribeDecorated = HOOK.onSubscribeStart(this, this.onSubscribe); onSubscribeDecorated.call(s); } catch (NullPointerException ex) { throw ex; } catch (Throwable ex) { Exceptions.throwIfFatal(ex); ex = HOOK.onSubscribeError(ex); ERROR_HANDLER.handleError(ex); throw toNpe(ex); } }
Source:
<code>public PlanWithProperties visitTableWriter(TableWriterNode node, PreferredProperties preferredProperties) { PlanWithProperties source = node.getSource().accept(this, preferredProperties); Optional<PartitioningScheme> partitioningScheme = node.getPartitioningScheme(); if (!partitioningScheme.isPresent()) { if (scaleWriters) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(SCALED_WRITER_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputSymbols())); } else if (redistributeWrites) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputSymbols())); } } if (partitioningScheme.isPresent() && !source.getProperties().isCompatibleTablePartitioningWith(partitioningScheme.get().getPartitioning(), false, metadata, session) && !(partialMergePushdownStrategy == PUSHDOWN_BUT_NOT_THROUGH_JOIN_AND_AGGREGATION && source.getProperties().isRefinedPartitioningOver(partitioningScheme.get().getPartitioning(), false, metadata, session) && canPushdownPartialMerge(source.getNode()))) { <START> source = withDerivedProperties( <END> partitionedExchange( idAllocator.getNextId(), REMOTE_STREAMING, source.getNode(), partitioningScheme.get()), source.getProperties()); } return rebaseAndDeriveProperties(node, source); }</code><technical_language>I understand correctly optimizing simple projections/filters of a bucketed table other bucketed table? save memory, potentially saves CPU cycles shuffle</technical_language>

Target:
public PlanWithProperties visitTableWriter(TableWriterNode node, PreferredProperties preferredProperties) { PlanWithProperties source = node.getSource().accept(this, preferredProperties); Optional<PartitioningScheme> partitioningScheme = node.getPartitioningScheme(); if (!partitioningScheme.isPresent()) { if (scaleWriters) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(SCALED_WRITER_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputSymbols())); } else if (redistributeWrites) { partitioningScheme = Optional.of(new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), source.getNode().getOutputSymbols())); } } if (partitioningScheme.isPresent() && !source.getProperties().isCompatibleTablePartitioningWith(partitioningScheme.get().getPartitioning(), false, metadata, session) && !(source.getProperties().isRefinedPartitioningOver(partitioningScheme.get().getPartitioning(), false, metadata, session) && canPushdownPartialMerge(source.getNode(), partialMergePushdownStrategy))) { source = withDerivedProperties( partitionedExchange( idAllocator.getNextId(), REMOTE_STREAMING, source.getNode(), partitioningScheme.get()), source.getProperties()); } return rebaseAndDeriveProperties(node, source); }
Source:
<code><START> public org.robolectric.res.builder.XmlBlock getXml(ResName resName, String qualifiers) { <END> return pickFor(resName).getXml(resName, qualifiers); }</code><technical_language>need fuilly qualified</technical_language>

Target:
public XmlBlock getXml(ResName resName, String qualifiers) { return pickFor(resName).getXml(resName, qualifiers); }
Source:
<code>private void transferAllJobBlobs() throws IOException { final Predicate transferPredicate = () -> ! canceled; final AtomicInteger numBlobsRemaining = new AtomicInteger(jobState.numBlobsInJob()); <START> while ( ! Thread.currentThread().isInterrupted() && transferPredicate.test() && numBlobsRemaining.get() > 0) { <END> try { final Iterable<JobPart> jobParts = jobPartsNotAlreadyTransferred(transferPredicate); final int numJobParts = Iterables.size(jobParts); if (numJobParts <= 0) { break; } final CountDownLatch countDownLatch = new CountDownLatch(1); transferJobParts(jobParts, countDownLatch, numBlobsRemaining, transferPredicate); countDownLatch.await(); } catch (final Ds3NoMoreRetriesException | FailedRequestException e) { emitFailureEvent(makeFailureEvent(failureActivity, e, firstChunk())); throw e; } catch (final InterruptedException | NoSuchElementException e) { Thread.currentThread().interrupt(); } catch (final Throwable t) { emitFailureAndSetCachedException(t); } } }</code><technical_language>a lambda evaluates ! canceled defined line 130</technical_language>

Target:
private void transferAllJobBlobs() throws IOException { final BooleanSupplier cancellationCheck = () -> !canceled; final AtomicInteger numBlobsRemaining = new AtomicInteger(jobState.numBlobsInJob()); while (!Thread.currentThread().isInterrupted() && cancellationCheck.getAsBoolean() && numBlobsRemaining.get() > 0) { try { final Iterable<JobPart> jobParts = jobPartsNotAlreadyTransferred(cancellationCheck); final int numJobParts = Iterables.size(jobParts); if (numJobParts <= 0) { break; } final CountDownLatch jobPartsCompleteLatch = new CountDownLatch(numJobParts); transferJobParts(jobParts, jobPartsCompleteLatch, numBlobsRemaining, cancellationCheck); jobPartsCompleteLatch.await(); } catch (final Ds3NoMoreRetriesException | FailedRequestException e) { emitFailureEvent(makeFailureEvent(failureActivity, e, firstChunk())); throw e; } catch (final InterruptedException | NoSuchElementException e) { LOG.warn("Thread was interrupted"); Thread.currentThread().interrupt(); } catch (final Throwable t) { emitFailureAndSetCachedException(t); } } }
Source:
<code>private IkeSaPayload makeSaRequestPayload() throws Exception { byte[] inputPacket = TestUtils.hexStringToByteArray(TWO_PROPOSAL_RAW_PACKET); Proposal.sTransformDecoder = new TransformDecoder() { private int mProposalCnt = 0; @Override public Transform[] decodeTransforms(int count, ByteBuffer inputBuffer) throws IkeException { mProposalCnt++; for (int i = 0; i < count; i++) { inputBuffer.getShort(); int length = Short.toUnsignedInt(inputBuffer.getShort()); byte[] temp = new byte[length - 4]; inputBuffer.get(temp); } if <START> (mProposalCnt == <END> 1) { return new Transform[] { mEncrAesCbc128Transform, mIntegHmacSha1Transform, mPrfHmacSha1Transform, mDhGroup1024Transform, mDhGroup2048Transform }; } else { return new Transform[] { mEncrAesGcm8Key128Transform, mEncrAesGcm12Key128Transform, mPrfHmacSha1Transform, mDhGroup1024Transform, mDhGroup2048Transform }; } } }; IkeSaPayload reqPayload = new IkeSaPayload(false, false, inputPacket); return reqPayload; }</code><technical_language>this changes result of decodeTransforms based times method is called, I why..</technical_language>

Target:
private IkeSaPayload makeSaRequestPayload() throws Exception { return new IkeSaPayload(new SaProposal[] {mSaProposalOne, mSaProposalTwo}); }
Source:
<code>public SystemAdmin getSystemAdmin(String systemName, String adminLabel) { <START> return getSystemAdmins(adminLabel).get(systemName); <END> }</code><technical_language>I understand this is existing code, weird create admins time get a single one. create a single Admin, cache results of previous getAdmins()</technical_language>

Target:
public SystemAdmin getSystemAdmin(String systemName, String adminLabel) { if (systemAdminMap.isEmpty() || (systemAdminMap.containsKey(systemName) && systemAdminMap.get(systemName).isStopped())) { systemAdminMap.clear(); } return getSystemAdmins(adminLabel).get(systemName); }
Source:
<code>public ItemStack build() throws IllegalStateException { checkState(this.type != null, "Item type has not been set"); int max = this.type.getMaxStackQuantity(); <START> if (type == ItemTypes.AIR || quantity <= 0) { <END> return ((ItemStack) net.minecraft.item.ItemStack.EMPTY); } final ItemStack stack = (ItemStack) new net.minecraft.item.ItemStack((Item) this.type, this.quantity, this.damageValue); if (this.compound != null) { ((net.minecraft.item.ItemStack) stack).setTagCompound(this.compound.copy()); } if (this.itemDataSet != null) { this.itemDataSet.forEach(stack::offer); } if (this.keyValues != null) { this.keyValues.entrySet().forEach(entry -> stack.offer((Key) entry.getKey(), entry.getValue())); } return stack; }</code><technical_language>Do forget ItemTypes.NONE</technical_language>

Target:
public ItemStack build() throws IllegalStateException { checkState(this.type != null, "Item type has not been set"); if (type == ItemTypes.NONE || quantity <= 0) { return ((ItemStack) net.minecraft.item.ItemStack.EMPTY); } final ItemStack stack = (ItemStack) new net.minecraft.item.ItemStack((Item) this.type, this.quantity, this.damageValue); if (this.compound != null) { ((net.minecraft.item.ItemStack) stack).setTagCompound(this.compound.copy()); } if (this.itemDataSet != null) { this.itemDataSet.forEach(stack::offer); } if (this.keyValues != null) { this.keyValues.entrySet().forEach(entry -> stack.offer((Key) entry.getKey(), entry.getValue())); } return stack; }
Source:
<code>public VertxOptions setWarningExceptionTime(long warningExceptionTime) { <START> this.warningExceptionTime = warningExceptionTime; <END> return this; }</code><technical_language>Need check argument is < 1 in other getters</technical_language>

Target:
public VertxOptions setWarningExceptionTime(long warningExceptionTime) { if (warningExceptionTime < 1) { throw new IllegalArgumentException("warningExceptionTime must be > 0"); } this.warningExceptionTime = warningExceptionTime; return this; }
Source:
<code>private void checkExecStringArrayArgument(NewArrayTree newArrayTree) { List<ExpressionTree> initializers = newArrayTree.initializers(); if (initializers.size() < 3) { return; } if (!chmodCommand(initializers.get(0)).isPresent()) { return; } ExpressionTree modeArg = initializers.get(1); <START> if (initializers.size() > 3 && isRecursiveArgument(modeArg)) { <END> modeArg = initializers.get(2); } if (modeArg.asConstant(String.class).filter(FilePermissionsCheck::isSensisitiveChmodMode).isPresent()) { reportIssue(modeArg, ISSUE_MESSAGE); } }</code><technical_language>-recursive is of options pass chmod, others multiple options passed. need index is mode argument, safely test isSensisitiveChmodMode initializers list (skipping first)</technical_language>

Target:
private void checkExecStringArrayArgument(NewArrayTree newArrayTree) { List<ExpressionTree> initializers = newArrayTree.initializers(); if (initializers.size() < 3 || !chmodCommand(initializers.get(0)).isPresent()) { return; } for (int i = 1; i < initializers.size(); i++) { ExpressionTree arg = initializers.get(i); if (arg.asConstant(String.class).filter(FilePermissionsCheck::isSensisitiveChmodMode).isPresent()) { reportIssue(arg, ISSUE_MESSAGE); } } }
Source:
<code>private Mono<HttpResponse> attemptAsync(final HttpPipelineCallContext context, final HttpPipelineNextPolicy next, final HttpRequest originalHttpRequest, final int tryCount) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process() .flatMap(httpResponse -> { if (shouldRetry(httpResponse, tryCount)) { <START> logger.info("[Retrying] Try count: {}, HTTP response: {}, Original HTTP Request: {}", <END> tryCount, httpResponse, originalHttpRequest); return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(determineDelayDuration(httpResponse)); } else { return Mono.just(httpResponse); } }) .onErrorResume(err -> { if (tryCount < maxRetries) { logger.info("[Error Resume] Try count: {}, Error: {}, Original HTTP Request: {}", tryCount, err, originalHttpRequest); return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(this.delayDuration); } else { return Mono.error(err); } }); }</code><technical_language>move this determineDelayDuration get delay used. Another option is setting a local variable delay duration log here</technical_language>

Target:
private Mono<HttpResponse> attemptAsync(final HttpPipelineCallContext context, final HttpPipelineNextPolicy next, final HttpRequest originalHttpRequest, final int tryCount) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process() .flatMap(httpResponse -> { if (shouldRetry(httpResponse, tryCount)) { final Duration delayDuration = determineDelayDuration(httpResponse); logger.verbose("[Retrying] Try count: {}, Delay duration in seconds: {}", tryCount, delayDuration.getSeconds()); return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(delayDuration); } else { return Mono.just(httpResponse); } }) .onErrorResume(err -> { if (tryCount < maxRetries) { logger.verbose("[Error Resume] Try count: {}, Error: {}", tryCount, err); return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(this.delayDuration); } else { return Mono.error(err); } }); }
Source:
<code>String getEndpointPath() { <START> return callContext.getEndpoint().getEndpointPath(); <END> }</code><technical_language>getEndpoint() getter maintain access endpoint in place</technical_language>

Target:
String getEndpointPath() { return getEndpoint().getEndpointPath(); }
Source:
<code>public void interruptingLocalLeaderElectionTerminates() throws IOException { <START> Path tempDir = Files.createTempDirectory("foo"); <END> Leaders.LocalPaxosServices localPaxosServices = Leaders.createAndRegisterLocalServices( metricsManager, environment, ImmutableLeaderConfig.builder() .localServer("https://example") .quorumSize(1) .addLeaders("https://example") .acceptorLogDir(tempDir.resolve("acceptor").toFile()) .learnerLogDir(tempDir.resolve("learner").toFile()) .build(), () -> ImmutableLeaderRuntimeConfig.builder().build(), USER_AGENT); LeaderElectionService leader = localPaxosServices.leaderElectionService(); LockService lockService = LockServiceImpl.create(); LockService leadershipLock = AwaitingLeadershipProxy.newProxyInstance( LockService.class, () -> lockService, leader); LockService localOrRemoteLock = LocalOrRemoteProxy.newProxyInstance( LockService.class, leadershipLock, null, CompletableFuture.completedFuture(true)); try { Thread.currentThread().interrupt(); localOrRemoteLock.currentTimeMillis(); fail("expected InterruptedException"); } catch (UndeclaredThrowableException e) { assertThat(e.getCause()).isInstanceOf(InterruptedException.class); } }</code><technical_language>please temporaryFolder setup for test</technical_language>

Target:
public void interruptingLocalLeaderElectionTerminates() throws IOException { Leaders.LocalPaxosServices localPaxosServices = Leaders.createAndRegisterLocalServices( metricsManager, environment, ImmutableLeaderConfig.builder() .localServer("https://example") .quorumSize(1) .addLeaders("https://example") .acceptorLogDir(temporaryFolder.newFolder()) .learnerLogDir(temporaryFolder.newFolder()) .build(), () -> ImmutableLeaderRuntimeConfig.builder().build(), USER_AGENT); LeaderElectionService leader = localPaxosServices.leaderElectionService(); LockService lockService = LockServiceImpl.create(); LockService leadershipLock = AwaitingLeadershipProxy.newProxyInstance( LockService.class, () -> lockService, leader); LockService localOrRemoteLock = LocalOrRemoteProxy.newProxyInstance( LockService.class, leadershipLock, null, CompletableFuture.completedFuture(true)); try { Thread.currentThread().interrupt(); assertThatCode(localOrRemoteLock::currentTimeMillis) .as("proxy correctly handles interrupts") .isInstanceOf(SafeIllegalStateException.class); assertThat(Thread.currentThread().isInterrupted()); } finally { Thread.interrupted(); } }
Source:
<code>private static Set<Class<?>> findExceptionContextClasses() { final String[] classNames = new String[] { "org.apache.commons.lang3.exception.ExceptionContext", <START> "com.joyent.manta.org.apache.commons.lang3.exception.ExceptionContext" <END> }; final Set<Class<?>> classes = new LinkedHashSet<>(classNames.length); for (String className : classNames) { try { classes.add(Class.forName(className)); } catch (ClassNotFoundException ignored) { } } return Collections.unmodifiableSet(classes); }</code><technical_language>delete shaded class I testing monitoring utility provide a for users configure class names here</technical_language>

Target:
private static Set<Class<?>> findExceptionContextClasses() { final String[] classNames = new String[] { "org.apache.commons.lang3.exception.ExceptionContext" }; final Set<Class<?>> classes = new LinkedHashSet<>(classNames.length); for (String className : classNames) { try { classes.add(Class.forName(className)); } catch (ClassNotFoundException ignored) { } } return Collections.unmodifiableSet(classes); }
Source:
<code>public Builder toBuilder() { <START> return new Builder(); <END> }</code><technical_language>This return a builder current options set</technical_language>

Target:
public Builder toBuilder() { return new Builder() .setIdTokenProvider(this.idTokenProvider) .setTargetAudience(this.targetAudience) .setOptions(this.options); }
Source:
<code><START> public void putObject(String bucketName, String objectName, String fileName, String contentType) <END> throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); try { putObject(bucketName, objectName, contentType, size, file); } finally { file.close(); } }</code><technical_language>public void putObject(String bucketName, String objectName, String fileName) method this version of method avoid code duplication</technical_language>

Target:
public void putObject(String bucketName, String objectName, String fileName, String contentType) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } if (contentType == null) { contentType = Files.probeContentType(filePath); } long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); try { putObject(bucketName, objectName, contentType, size, file); } finally { file.close(); } }
Source:
<code>void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); <START> System.out.println(advancedCache(0).getCacheConfiguration().clustering().partitionHandling().getMergePolicy()); <END> cache(0).put(conflictKey, "BEFORE SPLIT"); }</code><technical_language>System.out</technical_language>

Target:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); cache(0).put(conflictKey, "BEFORE SPLIT"); }
Source:
<code>public void shouldNotDisableAgentsWhenInvalidAgentUUIDIsprovided() throws Exception { AgentConfig agentConfig1 = new AgentConfig(UUID.randomUUID().toString(), "remote-host1", "50.40.30.21"); AgentConfig agentConfig2 = new AgentConfig(UUID.randomUUID().toString(), "remote-host2", "50.40.30.22"); agentConfigService.addAgent(agentConfig1, Username.ANONYMOUS); agentConfigService.addAgent(agentConfig2, Username.ANONYMOUS); CruiseConfig cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); ArrayList<String> uuids = new ArrayList<>(); uuids.add(agentConfig1.getUuid()); uuids.add(agentConfig2.getUuid()); uuids.add("invalid-uuid"); agentConfigService.bulkUpdateAgentAttributes(Username.ANONYMOUS, result, uuids, new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), TriState.FALSE); cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); <START> assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); <END> assertFalse(result.isSuccessful()); assertThat(result.toString(), result.httpCode(), is(400)); assertTrue(result.toString(), result.toString().contains("AGENTS_WITH_UUIDS_NOT_FOUND")); assertTrue(result.toString(), result.toString().contains("invalid-uuid")); }</code><technical_language>assertion twice, assert agentConfig2</technical_language>

Target:
public void shouldNotDisableAgentsWhenInvalidAgentUUIDIsprovided() throws Exception { AgentConfig agentConfig1 = new AgentConfig(UUID.randomUUID().toString(), "remote-host1", "50.40.30.21"); AgentConfig agentConfig2 = new AgentConfig(UUID.randomUUID().toString(), "remote-host2", "50.40.30.22"); agentConfigService.addAgent(agentConfig1, Username.ANONYMOUS); agentConfigService.addAgent(agentConfig2, Username.ANONYMOUS); CruiseConfig cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); ArrayList<String> uuids = new ArrayList<>(); uuids.add(agentConfig1.getUuid()); uuids.add(agentConfig2.getUuid()); uuids.add("invalid-uuid"); agentConfigService.bulkUpdateAgentAttributes(Username.ANONYMOUS, result, uuids, new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), TriState.FALSE); cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig2.getUuid()).isDisabled()); assertFalse(result.isSuccessful()); assertThat(result.toString(), result.httpCode(), is(400)); assertTrue(result.toString(), result.toString().contains("AGENTS_WITH_UUIDS_NOT_FOUND")); assertTrue(result.toString(), result.toString().contains("invalid-uuid")); }
Source:
<code>public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .onErrorResume(throwable -> { <START> logger.warn("Unexpected exception from thread {}", Thread.currentThread().getId(), throwable); <END> return Mono.error(throwable); }) .then(this.afterProcessChanges(context)); }</code><technical_language>logger.error ? logger.debug</technical_language>

Target:
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .doOnError(throwable -> { logger.warn("Unexpected exception from thread {}", Thread.currentThread().getId(), throwable); }) .then(this.afterProcessChanges(context)); }
Source:
<code>public void testOpenTransientSession() { SWTBotTreeItem projectTreeItemBot = modelExplorerViewBot.tree().expandNode(getProjectName(), true); SWTBotTreeItem modelResourceTreeItemBot = projectTreeItemBot.getNode(SEMANTIC_RESOURCE_NAME); modelResourceTreeItemBot.select(); SWTBotUtils.clickContextMenu(modelResourceTreeItemBot, "Sirius Ecore Editor"); SWTBotUtils.waitAllUiEvents(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.editors().size() == 1; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Sirius Ecore Editor should be opened"; } }); modelResourceTreeItemBot.select().doubleClick(); <START> assertTrue("Double click on the opened model should not open a second editor", bot.editors().size() == 1); <END> assertTrue("The double click action should not open a second session", localSession.getOpenedSession().getAllSessionResources().size() == 1); }</code><technical_language>assertEquals() prefered instead of assertTrue() results in case of failure</technical_language>

Target:
public void testOpenTransientSession() { SWTBotTreeItem projectTreeItemBot = modelExplorerViewBot.tree().expandNode(getProjectName(), true); SWTBotTreeItem modelResourceTreeItemBot = projectTreeItemBot.getNode(SEMANTIC_RESOURCE_NAME); modelResourceTreeItemBot.select(); SWTBotUtils.clickContextMenu(modelResourceTreeItemBot, "Sirius Ecore Editor"); SWTBotUtils.waitAllUiEvents(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.editors().size() == 1; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Sirius Ecore Editor should be opened"; } }); modelResourceTreeItemBot.select().doubleClick(); assertEquals("Double click on the opened model should not open a second editor", true, bot.editors().size() == 1); assertEquals("The double click action should not open a second session", true, localSession.getOpenedSession().getAllSessionResources().size() == 1); }
Source:
<code>public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException { <START> final String res = DateTimeFormatter.ISO_INSTANT.format(value.withZoneSameInstant(ZoneId.of("Z"))); <END> gen.writeString(res); }</code><technical_language>ZoneOffset.UTC similar used, in order more readable</technical_language>

Target:
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException { final String res = DateTimeFormatter.ISO_INSTANT.format(value.withZoneSameInstant(ZoneOffset.UTC)); gen.writeString(res); }
Source:
<code>private void copyPrivateKeysWithPermissions(PodSpec podSpec, VolumeMount sshKeysVolumeMount) { String copiedSshKeysVolumeName = "copied-private-keys"; podSpec .getVolumes() .add( new VolumeBuilder() .withName(copiedSshKeysVolumeName) .withNewEmptyDir() .endEmptyDir() .build()); VolumeMount copiedSshKeysVolumeMount = new VolumeMountBuilder() .withName(copiedSshKeysVolumeName) .withMountPath(SSH_PRIVATE_KEYS_PATH + "-copy") .build(); Container initContainer = new ContainerBuilder() .withName("ssh-private-keys-modifier") <START> .withImage("centos:centos7") <END> .withVolumeMounts(sshKeysVolumeMount, copiedSshKeysVolumeMount) .withCommand( asList( "/bin/sh", "-c", format( "(cp -r %1$s/. %1$s-copy && chmod -R 600 %1$s-copy) || exit 0", SSH_PRIVATE_KEYS_PATH))) .build(); podSpec .getContainers() .forEach(container -> container.getVolumeMounts().add(copiedSshKeysVolumeMount)); podSpec.getInitContainers().add(initContainer); }</code><technical_language>This is bad practice a nightmare for airgap users</technical_language>

Target:
private void copyPrivateKeysWithPermissions(PodSpec podSpec, VolumeMount sshKeysVolumeMount) { String copiedSshKeysVolumeName = "copied-private-keys"; podSpec .getVolumes() .add( new VolumeBuilder() .withName(copiedSshKeysVolumeName) .withNewEmptyDir() .endEmptyDir() .build()); VolumeMount copiedSshKeysVolumeMount = new VolumeMountBuilder() .withName(copiedSshKeysVolumeName) .withMountPath(SSH_PRIVATE_KEYS_PATH + "-copy") .build(); Container initContainer = new ContainerBuilder() .withName("ssh-private-keys-modifier") .withImage(jobImage) .withVolumeMounts(sshKeysVolumeMount, copiedSshKeysVolumeMount) .withCommand( asList( "/bin/sh", "-c", format( "(cp -r %1$s/. %1$s-copy && chmod -R 600 %1$s-copy) || exit 0", SSH_PRIVATE_KEYS_PATH))) .build(); podSpec .getContainers() .forEach(container -> container.getVolumeMounts().add(copiedSshKeysVolumeMount)); podSpec.getInitContainers().add(initContainer); }
Source:
<code>private URI determineRepositoryPath(URI baseUri) throws IOException, FcrepoOperationFailedException { <START> PID parentPid = null; <END> try (FcrepoResponse response = client.post(baseUri).perform()) { parentPid = PIDs.get(response.getLocation()); } catch(FcrepoOperationFailedException e) { if (e.getStatusCode() != HttpStatus.SC_CONFLICT) { throw e; } } return parentPid.getRepositoryUri(); }</code><technical_language>a couple of errant tab characters</technical_language>

Target:
private URI determineRepositoryPath(URI baseUri) throws IOException, FcrepoOperationFailedException { URI repoPath = null; try (FcrepoResponse response = client.post(baseUri).perform()) { repoPath = response.getLocation(); } catch(FcrepoOperationFailedException e) { if (e.getStatusCode() != HttpStatus.SC_CONFLICT) { throw e; } } return repoPath; }
Source:
<code>public void onMessage(String message) { InputStream in = null; try { <START> in = StreamUtils.getInputStream(message); <END> JsonReader reader = Json.createReader(in); JsonObject json = reader.readObject(); reader.close(); JsonObject dataJson = json.getJsonObject(ATTRIBUTE_DATA); URLNotification notification = URLNotificationJSONConverter.parseJSON(dataJson); receiveNotification(notification); HeartbeatListener.sendHeartbeatMessage(getName(), "nats notification timestamp", json.getJsonNumber(TIMESTAMP_PROPERTY).toString()); sequence = json.getJsonNumber(SEQUENCE_PROPERTY).toString(); writeTrackingFile(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while processing URLNotification ", e); } finally { StreamUtils.closeStream(in); } }</code><technical_language>try resources, stream is automatically closed. This URLNotification.parseJSON(InputStream). Read url notification in a separate try block receiving notification</technical_language>

Target:
public void onMessage(String message) { JsonObject json; try (InputStream in = StreamUtils.getInputStream(message); JsonReader reader = Json.createReader(in)) { json = reader.readObject(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while receiving notification; is it encoded as JSON? ", e); return; } try { JsonObject dataJson = json.getJsonObject(ATTRIBUTE_DATA); URLNotification notification = URLNotificationJSONConverter.parseJSON(dataJson); receiveNotification(notification); HeartbeatListener.sendHeartbeatMessage(getName(), "nats notification timestamp", json.getJsonNumber(TIMESTAMP_PROPERTY).toString()); sequence = json.getJsonNumber(SEQUENCE_PROPERTY).toString(); writeTrackingFile(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while processing URLNotification ", e); } }
Source:
<code><START> public List<CategoryDTO> fetchInstallableApplications() { <END> final String[] urls = sourceUrl.split(";"); final ApplicationsSource applicationsSource = new MultipleApplicationSource(Arrays.stream(urls).map(this::toApplicationSource).collect(Collectors.toList())); return applicationsSource.fetchInstallableApplications(); }</code><technical_language>MultipleApplicationSources created time this is called. create MultipleApplicationSources in constructor</technical_language>

Target:
public List<CategoryDTO> fetchInstallableApplications() { return applicationsSource.fetchInstallableApplications(); }
Source:
<code>protected void convertAllTitlesToUnderscores(SQLiteDatabase db) { Cursor cursor = db.query(getTableName(), null, null, null, null, null, null); <START> int idIndex = cursor.getColumnIndexOrThrow("_id"); <END> int titleIndex = cursor.getColumnIndexOrThrow(Col.TITLE.getName()); ContentValues values = new ContentValues(); while (cursor.moveToNext()) { String title = cursor.getString(titleIndex); if (title.contains(" ")) { values.put(Col.TITLE.getName(), title.replace(" ", "_")); String id = Long.toString(cursor.getLong(idIndex)); db.updateWithOnConflict(getTableName(), values, "_id = ?", new String[]{id}, SQLiteDatabase.CONFLICT_REPLACE); } } cursor.close(); }</code><technical_language>Col.ID.getName() here? (Ditto for PageImage SavedPage tables)</technical_language>

Target:
protected void convertAllTitlesToUnderscores(SQLiteDatabase db) { Cursor cursor = db.query(getTableName(), null, null, null, null, null, null); ContentValues values = new ContentValues(); while (cursor.moveToNext()) { String title = Col.TITLE.val(cursor); if (title.contains(" ")) { values.put(Col.TITLE.getName(), title.replace(" ", "_")); String id = Long.toString(Col.ID.val(cursor)); db.updateWithOnConflict(getTableName(), values, Col.ID.getName() + " = ?", new String[]{id}, SQLiteDatabase.CONFLICT_REPLACE); } } cursor.close(); }
Source:
<code>public void testIsValid_collection_all_is_invalid() throws Exception { Name_Collection name = new Name_Collection(Arrays.asList("ＡＢＣ", "GHI"), Arrays.asList("ABC", "ＧＨＩ")); Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); Set<ConstraintViolation<Name_Collection>> violations = validator .validate(name); assertThat(violations, is(notNullValue())); assertThat(violations.size(), is(2)); Iterator<ConstraintViolation<Name_Collection>> iterator = violations .iterator(); List<ConstraintViolation<Name_Collection>> lst = new ArrayList<ConstraintViolation<Name_Collection>>(2); lst.add(iterator.next()); lst.add(iterator.next()); Collections.sort(lst, new Comparator<ConstraintViolation<Name_Collection>>() { @Override public int compare(ConstraintViolation<Name_Collection> o1, ConstraintViolation<Name_Collection> o2) { return o1.getPropertyPath().toString().compareTo(o2 .getPropertyPath().toString()); } }); assertThat(lst.get(0).getPropertyPath().toString(), is( "firstNameList[0].<list element>")); assertThat(lst.get(0).getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); assertThat(lst.get(1).getPropertyPath().toString(), is( "lastNameList[1].<list element>")); assertThat(lst.get(1).getMessage(), is( <START> "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); <END> }</code><technical_language>Sorry, ((ConstraintViolation<?>) v) casting is unnecessary. (Since Iterator sorted modification, casting necessary.)</technical_language>

Target:
public void testIsValid_collection_all_is_invalid() throws Exception { Name_Collection name = new Name_Collection(Arrays.asList("GHI", "ABC"), Arrays.asList("GHI", "ABC")); Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); Set<ConstraintViolation<Name_Collection>> violations = validator .validate(name); assertThat(violations, is(notNullValue())); assertThat(violations.size(), is(2)); Iterator<ConstraintViolation<Name_Collection>> iterator = violations .stream().sorted(comparing(v -> v.getPropertyPath().toString())) .iterator(); ConstraintViolation<Name_Collection> violation = iterator.next(); assertThat(violation.getPropertyPath().toString(), is( "firstNames[0].<list element>")); assertThat(violation.getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); violation = iterator.next(); assertThat(violation.getPropertyPath().toString(), is( "lastNames[1].<list element>")); assertThat(violation.getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); }
Source:
<code>public void shouldPurgeAnIdentifierSource() throws Exception { assertNotNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); handle(newDeleteRequest(getURI() + "/" + IDENTIFIER_SOURCE_TO_PURGE_UUID, new Parameter("purge", ""))); assertNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); <START> <END> }</code><technical_language>remove empty lines</technical_language>

Target:
public void shouldPurgeAnIdentifierSource() throws Exception { assertNotNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); handle(newDeleteRequest(getURI() + "/" + IDENTIFIER_SOURCE_TO_PURGE_UUID, new Parameter("purge", "true"))); assertNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); }
Source:
<code>private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } List<QuotaConsumptionParameter> consumptionParameters = new ArrayList<QuotaConsumptionParameter>(); switch (this.getActionType().getQuotaDependency()) { case NONE: return true; <START> case STORAGE: <END> consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); break; case VDS: consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; case BOTH: consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper; if (getStoragePool() != null) { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( this.getStoragePool(), this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); } else { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( null,this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } return consumptionParameters.isEmpty() ? true: true; }</code><technical_language>consumptionParameters = getQuotaStorageConsumptionParameters() work fine</technical_language>

Target:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } if (getStoragePool() == null) { log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper(this, getReturnValue().getCanDoActionMessages()); quotaConsumptionParametersWrapper.setParameters(getQuotaConsumptionParameters()); return true; }
Source:
<code>public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy = resourcePolicyService.create(c); <START> policy = srp.copyToDSpaceObject(policy,dest); <END> resourcePolicyService.update(c,policy); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }</code><technical_language>This kind of beats purpose of "copyToDSpaceObject" method. This code force hibernate execute DB statements: insert update. I move copyToDSpaceObject ResourcePolicyService: * Create a new empty resource policy * Copy values * pass filled in resource policy resourcePolicyDAO.create(). enable Hibernate DEBUG logging in hibernate.cfg.xml SQL statements executes</technical_language>

Target:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy =resourcePolicyService.copyToDSpaceObject(c,srp,dest); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }