auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Estimate calculateDataSizeForPartitioningKey( HiveColumnHandle partitionColumn, List<HivePartition> queriedPartitions, Map<String, PartitionStatistics> statisticsSample, Estimate rowCount, OptionalDouble rowsPerPartition) { if (rowCount.isValueUnknown() || !rowsPerPartition.isPresent()) { return Estimate.unknownValue(); } String baseType = partitionColumn.getTypeSignature().getBase(); if (!VARCHAR.equals(baseType) && !CHAR.equalsIgnoreCase(baseType)) { return Estimate.unknownValue(); } double knownRowCount = 0; double knownDataSize = 0; for (HivePartition partition : queriedPartitions) { NullableValue value = partition.getKeys().get(partitionColumn); int length = value.isNull() ? 0 : ((Slice) value.getValue()).length(); HiveBasicStatistics partitionStats = statisticsSample.get(partition.getPartitionId()).getBasicStatistics(); double partitionRowCount = partitionStats.getRowCount().isPresent() ? partitionStats.getRowCount().getAsLong() : rowsPerPartition.getAsDouble(); knownRowCount += partitionRowCount; knownDataSize += length * partitionRowCount; } if (knownRowCount <= 0) { return Estimate.unknownValue(); } return new Estimate(knownDataSize / knownRowCount * rowCount.getValue()); <START> } <END></code><technical_language>== 0 p.s.: I this kind of a defensive programming. i realize is more reliable, introduces additional confusion for future readers. + I do this in Presto</technical_language>

Target:
private Estimate calculateDataSizeForPartitioningKey( HiveColumnHandle partitionColumn, List<HivePartition> queriedPartitions, Map<String, PartitionStatistics> statisticsSample, Estimate rowCount, OptionalDouble rowsPerPartition) { if (rowCount.isValueUnknown() || !rowsPerPartition.isPresent()) { return Estimate.unknownValue(); } String baseType = partitionColumn.getTypeSignature().getBase(); if (!VARCHAR.equals(baseType) && !CHAR.equalsIgnoreCase(baseType)) { return Estimate.unknownValue(); } double knownRowCount = 0; double knownDataSize = 0; for (HivePartition partition : queriedPartitions) { NullableValue value = partition.getKeys().get(partitionColumn); int length = value.isNull() ? 0 : ((Slice) value.getValue()).length(); double partitionRowCount = orElse( Optional.ofNullable(statisticsSample.get(partition.getPartitionId())) .orElseGet(PartitionStatistics::empty) .getBasicStatistics() .getRowCount(), rowsPerPartition.getAsDouble()); knownRowCount += partitionRowCount; knownDataSize += length * partitionRowCount; } if (knownRowCount == 0) { return Estimate.unknownValue(); } return new Estimate(knownDataSize / knownRowCount * rowCount.getValue()); }
Source:
<code>private void emitOutlinks(Tuple tuple, String url, Metadata metadata, List<Link> links) { URL url_; try { url_ = new URL(url); } catch (MalformedURLException e1) { LOG.error("MalformedURLException on {}", url); eventCounter.scope( "error_outlinks_parsing_" + e1.getClass().getSimpleName()) <START> .incr(); <END> return; } Set<String> slinks = new HashSet<String>(links.size()); for (Link l : links) { if (StringUtils.isBlank(l.getUri())) { continue; } String urlOL = null; try { URL tmpURL = URLUtil.resolveURL(url_, l.getUri()); urlOL = tmpURL.toExternalForm(); } catch (MalformedURLException e) { LOG.debug("MalformedURLException on {}", l.getUri()); eventCounter.scope( "error_out_link_parsing_" + e.getClass().getSimpleName()).incrBy(1); continue; } if (urlFilters != null) { urlOL = urlFilters.filter(url_, metadata, urlOL); if (urlOL == null) { eventCounter.scope("outlink_filtered").incrBy(1); } } if (urlOL != null) { slinks.add(urlOL); eventCounter.scope("outlink_kept").incrBy(1); } } for (String outlink : slinks) { Metadata linkMetadata = metadataTransfer.getMetaForOutlink(url, metadata); collector.emit(StatusStreamName, tuple, new Values(outlink, linkMetadata, Status.DISCOVERED)); } }</code><technical_language>pedantic ;-)</technical_language>

Target:
private void emitOutlinks(Tuple tuple, String url, Metadata metadata, List<Link> links) { URL url_; try { url_ = new URL(url); } catch (MalformedURLException e1) { LOG.error("MalformedURLException on {}", url); eventCounter.scope("error_invalid_source_url").incrBy(1); return; } Set<String> slinks = new HashSet<String>(links.size()); for (Link l : links) { if (StringUtils.isBlank(l.getUri())) { continue; } String urlOL = null; try { URL tmpURL = URLUtil.resolveURL(url_, l.getUri()); urlOL = tmpURL.toExternalForm(); } catch (MalformedURLException e) { LOG.debug("MalformedURLException on {}", l.getUri()); eventCounter .scope("error_outlink_parsing_" + e.getClass().getSimpleName()).incrBy(1); continue; } if (urlFilters != null) { urlOL = urlFilters.filter(url_, metadata, urlOL); if (urlOL == null) { eventCounter.scope("outlink_filtered").incrBy(1); } } if (urlOL != null) { slinks.add(urlOL); eventCounter.scope("outlink_kept").incrBy(1); } } for (String outlink : slinks) { Metadata linkMetadata = metadataTransfer.getMetaForOutlink(url, metadata); collector.emit(StatusStreamName, tuple, new Values(outlink, linkMetadata, Status.DISCOVERED)); } }
Source:
<code>public void setWebDialogEnabled(boolean isEnabled) { isWebDialogEnabled = isEnabled; <START> addConfig("webDialogEnabled", isWebDialogEnabled ? "true" : "false"); <END> }</code><technical_language>Please remove this line</technical_language>

Target:
public void setWebDialogEnabled(boolean isEnabled) { isWebDialogEnabled = isEnabled; }
Source:
<code>private void doMutation(final Mutation mutation) throws RetriesExhaustedWithDetailsException { Long sequenceId = null; try { sequenceId = sizeManager.registerOperationWithHeapSize(mutation.heapSize()); } catch (InterruptedException e) { synchronized (globalExceptions) { addGlobalException(mutation, e); handleExceptions(); } Thread.currentThread().interrupt(); } AccountingFutureCallback callback = new AccountingFutureCallback(mutation, sequenceId); ListenableFuture<? extends GeneratedMessage> request = null; try { <START> request = batchExecutor.issueRequest(mutation); <END> } catch (RuntimeException e) { synchronized (globalExceptions) { callback.onFailure(e); handleExceptions(); } } Futures.addCallback(request, callback, heapSizeExecutor); }</code><technical_language>Is this raising UnsupportedOperationException? (that is I reading). is a pity is unchecked exception, easier catch this. :/ added issueRequest OperationAdapter.adapt</technical_language>

Target:
private void doMutation(final Mutation mutation) throws RetriesExhaustedWithDetailsException { Long sequenceId = null; try { sequenceId = sizeManager.registerOperationWithHeapSize(mutation.heapSize()); } catch (InterruptedException e) { synchronized (globalExceptions) { addGlobalException(mutation, e); handleExceptions(); } Thread.currentThread().interrupt(); return; } AccountingFutureCallback callback = new AccountingFutureCallback(mutation, sequenceId); Futures.addCallback(issueRequest(mutation), callback, heapSizeExecutor); }
Source:
<code><START> public BoxRequestsMetadata.UpdateFileMetadata getUpdateMetadataRequest(String id, String scope, String template) { <END> BoxRequestsMetadata.UpdateFileMetadata request = new BoxRequestsMetadata.UpdateFileMetadata(getFileMetadataUrl(id, scope, template), mSession); return request; }</code><technical_language>I re-routing this new API is cleaner</technical_language>

Target:
public BoxRequestsMetadata.UpdateFileMetadata getUpdateMetadataRequest(String id, String scope, String template) { return getUpdateFileMetadataRequest(id, scope, template); }
Source:
<code>void testFilterInstances() { for (String region : view.unwrapApi(EC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); assert allResults.size() >= 0 : allResults.size(); <START> if (!allResults.isEmpty()) { <END> RunningInstance instance = getFirst(getFirst(allResults, null), null); assertNotNull(instance); Set<? extends Reservation<? extends RunningInstance>> filterResults = client.describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("key-name", instance.getKeyName()) .build()); assertNotNull(filterResults); assertTrue(!filterResults.isEmpty(), "No results found for filter, but there should be."); } } }</code><technical_language>Again: do legitimately expect results here</technical_language>

Target:
void testFilterInstances() { for (String region : view.unwrapApi(EC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); if (!allResults.isEmpty()) { RunningInstance instance = getFirst(getFirst(allResults, null), null); assertNotNull(instance); Set<? extends Reservation<? extends RunningInstance>> filterResults = client.describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("key-name", instance.getKeyName()) .build()); assertNotNull(filterResults); assertTrue(!filterResults.isEmpty(), "No results found for filter, but there should be."); } } }
Source:
<code>private void getInstalledFontList() { <START> final Set<String> browserFonts = new TreeSet<String>(); <END> JsArrayString candidates = userPrefs_.browserFixedWidthFonts().getGlobalValue(); for (String candidate: JsUtil.asIterable(candidates)) { if (FontDetector.isFontSupported(candidate)) { browserFonts.add(candidate); } } server_.getInstalledFonts(new ServerRequestCallback<JsArrayString>() { @Override public void onResponseReceived(JsArrayString fonts) { browserFonts.addAll(JsUtil.toList(fonts)); populateFontList(browserFonts.toArray(new String[browserFonts.size()])); fontFace_.insertValue(0, DEFAULT_FONT_NAME, DEFAULT_FONT_VALUE); String font = null; if (userPrefs_.serverEditorFontEnabled().getValue()) { font = userPrefs_.serverEditorFont().getValue(); } if (StringUtil.isNullOrEmpty(font)) { fontFace_.setValue(DEFAULT_FONT_VALUE); } else { fontFace_.setValue(font); preview_.setFont(font, true); } initialFontFace_ = StringUtil.notNull(fontFace_.getValue()); } @Override public void onError(ServerError error) { fontFace_.setLabel("Editor font:"); Debug.logError(error); } }); }</code><technical_language>leave out String in new, i.e. new TreeSet<>();</technical_language>

Target:
private void getInstalledFontList() { final Set<String> browserFonts = new TreeSet<>(); JsArrayString candidates = userPrefs_.browserFixedWidthFonts().getGlobalValue(); for (String candidate: JsUtil.asIterable(candidates)) { if (FontDetector.isFontSupported(candidate)) { browserFonts.add(candidate); } } server_.getInstalledFonts(new ServerRequestCallback<JsArrayString>() { @Override public void onResponseReceived(JsArrayString fonts) { browserFonts.addAll(JsUtil.toList(fonts)); populateFontList(browserFonts.toArray(new String[browserFonts.size()])); fontFace_.insertValue(0, DEFAULT_FONT_NAME, DEFAULT_FONT_VALUE); String font = null; if (userPrefs_.serverEditorFontEnabled().getValue()) { font = userPrefs_.serverEditorFont().getValue(); } if (StringUtil.isNullOrEmpty(font)) { fontFace_.setValue(DEFAULT_FONT_VALUE); } else { fontFace_.setValue(font); preview_.setFont(font, true); } initialFontFace_ = StringUtil.notNull(fontFace_.getValue()); } @Override public void onError(ServerError error) { fontFace_.setLabel("Editor font:"); Debug.logError(error); } }); }
Source:
<code>public Map<String, SourceFile> processImports(String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface) { Map<String, SourceFile> imports = new HashMap<>(); SourceFile.FileType fileType = SourceFile.FileType.DOCKSTORE_WDL; final File tempDesc; try { tempDesc = File.createTempFile("temp", ".wdl", Files.createTempDir()); Files.asCharSink(tempDesc, StandardCharsets.UTF_8).write(content); List<String> lines = FileUtils.readLines(tempDesc, StandardCharsets.UTF_8); ArrayList<String> importPaths = new ArrayList<>(); Pattern p = Pattern.compile("^import\\s+\"(\\S+)\""); for (String line : lines) { Matcher m = p.matcher(line); while (m.find()) { String match = m.group(1); if (!match.startsWith("http://") && !match.startsWith("https://")) { importPaths.add(match.replaceFirst("file://", "")); } } } for (String importPath : importPaths) { SourceFile importFile = new SourceFile(); final String fileResponse = sourceCodeRepoInterface.readGitRepositoryFile(fileType, version, importPath); if (fileResponse == null) { SourceCodeRepoInterface.LOG.error("Could not read: " + importPath); continue; } importFile.setContent(fileResponse); importFile.setPath(importPath); importFile.setType(SourceFile.FileType.DOCKSTORE_WDL); imports.put(importFile.getPath(), importFile); } for (SourceFile sf : imports.values()) { <START> imports.putAll(processImports(sf.getContent(), version, sourceCodeRepoInterface)); <END> } } catch (IOException e) { throw new CustomWebApplicationException("Internal server error, out of space", HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE); } return imports; }</code><technical_language>I if this is possible, a good WDL practice, if a imported b, b imported a, lead infinite loop, eventually bring Dockstore? I a catch, I if late recover from</technical_language>

Target:
public Map<String, SourceFile> processImports(String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface) { return processImports(content, version, sourceCodeRepoInterface, new HashMap<>()); }
Source:
<code>public WebDavHarvester(String address, Set<Listener> initialListeners) { super(5L); Validate.notEmpty(address, "address {location} cannot be empty"); persistenceProvider = new FileSystemPersistenceProvider("harvest/webdav"); webdavListener = new HarvestedResourceListener(); initialListeners.forEach(this::registerListener); <START> persistentKey = DigestUtils.sha1Hex(address); <END> observer = getCachedObserverOrCreate(persistentKey, address); super.init(); }</code><technical_language>avoid sha1 in new code. Hashing.sha256().hashString(...) google libraries instead</technical_language>

Target:
public WebDavHarvester(String address, Set<Listener> initialListeners) { super(5L); Validate.notEmpty(address, "Argument address may not be empty"); persistenceProvider = new FileSystemPersistenceProvider("harvest/webdav"); webdavListener = new HarvestedResourceListener(); initialListeners.forEach(this::registerListener); persistentKey = Hashing.sha256().hashString(address, StandardCharsets.UTF_8).toString(); observer = getCachedObserverOrCreate(persistentKey, address); super.init(); }
Source:
<code><START> private <A> Optional<A> getAnnotation(Class<A> annotationClass) { <END> return Optional.ofNullable((A) annotations.get(annotationClass)); }</code><technical_language>suggestion private <A extends Annotation> Optional<A> getAnnotation(Class<A> annotationClass) { Avoids "suspicious call" warning annotations.get</technical_language>

Target:
private <A extends Annotation> Optional<A> getAnnotation(Class<A> annotationClass) { return Optional.ofNullable(annotationClass.cast(annotations.get(annotationClass))); }
Source:
<code>private void executePostLoad(Object instance) { ClassInfo classInfo = metadata.classInfo(instance); MethodInfo postLoadMethod = classInfo.postLoadMethodOrNull(); if (postLoadMethod != null) { final Method method = classInfo.getMethod(postLoadMethod); try { method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { <START> logger.error("Failed to execute post load method", e); <END> } } }</code><technical_language>PostLoad method respect "contract" (public, arg method), level java exceptions thrown IllegalArgumentException: wrong number of arguments some guidance useful "Cannot call PostLoad annotated method {method fqn}. is public arguments"</technical_language>

Target:
private void executePostLoad(Object instance) { ClassInfo classInfo = metadata.classInfo(instance); MethodInfo postLoadMethod = classInfo.postLoadMethodOrNull(); if (postLoadMethod != null) { final Method method = classInfo.getMethod(postLoadMethod); try { method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { logger.warn("Cannot call PostLoad annotated method on class {}. " + "Make sure it is public and has no arguments", method.getName(), classInfo.name(), e); } } }
Source:
<code>public void dispatchHandle(final Command command) { if (command instanceof DeletePresentationModelCommand) { handleDeletePresentationModelCommand((DeletePresentationModelCommand) command); } else if (command instanceof CreatePresentationModelCommand) { handleCreatePresentationModelCommand((CreatePresentationModelCommand) command); } else if (command instanceof ValueChangedCommand) { handleValueChangedCommand((ValueChangedCommand) command); } else if (command instanceof AttributeMetadataChangedCommand) { handleAttributeMetadataChangedCommand((AttributeMetadataChangedCommand) command); } else { <START> LOG.info("C: cannot handle unknown command '{}'", command ); <END> } }</code><technical_language>This error</technical_language>

Target:
public void dispatchHandle(final Command command) { if (command instanceof DeletePresentationModelCommand) { handleDeletePresentationModelCommand((DeletePresentationModelCommand) command); } else if (command instanceof CreatePresentationModelCommand) { handleCreatePresentationModelCommand((CreatePresentationModelCommand) command); } else if (command instanceof ValueChangedCommand) { handleValueChangedCommand((ValueChangedCommand) command); } else if (command instanceof AttributeMetadataChangedCommand) { handleAttributeMetadataChangedCommand((AttributeMetadataChangedCommand) command); } else { LOG.error("C: cannot handle unknown command '{}'", command ); } }
Source:
<code>public Builder mergeFrom(io.netty.example.worldclock.WorldClockProtocol.Location other) { if (other == io.netty.example.worldclock.WorldClockProtocol.Location.getDefaultInstance()) { <START> return this; <END> } if (other.hasContinent()) { setContinent(other.getContinent()); } if (other.hasCity()) { bitField0_ |= 0x00000002; city_ = other.city_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; }</code><technical_language>4 spaces</technical_language>

Target:
public Builder mergeFrom(io.netty.example.worldclock.WorldClockProtocol.Location other) { if (other == io.netty.example.worldclock.WorldClockProtocol.Location.getDefaultInstance()) return this; if (other.hasContinent()) { setContinent(other.getContinent()); } if (other.hasCity()) { bitField0_ |= 0x00000002; city_ = other.city_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; }
Source:
<code>public void sanitizeForSaving() { this.courseId = this.courseId.trim(); this.commentText = Sanitizer.sanitizeTextField(this.commentText); this.courseId = Sanitizer.sanitizeForHtml(courseId); <START> this.giverEmail = Sanitizer.sanitizeForHtml(giverEmail); <END> if (commentText != null) { String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n<br>"); this.commentText = new Text(sanitizedText); } if (recipientType != null) { sanitizeForVisibilityOptions(); } removeIrrelevantVisibilityOptions(); }</code><technical_language>if recipients changed, this changed</technical_language>

Target:
public void sanitizeForSaving() { this.courseId = this.courseId.trim(); this.commentText = Sanitizer.sanitizeTextField(this.commentText); this.courseId = Sanitizer.sanitizeForHtml(courseId); this.giverEmail = Sanitizer.sanitizeForHtml(giverEmail); if (recipients != null) { HashSet<String> sanitizedRecipients = new HashSet<String>(); for (String recipientId : recipients) { sanitizedRecipients.add(Sanitizer.sanitizeForHtml(recipientId)); } recipients = sanitizedRecipients; } if (commentText != null) { String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n<br>"); this.commentText = new Text(sanitizedText); } if (recipientType != null) { sanitizeForVisibilityOptions(); } removeIrrelevantVisibilityOptions(); }
Source:
<code>public void process(EntityUpdatedMessage message) { rotateTelescope(); String eid = message.getEntityId(); Content content = resolveId(idCodec.decode(eid).longValue()); if (content == null) { log.warn("{} resolved null/not Content for {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); return; } if (filter.apply(content)) { log.debug("{} updating equivalence: {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); try { equivUpdater.updateEquivalences(content, telescope); } catch (ContainerSummaryRequiredException e) { <START> log.error(e.getMessage()); <END> } } else { log.trace("{} skipping equiv update: {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); } }</code><technical_language>obv next step rerun equiv container, re-try item..</technical_language>

Target:
public void process(EntityUpdatedMessage message) { rotateTelescope(); String eid = message.getEntityId(); Content content = resolveId(idCodec.decode(eid).longValue()); if (content == null) { log.warn("{} resolved null/not Content for {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); return; } if (filter.apply(content)) { log.debug("{} updating equivalence: {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); try { equivUpdater.updateEquivalences(content, telescope); } catch (ContainerSummaryRequiredException containerSummaryError) { log.trace("Container summary required, attempting to run", containerSummaryError); try { Maybe<Identified> maybeContainer = contentResolver.findByCanonicalUris( ImmutableSet.of(containerSummaryError.getItem() .getContainer() .getUri())).getFirstValue(); if (maybeContainer.hasValue()) { Identified container = maybeContainer.requireValue(); equivUpdater.updateEquivalences((Content) container, telescope); equivUpdater.updateEquivalences(containerSummaryError.getItem(), telescope); } else { log.error("Container summary missing AND container not resolved. Unable to " + "run equivalence on item with ID: " + content.getId()); } } catch (Exception e) { log.error("Failed to rerun equivalence for missing container summary", e); } } } else { log.trace("{} skipping equiv update: {}", new Object[]{message.getMessageId(), message.getEntitySource(), message.getEntityType(), eid}); } }
Source:
<code>public void initTraceState(Map<String, Object> state) { Object traceId = state.get(Constants.HAWKULAR_APM_TRACEID); Object transaction = state.get(Constants.HAWKULAR_APM_TXN); Object level = state.get(Constants.HAWKULAR_APM_LEVEL); if (traceId != null) { setTraceId(traceId.toString()); } else { log.severe("Trace id has not been propagated"); } if (transaction != null) { setTransaction(transaction.toString()); } if (level != null) { <START> setReportingLevel(ReportingLevel.All.valueOf(level.toString())); <END> } }</code><technical_language>ReportingLevel.valueOf(....);</technical_language>

Target:
public void initTraceState(Map<String, Object> state) { Object traceId = state.get(Constants.HAWKULAR_APM_TRACEID); Object transaction = state.get(Constants.HAWKULAR_APM_TXN); Object level = state.get(Constants.HAWKULAR_APM_LEVEL); if (traceId != null) { setTraceId(traceId.toString()); } else { log.severe("Trace id has not been propagated"); } if (transaction != null) { setTransaction(transaction.toString()); } if (level != null) { setReportingLevel(ReportingLevel.valueOf(level.toString())); } }
Source:
<code>public static Page submit(HtmlForm htmlForm, HtmlElement submitElement) throws IOException { final HtmlPage htmlPage = (HtmlPage) htmlForm.getPage(); final WebClient webClient = htmlPage.getWebClient(); try { if (submitElement != null && !(submitElement instanceof SubmittableElement)) { <START> return submitElement.click(); <END> } try { htmlForm.submit((SubmittableElement) submitElement); } finally { webClient.loadDownloadedResponses(); Page resultPage = webClient.getCurrentWindow().getEnclosedPage(); if (resultPage == htmlPage) { return submitElement.click(); } return resultPage; } } finally { WebClientUtil.waitForJSExec(webClient); } }</code><technical_language>HtmlElementUtil.click(submitElement) a choice</technical_language>

Target:
public static Page submit(HtmlForm htmlForm, HtmlElement submitElement) throws IOException { final HtmlPage htmlPage = (HtmlPage) htmlForm.getPage(); final WebClient webClient = htmlPage.getWebClient(); try { if (submitElement != null && !(submitElement instanceof SubmittableElement)) { return submitElement.click(); } try { htmlForm.submit((SubmittableElement) submitElement); } finally { webClient.loadDownloadedResponses(); Page resultPage = webClient.getCurrentWindow().getEnclosedPage(); if (resultPage == htmlPage) { return HtmlElementUtil.click(submitElement); } else { return resultPage; } } } finally { WebClientUtil.waitForJSExec(webClient); } }
Source:
<code>public void testLeftBubblePositionAfterMoveX() { <START> Float expectedXLeft = 5.0f; <END> Float expectedYLeft = EXPECTED_Y_STD; sprite.look.setX(SPRITE_X_FOR_MOVE_X); ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(expectedXLeft, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(expectedYLeft, bubbleActor.calculateImageY(CALC_Y_LEFT)); }</code><technical_language>Is special this value? Else declare this variable a constant</technical_language>

Target:
public void testLeftBubblePositionAfterMoveX() { sprite.look.setX(SPRITE_X_FOR_MOVE_X); ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(EXPECTED_X_LEFT_FOR_MOVE_X, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(EXPECTED_Y_STD, bubbleActor.calculateImageY(CALC_Y_LEFT)); }
Source:
<code>public void open() { try { if (!mDevice.isScreenOn()) { mDevice.wakeUp(); } } catch (RemoteException e) { throw new RuntimeException("Could not unlock the device.", e); } if (mDevice.hasObject(By.res("com.android.systemui", "keyguard_bottom_area"))) { mDevice.pressMenu(); mDevice.waitForIdle(); } String pkg = getPackage(); long launchInitiationTimeMs = System.currentTimeMillis(); if (mFavorShellCommands) { String output = null; try { Intent intent = mInstrumentation .getContext() .getPackageManager() .getLaunchIntentForPackage(pkg); mInstrumentation.getContext().startActivity(intent); Log.i(LOG_TAG, String.format("Sent command to launch: %s", pkg)); } catch (ActivityNotFoundException e) { throw new RuntimeException(String.format("Failed to find package: %s", pkg), e); } } else { String id = getLauncherName(); <START> registerWatcher( AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); if (!mDevice.hasObject(By.pkg(pkg).depth(0))) { mLauncherStrategy.launch(id, pkg); Log.i(LOG_TAG, "Launched package: id=" + id + ", pkg=" + pkg); } removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); <END> } if (!mDevice.wait(Until.hasObject(By.pkg(pkg).depth(0)), mLaunchTimeout)) { throw new IllegalStateException( String.format( "Did not find package, %s, in foreground after %d ms.", pkg, System.currentTimeMillis() - launchInitiationTimeMs)); } }</code><technical_language>I this needs registered for favorShellCommands version without, do this if-else statement</technical_language>

Target:
public void open() { try { if (!mDevice.isScreenOn()) { mDevice.wakeUp(); } } catch (RemoteException e) { throw new RuntimeException("Could not unlock the device.", e); } if (mDevice.hasObject(By.res("com.android.systemui", "keyguard_bottom_area"))) { mDevice.pressMenu(); mDevice.waitForIdle(); } String pkg = getPackage(); long launchInitiationTimeMs = System.currentTimeMillis(); registerWatcher( AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); if (mFavorShellCommands) { String output = null; try { Intent intent = mInstrumentation .getContext() .getPackageManager() .getLaunchIntentForPackage(pkg); mInstrumentation.getContext().startActivity(intent); Log.i(LOG_TAG, String.format("Sent command to launch: %s", pkg)); } catch (ActivityNotFoundException e) { removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); throw new RuntimeException(String.format("Failed to find package: %s", pkg), e); } } else { String id = getLauncherName(); if (!mDevice.hasObject(By.pkg(pkg).depth(0))) { mLauncherStrategy.launch(id, pkg); Log.i(LOG_TAG, "Launched package: id=" + id + ", pkg=" + pkg); } } if (!mDevice.wait(Until.hasObject(By.pkg(pkg).depth(0)), mLaunchTimeout)) { removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); throw new IllegalStateException( String.format( "Did not find package, %s, in foreground after %d ms.", pkg, System.currentTimeMillis() - launchInitiationTimeMs)); } removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); }
Source:
<code>public void testDelete() { try { fixture.setDirectory(testResourcesDir); fixture.copyTo(txtFilename, copyFilename); fixture.delete(copyFilename); <START> } catch (IOException ioe) { <END> fail("Should not happen: " + ioe.getMessage()); } catch (SlimFixtureException sfe) { fail("Should not happen: " + sfe.getMessage()); } }</code><technical_language>Please merge catch blocks one. is catch Exception instead of SlimFixtureException</technical_language>

Target:
public void testDelete() { try { fixture.setDirectory(testResourcesDir); fixture.copyTo(txtFilename, copyFilename); fixture.delete(copyFilename); } catch (Exception ex) { fail("Should not happen: " + ex.getMessage()); } }
Source:
<code>public OffsetFetchRequest build(short version) { if (isAllTopicPartitions() && version < 2) { throw new UnsupportedVersionException("The broker only supports OffsetFetchRequest " + "v" + version + ", but we need v2 or newer to request all topic partitions."); } if (data.requireStable() && version < 7) { <START> log.warn("Fallback the requireStable flag to false as broker " + <END> "only supports OffsetFetchRequest version {}. Need " + "v7 or newer to enable this feature", version); return new OffsetFetchRequest(new OffsetFetchRequestData() .setGroupId(data.groupId()) .setTopics(data.topics()) .setRequireStable(false), version); } return new OffsetFetchRequest(data, version); }</code><technical_language>Is WARN level chatty? If a 2.5 client connects older broker, this message logged time a OffsetFetchRequest is send (that happen in rebalance? -- other occurrence?)</technical_language>

Target:
public OffsetFetchRequest build(short version) { if (isAllTopicPartitions() && version < 2) { throw new UnsupportedVersionException("The broker only supports OffsetFetchRequest " + "v" + version + ", but we need v2 or newer to request all topic partitions."); } if (data.requireStable() && version < 7) { log.info("Fallback the requireStable flag to false as broker " + "only supports OffsetFetchRequest version {}. Need " + "v7 or newer to enable this feature", version); return new OffsetFetchRequest(data.setRequireStable(false), version); } return new OffsetFetchRequest(data, version); }
Source:
<code>public ImmutableListValue<Living> targets() { <START> return new ImmutableSpongeListValue<>(Keys.TARGETS, ImmutableList.copyOf(this.value)); <END> }</code><technical_language>able call getValueGetter()</technical_language>

Target:
public ImmutableListValue<Living> targets() { return getValueGetter(); }
Source:
<code>public void patchAndCheckJsonFork() throws IOException { final String nidentifier = "id"; final String norganization = "organization"; final int identifier = 1; final String organization = "some organization"; final String porganization = "some patched organization"; <START> final MkAnswer first = new MkAnswer.Simple( <END> HttpURLConnection.HTTP_OK, Json.createObjectBuilder() .add(norganization, organization) .add(nidentifier, identifier) .build().toString() ); final MkAnswer second = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, Json.createObjectBuilder() .add(norganization, porganization) .add(nidentifier, identifier) .build().toString() ); final MkAnswer third = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, Json.createObjectBuilder() .add(norganization, organization) .add(nidentifier, identifier) .build().toString() ); final MkContainer container = new MkGrizzlyContainer().next(first).next(second).next(third) .start(); final MkContainer forksContainer = new MkGrizzlyContainer().start(); final RtRepo repo = new RtRepo( new MkGithub(), new ApacheRequest(forksContainer.home()), new Coordinates.Simple("test_user", "test_repo") ); final RtFork fork = new RtFork( new ApacheRequest(container.home()), repo, identifier ); fork.patch(Json.createObjectBuilder() .add(norganization, porganization) .add(nidentifier, identifier) .build() ); MatcherAssert.assertThat( fork.json().getString(norganization), Matchers.equalTo(porganization) ); container.stop(); forksContainer.stop(); }</code><technical_language>move this MkAnswer instantiating code a private method answer(org, identifier)</technical_language>

Target:
public void patchAndCheckJsonFork() throws IOException { final String original = "some organization"; final String patched = "some patched organization"; final MkContainer container = new MkGrizzlyContainer().next(answer(original)) .next(answer(patched)).next(answer(original)).start(); final MkContainer forksContainer = new MkGrizzlyContainer().start(); final RtRepo repo = new RtRepo( new MkGithub(), new ApacheRequest(forksContainer.home()), new Coordinates.Simple("test_user", "test_repo") ); final RtFork fork = new RtFork( new ApacheRequest(container.home()), repo, 1 ); fork.patch(fork(patched)); MatcherAssert.assertThat( fork.json().getString(ORGANIZATION), Matchers.equalTo(patched) ); container.stop(); forksContainer.stop(); }
Source:
<code>public void init() throws Exception { _handler = new RewriteHandler(); _handler.setRewriteRequestURI(true); _rule = new RewritePatternRule(); _rule.setPattern("/cheese/*"); _rule.setReplacement("/rule"); _fooRule = new RewritePatternRule(); _fooRule.setPattern("/cheese/bar/*"); _fooRule.setReplacement("/cheese/fooRule"); _fooContainerRule = new VirtualHostRuleContainer(); _fooContainerRule.setVirtualHosts(new String[]{"foo.com"}); _fooContainerRule.setRules(new Rule[]{_fooRule}); start(false); <START> _request.setHttpURI(HttpURI.build(_request.getHttpURI(), "/cheese/bar").asImmutable()); <END> _handler.setServer(_server); _handler.start(); }</code><technical_language>Remove asImmutable() this test class</technical_language>

Target:
public void init() throws Exception { _handler = new RewriteHandler(); _handler.setRewriteRequestURI(true); _rule = new RewritePatternRule(); _rule.setPattern("/cheese/*"); _rule.setReplacement("/rule"); _fooRule = new RewritePatternRule(); _fooRule.setPattern("/cheese/bar/*"); _fooRule.setReplacement("/cheese/fooRule"); _fooContainerRule = new VirtualHostRuleContainer(); _fooContainerRule.setVirtualHosts(new String[]{"foo.com"}); _fooContainerRule.setRules(new Rule[]{_fooRule}); start(false); _request.setHttpURI(HttpURI.build(_request.getHttpURI(), "/cheese/bar")); _handler.setServer(_server); _handler.start(); }
Source:
<code>void writeBranches(FileReftableStack stack, String template, int start, int N) throws IOException { for (int i = 0; i < N; i++) { while (true) { final long next = stack.getMergedReftable().maxUpdateIndex() + 1; <START> System.err.println(next + template); <END> String name = String.format(template, Integer.valueOf(start + i)); Ref r = newRef(name, ObjectId.zeroId()); boolean ok = stack.addReftable(rw -> { rw.setMinUpdateIndex(next).setMaxUpdateIndex(next).begin() .writeRef(r); }); if (ok) { break; } } } }</code><technical_language>remove debug trace</technical_language>

Target:
void writeBranches(FileReftableStack stack, String template, int start, int N) throws IOException { for (int i = 0; i < N; i++) { while (true) { final long next = stack.getMergedReftable().maxUpdateIndex() + 1; String name = String.format(template, Integer.valueOf(start + i)); Ref r = newRef(name, ObjectId.zeroId()); boolean ok = stack.addReftable(rw -> { rw.setMinUpdateIndex(next).setMaxUpdateIndex(next).begin() .writeRef(r); }); if (ok) { break; } } } }
Source:
<code>public OpenTok build() { <START> if (this.apiUrl != null && this.proxy != null) { <END> OpenTok openTok = new OpenTok(apiKey, apiSecret); HttpClient.Builder clientBuilder = new HttpClient.Builder(apiKey, apiSecret).apiUrl(apiUrl) .proxy(proxy); openTok.setClient(clientBuilder.build()); return openTok; } else if (this.apiUrl != null) { OpenTok openTok = new OpenTok(apiKey, apiSecret); HttpClient.Builder clientBuilder = new HttpClient.Builder(apiKey, apiSecret).apiUrl(apiUrl); openTok.setClient(clientBuilder.build()); return openTok; } else return new OpenTok(apiKey, apiSecret); }</code><technical_language>This moving defaultApiUrl HttpClient class. a constant too</technical_language>

Target:
public OpenTok build() { HttpClient.Builder clientBuilder = new HttpClient.Builder(apiKey, apiSecret); if (this.apiUrl != null) { clientBuilder.apiUrl(this.apiUrl); } if (this.proxy != null) { clientBuilder.proxy(this.proxy); } return new OpenTok(this.apiKey, this.apiSecret, clientBuilder.build()); }
Source:
<code>private void deliverAudioLevelsToMediaStream() { <START> final AudioMediaStreamImpl stream = mediaStream.get(); <END> final long[] latestAudioLevels = levels.getAndSet(null); if (stream != null && latestAudioLevels != null) { stream.audioLevelsReceived(latestAudioLevels); } }</code><technical_language>is concern of mediaStream checked schedule call deliverAudioLevelsToMediaStream? technically i this run in setting new media stream in setMediaStream clearing audio levels in setMediaStream</technical_language>

Target:
private void deliverAudioLevelsToMediaStream() { if (!running.get()) { return; } final long[] latestAudioLevels = levels.getAndSet(null); if (latestAudioLevels != null) { mediaStream.audioLevelsReceived(latestAudioLevels); } }
Source:
<code>protected Object doReceive() { Assert.state(this.running.get(), () -> getComponentName() + " is not running"); AbstractFileInfo<F> file = poll(); while (file != null) { if (this.filter != null && this.filter.supportsSingleFileFiltering() && !this.filter.accept(file.getFileInfo())) { if (this.toBeReceived.size() > 0) { file = poll(); continue; } else { <START> break; <END> } } if (file != null) { try { String remotePath = remotePath(file); Session<?> session = this.remoteFileTemplate.getSession(); try { return getMessageBuilderFactory() .withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .setHeader(FileHeaders.REMOTE_HOST_PORT, session.getHostPort()) .setHeader(FileHeaders.REMOTE_FILE_INFO, this.fileInfoJson ? file.toJson() : file); } catch (IOException e) { throw new UncheckedIOException("IOException when retrieving " + remotePath, e); } } catch (RuntimeException e) { resetFilterIfNecessary(file); throw e; } } } return null; }</code><technical_language>Grate! I need if (file != null) more this</technical_language>

Target:
protected Object doReceive() { Assert.state(this.running.get(), () -> getComponentName() + " is not running"); AbstractFileInfo<F> file = poll(); while (file != null) { if (this.filter != null && this.filter.supportsSingleFileFiltering() && !this.filter.accept(file.getFileInfo())) { if (this.toBeReceived.size() > 0) { file = poll(); continue; } else { break; } } try { String remotePath = remotePath(file); Session<?> session = this.remoteFileTemplate.getSession(); try { return getMessageBuilderFactory() .withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .setHeader(FileHeaders.REMOTE_HOST_PORT, session.getHostPort()) .setHeader(FileHeaders.REMOTE_FILE_INFO, this.fileInfoJson ? file.toJson() : file); } catch (IOException e) { throw new UncheckedIOException("IOException when retrieving " + remotePath, e); } } catch (RuntimeException e) { resetFilterIfNecessary(file); throw e; } } return null; }
Source:
<code>private String getPrimaryActionText() { switch (getPrimaryAction()) { case SUBMIT_FOR_REVIEW: return getString(R.string.submit_for_review); case PUBLISH_NOW: return getString(R.string.button_publish); case SCHEDULE: return getString(R.string.schedule_verb); case UPDATE: return getString(R.string.update_verb); case SAVE: return getString(R.string.save); } <START> return getString(R.string.save); <END> }</code><technical_language>I this line is technically unreachable, right? want follow fail fast principle throw exception here. Imagine forgets "return" keyword. This code continue work app in undefined state. Wdyt</technical_language>

Target:
private String getPrimaryActionText() { switch (getPrimaryAction()) { case SUBMIT_FOR_REVIEW: return getString(R.string.submit_for_review); case PUBLISH_NOW: return getString(R.string.button_publish); case SCHEDULE: return getString(R.string.schedule_verb); case UPDATE: return getString(R.string.update_verb); case SAVE: return getString(R.string.save); } throw new IllegalStateException( "Switch in getPrimaryActionText is missing a required case or the case is missing \"return\" keyword "); }
Source:
<code>public synchronized void addChild(AbstractCalledFunction child, AggregatedCalledFunction aggregatedChild) { <START> fSelfTime -= aggregatedChild.getDuration(); <END> if (child.getDepth() >= 0) { aggregatedChild.getFunctionStatistics().update(child); } AggregatedCalledFunction node = fChildren.get(aggregatedChild.getSymbol()); if (node == null) { fChildren.put(aggregatedChild.getSymbol(), aggregatedChild); } else { merge(node, aggregatedChild); } }</code><technical_language>time decremented</technical_language>

Target:
public synchronized void addChild(AbstractCalledFunction child, AggregatedCalledFunction aggregatedChild) { if (child.getDepth() >= 0) { fSelfTime -= aggregatedChild.getDuration(); aggregatedChild.getFunctionStatistics().update(child); } AggregatedCalledFunction node = fChildren.get(aggregatedChild.getSymbol()); if (node == null) { fChildren.put(aggregatedChild.getSymbol(), aggregatedChild); } else { merge(node, aggregatedChild); } }
Source:
<code>public void testManualImmediateRuleWithActions() throws InterruptedException { RetentionRule testRule = createImmediateRuleMillis(RetentionRule.ApplicationPolicy.MANUAL, 100L, null, Arrays.asList("Document.Trash")); file = service.attachRule(file, testRule, session); assertTrue(session.isRecord(file.getRef())); assertTrue(session.isUnderRetentionOrLegalHold(file.getRef())); <START> awaitRetentionExpiration(1000L); <END> file = session.getDocument(file.getRef()); assertFalse(session.isUnderRetentionOrLegalHold(file.getRef())); assertTrue(file.isTrashed()); }</code><technical_language>replaced 1_000 i L litteral is needed (awaitRetentionExpiration takes a primitif type), i awaitRetentionExpiration(1_000); code compile</technical_language>

Target:
public void testManualImmediateRuleWithActions() throws InterruptedException { RetentionRule testRule = createImmediateRuleMillis(RetentionRule.ApplicationPolicy.MANUAL, 100, null, Arrays.asList("Document.Trash")); file = service.attachRule(file, testRule, session); assertTrue(session.isRecord(file.getRef())); assertTrue(session.isUnderRetentionOrLegalHold(file.getRef())); awaitRetentionExpiration(1000); file = session.getDocument(file.getRef()); assertFalse(session.isUnderRetentionOrLegalHold(file.getRef())); assertTrue(file.isTrashed()); }
Source:
<code>public void init() { <START> LOGGER.debug("Configuring monitor for {}", monitoredDirectory); <END> security.runAsAdmin( () -> { CompletableFuture.runAsync(this::configure, configurationExecutor); return null; }); }</code><technical_language>this "Initializing monitor for..." distinguish init() configure() method below</technical_language>

Target:
public void init() { CDM_LOGGER.debug("Initializing monitor for {}", monitoredDirectory); security.runAsAdmin( () -> { CompletableFuture.runAsync(this::configure, configurationExecutor); return null; }); }
Source:
<code><START> public RxSharedPreferences(final SharedPreferences sharedPreferences) { <END> this.sharedPreferences = checkNotNull(sharedPreferences, "sharedPreferences == null"); this.changedKeys = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> subscriber) { final OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { subscriber.onNext(key); } }; Subscription subscription = Subscriptions.create(new Action0() { @Override public void call() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } }); subscriber.add(subscription); sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } }).share(); }</code><technical_language>This private forced create. I add param null checks. Oops</technical_language>

Target:
private RxSharedPreferences(final SharedPreferences sharedPreferences) { this.sharedPreferences = checkNotNull(sharedPreferences, "sharedPreferences == null"); this.changedKeys = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> subscriber) { final OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { subscriber.onNext(key); } }; Subscription subscription = Subscriptions.create(new Action0() { @Override public void call() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } }); subscriber.add(subscription); sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } }).share(); }
Source:
<code>public Response getWorkflowZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow; if (user.isPresent()) { workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkCanReadWorkflow(user.get(), workflow); } else { workflow = workflowDAO.findPublishedById(workflowId); checkEntry(workflow); } WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); Set<SourceFile> sourceFiles = workflowVersion.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { <START> return null; <END> } String fileName = workflow.getWorkflowPath().replaceAll("/", "-") + ".zip"; File returnZipFile = downloadAsZip(sourceFiles, fileName); return Response .ok(returnZipFile) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"") .build(); }</code><technical_language>return null do -- code returned? I if explicitly return HTTP status code, I if this a 5xx a 4xx</technical_language>

Target:
public Response getWorkflowZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow; if (user.isPresent()) { workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkCanReadWorkflow(user.get(), workflow); } else { workflow = workflowDAO.findPublishedById(workflowId); checkEntry(workflow); } WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); Set<SourceFile> sourceFiles = workflowVersion.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { throw new CustomWebApplicationException("no files found to zip", HttpStatus.SC_NO_CONTENT); } String fileName = workflow.getWorkflowPath().replaceAll("/", "-") + ".zip"; return Response.ok().entity((StreamingOutput)output -> writeStreamAsZip(sourceFiles, output)) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build(); }