auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected Void doInBackground() throws Exception { try { List<FileSearch.AttributeType> attrsForGroupingAndSorting = new ArrayList<>(); attrsForGroupingAndSorting.add(groupingAttr); <START> attrsForGroupingAndSorting.addAll(fileSort.getRequiredAttributes()); <END> SearchResults results = FileSearch.runFileSearchDebug(filters, groupingAttr, groupSortAlgorithm, fileSort, Case.getCurrentCase().getSleuthkitCase(), centralRepoDb); DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchCompleteEvent(results)); } catch (FileSearchException ex) { logger.log(Level.SEVERE, "Error running file search test", ex); } return null; }</code><technical_language>This is longer needed - search method takes care of</technical_language>

Target:
protected Void doInBackground() throws Exception { try { SearchResults results = FileSearch.runFileSearchDebug(filters, groupingAttr, groupSortAlgorithm, fileSort, Case.getCurrentCase().getSleuthkitCase(), centralRepoDb); DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchCompleteEvent(results)); } catch (FileSearchException ex) { logger.log(Level.SEVERE, "Error running file search test", ex); } return null; }
Source:
<code>public void onNext(T element) { env.debug(this + "::onNext(" + element + ")"); if (subscription.isCompleted()) { <START> } else { <END> env.flop("Subscriber::onNext(" + element + ") called before Subscriber::onSubscribe"); } }</code><technical_language>weird? if(!subscription.isCompleted) env.flop( )</technical_language>

Target:
public void onNext(T element) { env.debug(String.format("%s::onNext(%s)", this, element)); if (!subscription.isCompleted()) { env.flop(String.format("Subscriber::onNext(%s) called before Subscriber::onSubscribe", element)); } }
Source:
<code><START> public void setProjectKey(String projectKey) { <END> this.projectKey = projectKey; }</code><technical_language>missed a @DataBoundSetter here</technical_language>

Target:
public void setProjectKey(String projectKey) { this.projectKey = StringUtils.trimToNull(projectKey); }
Source:
<code>public StringListType(String... rows) { <START> this(Arrays.asList(rows)); <END> }</code><technical_language>I this approach is creating a collection twice. prefer previous approach assigning newly created collection typeDetails</technical_language>

Target:
public StringListType(String... rows) { typeDetails = Arrays.asList(rows); }
Source:
<code>protected boolean skipLoadForWriteCommand(WriteCommand cmd, Object key, InvocationContext ctx) { if (transactional) { if (!ctx.isOriginLocal() && cmd.loadType() != VisitableCommand.LoadType.OWNER) { return true; } } else { switch (cmd.loadType()) { case DONT_LOAD: return true; case PRIMARY: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } if (!cdl.localNodeIsPrimaryOwner(key)) { if (trace) { log.tracef("Skip load for command %s. This node is not the primary owner of %s", cmd, toStr(key)); } return true; } break; case OWNER: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } List<Address> owners = cdl.getOwners(key); int index = owners == null ? 0 : owners.indexOf(cdl.getAddress()); if (index != 0 && (index < 0 || ctx.isOriginLocal())) { if (trace) { <START> log.tracef("Skip load for command %s. This node is not the primary owner or backup (and not origin) of %s", cmd, toStr(key)); <END> } return true; } break; } } return super.skipLoadForWriteCommand(cmd, key, ctx); }</code><technical_language>split this separate separate messages, "local command primary" "remote command owner"</technical_language>

Target:
protected boolean skipLoadForWriteCommand(WriteCommand cmd, Object key, InvocationContext ctx) { if (transactional) { if (!ctx.isOriginLocal() && cmd.loadType() != VisitableCommand.LoadType.OWNER) { return true; } } else { switch (cmd.loadType()) { case DONT_LOAD: return true; case PRIMARY: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } if (!cdl.localNodeIsPrimaryOwner(key)) { if (trace) { log.tracef("Skip load for command %s. This node is not the primary owner of %s", cmd, toStr(key)); } return true; } break; case OWNER: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } List<Address> owners = cdl.getOwners(key); int index = owners == null ? 0 : owners.indexOf(cdl.getAddress()); if (index != 0 && (index < 0 || ctx.isOriginLocal())) { if (trace) { log.tracef("Skip load for command %s. This node is neither the primary owner nor non-origin backup of %s", cmd, toStr(key)); } return true; } break; } } return super.skipLoadForWriteCommand(cmd, key, ctx); }
Source:
<code>private void buildStorageEngine() { assertNonNull(configuration, "The AxonServerConfiguration is a hard requirement and should be provided"); assertNonNull(platformConnectionManager, "The PlatformConnectionManager is a hard requirement and should be provided"); AxonDBClient axonDBClient = new AxonDBClient(configuration, platformConnectionManager); super.storageEngine(AxonIQEventStorageEngine.builder() .snapshotSerializer(snapshotSerializer) .upcasterChain(upcasterChain) <START> .snapshotFilter(snapshotFilter) <END> .eventSerializer(eventSerializer) .configuration(configuration) .eventStoreClient(axonDBClient) .converter(new GrpcMetaDataConverter(eventSerializer)) .build()); }</code><technical_language>check if snapshotFilter is null</technical_language>

Target:
private void buildStorageEngine() { assertNonNull(configuration, "The AxonServerConfiguration is a hard requirement and should be provided"); assertNonNull(platformConnectionManager, "The PlatformConnectionManager is a hard requirement and should be provided"); AxonServerEventStoreClient eventStoreClient = new AxonServerEventStoreClient(configuration, platformConnectionManager); super.storageEngine(AxonIQEventStorageEngine.builder() .snapshotSerializer(snapshotSerializer) .upcasterChain(upcasterChain) .snapshotFilter(snapshotFilter) .eventSerializer(eventSerializer) .configuration(configuration) .eventStoreClient(eventStoreClient) .converter(new GrpcMetaDataConverter(eventSerializer)) .build()); }
Source:
<code>public CompletableFuture<List<PlayerAchievement>> getPlayerAchievements(Integer playerId) { int currentPlayerId = playerService.getCurrentPlayer().orElseThrow(() -> new IllegalStateException("Player has to be set")).getId(); if (Objects.equals(currentPlayerId, playerId)) { if (readOnlyPlayerAchievements.isEmpty()) { CompletableFuture<List<PlayerAchievement>> achievmentsLoadedFuture = new CompletableFuture<>(); reloadAchievements(achievmentsLoadedFuture); <START> return achievmentsLoadedFuture; <END> } return CompletableFuture.completedFuture(readOnlyPlayerAchievements); } return fafService.getPlayerAchievements(playerId); }</code><technical_language>return reloadAchievements(); method create future. in postConstruct() ignore return value</technical_language>

Target:
public CompletableFuture<List<PlayerAchievement>> getPlayerAchievements(Integer playerId) { int currentPlayerId = playerService.getCurrentPlayer().orElseThrow(() -> new IllegalStateException("Player has to be set")).getId(); if (Objects.equals(currentPlayerId, playerId)) { if (readOnlyPlayerAchievements.isEmpty()) { return reloadAchievements(); } return CompletableFuture.completedFuture(readOnlyPlayerAchievements); } return fafService.getPlayerAchievements(playerId); }
Source:
<code>protected void loadDefaultConfigurationFromClasspath(String defaultConfigFile) { try { LOGGER.info("Loading '" + defaultConfigFile + "' from classpath."); configurationUrl = Config.class.getClassLoader().getResource(defaultConfigFile); if (configurationUrl == null) { <START> throw new HazelcastException("Could not find '" + defaultConfigFile + "' in the classpath!" <END> + "This may be due to a wrong-packaged or corrupted jar file."); } in = Config.class.getClassLoader().getResourceAsStream(defaultConfigFile); if (in == null) { throw new HazelcastException("Could not load '" + defaultConfigFile + "' from classpath"); } } catch (RuntimeException e) { throw new HazelcastException(e); } }</code><technical_language>Minor suggestion: Consider String.format(), like: String.format"Could find '%s' in classpath!", defaultConfigFile) (in places concatenate exception message)</technical_language>

Target:
protected void loadDefaultConfigurationFromClasspath(String defaultConfigFile) { try { LOGGER.info(String.format("Loading '%s' from the classpath.", defaultConfigFile)); configurationUrl = Config.class.getClassLoader().getResource(defaultConfigFile); if (configurationUrl == null) { throw new HazelcastException(String.format("Could not find '%s' in the classpath! This may be due to a " + "wrong-packaged or corrupted jar file.", defaultConfigFile)); } in = Config.class.getClassLoader().getResourceAsStream(defaultConfigFile); if (in == null) { throw new HazelcastException(String.format("Could not load '%s' from the classpath", defaultConfigFile)); } } catch (RuntimeException e) { throw new HazelcastException(e); } }
Source:
<code>public void addToOrderBook(Order order) { <START> if (order instanceof BuyOrder) { ArrayList<Order> orders; if (buyOrders.containsKey(order.getStockSymbol())) { orders = buyOrders.get(order.getStockSymbol()); } else { orders = new ArrayList<Order>(); } orders.add(order); buyOrders.put(order.getStockSymbol(), orders); } else { ArrayList<Order> orders; if (sellOrders.containsKey(order.getStockSymbol())) { orders = sellOrders.get(order.getStockSymbol()); } else { orders = new ArrayList<Order>(); } orders.add(order); sellOrders.put(order.getStockSymbol(), orders); } <END> }</code><technical_language>work, extract method combine two</technical_language>

Target:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { addToOrders(buyOrders, order); } else { addToOrders(sellOrders, order); } }
Source:
<code>public TestCase(@JsonProperty(value = "before", required = true) List<Request> setupRequestList, @JsonProperty(value = "request", required = true) Request request, @JsonProperty(value = "after", required = true) List<Request> tearDownRequestList, @JsonProperty(value = "assertions", required = true) List<RequestAndResponseAssertion> assertions) { this.setupRequestList = Optional.fromNullable(tearDownRequestList).or(new ArrayList<Request>()); this.request = request; <START> this.tearDownRequestList = Optional.fromNullable(setupRequestList).or(new ArrayList<Request>()); <END> this.assertions = Optional.fromNullable(assertions).or(new ArrayList<RequestAndResponseAssertion>()); }</code><technical_language>emptyList() instead of new ArrayList(), in next line</technical_language>

Target:
public TestCase(@JsonProperty(value = "before", required = true) List<Request> setupRequestList, @JsonProperty(value = "request", required = true) Request request, @JsonProperty(value = "after", required = true) List<Request> tearDownRequestList, @JsonProperty(value = "assertions", required = true) List<RequestAndResponseAssertion> assertions) { this.setupRequestList = Optional.fromNullable(tearDownRequestList).or(Collections.<Request>emptyList()); this.request = request; this.tearDownRequestList = Optional.fromNullable(setupRequestList).or(Collections.<Request>emptyList()); this.assertions = Optional.fromNullable(assertions).or(Collections.<RequestAndResponseAssertion>emptyList()); }
Source:
<code>private void drawPieChart(PaintEvent e, double series[], Rectangle bounds) { int nelemSeries = series.length; double sumTotal = 0; for (int i = 0; i < nelemSeries; i++) { sumTotal += series[i]; } GC gc = e.gc; gc.setLineWidth(1); int pieWidth = Math.min(bounds.width - X_GAP, bounds.height); int pieX = bounds.x + (bounds.width - pieWidth) / 2; int pieY = bounds.y + (bounds.height - pieWidth) / 2; if (sumTotal == 0) gc.drawOval(pieX, pieY, pieWidth, pieWidth); else { double factor = 100 / sumTotal; int sweepAngle = 0; int incrementAngle = 0; int initialAngle = 90; for (int i = 0; i < nelemSeries; i++) { <START> gc.setBackground(new Color(e.display, chart.colorList.get(i))); <END> if (i == (nelemSeries - 1)) sweepAngle = 360 - incrementAngle; else { double angle = series[i] * factor * 3.6; sweepAngle = (int) Math.round(angle); } gc.fillArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); gc.drawArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); incrementAngle += sweepAngle; initialAngle += (-sweepAngle); } } }</code><technical_language>I accesser instead of accessing colorList directly. In fact sliceColor protected</technical_language>

Target:
private void drawPieChart(PaintEvent e, double series[], Rectangle bounds) { int nelemSeries = series.length; double sumTotal = 0; for (int i = 0; i < nelemSeries; i++) { sumTotal += series[i]; } GC gc = e.gc; gc.setLineWidth(1); int pieWidth = Math.min(bounds.width - X_GAP, bounds.height); int pieX = bounds.x + (bounds.width - pieWidth) / 2; int pieY = bounds.y + (bounds.height - pieWidth) / 2; if (sumTotal == 0) { gc.drawOval(pieX, pieY, pieWidth, pieWidth); } else { double factor = 100 / sumTotal; int sweepAngle = 0; int incrementAngle = 0; int initialAngle = 90; for (int i = 0; i < nelemSeries; i++) { gc.setBackground(new Color(e.display, chart.getSliceColor(i))); if (i == (nelemSeries - 1)) { sweepAngle = 360 - incrementAngle; } else { double angle = series[i] * factor * 3.6; sweepAngle = (int) Math.round(angle); } gc.fillArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); gc.drawArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); incrementAngle += sweepAngle; initialAngle += (-sweepAngle); } } }
Source:
<code>public Iterable<RevCommit> call() throws GitAPIException, NoHeadException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1 && maxCount > -1) walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip), MaxCountRevFilter.create(maxCount))); else if (skip > -1) walk.setRevFilter(SkipRevFilter.create(skip)); else if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } <START> if (onlyMerges) <END> walk.setRevFilter(RevFilter.ONLY_MERGES); if (noMerges) walk.setRevFilter(RevFilter.NO_MERGES); setCallable(false); return walk; }</code><technical_language>style nit: missing braces</technical_language>

Target:
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1 && maxCount > -1) walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip), MaxCountRevFilter.create(maxCount))); else if (skip > -1) walk.setRevFilter(SkipRevFilter.create(skip)); else if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } if (this.revFilter != null){ walk.setRevFilter(this.revFilter); } setCallable(false); return walk; }
Source:
<code>public void testCustomMetricsTransport() throws Exception { TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class); GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class); dag.addStream("o1.outport", o1.outport, o2.inport1); dag.setAttribute(LogicalPlan.METRICS_TRANSPORT, new TestMetricTransport("xyz")); StramLocalCluster lc = new StramLocalCluster(dag); StreamingContainerManager dnmgr = lc.dnmgr; StramAppContext appContext = new StramTestSupport.TestAppContext(); AppDataPushAgent pushAgent = new AppDataPushAgent(dnmgr, appContext); pushAgent.init(); pushAgent.pushData(); Assert.assertTrue(TestMetricTransport.messages.size() > 0); pushAgent.close(); String msg = TestMetricTransport.messages.get(0); <START> System.out.println("Got this message: " + msg); <END> Assert.assertTrue(msg.startsWith("xyz:")); }</code><technical_language>needed</technical_language>

Target:
public void testCustomMetricsTransport() throws Exception { TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class); GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class); dag.addStream("o1.outport", o1.outport, o2.inport1); dag.setAttribute(LogicalPlan.METRICS_TRANSPORT, new TestMetricTransport("xyz")); StramLocalCluster lc = new StramLocalCluster(dag); StreamingContainerManager dnmgr = lc.dnmgr; StramAppContext appContext = new StramTestSupport.TestAppContext(); AppDataPushAgent pushAgent = new AppDataPushAgent(dnmgr, appContext); pushAgent.init(); pushAgent.pushData(); Assert.assertTrue(TestMetricTransport.messages.size() > 0); pushAgent.close(); String msg = TestMetricTransport.messages.get(0); Assert.assertTrue(msg.startsWith("xyz:")); }
Source:
<code>public void shutdown() { try { logger.info("Stopping HTTP server."); shutdownHandler.shutdown(); shutdownHandler.awaitShutdown(HTTP_SHUTDOWN_GRACE_PERIOD_MILLIS); undertow.stop(); } catch (final Exception ie) { Thread.currentThread().interrupt(); } logger.info("Stopping thread pools."); mappingProcessors.values().forEach(ProcessingPool::stop); sinks.values().forEach(ProcessingPool::stop); <START> logger.info("Closing HDFS filesystem connection."); <END> try { FileSystem.closeAll(); } catch (final IOException ioe) { logger.warn("Failed to cleanly close HDFS file system.", ioe); } }</code><technical_language>needed here? HDFS specific sink responsible for closing</technical_language>

Target:
public void shutdown() { try { logger.info("Stopping HTTP server."); shutdownHandler.shutdown(); shutdownHandler.awaitShutdown(HTTP_SHUTDOWN_GRACE_PERIOD_MILLIS); undertow.stop(); } catch (final Exception ie) { Thread.currentThread().interrupt(); } logger.info("Stopping thread pools."); incomingRequestProcessingPool.stop(); sinks.values().forEach(ProcessingPool::stop); logger.info("Closing HDFS filesystem connection."); try { FileSystem.closeAll(); } catch (final IOException ioe) { logger.warn("Failed to cleanly close HDFS file system.", ioe); } }
Source:
<code>private static void addBuiltInFunction(Class<? extends FunctionExpression> f) throws Exception { BuiltInFunction d = f.getAnnotation(BuiltInFunction.class); if (d == null) { return; } int nArgs = d.args().length; BuiltInFunctionInfo value = new BuiltInFunctionInfo(f, d); <START> SINGLE_SIGNATURE_BUILT_IN_FUNCTION_MAP.put(value.getName(), value); <END> do { BuiltInFunctionKey key = new BuiltInFunctionKey(value.getName(), nArgs); if (BUILT_IN_FUNCTION_MAP.put(key, value) != null) { throw new IllegalStateException("Multiple " + value.getName() + " functions with " + nArgs + " arguments"); } } while (--nArgs >= 0 && d.args()[nArgs].defaultValue().length() > 0); while (--nArgs >= 0) { if (d.args()[nArgs].defaultValue().length() > 0) { throw new IllegalStateException("Function " + value.getName() + " has non trailing default value of '" + d.args()[nArgs].defaultValue() + "'. Only trailing arguments may have default values"); } } }</code><technical_language>adjust map initialization logic new annotation. Avoid "ABSTRACT" for "SINGLE_SIGNATURE_BUILT_IN_FUNCTION_MAP" "DERIVED" for "BUILT_IN_FUNCTION_MAP"</technical_language>

Target:
private static void addBuiltInFunction(Class<? extends FunctionExpression> f) throws Exception { BuiltInFunction d = f.getAnnotation(BuiltInFunction.class); if (d == null) { return; } int nArgs = d.args().length; BuiltInFunctionInfo value = new BuiltInFunctionInfo(f, d); if (d.classType() != FunctionParseNode.FunctionClassType.ABSTRACT) { BUILT_IN_FUNCTION_MULTIMAP.put(value.getName(), value); } if (d.classType() != FunctionParseNode.FunctionClassType.DERIVED) { do { BuiltInFunctionKey key = new BuiltInFunctionKey(value.getName(), nArgs); if (BUILT_IN_FUNCTION_MAP.put(key, value) != null) { throw new IllegalStateException("Multiple " + value.getName() + " functions with " + nArgs + " arguments"); } } while (--nArgs >= 0 && d.args()[nArgs].defaultValue().length() > 0); while (--nArgs >= 0) { if (d.args()[nArgs].defaultValue().length() > 0) { throw new IllegalStateException("Function " + value.getName() + " has non trailing default value of '" + d.args()[nArgs].defaultValue() + "'. Only trailing arguments may have default values"); } } } }
Source:
<code>private InvocationStage handleReadCommand(InvocationContext ctx, AbstractTopologyAffectedCommand command) throws Throwable { if (isLocalOnly(command)) { return invokeNext(ctx, command); } updateTopologyId(command); if (!ctx.isOriginLocal()) { return invokeNext(ctx, command); } return invokeNext(ctx, command).compose((stage, rCtx, rCommand, rv, t) -> { if (t == null) return stage; Throwable ce = t; while (ce instanceof RemoteException) { ce = ce.getCause(); } if (!(ce instanceof OutdatedTopologyException) && !(ce instanceof SuspectException)) throw t; <START> int currentTopologyId = currentTopologyId(); <END> if (trace) log.tracef("Retrying command because of topology change, current topology is %d: %s", currentTopologyId(), rCommand); AbstractTopologyAffectedCommand cmd = (AbstractTopologyAffectedCommand) rCommand; int newTopologyId = Math.max(currentTopologyId(), cmd.getTopologyId() + 1); cmd.setTopologyId(newTopologyId); waitForTopology(newTopologyId); return handleReadCommand(rCtx, cmd); }); }</code><technical_language>unused</technical_language>

Target:
private InvocationStage handleReadCommand(InvocationContext ctx, AbstractTopologyAffectedCommand command) throws Throwable { if (isLocalOnly(command)) { return invokeNext(ctx, command); } updateTopologyId(command); return invokeNext(ctx, command).compose(this::handleReadCommandReturn); }
Source:
<code>public void setUp() <START> throws Exception { <END> User.disableStorage(); }</code><technical_language>this throw Exception</technical_language>

Target:
public void setUp() { User.disableStorage(); }
Source:
<code>public void verifyPinResetConfirmationCode(UUID userId, String userProvidedConfirmationCode) { User userEntity = userService.getUserEntityById(userId); logger.info("User with mobile number '{}' and ID '{}' requested to verify the pin reset confirmation code", userEntity.getMobileNumber(), userId); Optional<ConfirmationCode> confirmationCodeOpt = userEntity.getPinResetConfirmationCode(); Require.that(isValidConfirmationCode(confirmationCodeOpt), () -> PinResetRequestConfirmationException.confirmationCodeNotSet(userEntity.getMobileNumber())); <START> ConfirmationCode confirmationCode = confirmationCodeOpt.get(); <END> int remainingAttempts = yonaProperties.getSecurity().getConfirmationCodeMaxAttempts() - confirmationCode.getAttempts(); Require.that(remainingAttempts > 0, () -> PinResetRequestConfirmationException.tooManyAttempts(userEntity.getMobileNumber())); if (!userProvidedConfirmationCode.equals(confirmationCode.getCode())) { userService.registerFailedAttempt(userEntity, confirmationCode); throw PinResetRequestConfirmationException.confirmationCodeMismatch(userEntity.getMobileNumber(), userProvidedConfirmationCode, remainingAttempts - 1); } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Call "confirmationCodeOpt.isPresent()" accessing value. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public void verifyPinResetConfirmationCode(UUID userId, String userProvidedConfirmationCode) { User user = userService.lockUserForUpdate(userId); logger.info("User with mobile number '{}' and ID '{}' requested to verify the pin reset confirmation code", user.getMobileNumber(), userId); Optional<ConfirmationCode> confirmationCodeOpt = user.getPinResetConfirmationCode(); Require.that(isValidConfirmationCode(confirmationCodeOpt), () -> PinResetRequestConfirmationException.confirmationCodeNotSet(user.getMobileNumber())); ConfirmationCode confirmationCode = confirmationCodeOpt.get(); int remainingAttempts = yonaProperties.getSecurity().getConfirmationCodeMaxAttempts() - confirmationCode.getAttempts(); Require.that(remainingAttempts > 0, () -> PinResetRequestConfirmationException.tooManyAttempts(user.getMobileNumber())); if (!userProvidedConfirmationCode.equals(confirmationCode.getCode())) { confirmationCode.incrementAttempts(); throw PinResetRequestConfirmationException.confirmationCodeMismatch(user.getMobileNumber(), userProvidedConfirmationCode, remainingAttempts - 1); } }
Source:
<code>public void notLeader() { <START> _log.info("Not assuming leader role. Probably there is another PinManager that already is entitled to the leader role."); <END> expirationFuture.cancel(false); unpinFuture.cancel(true); }</code><technical_language>text is a misleading: notLeader method is called a pinmanager leader is demoted is longer leader. Suggest like: Dropping leader role. [...] Also, is (almost always) a bad idea speculate in log messages: report true; e.g., Dropping leader role. Cancelling expiration unpin tasks</technical_language>

Target:
public void notLeader() { _log.info("Dropping leader role. Cancelling Expiration and Unpin tasks."); expirationFuture.cancel(false); unpinFuture.cancel(true); }
Source:
<code>public String getComponentType() { <START> return (this.getExpectReply() ? "http:outbound-reactive-gateway" : "http:outbound-reactive-channel-adapter"); <END> }</code><technical_language>s/this//</technical_language>

Target:
public String getComponentType() { return (isExpectReply() ? "http:outbound-reactive-gateway" : "http:outbound-reactive-channel-adapter"); }
Source:
<code><START> LineReader(Reader reader, LineDelimiter lineDelimiter, int bufferSize) { <END> super(reader); this.lineDelimiter = lineDelimiter; this.buffer = new char[bufferSize]; this.offset = UNREAD; this.charsRead = 0; }</code><technical_language>making this constructor private, another static initializer method (.of .create, else) to: 1. Return BufferedReader created as-is if lineDelimiter is null. 2. Return LineReader if lineDelimiter is null. impacts LineReader for existing configurations</technical_language>

Target:
private LineReader(Reader reader, LineDelimiter lineDelimiter, int bufferSize) { super(reader); this.lineDelimiter = lineDelimiter; this.buffer = new char[bufferSize]; this.offset = UNREAD; this.charsRead = 0; }
Source:
<code><START> private int getBarcodeValue(final SAMRecord record) { <END> if (null == BARCODE_TAG) return 0; final String tag = record.getStringAttribute(BARCODE_TAG); if (null == tag) return 0; else return tag.hashCode(); }</code><technical_language>this function getReadBarcodeValue(final SAMRecord record, final String tag) avoid code duplication</technical_language>

Target:
private int getBarcodeValue(final SAMRecord record) { return EstimateLibraryComplexity.getReadBarcodeValue(record, BARCODE_TAG); }
Source:
<code><START> public BufferableHandle getParamValue() { <END> return (BufferableHandle) paramValue; }</code><technical_language>If change BufferableHandle extend AbstractWriteHandle, remove need change this method</technical_language>

Target:
public AbstractWriteHandle getParamValue() { return paramValue; }
Source:
<code>private void testSelectForUpdateConcurrency() throws SQLException { Connection conn = getConnection(url); conn.setAutoCommit(false); String sql = "CREATE TABLE test (" + "entity_id INTEGER NOT NULL PRIMARY KEY, " + "lastUpdated INTEGER NOT NULL)"; Statement smtm = conn.createStatement(); smtm.executeUpdate(sql); PreparedStatement ps = conn.prepareStatement( "INSERT INTO test (entity_id, lastUpdated) VALUES (?, ?)"); ps.setInt(1, 1); ps.setInt(2, 100); ps.executeUpdate(); conn.commit(); for (int i = 0; i < 100; i++) <START> new SelectForUpdate().start(); <END> }</code><technical_language>need join() threads continuing, this test run concurrently next test is, potentially leading spurious failures need close connection</technical_language>

Target:
private void testSelectForUpdateConcurrency() throws SQLException { deleteDb(getTestName()); Connection conn = getConnection(getTestName() + url); conn.setAutoCommit(false); String sql = "CREATE TABLE testmvccmultithreaded2 (" + "entity_id INTEGER NOT NULL PRIMARY KEY, " + "lastUpdated INTEGER NOT NULL)"; Statement smtm = conn.createStatement(); smtm.executeUpdate(sql); PreparedStatement ps = conn.prepareStatement( "INSERT INTO testmvccmultithreaded2 (entity_id, lastUpdated) VALUES (?, ?)"); ps.setInt(1, 1); ps.setInt(2, 100); ps.executeUpdate(); conn.commit(); int howManyThreads = 100; Thread[] threads = new SelectForUpdate[howManyThreads]; for (int i = 0; i < howManyThreads; i++) { threads[i] = new SelectForUpdate(); threads[i].start(); } try { for (int i = 0; i < howManyThreads; i++) { threads[i].join(); } } catch (InterruptedException e) { e.printStackTrace(); } smtm = conn.createStatement(); smtm.execute("DROP TABLE testmvccmultithreaded2"); if (conn != null) { try { conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } } }
Source:
<code>public Path getAssetsDirectory() { <START> return fileAssets.toPath(); <END> }</code><technical_language>this</technical_language>

Target:
public Path getAssetsDirectory() { return this.fileAssets.toPath(); }
Source:
<code>private static List<String> toLonLatStrings(GeoPoint point) { <START> if (point == null) { return null; } <END> return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude())); }</code><technical_language>this Objects.requireNonNull, if null is returned eventually lead a NullPointerException in another, obvious, location</technical_language>

Target:
private static List<String> toLonLatStrings(GeoPoint point) { Objects.requireNonNull(point); return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude())); }
Source:
<code>public void oneDelayed() { Flowable.just(1, 2, 3, 4, 5) .concatMapEager(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) throws Exception { <START> System.out.println("Processing " + i); <END> return i == 3 ? Flowable.just(i) : Flowable .just(i) .delay(1, TimeUnit.MILLISECONDS, Schedulers.io()); } }) .observeOn(Schedulers.io()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5) ; }</code><technical_language>cluttering removed</technical_language>

Target:
public void oneDelayed() { Flowable.just(1, 2, 3, 4, 5) .concatMapEager(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) throws Exception { return i == 3 ? Flowable.just(i) : Flowable .just(i) .delay(1, TimeUnit.MILLISECONDS, Schedulers.io()); } }) .observeOn(Schedulers.io()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5) ; }
Source:
<code>public void testDefaultMethodInterception() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(Grounded.class), new CountingInterceptor()); } }); assertEquals(0, count.get()); assertEquals("I am a horse.", injector.getInstance(Unicorn.class).identifyMyself()); assertEquals(1, count.get()); assertEquals("I am a flying horse.", injector.getInstance(Pegasus.class).identifyMyself()); <START> assertEquals(1, count.get()); END> }</code><technical_language>This is a behavior change a bug fix , previous cglib based code 2 here</technical_language>

Target:
public void testDefaultMethodInterception() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(Grounded.class), new CountingInterceptor()); } }); assertEquals(0, count.get()); assertEquals("I am a horse.", injector.getInstance(Unicorn.class).identifyMyself()); assertEquals(1, count.get()); count.set(0); assertEquals(0, count.get()); assertEquals("I am a flying horse.", injector.getInstance(Pegasus.class).identifyMyself()); assertEquals(0, count.get()); }
Source:
<code>private void updatePartitionLeadershipMap() { Optional.ofNullable(_consumer.listTopics(_consumerRequestTimeout)).ifPresent(response -> response.values().stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(partitionInfo -> partitionInfo != null && partitionInfo.topic() != null && partitionInfo.leader() != null) .forEach(partitionInfo -> { final TopicPartition topicPartition = new TopicPartition(partitionInfo.topic(), partitionInfo.partition()); final Node leader = partitionInfo.leader(); <START> _partitionLeadershipMap.put(topicPartition, leader); <END> })); }</code><technical_language>clean map</technical_language>

Target:
private void updatePartitionLeadershipMap() { LOG.debug("Updating partition leadership map"); Optional.ofNullable(_consumer.listTopics(_consumerRequestTimeout)).ifPresent(response -> { Map<TopicPartition, Node> updateMap = response.values().stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(partitionInfo -> partitionInfo != null && partitionInfo.topic() != null && partitionInfo.leader() != null) .collect(Collectors.toMap( partitionInfo -> new TopicPartition(partitionInfo.topic(), partitionInfo.partition()), PartitionInfo::leader)); _partitionLeadershipMap.keySet().retainAll(updateMap.keySet()); _partitionLeadershipMap.putAll(updateMap); }); }
Source:
<code>public Comparator getComparator() { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>This means post-aggregator sorted on. sense a comparator understands Doubles, compute return a Double? useless sort this post-aggregator</technical_language>

Target:
public Comparator getComparator() { return ArithmeticPostAggregator.DEFAULT_COMPARATOR; }
Source:
<code>public Collection<ContentType> getDirectlyAssociated(final ContentTypeCatalog catalog, final String fileSpec, final int typeMask) { if ((typeMask & (IContentType.FILE_EXTENSION_SPEC | IContentType.FILE_NAME_SPEC)) == 0) { throw new IllegalArgumentException("This method only apply to name or extension based associations"); } final IEclipsePreferences root = context.getNode(ContentTypeManager.CONTENT_TYPE_PREF_NODE); final Set<ContentType> result = new HashSet<>(3); try { <START> root.accept(new IPreferenceNodeVisitor() { <END> @Override public boolean visit(IEclipsePreferences node) { if (node == root) return true; String[] fileSpecs = ContentTypeSettings.getFileSpecs(node, typeMask); for (String fileSpecification : fileSpecs) if (fileSpecification.equalsIgnoreCase(fileSpec)) { ContentType associated = catalog.getContentType(node.name()); if (associated != null) result.add(associated); break; } return false; } }); } catch (BackingStoreException bse) { ContentType.log(ContentMessages.content_errorLoadingSettings, bse); } return result == null ? Collections.EMPTY_SET : result; }</code><technical_language>Lambda preferred nowadays</technical_language>

Target:
public Collection<ContentType> getDirectlyAssociated(final ContentTypeCatalog catalog, final String fileSpec, final int typeMask) { if ((typeMask & (IContentType.FILE_EXTENSION_SPEC | IContentType.FILE_NAME_SPEC)) == 0) { throw new IllegalArgumentException("This method only apply to name or extension based associations"); } final IEclipsePreferences root = context.getNode(ContentTypeManager.CONTENT_TYPE_PREF_NODE); final Set<ContentType> result = new HashSet<>(3); try { root.accept(node -> { if (node == root) return true; String[] fileSpecs = ContentTypeSettings.getFileSpecs(node, typeMask); for (String fileSpecification : fileSpecs) if (fileSpecification.equalsIgnoreCase(fileSpec)) { ContentType associated = catalog.getContentType(node.name()); if (associated != null) result.add(associated); break; } return false; }); } catch (BackingStoreException bse) { ContentType.log(ContentMessages.content_errorLoadingSettings, bse); } return result == null ? Collections.EMPTY_SET : result; }
Source:
<code>protected String getFullHelpText() { <START> return "Analysis module: " + getName(); END> }</code><technical_language>externalize string</technical_language>

Target:
protected String getFullHelpText() { return String.format(Messages.TmfAbstractAnalysisModule_AnalysisModule, getName()); }
Source:
<code>protected ApplicationProcess start(java.io.File appDir, SDKRunnerConfiguration runnerCfg, CodeServerProcess codeServerProcess, ApplicationProcess.Callback callback) throws RunnerException { final java.io.File startUpScriptFile; final java.io.File logsDir = new java.io.File(appDir, LOG_FOLDER); try { generateSetEnvScript(appDir, runnerCfg); startUpScriptFile = generateStartUpScript(appDir, runnerCfg); Files.createDirectory(logsDir.toPath()); } catch (IOException e) { throw new RunnerException(e); } final List<java.io.File> logFiles = new ArrayList<>(1); logFiles.add(new java.io.File(logsDir, LOG_FILE)); <START> return new TomcatProcess(appDir, startUpScriptFile, logFiles, runnerCfg, callback, codeServerProcess, eventService); <END> }</code><technical_language>ImmutableList.of(new java.io.File(logsDir, LOG_FILE))</technical_language>

Target:
protected ApplicationProcess start(java.io.File appDir, SDKRunnerConfiguration runnerCfg, CodeServerProcess codeServerProcess, ApplicationProcess.Callback callback) throws RunnerException { final java.io.File startUpScriptFile; final java.io.File logsDir = new java.io.File(appDir, LOG_FOLDER); try { generateSetEnvScript(appDir, runnerCfg); startUpScriptFile = generateStartUpScript(appDir, runnerCfg); Files.createDirectory(logsDir.toPath()); } catch (IOException e) { throw new RunnerException(e); } final List<java.io.File> logFiles = ImmutableList.of(new java.io.File(logsDir, LOG_FILE)); return new TomcatProcess(appDir, startUpScriptFile, logFiles, runnerCfg, callback, codeServerProcess, eventService); }
Source:
<code>private void registerAllOvfDisks(List<DiskImage> ovfStoreDiskImages) { for (DiskImage ovfStoreDiskImage : ovfStoreDiskImages) { <START> ovfStoreDiskImage.setDiskAlias("OVF_STORE"); <END> ovfStoreDiskImage.setDiskDescription("OVF_STORE"); ovfStoreDiskImage.setShareable(true); RegisterDiskParameters registerDiskParams = new RegisterDiskParameters(ovfStoreDiskImage, getParameters().getStorageDomainId()); String result = "succeeded"; try { if (!runInternalAction(VdcActionType.RegisterDisk, registerDiskParams, null).getSucceeded()) { result = "failed"; } } catch (Exception e) { result = "failed"; log.error(e); } log.infoFormat("Register OVF_STORE disk id {0} for storage domain {1} has {2}", ovfStoreDiskImage.getId(), getParameters().getStorageDomainId(), result); } }</code><technical_language>a constant for in OvfInfoFileConstants</technical_language>

Target:
private void registerAllOvfDisks(List<DiskImage> ovfStoreDiskImages) { for (DiskImage ovfStoreDiskImage : ovfStoreDiskImages) { ovfStoreDiskImage.setDiskAlias(OvfInfoFileConstants.OvfStoreDescriptionLabel); ovfStoreDiskImage.setDiskDescription(OvfInfoFileConstants.OvfStoreDescriptionLabel); ovfStoreDiskImage.setShareable(true); RegisterDiskParameters registerDiskParams = new RegisterDiskParameters(ovfStoreDiskImage, getParameters().getStorageDomainId()); String result = "succeeded"; if (!runInternalAction(VdcActionType.RegisterDisk, registerDiskParams, null).getSucceeded()) { result = "failed"; } log.infoFormat("Register new floating OVF_STORE disk with disk id {0} for storage domain {1} has {2}", ovfStoreDiskImage.getId(), getParameters().getStorageDomainId(), result); } }
Source:
<code><START> private UpdateCalibrationResponse addUnprocessedItem(final String unprocessedItem) { <END> this.unprocessed.add(unprocessedItem); return this; }</code><technical_language>return this behavior want here. void is perfectly fine</technical_language>

Target:
private void addUnprocessedItem(final String unprocessedItem) { this.unprocessed.add(unprocessedItem); }
Source:
<code>public void testConfig_Basic() { Configuration conf = BigtableConfiguration.configure("projectId", "instanceId"); Assert.assertEquals("projectId", conf.get(BigtableOptionsFactory.PROJECT_ID_KEY)); Assert.assertEquals("instanceId", conf.get(BigtableOptionsFactory.INSTANCE_ID_KEY)); <START> Assert.assertEquals(BigtableConfiguration.getConnectionClass().getName(), conf.get("hbase.client.connection.impl")); <END> Assert.assertNull(conf.get(BigtableOptionsFactory.APP_PROFILE_ID_KEY)); }</code><technical_language>Move this app profile ID checking</technical_language>

Target:
public void testConfig_Basic() { Configuration conf = BigtableConfiguration.configure("projectId", "instanceId"); Assert.assertEquals("projectId", conf.get(BigtableOptionsFactory.PROJECT_ID_KEY)); Assert.assertEquals("instanceId", conf.get(BigtableOptionsFactory.INSTANCE_ID_KEY)); Assert.assertNull(conf.get(BigtableOptionsFactory.APP_PROFILE_ID_KEY)); Assert.assertEquals(BigtableConfiguration.getConnectionClass().getName(), conf.get(BigtableConfiguration.HBASE_CLIENT_CONNECTION_IMPL)); }
Source:
<code>private void removeTrailingSlash() { try { URI uri = new URI(settings.getServerURI()); uri = uri.normalize(); String uriString = uri.toString(); if (uriString.endsWith("/")) { settings.setServerURI(uriString.substring(0, uriString.length() - 1)); } <START> } catch (URISyntaxException e) { <END> String message = "There was an error loading json from the DHIS2 settings."; LOGGER.debug(message); throw new JsonIOException(message, e); } }</code><technical_language>duplicated code, this method throw this exception method catch this</technical_language>

Target:
private String removeTrailingSlash() throws URISyntaxException { URI uri = new URI(settings.getServerURI()); uri = uri.normalize(); String uriString = uri.toString(); if (uriString.endsWith("/")) { uriString = uriString.substring(0, uriString.length() - 1); } return uriString; }
Source:
<code>public void should_parse_but_not_add_issue_if_inputFile_not_found() { when(ruleFinder.find(any(RuleQuery.class))).thenReturn(Rule.create()); File report = FileUtils.toFile(getClass().getResource("parsing/sample.xml")); when(settings.getString(GroovyPlugin.CODENARC_REPORT_PATH)).thenReturn(report.getAbsolutePath()); File sonarhome = projectdir.newFolder("sonarhome"); <START> FileSystem fileSystem = mock(FileSystem.class); <END> when(fileSystem.predicates()).thenReturn(mock(FilePredicates.class)); when(fileSystem.workDir()).thenReturn(sonarhome); sensor = new CodeNarcSensor(groovy, perspectives, moduleFileSystem, fileSystem, profile, ruleFinder); sensor.analyse(project, context); verify(issuable, never()).addIssue(any(Issue.class)); }</code><technical_language>DefaultFileSystem avoid mocking of this API</technical_language>

Target:
public void should_parse_but_not_add_issue_if_inputFile_not_found() { when(ruleFinder.find(any(RuleQuery.class))).thenReturn(Rule.create()); File report = FileUtils.toFile(getClass().getResource("parsing/sample.xml")); when(settings.getString(GroovyPlugin.CODENARC_REPORT_PATH)).thenReturn(report.getAbsolutePath()); sensor.analyse(project, context); verify(issuable, never()).addIssue(any(Issue.class)); }
Source:
<code>public static void dropTables() throws Exception { try { disableAndDropNonSystemTables(driver); } finally { try { <START> if (driver != null) { <END> assertTrue(destroyDriver(driver)); } } finally { driver = null; } } }</code><technical_language>Is this required? driver null</technical_language>

Target:
public static void dropTables() throws Exception { try { disableAndDropNonSystemTables(driver); } finally { try { assertTrue(destroyDriver(driver)); } finally { driver = null; } } }
Source:
<code>void onPanelDragDrop(DropEvent event) { <START> String vmGid = event.getData("VM_GID"); END> if (!vmGid.isEmpty()) { Guid vmGuid = Guid.createGuidFromString(vmGid); boolean pinned = Boolean.valueOf(event.getData("PINNED")); int vNumaNodeIndex = Integer.parseInt(event.getData("INDEX")); container.removeStyleName(style.dragOver()); event.preventDefault(); UpdatedVnumaEvent.fire(this, vmGuid, pinned, vNumaNodeIndex, pNumaNodeIndex); } }</code><technical_language>this is null? I checking for empty, StringUtils method checks for null empty time</technical_language>

Target:
void onPanelDragDrop(DropEvent event) { String vmGid = event.getData("VM_GID"); if (StringUtils.isNotEmpty(vmGid)) { Guid vmGuid = Guid.createGuidFromString(vmGid); boolean pinned = Boolean.valueOf(event.getData("PINNED")); int vNumaNodeIndex = Integer.parseInt(event.getData("INDEX")); container.removeStyleName(style.dragOver()); event.preventDefault(); UpdatedVnumaEvent.fire(this, vmGuid, pinned, vNumaNodeIndex, pNumaNodeIndex); } else { container.removeStyleName(style.dragOver()); } }
Source:
<code>public <T> T withExtractedArchive(TaskRequest request, ArchiveProvider archiveProvider, WithWorkspaceAction<T> func) throws IOException { TempDir workspacePath = null; try { try { workspacePath = RetryExecutor.retryExecutor() .retryIf(exception -> true) .withInitialRetryWait(EXTRACT_MIN_RETRY_WAIT_MS) .withMaxRetryWait(EXTRACT_MAX_RETRY_WAIT_MS) .onRetry((exception, retryCount, retryLimit, retryWait) -> logger.warn("Failed to extract archive: retry of {}", retryCount, retryLimit, exception)) .withRetryLimit(EXTRACT_RETRIES) .run(() -> { TempDir newWorkSpacePath = null; try { newWorkSpacePath = createNewWorkspace(request); Optional<StorageObject> in = archiveProvider.open(); if (in.isPresent()) { ProjectArchives.extractTarArchive(newWorkSpacePath.get(), in.get().getContentInputStream()); } return newWorkSpacePath; } catch (Throwable e) { if (newWorkSpacePath != null) { newWorkSpacePath.close(); } throw e; } }); } catch (RetryExecutor.RetryGiveupException e) { <START> Throwables.propagate(e); <END> } return func.run(workspacePath.get()); } finally { if (workspacePath != null) { workspacePath.close(); } } }</code><technical_language>Throwables.propagate is marked deprecated. I guess miss throw did...Throwables.propagate returns a Throwable throw. I Throwables.propagate(e.getCause()) is cleanup stacktrace in log messages. Throwables.throwIfUnchecked this instead: java Throwables.throwIfUnchecked(e.getCause()); throw new RuntimeException(e.getCause());</technical_language>

Target:
public <T> T withExtractedArchive(TaskRequest request, ArchiveProvider archiveProvider, WithWorkspaceAction<T> func) throws IOException { TempDir workspacePath = null; try { try { workspacePath = RetryExecutor.retryExecutor() .retryIf(exception -> true) .withInitialRetryWait(EXTRACT_MIN_RETRY_WAIT_MS) .withMaxRetryWait(EXTRACT_MAX_RETRY_WAIT_MS) .onRetry((exception, retryCount, retryLimit, retryWait) -> logger.warn("Failed to extract archive: retry of {}", retryCount, retryLimit, exception)) .withRetryLimit(EXTRACT_RETRIES) .run(() -> { TempDir newWorkSpacePath = null; try { newWorkSpacePath = createNewWorkspace(request); Optional<StorageObject> in = archiveProvider.open(); if (in.isPresent()) { ProjectArchives.extractTarArchive(newWorkSpacePath.get(), in.get().getContentInputStream()); } return newWorkSpacePath; } catch (Throwable e) { if (newWorkSpacePath != null) { newWorkSpacePath.close(); } throw e; } }); } catch (RetryExecutor.RetryGiveupException e) { throw Throwables.propagate(e.getCause()); } return func.run(workspacePath.get()); } finally { if (workspacePath != null) { workspacePath.close(); } } }