auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<String[]> readSection(BufferedReader bufferedReader) { List<String[]> section = new ArrayList<String[]>(); String line = ""; String currKey = null; StringBuffer currVal = new StringBuffer(); boolean done = false; int linecount = 0; try { while (!done) { bufferedReader.mark(320); line = bufferedReader.readLine(); String firstSecKey = section.isEmpty() ? "" : section.get(0)[0]; if (line != null && line.matches("\\p{Space}*")) { continue; } if (line == null || (!line.startsWith(" ") && linecount++ > 0 && (!firstSecKey .equals(START_SEQUENCE_TAG) || line .startsWith(END_SEQUENCE_TAG)))) { section.add(new String[]{currKey, currVal.toString()}); bufferedReader.reset(); done = true; } else { <START> srcRecord += line + "\n"; <END> Matcher m = sectp.matcher(line); if (m.matches()) { if (currKey != null) { section.add(new String[]{currKey, currVal.toString()}); } currKey = m.group(2) == null ? (m.group(4) == null ? m .group(6) : m.group(4)) : m.group(2); currVal = new StringBuffer(); currVal.append((m.group(2) == null ? (m.group(4) == null ? "" : m.group(5)) : m.group(3)).trim()); } else { END line? if (line.startsWith(START_SEQUENCE_TAG) || line.startsWith(END_SEQUENCE_TAG)) { currKey = line; } else { currVal.append("\n"); currVal.append(currKey.charAt(0) == '/' ? line .substring(21) : line.substring(12)); } } } } } catch (IOException e) { throw new ParserException(e.getMessage()); } catch (RuntimeException e) { throw new ParserException(e.getMessage()); } return section; }</code><technical_language>a StringBuilder instead? I guess lines, string concat this effect performance</technical_language>

Target:
private List<String[]> readSection(BufferedReader bufferedReader) { List<String[]> section = new ArrayList<String[]>(); String line = ""; String currKey = null; StringBuffer currVal = new StringBuffer(); boolean done = false; int linecount = 0; try { while (!done) { bufferedReader.mark(320); line = bufferedReader.readLine(); String firstSecKey = section.isEmpty() ? "" : section.get(0)[0]; if (line != null && line.matches("\\p{Space}*")) { continue; } if (line == null || (!line.startsWith(" ") && linecount++ > 0 && (!firstSecKey .equals(START_SEQUENCE_TAG) || line .startsWith(END_SEQUENCE_TAG)))) { section.add(new String[]{currKey, currVal.toString()}); bufferedReader.reset(); done = true; } else { srcRecord.append(line + "\n"); Matcher m = sectp.matcher(line); if (m.matches()) { if (currKey != null) { section.add(new String[]{currKey, currVal.toString()}); } currKey = m.group(2) == null ? (m.group(4) == null ? m .group(6) : m.group(4)) : m.group(2); currVal = new StringBuffer(); currVal.append((m.group(2) == null ? (m.group(4) == null ? "" : m.group(5)) : m.group(3)).trim()); } else { END line? if (line.startsWith(START_SEQUENCE_TAG) || line.startsWith(END_SEQUENCE_TAG)) { currKey = line; } else { currVal.append("\n"); currVal.append(currKey.charAt(0) == '/' ? line .substring(21) : line.substring(12)); } } } } } catch (IOException e) { throw new ParserException(e.getMessage()); } catch (RuntimeException e) { throw new ParserException(e.getMessage()); } return section; }
Source:
<code>protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsVDSParameters(upServer.getId(), getGlusterVolumeName(), getParameters().getVolumeOption(), getParameters().isForceAction())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { if (getParameters().getVolumeOption() != null && !(getParameters().getVolumeOption().getKey().isEmpty())) { GlusterVolumeOptionEntity entity = getGlusterVolume().getOption(getParameters().getVolumeOption().getKey()); removeOptionInDb(entity); isResetAllOptions = false; if(entity != null) { String optionValue = entity.getValue(); getParameters().getVolumeOption().setValue(optionValue != null ? optionValue : ""); <START> } <END> } else { for (GlusterVolumeOptionEntity option : getGlusterVolume().getOptions()) { removeOptionInDb(option); } isResetAllOptions = true; } } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED, returnValue.getVdsError().getMessage()); return; } }</code><technical_language>do need override getCustomValues() instead of adding custom values here? override affect command inheriting this command</technical_language>

Target:
protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsVDSParameters(upServer.getId(), getGlusterVolumeName(), getParameters().getVolumeOption(), getParameters().isForceAction())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { if (getParameters().getVolumeOption() != null && !(getParameters().getVolumeOption().getKey().isEmpty())) { GlusterVolumeOptionEntity entity = getGlusterVolume().getOption(getParameters().getVolumeOption().getKey()); removeOptionInDb(entity); isResetAllOptions = false; if(entity != null) { String optionValue = entity.getValue(); getParameters().getVolumeOption().setValue(optionValue != null ? optionValue : ""); addCustomValue(GlusterConstants.OPTION_KEY, getParameters().getVolumeOption().getKey()); addCustomValue(GlusterConstants.OPTION_VALUE, getParameters().getVolumeOption().getValue()); } } else { for (GlusterVolumeOptionEntity option : getGlusterVolume().getOptions()) { removeOptionInDb(option); } isResetAllOptions = true; } } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED, returnValue.getVdsError().getMessage()); return; } }
Source:
<code>private void roundTrip(List<String> typeQueryParameters) { StoredWorkflowDefinition convertedOriginal = dao.convert(original); dao.storeWorkflowDefinition(original); List<StoredWorkflowDefinition> storedDefinitions = dao.queryStoredWorkflowDefinitions(typeQueryParameters); assertThat(storedDefinitions.size(), is(1)); StoredWorkflowDefinition stored = storedDefinitions.get(0); assertThat(stored.type, is(convertedOriginal.type)); assertThat(stored.onError, is(convertedOriginal.onError)); assertThat(stored.description, is(convertedOriginal.description)); <START> for (int i = 0; i < convertedOriginal.states.size(); i++) { <END> assertThat(stored.states.get(i), reflectEquals(convertedOriginal.states.get(i))); } }</code><technical_language>assert convertedOriginal.states.size == stored.states.size</technical_language>

Target:
private void roundTrip(List<String> typeQueryParameters) { StoredWorkflowDefinition convertedOriginal = dao.convert(original); dao.storeWorkflowDefinition(original); List<StoredWorkflowDefinition> storedDefinitions = dao.queryStoredWorkflowDefinitions(typeQueryParameters); assertThat(storedDefinitions.size(), is(1)); StoredWorkflowDefinition stored = storedDefinitions.get(0); assertThat(stored.type, is(convertedOriginal.type)); assertThat(stored.onError, is(convertedOriginal.onError)); assertThat(stored.description, is(convertedOriginal.description)); assertThat(stored.states.size(), is(convertedOriginal.states.size())); for (int i = 0; i < convertedOriginal.states.size(); i++) { assertThat(stored.states.get(i), reflectEquals(convertedOriginal.states.get(i))); } }
Source:
<code>public void shouldScheduleDailyReportJob() throws SchedulerException { ebodacScheduler.unscheduleDailyReportJob(); <START> verify(motechSchedulerService).safeUnscheduleAllJobs(EbodacConstants.DAILY_REPORT_EVENT); <END> DateTime startDate = DateTime.parse(DateTime.now().plusDays(1).toString(DateTimeFormat.forPattern(EbodacConstants.REPORT_DATE_FORMAT)) + EbodacConstants.DAILY_REPORT_EVENT_START_HOUR, DateTimeFormat.forPattern(EbodacConstants.REPORT_START_DATE_FORMAT)); ebodacScheduler.scheduleDailyReportJob(startDate); Period period = Period.days(1); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.DAILY_REPORT_EVENT_START_DATE, startDate); MotechEvent event = new MotechEvent(EbodacConstants.DAILY_REPORT_EVENT, eventParameters); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate.toDate(), null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }</code><technical_language>move new test</technical_language>

Target:
public void shouldScheduleDailyReportJob() { DateTime startDate = DateTime.parse(DateTime.now().plusDays(1).toString(DateTimeFormat.forPattern(EbodacConstants.REPORT_DATE_FORMAT)) + EbodacConstants.DAILY_REPORT_EVENT_START_HOUR, DateTimeFormat.forPattern(EbodacConstants.REPORT_START_DATE_FORMAT)); ebodacScheduler.scheduleDailyReportJob(startDate); Period period = Period.days(1); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.DAILY_REPORT_EVENT_START_DATE, startDate); MotechEvent event = new MotechEvent(EbodacConstants.DAILY_REPORT_EVENT, eventParameters); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate.toDate(), null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }
Source:
<code>private Map<SafeHtml, SafeHtml> getImagesToTooltipTextMap(VM vm) { Map<SafeHtml, SafeHtml> res = new LinkedHashMap<>(); if (vm.getVmPoolId() == null) { VmTypeConfig config = VmTypeConfig.from(vm.getVmType(), vm.isStateless(), isConfigurationOrClusterNextRunExists(vm)); res.put(getImageSafeHtml(config.getImageResource()), config.getTooltip()); } else { ImageResource img = getPoolVmImageResource(vm.getVmType(), isConfigurationOrClusterNextRunExists(vm)); res.put(getImageSafeHtml(img), getPoolVmTooltip(vm.getVmType())); } if (vm.isHostedEngine()) { res.put(getImageSafeHtml(resources.mgmtNetwork()), SafeHtmlUtils.fromString(constants.isHostedEngineVmTooltip())); } if (isConfigurationOrClusterNextRunExists(vm)) { Set<String> nextRunFields = vm.getNextRunChangedFields() != null ? vm.getNextRunChangedFields() : new HashSet<>(); <START> if (isClusterCpuNeedsChange(vm, nextRunFields)){ <END> nextRunFields.add("clusterCpuChange"); } res.put(SafeHtmlUtils.EMPTY_SAFE_HTML, getNextRunChangedFieldsTooltip(nextRunFields)); } return res; }</code><technical_language>I in this case code more understandable if replaced condition if (nextConfigurationChanged(vm) && !nextRunFields.contains("customCpuName") instead of creating separate method (with clear name)</technical_language>

Target:
private Map<SafeHtml, SafeHtml> getImagesToTooltipTextMap(VM vm) { Map<SafeHtml, SafeHtml> res = new LinkedHashMap<>(); if (vm.getVmPoolId() == null) { VmTypeConfig config = VmTypeConfig.from(vm.getVmType(), vm.isStateless(), configurationWillChangeAfterRestart(vm)); res.put(getImageSafeHtml(config.getImageResource()), config.getTooltip()); } else { ImageResource img = getPoolVmImageResource(vm.getVmType(), configurationWillChangeAfterRestart(vm)); res.put(getImageSafeHtml(img), getPoolVmTooltip(vm.getVmType())); } if (vm.isHostedEngine()) { res.put(getImageSafeHtml(resources.mgmtNetwork()), SafeHtmlUtils.fromString(constants.isHostedEngineVmTooltip())); } if (configurationWillChangeAfterRestart(vm)) { Set<String> nextRunFields = vm.getNextRunChangedFields() != null ? vm.getNextRunChangedFields() : new HashSet<>(); if (clusterCpuChanged(vm) && !nextRunFields.contains("customCpuName")){ nextRunFields.add("clusterCpuChange"); } res.put(SafeHtmlUtils.EMPTY_SAFE_HTML, getNextRunChangedFieldsTooltip(nextRunFields)); } return res; }
Source:
<code>private void addResult(int offsetIndex, long value) { if (rowNumbersOut != null) { if (inputNumbers == null) { rowNumbersOut[numResults] = offsets[offsetIndex]; inputNumbersOut[numResults] = offsetIndex; } else { int outerIdx = inputNumbers[offsetIndex]; rowNumbersOut[numResults] = rowNumbers[outerIdx]; inputNumbersOut[numResults] = outerIdx; <START> } <END> } if (values != null) { values[numResults + numValues] = adjustValue(offsetIndex, value); } ++numResults; }</code><technical_language>outerIndex</technical_language>

Target:
private void addResult(int offsetIndex, long value) { if (rowNumbersOut != null) { if (inputNumbers == null) { rowNumbersOut[numResults] = offsets[offsetIndex]; inputNumbersOut[numResults] = offsetIndex; } else { int outerIdx = inputNumbers[offsetIndex]; rowNumbersOut[numResults] = rowNumbers[outerIdx]; inputNumbersOut[numResults] = outerIdx; } } if (values != null) { values[numResults + numValues] = value; } ++numResults; }
Source:
<code>public InferredType type() { if (valueAsStringLowerCase.contains("j")) { return InferredTypes.runtimeType("complex"); } if (valueAsString.contains(".") || valueAsStringLowerCase.contains("e")) { return InferredTypes.runtimeType("float"); } <START> return InferredTypes.runtimeType("int"); <END> }</code><technical_language>constants for InferredTypes.runtimeType("int") other types avoid reinstantiating times</technical_language>

Target:
public InferredType type() { return type; }
Source:
<code>private void calculateStatistics() { eclipseOpen = aggregateDurations(getIntervalsOfType(IntervalType.ECLIPSE_OPEN)); userActive = aggregateDurations(getIntervalsOfType(IntervalType.USER_ACTIVE)); userReading = aggregateDurations(getIntervalsOfType(IntervalType.READING)); userTyping = aggregateDurations(getIntervalsOfType(IntervalType.TYPING)); userTest = aggregateDurations( getEditorIntervalsOfDocType(DocumentType.TEST)) .plus(aggregateDurations(getEditorIntervalsOfDocType(DocumentType.TEST_FRAMEWORK))) .plus(aggregateDurations(getEditorIntervalsOfDocType(DocumentType.FILENAME_TEST))) .plus(aggregateDurations(getEditorIntervalsOfDocType(DocumentType.PATHNAMME_TEST))); userProduction = aggregateDurations(getEditorIntervalsOfDocType(DocumentType.PRODUCTION)); <START> performDataSanitation(); <END> perspectiveDebug = aggregateDurations(getPerspectiveIntervalsOfType(Perspective.DEBUG)); perspectiveJava = aggregateDurations(getPerspectiveIntervalsOfType(Perspective.JAVA)); perspectiveOther = aggregateDurations(getPerspectiveIntervalsOfType(Perspective.OTHER)); averageTestDuration = getPreciseTime(aggregateDurations(getIntervalsOfType(IntervalType.JUNIT))) / getIntervalsOfType(IntervalType.JUNIT).size(); junitRunsCount = getIntervalsOfType(IntervalType.JUNIT).size(); }</code><technical_language>Please add empty line belongs together</technical_language>

Target:
private void calculateStatistics() { eclipseOpen = aggregateDurations(getIntervals(EclipseOpenInterval.class)); userActive = aggregateDurations(getIntervals(UserActiveInterval.class)); userReading = aggregateDurations(getIntervals(ReadingInterval.class)); userTyping = aggregateDurations(getIntervals(TypingInterval.class)); userTest = aggregateDurations(getEditorIntervals(DocumentType.TEST)) .plus(aggregateDurations(getEditorIntervals(DocumentType.TEST_FRAMEWORK))) .plus(aggregateDurations(getEditorIntervals(DocumentType.FILENAME_TEST))) .plus(aggregateDurations(getEditorIntervals(DocumentType.PATHNAMME_TEST))); userProduction = aggregateDurations(getEditorIntervals(DocumentType.PRODUCTION)); performDataSanitation(); perspectiveDebug = aggregateDurations(getPerspectiveIntervals(Perspective.DEBUG)); perspectiveJava = aggregateDurations(getPerspectiveIntervals(Perspective.JAVA)); perspectiveOther = aggregateDurations(getPerspectiveIntervals(Perspective.OTHER)); averageTestDuration = getPreciseTime(aggregateDurations(getIntervals(JUnitInterval.class))) / getIntervals(JUnitInterval.class).size(); junitRunsCount = getIntervals(JUnitInterval.class).size(); }
Source:
<code>public void shouldParseVepOutputWithExtraFields() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(); VariantAnnotation variantAnnotation = lineMapper.mapLine(VepOutputContent.vepOutputContentWithExtraFields, 0); List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertTrue(consequenceTypes.size() == 1); ConsequenceType consequenceType = consequenceTypes.get(0); List<Score> actualScores = consequenceType.getProteinSubstitutionScores(); assertNotNull(actualScores); <START> assertTrue(actualScores.size() == 2); <END> Score expectedSift = new Score(0.07, "Sift", "tolerated"); Score expectedPolyphen = new Score(0.859, "Polyphen", "possibly_damaging"); Comparator<Score> scoreComparator = Comparator.comparing(Score::getSource).thenComparing(Score::getDescription) .thenComparing(Score::getScore); actualScores.sort(scoreComparator); assertTrue(Collections.binarySearch(actualScores, expectedSift, scoreComparator) >= 0); assertTrue(Collections.binarySearch(actualScores, expectedPolyphen, scoreComparator) >= 0); }</code><technical_language>assertEquals(2, actualScores.size())</technical_language>

Target:
public void shouldParseVepOutputWithExtraFields() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(); VariantAnnotation variantAnnotation = lineMapper.mapLine(VepOutputContent.vepOutputContentWithExtraFields, 0); List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertEquals(1, consequenceTypes.size()); ConsequenceType consequenceType = consequenceTypes.get(0); List<Score> actualScores = consequenceType.getProteinSubstitutionScores(); assertNotNull(actualScores); assertEquals(2, actualScores.size()); Score expectedSift = new Score(0.07, "Sift", "tolerated"); Score expectedPolyphen = new Score(0.859, "Polyphen", "possibly_damaging"); Comparator<Score> scoreComparator = Comparator.comparing(Score::getSource).thenComparing(Score::getDescription) .thenComparing(Score::getScore); actualScores.sort(scoreComparator); assertTrue(Collections.binarySearch(actualScores, expectedSift, scoreComparator) >= 0); assertTrue(Collections.binarySearch(actualScores, expectedPolyphen, scoreComparator) >= 0); }
Source:
<code>protected boolean tryFeed(Material type, GlowPlayer player) { <START> if (getBreedingFoods().contains(type)) { <END> if (canBreed() && (getInLove() <= 0)) { setInLove(1000); player.incrementStatistic(Statistic.ANIMALS_BRED); return true; } else { int growth = computeGrowthAmount(type); if (growth > 0) { grow(growth); return true; } } } return false; }</code><technical_language>Remove a nesting level inverting this if-statement</technical_language>

Target:
protected boolean tryFeed(Material type, GlowPlayer player) { if (!getBreedingFoods().contains(type)) { return false; } if (canBreed() && getInLove() <= 0) { setInLove(1000); player.incrementStatistic(Statistic.ANIMALS_BRED); return true; } int growth = computeGrowthAmount(type); if (growth > 0) { grow(growth); return true; } return false; }
Source:
<code>public MailClient sendMail(MailMessage message, Handler<AsyncResult<MailResult>> resultHandler) { Context context = vertx.getOrCreateContext(); if (!closed) { if (validateHeaders(message, resultHandler, context)) { vertx.executeBlocking( fut -> { if (hostname == null) { if (config.getOwnHostname() != null) { hostname = config.getOwnHostname(); } else { hostname = Utils.getHostname(); } } <START> log.info("hostname: "+hostname); <END> fut.complete(null); }, res -> { connectionPool.getConnection(hostname, result -> { if (result.succeeded()) { result.result().setErrorHandler(th -> handleError(th, resultHandler, context)); sendMessage(message, result.result(), resultHandler, context); } else { handleError(result.cause(), resultHandler, context); } }); }); } } else { handleError("mail client has been closed", resultHandler, context); } return this; }</code><technical_language>debug info for logging</technical_language>

Target:
public MailClient sendMail(MailMessage message, Handler<AsyncResult<MailResult>> resultHandler) { Context context = vertx.getOrCreateContext(); if (!closed) { if (validateHeaders(message, resultHandler, context)) { if (hostname == null) { vertx.<String>executeBlocking( fut -> { String hname; if (config.getOwnHostname() != null) { hname = config.getOwnHostname(); } else { hname = Utils.getHostname(); } fut.complete(hname); }, res -> { if (res.succeeded()) { hostname = res.result(); getConnection(message, resultHandler, context); } else { handleError(res.cause(), resultHandler, context); } }); } else { getConnection(message, resultHandler, context); } } } else { handleError("mail client has been closed", resultHandler, context); } return this; }
Source:
<code>private ValidationResult isVirtIoScsiValid(VM vm, DiskVmElementValidator diskVmElementValidator) { ValidationResult result = diskVmElementValidator.verifyVirtIoScsi(vm); if (!result.isValid()) { return result; } <START> if (vm != null && diskVmElementValidator.isVirtIoScsi()) { <END> if (!VmDeviceCommonUtils.isVirtIoScsiDeviceExists(getVm().getManagedVmDeviceMap().values())) { return new ValidationResult(EngineMessage.CANNOT_PERFORM_ACTION_VIRTIO_SCSI_IS_DISABLED); } } return ValidationResult.VALID; }</code><technical_language>check is done in verifyVirtIoScsi, repeat it</technical_language>

Target:
private ValidationResult isVirtIoScsiValid(VM vm, DiskVmElementValidator diskVmElementValidator) { ValidationResult result = diskVmElementValidator.verifyVirtIoScsi(vm); if (!result.isValid()) { return result; } return ValidationResult.VALID; }
Source:
<code>public void addBatch(String sql) throws SQLException { if (statementInformation.getStatementQuery() == null) { statementInformation.setStatementQuery(sql); } else { <START> statementInformation.setStatementQuery(sql + statementInformation.getStatementQuery()); <END> } SQLException e = null; long start = System.nanoTime(); try { eventListener.onBeforeAddBatch(statementInformation, sql); delegate.addBatch(sql); } catch (SQLException sqle) { e = sqle; throw e; } finally { eventListener.onAfterAddBatch(statementInformation, System.nanoTime() - start, sql, e); } }</code><technical_language>line break maybe</technical_language>

Target:
public void addBatch(String sql) throws SQLException { if (statementInformation.getStatementQuery() == null) { statementInformation.setStatementQuery(sql); } else { statementInformation.setStatementQuery(sql + LINE_SEPARATOR + statementInformation.getStatementQuery()); } SQLException e = null; long start = System.nanoTime(); try { eventListener.onBeforeAddBatch(statementInformation, sql); delegate.addBatch(sql); } catch (SQLException sqle) { e = sqle; throw e; } finally { eventListener.onAfterAddBatch(statementInformation, System.nanoTime() - start, sql, e); } }
Source:
<code>public <PBM, M> M finalizeMapping(MappingKey<PBM, M> mappingKey, Function<PBM, MappingImplementor<M>> director) { @SuppressWarnings("unchecked") PBM partiallyBuiltMapping = (PBM) partiallyBuiltMappings.get( mappingKey ); if ( partiallyBuiltMapping == null ) { throw new AssertionFailure( <START> "Some partially mapping could not be found during bootstrap; there is probably a bug in Hibernate Search." <END> + " Key: " + mappingKey ); } MappingImplementor<M> mapping = director.apply( partiallyBuiltMapping ); fullyBuiltMappings.put( mappingKey, mapping ); partiallyBuiltMappings.remove( mappingKey ); return mapping.toAPI(); }</code><technical_language>partially **built** mapping</technical_language>

Target:
public <PBM, M> M finalizeMapping(MappingKey<PBM, M> mappingKey, Function<PBM, MappingImplementor<M>> director) { @SuppressWarnings("unchecked") PBM partiallyBuiltMapping = (PBM) partiallyBuiltMappings.get( mappingKey ); if ( partiallyBuiltMapping == null ) { throw new AssertionFailure( "Some partially built mapping could not be found during bootstrap; there is probably a bug in Hibernate Search." + " Key: " + mappingKey ); } MappingImplementor<M> mapping = director.apply( partiallyBuiltMapping ); fullyBuiltMappings.put( mappingKey, mapping ); partiallyBuiltMappings.remove( mappingKey ); return mapping.toAPI(); }
Source:
<code>public void cameraDeviceCallsAreForwardedToCallback() throws InterruptedException { <START> Assume.assumeTrue(mCameraId != null); <END> mUseCase.addStateChangeListener( mCameraRepository.getCamera( getCameraIdForLensFacingUnchecked(mConfig.getLensFacing()))); mUseCase.doNotifyActive(); mCameraRepository.onGroupActive(mUseCaseGroup); mUseCase.mDeviceStateCallback.waitForOnOpened(1); mCameraRepository.onGroupInactive(mUseCaseGroup); mUseCase.mDeviceStateCallback.waitForOnClosed(1); }</code><technical_language>Move setUp(). mCameraId a local variable again</technical_language>

Target:
public void cameraDeviceCallsAreForwardedToCallback() throws InterruptedException { mUseCase.addStateChangeListener( mCameraRepository.getCamera( getCameraIdForLensFacingUnchecked(mConfig.getLensFacing()))); mUseCase.doNotifyActive(); mCameraRepository.onGroupActive(mUseCaseGroup); mUseCase.mDeviceStateCallback.waitForOnOpened(1); mCameraRepository.onGroupInactive(mUseCaseGroup); mUseCase.mDeviceStateCallback.waitForOnClosed(1); }
Source:
<code><START> protected static double average(Double... args) { <END> return average(Arrays.asList(args)); }</code><technical_language>protected? default is package visibility accessible test class. Protected = package + subclasses</technical_language>

Target:
static double average(Double... args) { return average(Arrays.asList(args)); }
Source:
<code>public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); <START> for (CompilerInput compilerInput : compiler.getInputsById().values()) { <END> provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); for (String provide : provides) { emitNoSpace("declare module 'goog:"); emitNoSpace(provide); emitNoSpace("' {"); indent(); emitBreak(); TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); if (symbol.getType() != null) { walkScope(symbol, true); } else { String prefix = provide + "."; for (TypedVar other : topScope.getAllSymbols()) { String otherName = other.getName(); if (otherName.startsWith(prefix) && other.getType() != null && !other.getType().isFunctionPrototypeType()) { walkScope(other, false); } } } unindent(); emit("}"); emitBreak(); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }</code><technical_language>Ultimately want ignore provides for files explicitly passed in, e.g. stuff transitive closure base.js other libraries. early do that, leave a TODO here</technical_language>

Target:
public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); for (String provide : provides) { emitNoSpace("declare module "); emitNoSpace(INTERNAL_NAMESPACE); emitNoSpace(provide); emitNoSpace(" {"); indent(); emitBreak(); TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); if (symbol.getType() != null) { walkScope(symbol, true); } else { String prefix = provide + "."; for (TypedVar other : topScope.getAllSymbols()) { String otherName = other.getName(); if (otherName.startsWith(prefix) && other.getType() != null && !other.getType().isFunctionPrototypeType()) { walkScope(other, false); } } } unindent(); emit("}"); emitBreak(); defineExternalModule(provide); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }
Source:
<code>void render() { String spotId = mAdConfiguration.getServerParameters().getString(FyberMediationAdapter.KEY_SPOT_ID); if (TextUtils.isEmpty(spotId)) { <START> Log.w(TAG, "Cannot render interstitial ad. Please define a valid spot id on the AdMob console"); <END> mAdLoadCallback.onFailure("Cannot render interstitial ad. Please define a valid spot id on the AdMob console"); return; } mRewardedSpot = InneractiveAdSpotManager.get().createSpot(); mRewardedSpot.setMediationName(InneractiveMediationName.ADMOB); mUnitController = new InneractiveFullscreenUnitController(); mRewardedSpot.addUnitController(mUnitController); InneractiveAdRequest request = new InneractiveAdRequest(spotId); InneractiveAdSpot.RequestListener requestListener = createRequestListener(); mRewardedSpot.setRequestListener(requestListener); mRewardedSpot.requestAd(request); }</code><technical_language>render interstitial ad. -> render rewarded ad. Also, create a single String variable in 2 places</technical_language>

Target:
void render() { String spotId = mAdConfiguration.getServerParameters().getString(FyberMediationAdapter.KEY_SPOT_ID); if (TextUtils.isEmpty(spotId)) { Log.w(TAG, RENDER_FAILURE_ERROR_STR); mAdLoadCallback.onFailure(RENDER_FAILURE_ERROR_STR); return; } mRewardedSpot = InneractiveAdSpotManager.get().createSpot(); mRewardedSpot.setMediationName(InneractiveMediationName.ADMOB); mUnitController = new InneractiveFullscreenUnitController(); mRewardedSpot.addUnitController(mUnitController); InneractiveAdRequest request = new InneractiveAdRequest(spotId); InneractiveAdSpot.RequestListener requestListener = createRequestListener(); mRewardedSpot.setRequestListener(requestListener); mRewardedSpot.requestAd(request); }
Source:
<code>public void afterPropertiesSet() throws Exception { objectMapper = null; <START> if (applicationContext != null && applicationContext.containsBean("objectMapper")) { <END> objectMapper = (ObjectMapper) applicationContext.getBean("objectMapper"); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } jsonRpcServer = new JsonRpcServer( objectMapper, null == getServiceInterface() ? getService() : getProxyForService(), getServiceInterface()); jsonRpcServer.setErrorResolver(errorResolver); jsonRpcServer.setBackwardsCompatible(backwardsCompatible); jsonRpcServer.setRethrowExceptions(rethrowExceptions); jsonRpcServer.setAllowExtraParams(allowExtraParams); jsonRpcServer.setAllowLessParams(allowLessParams); jsonRpcServer.setInvocationListener(invocationListener); jsonRpcServer.setHttpStatusCodeProvider(httpStatusCodeProvider); jsonRpcServer.setConvertedParameterTransformer(convertedParameterTransformer); jsonRpcServer.setShouldLogInvocationErrors(shouldLogInvocationErrors); if (contentType != null) { jsonRpcServer.setContentType(contentType); } if (interceptorList != null) { jsonRpcServer.setInterceptorList(interceptorList); } ReflectionUtil.clearCache(); exportService(); }</code><technical_language>purpose of removing objectMapper == null this if statement instead setting null line 41? is of objectMapper afterPropertiesSet() is called</technical_language>

Target:
public void afterPropertiesSet() throws Exception { if (objectMapper == null && applicationContext != null && applicationContext.containsBean("objectMapper")) { objectMapper = (ObjectMapper) applicationContext.getBean("objectMapper"); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } jsonRpcServer = new JsonRpcServer( objectMapper, null == getServiceInterface() ? getService() : getProxyForService(), getServiceInterface()); jsonRpcServer.setErrorResolver(errorResolver); jsonRpcServer.setBackwardsCompatible(backwardsCompatible); jsonRpcServer.setRethrowExceptions(rethrowExceptions); jsonRpcServer.setAllowExtraParams(allowExtraParams); jsonRpcServer.setAllowLessParams(allowLessParams); jsonRpcServer.setInvocationListener(invocationListener); jsonRpcServer.setHttpStatusCodeProvider(httpStatusCodeProvider); jsonRpcServer.setConvertedParameterTransformer(convertedParameterTransformer); jsonRpcServer.setShouldLogInvocationErrors(shouldLogInvocationErrors); if (contentType != null) { jsonRpcServer.setContentType(contentType); } if (interceptorList != null) { jsonRpcServer.setInterceptorList(interceptorList); } ReflectionUtil.clearCache(); exportService(); }
Source:
<code>public void shouldRevertCommit() throws Exception { String newFile = "newFile.xml"; String htmlFile = "file.html"; String changeContent = "<! change content>"; <START> String messInitRepo = "init"; <END> String messCreateFile = "create newFile.xml"; String messUpdateFile = "update file.html"; String pathToNewFile = String.format("%s/%s", PROJECT_NAME, newFile); String pathToHtmlFile = String.format("%s/%s", PROJECT_NAME, htmlFile); projectExplorer.waitProjectExplorer(); gitInitRepo(); commitFiles(messInitRepo); testProjectServiceClient.createFileInProject(ws.getId(), PROJECT_NAME, newFile, changeContent); projectExplorer.quickExpandWithJavaScript(); projectExplorer.waitItem(pathToNewFile); commitFiles(messCreateFile); projectExplorer.waitAndSelectItem(PROJECT_NAME); performGitRevert(); projectExplorer.waitDisappearItemByPath(pathToNewFile); testProjectServiceClient.updateFile(ws.getId(), pathToHtmlFile, changeContent); projectExplorer.waitAndSelectItem(PROJECT_NAME); commitFiles(messUpdateFile); performGitRevert(); projectExplorer.openItemByPath(pathToHtmlFile); editor.waitActive(); editor.waitTextNotPresentIntoEditor(changeContent); }</code><technical_language>messInitRepo > initRepoMessage</technical_language>

Target:
public void shouldRevertCommit() throws Exception { String newFile = "newFile.xml"; String htmlFile = "file.html"; String changeContent = "<! change content>"; String initRepoMessage = "init"; String createFileMessage = "create newFile.xml"; String updateFileMessage = "update file.html"; String pathToNewFile = String.format("%s/%s", PROJECT_NAME, newFile); String pathToHtmlFile = String.format("%s/%s", PROJECT_NAME, htmlFile); projectExplorer.waitProjectExplorer(); gitInitRepo(); commitFiles(initRepoMessage); testProjectServiceClient.createFileInProject(ws.getId(), PROJECT_NAME, newFile, changeContent); projectExplorer.quickExpandWithJavaScript(); projectExplorer.waitItem(pathToNewFile); commitFiles(createFileMessage); projectExplorer.waitAndSelectItem(PROJECT_NAME); performGitRevert(); projectExplorer.waitDisappearItemByPath(pathToNewFile); testProjectServiceClient.updateFile(ws.getId(), pathToHtmlFile, changeContent); projectExplorer.waitAndSelectItem(PROJECT_NAME); commitFiles(updateFileMessage); performGitRevert(); projectExplorer.openItemByPath(pathToHtmlFile); editor.waitActive(); editor.waitTextNotPresentIntoEditor(changeContent); }
Source:
<code>public Response runNoteJobs(@PathParam("notebookId") String notebookId) throws IOException, IllegalArgumentException { LOG.info("run notebook jobs ", notebookId); Note note = notebook.getNote(notebookId); if (note == null) { return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build(); } for (Paragraph paragraph : note.getParagraphs()) { <START> note.setLastReplName(paragraph.getId()); <END> try { note.run(paragraph.getId()); } catch (Exception ex) { LOG.error("Exception from run", ex); if (paragraph != null) { paragraph.setReturn( new InterpreterResult(InterpreterResult.Code.ERROR, ex.getMessage()), ex); paragraph.setStatus(Job.Status.ERROR); } return new JsonResponse<>(Status.PRECONDITION_FAILED, paragraph.getJobName() + " Not selected or Invalid Interpreter bind").build(); } } return new JsonResponse<>(Status.OK).build(); }</code><technical_language>I located note.run</technical_language>

Target:
public Response runNoteJobs(@PathParam("notebookId") String notebookId) throws IOException, IllegalArgumentException { LOG.info("run notebook jobs ", notebookId); Note note = notebook.getNote(notebookId); if (note == null) { return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build(); } try { note.runAll(); } catch (Exception ex) { LOG.error("Exception from run", ex); return new JsonResponse<>(Status.PRECONDITION_FAILED, ex.getMessage() + "- Not selected or Invalid Interpreter bind").build(); } return new JsonResponse<>(Status.OK).build(); }
Source:
<code>public void testCreateProject() throws ProjectManagerException { System.out.println("projectManagerTest: testCreateProject"); ProjectManager manager = createProjectManager(); String projectName = "myTestCreateProject"; String projectDescription = "This is to test creating a project"; User user = new User("testUser"); <START> createProjectUtil(manager, projectName, projectDescription, user); <END> System.out.println("Created project successfully"); }</code><technical_language>clear assertions are. Consider keeping util function a helper create projects do assertions</technical_language>

Target:
public void testCreateProject() throws Exception { System.out.println("TestCreateProject"); Project project = manager.createProject(PROJECT_NAME, PROJECT_DESCRIPTION, user); verify(loader).postEvent(project, ProjectLogEvent.EventType.CREATED, user.getUserId(), null); Assert.assertEquals("Project Id", PROJECT_ID, project.getId()); Assert.assertEquals("Project name", PROJECT_NAME, project.getName()); Assert.assertEquals("Project description", PROJECT_DESCRIPTION, project.getDescription()); Assert.assertTrue("Project is active", project.isActive()); }
Source:
<code>public void setObject_unmanagedObjectThrows() { RealmResults<AllTypes> collection = realm.where(AllTypes.class).findAll(); realm.beginTransaction(); try { collection.setObject(AllTypes.FIELD_REALMOBJECT, new Dog()); fail(); } catch (IllegalArgumentException e) { <START> assertTrue("Wrong error message: " + e.getMessage(), e.getMessage().contains("is not a valid a valid, managed Realm object.")); <END> } }</code><technical_language>remove double a valid test & original exception</technical_language>

Target:
public void setObject_unmanagedObjectThrows() { RealmResults<AllTypes> collection = realm.where(AllTypes.class).findAll(); realm.beginTransaction(); try { collection.setObject(AllTypes.FIELD_REALMOBJECT, new Dog()); fail(); } catch (IllegalArgumentException e) { assertTrue("Wrong error message: " + e.getMessage(), e.getMessage().contains("is not a valid, managed Realm object.")); } }
Source:
<code>public void handleReconnect(ClientDescriptor clientDescriptor, byte[] extendedReconnectData) { ClientState clientState = this.clientStateMap.get(clientDescriptor); if (clientState == null) { throw new AssertionError("Client "+ clientDescriptor +" trying to reconnect is not connected to entity"); } clientState.attach(); ReconnectData reconnectData = reconnectDataCodec.decode(extendedReconnectData); clientIdMap.put(clientDescriptor, reconnectData.getClientId()); <START> invalidIds.add(reconnectData.getClientId()); <END> Set<String> cacheIds = reconnectData.getAllCaches(); for (final String cacheId : cacheIds) { ServerStoreImpl serverStore = ehcacheStateService.getStore(cacheId); if (serverStore == null) { LOGGER.warn("ServerStore '{}' does not exist as expected by Client '{}'.", cacheId, clientDescriptor); continue; } serverStore.setEvictionListener(new ServerStoreEvictionListener() { @Override public void onEviction(long key) { invalidateHashAfterEviction(cacheId, key); } }); attachStore(clientDescriptor, cacheId); } LOGGER.info("Client '{}' successfully reconnected to newly promoted ACTIVE after failover.", clientDescriptor); }</code><technical_language>This call a logical group, duplicated - extract method</technical_language>

Target:
public void handleReconnect(ClientDescriptor clientDescriptor, byte[] extendedReconnectData) { ClientState clientState = this.clientStateMap.get(clientDescriptor); if (clientState == null) { throw new AssertionError("Client "+ clientDescriptor +" trying to reconnect is not connected to entity"); } clientState.attach(); ReconnectData reconnectData = reconnectDataCodec.decode(extendedReconnectData); addClientId(clientDescriptor, reconnectData.getClientId()); Set<String> cacheIds = reconnectData.getAllCaches(); for (final String cacheId : cacheIds) { ServerStoreImpl serverStore = ehcacheStateService.getStore(cacheId); if (serverStore == null) { LOGGER.warn("ServerStore '{}' does not exist as expected by Client '{}'.", cacheId, clientDescriptor); continue; } serverStore.setEvictionListener(new ServerStoreEvictionListener() { @Override public void onEviction(long key) { invalidateHashAfterEviction(cacheId, key); } }); attachStore(clientDescriptor, cacheId); } LOGGER.info("Client '{}' successfully reconnected to newly promoted ACTIVE after failover.", clientDescriptor); }
Source:
<code>public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { <START> if (!isMenuToBeSetUp()) { <END> return; } if (firstRun && cursor.getCount() == 0) { entryFilter.setVisibility(View.GONE); } firstRun = false; adapter.swapCursor(cursor); getActivity().supportInvalidateOptionsMenu(); }</code><technical_language>want swap cursor main activity is searching</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { if (!isAdded() || cursor == null) { return; } if (firstRun && cursor.getCount() == 0) { entryFilter.setVisibility(View.GONE); } firstRun = false; adapter.swapCursor(cursor); getActivity().supportInvalidateOptionsMenu(); }
Source:
<code>public void testDeploymentStart() { ResteasyProviderFactory orig = ResteasyProviderFactory.peekInstance(); try { ResteasyProviderFactory.setInstance(null); ResteasyProviderFactory rpf1 = ResteasyProviderFactory.newInstance(); RegisterBuiltin.register(rpf1); rpf1.registerProvider(MyInterceptor.class); ResteasyDeployment dep1 = new ResteasyDeployment(); dep1.setProviderFactory(rpf1); dep1.setDeploymentSensitiveFactoryEnabled(true); dep1.start(); ResteasyProviderFactory rpf2 = ResteasyProviderFactory.newInstance(); RegisterBuiltin.register(rpf2); rpf2.register(new DynamicFeature() { @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { <START> if (ResteasyProviderFactory.newInstance().isRegistered(MyInterceptor.class)) <END> { Assert.fail("Second deployment consuming provider factory from first deployment"); } } }); ResteasyDeployment dep2 = new ResteasyDeployment(); dep2.setProviderFactory(rpf2); dep2.setDeploymentSensitiveFactoryEnabled(true); dep2.getResourceClasses().add(NamespaceMappingResource.class.getName()); dep2.start(); dep1.stop(); dep2.stop(); } finally { ResteasyProviderFactory.setInstance(orig); } }</code><technical_language>This changed, judging test code</technical_language>

Target:
public void testDeploymentStart() { ResteasyProviderFactory orig = ResteasyProviderFactory.peekInstance(); try { ResteasyProviderFactory.setInstance(null); ResteasyProviderFactory rpf1 = ResteasyProviderFactory.newInstance(); RegisterBuiltin.register(rpf1); rpf1.registerProvider(MyInterceptor.class); ResteasyDeployment dep1 = new ResteasyDeployment(); dep1.setProviderFactory(rpf1); dep1.setDeploymentSensitiveFactoryEnabled(true); dep1.start(); ResteasyProviderFactory rpf2 = ResteasyProviderFactory.newInstance(); RegisterBuiltin.register(rpf2); rpf2.register(new DynamicFeature() { @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { if (ResteasyProviderFactory.getInstance().isRegistered(MyInterceptor.class)) { Assert.fail("Second deployment consuming provider factory from first deployment"); } } }); ResteasyDeployment dep2 = new ResteasyDeployment(); dep2.setProviderFactory(rpf2); dep2.setDeploymentSensitiveFactoryEnabled(true); dep2.getResourceClasses().add(NamespaceMappingResource.class.getName()); dep2.start(); dep1.stop(); dep2.stop(); } finally { ResteasyProviderFactory.setInstance(orig); } }
Source:
<code>private boolean handlePositiveEnforcingAffinityGroup(Guid vdsId, List<VM> runningVms) { List<AffinityGroup> affinityGroups = affinityGroupDao.getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId(vdsId); if (!affinityGroups.isEmpty()) { List<Object> items = new ArrayList<>(); affinityGroups.stream() .filter(ag -> <START> (!ag.getVdsIds().isEmpty()) || (ag.getVdsIds().isEmpty() && ag.isVmAffinityEnabled() && runningVms.size() > 1 && ag.getVmIds().size() > 1 && runningVms.stream() .filter(vm -> ag.getVmIds().contains(vm.getId())).collect (Collectors.toList()).size() > 1) <END> ) .collect(Collectors.toList()) .forEach(affinityGroup -> { items.add(String.format("%1$s (%2$s)", affinityGroup.getName(), StringUtils.join(affinityGroup.getVmEntityNames(), " ,"))); }); if (!items.isEmpty()) { addValidationMessage(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_HAS_AFFINITY_VMS); getReturnValue().getValidationMessages() .addAll(ReplacementUtils.replaceWith("AFFINITY_GROUPS_VMS", items)); return false; } } return true; }</code><technical_language>encapsulate this a "simple" AffinityGroup method called here</technical_language>

Target:
private boolean handlePositiveEnforcingAffinityGroup(Guid vdsId, List<VM> runningVms) { List<AffinityGroup> affinityGroups = affinityGroupDao.getPositiveEnforcingAffinityGroupsByRunningVmsOnVdsId(vdsId); if (!affinityGroups.isEmpty()) { List<Object> items = new ArrayList<>(); affinityGroups.stream() .filter(ag -> (!ag.getVdsIds().isEmpty()) || affinityGroupContainsRunningVMs(ag, runningVms) ) .forEach(affinityGroup -> { items.add(String.format("%1$s (%2$s)", affinityGroup.getName(), StringUtils.join(affinityGroup.getVmEntityNames(), " ,"))); }); if (!items.isEmpty()) { addValidationMessage(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_HAS_AFFINITY_VMS); getReturnValue().getValidationMessages() .addAll(ReplacementUtils.replaceWith("AFFINITY_GROUPS_VMS", items)); return false; } } return true; }
Source:
<code>public List<Contentlet> findFileAssetsByFolderInDB( final Folder parentFolder, final User user, final boolean live) throws DotDataException, DotSecurityException { final boolean respectFrontendRoles = live; final DotConnect dotConnect = new DotConnect(); dotConnect.setSQL(String.format(FIND_FILE_ASSETS_BY_FOLDER_QUERY, live ? "live" : "working")); dotConnect.addParam(parentFolder.getPath()); dotConnect.addParam(parentFolder.getHostId()); <START> if(!permissionAPI.doesUserHavePermission(parentFolder, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)){ <END> throw new DotSecurityException("User:" + user.getUserId() + " does not have permissions on Folder " + parentFolder); } final List<Map<String, Object>> queryResults = dotConnect.loadObjectResults(); return convertToFileAssets(user, respectFrontendRoles, queryResults); }</code><technical_language>this line, dotConnect</technical_language>

Target:
public List<Contentlet> findFileAssetsByFolderInDB( final Folder parentFolder, final User user, final boolean live) throws DotDataException, DotSecurityException { final boolean respectFrontendRoles = live; if(!permissionAPI.doesUserHavePermission(parentFolder, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)){ throw new DotSecurityException("User:" + user.getUserId() + " does not have permissions on Folder " + parentFolder); } final DotConnect dotConnect = new DotConnect(); dotConnect.setSQL(String.format(FIND_FILE_ASSETS_BY_FOLDER_QUERY, live ? "live" : "working")); dotConnect.addParam(parentFolder.getPath()); dotConnect.addParam(parentFolder.getHostId()); final List<Map<String, Object>> queryResults = dotConnect.loadObjectResults(); return convertToFileAssets(user, respectFrontendRoles, queryResults); }