auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean validateExtension(String path) { boolean isValid = false; <START> String[] splittedPath = path.split("\\.", -1); if (splittedPath.length > 1) { String extension = splittedPath[splittedPath.length - 1]; <END> for (ImageFileFormat element : ImageFileFormat.VALUES) { if (element.getName().toLowerCase().equals(extension.toLowerCase())) { isValid = true; break; } } } return isValid; }</code><technical_language>Avoid re-coding scratch utility code exists. In this case guess out of blue, like: new org.eclipse.core.runtime.Path(path).getFileExtension() is more readable more robust (it debugged for years in contexts)</technical_language>

Target:
private boolean validateExtension(String path) { boolean isValid = false; String extension = new org.eclipse.core.runtime.Path(path).getFileExtension(); for (ImageFileFormat element : ImageFileFormat.VALUES) { if (element.getName().equalsIgnoreCase(extension)) { isValid = true; break; } } return isValid; }
Source:
<code>private Server createAndStartServer(int port, HandlerList handlers) throws Exception { final Server server = new Server(port); server.setHandler(handlers); server.setStopAtShutdown(true); server.start(); this.port = ((NetworkConnector)server.getConnectors()[0]).getLocalPort(); LOGGER.info("Jetty started on port {}", this.port); <START> return server; <END> }</code><technical_language>do remote JMX support for embedded Jetty instance</technical_language>

Target:
private Server createAndStartServer(int port, HandlerList handlers) throws Exception { final Server server = new Server(port); server.setHandler(handlers); server.setStopAtShutdown(true); server.setRequestLog(createRequestLog()); server.start(); this.port = ((NetworkConnector)server.getConnectors()[0]).getLocalPort(); LOGGER.info("Jetty started on port {}", this.port); return server; }
Source:
<code>private String convertToJSONString(Object content){ Gson gson = new Gson(); String json = gson.toJson(content); <START> System.out.println(json); <END> return json; }</code><technical_language>leave System.out calls in code done. Other LOG.debug' delete them</technical_language>

Target:
private String convertToJSONString(Object content){ Gson gson = new Gson(); String json = gson.toJson(content); LOG.debug(json); return json; }
Source:
<code>private static void append(StringBuilder builder, String value) { if (StringUtils.hasText(value)) { <START> builder.append(value).append(SEPARATOR); <END> } }</code><technical_language>builder.append(SEPARATOR).append(value) . In this , is need remove ":" in build method</technical_language>

Target:
private static void append(StringBuilder builder, String value) { if (StringUtils.hasText(value)) { builder.append(SEPARATOR).append(value); } }
Source:
<code>protected void configure() { super.configure(); install(new LocationsFromComputeServiceAdapterModule<ServerInDataCenter, Hardware, Provisionable, DataCenter>() { <START> }); <END> install(new FactoryModuleBuilder().build(ProvisioningJob.Factory.class)); bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Singleton.class); bind(new TypeLiteral<ComputeServiceAdapter<ServerInDataCenter, Hardware, Provisionable, DataCenter>>() { }).to(ProfitBricksComputeServiceAdapter.class); bind(new TypeLiteral<Function<org.apache.jclouds.profitbricks.rest.domain.Location, Location>>() { }).to(LocationToLocation.class); bind(new TypeLiteral<Function<DataCenter, Location>>() { }).to(DataCenterToLocation.class); bind(new TypeLiteral<Function<ServerInDataCenter, NodeMetadata>>() { }).to(ServerInDataCenterToNodeMetadata.class); bind(new TypeLiteral<Function<Server, NodeMetadata>>() { }).to(ServerToNodeMetadata.class); bind(new TypeLiteral<Function<Provisionable, Image>>() { }).to(ProvisionableToImage.class); bind(new TypeLiteral<Function<org.apache.jclouds.profitbricks.rest.domain.Volume, Volume>>() { }).to(VolumeToVolume.class); bind(new TypeLiteral<Function<Hardware, Hardware>>() { }).to(Class.class.cast(IdentityFunction.class)); }</code><technical_language>Remove this locations configured properties int metadata</technical_language>

Target:
protected void configure() { super.configure(); install(new FactoryModuleBuilder().build(ProvisioningJob.Factory.class)); bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON); bind(CreateNodesInGroupThenAddToSet.class).to(AssignDataCenterToTemplate.class).in(Scopes.SINGLETON); bind(new TypeLiteral<ComputeServiceAdapter<ServerInDataCenter, Hardware, Provisionable, Location>>() { }).to(ProfitBricksComputeServiceAdapter.class); bind(TemplateBuilderImpl.class).to(ArbitraryCpuRamTemplateBuilderImpl.class); bind(new TypeLiteral<Function<ServerInDataCenter, NodeMetadata>>() { }).to(ServerInDataCenterToNodeMetadata.class); bind(new TypeLiteral<Function<Provisionable, Image>>() { }).to(ProvisionableToImage.class); bind(new TypeLiteral<Function<org.apache.jclouds.profitbricks.rest.domain.Volume, Volume>>() { }).to(VolumeToVolume.class); bind(new TypeLiteral<Function<Hardware, Hardware>>() { }).to(Class.class.cast(IdentityFunction.class)); }
Source:
<code><START> private boolean setLookAndFeel(String lookAndFeelClassname) { <END> if (lookAndFeelClassname != "" && lookAndFeelClassname != null) { try { UIManager.setLookAndFeel(lookAndFeelClassname); lookAndFeelSet = true; } catch (final UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.warn("Failed to set the look and feel: " + e.getMessage()); } } return lookAndFeelSet; }</code><technical_language>static</technical_language>

Target:
private static boolean setLookAndFeel(String lookAndFeelClassname) { if (StringUtils.isNotEmpty(lookAndFeelClassname)) { try { UIManager.setLookAndFeel(lookAndFeelClassname); return true; } catch (final UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.warn("Failed to set the look and feel: " + e.getMessage()); } } return false; }
Source:
<code>public void truncate(long zxid) throws IOException { FileTxnIterator itr = null; RandomAccessFile raf = null; try { itr = new FileTxnIterator(this.logDir, zxid); PositionInputStream input = itr.inputStream; if(input == null) { throw new IOException("No log files found to truncate! This could " + "happen if you still have snapshots from an old setup or " + "log files were deleted accidentally or dataLogDir was changed in zoo.cfg."); } long pos = input.getPosition(); raf = new RandomAccessFile(itr.logFile, "rw"); raf.setLength(pos); while(itr.goToNextLog()) { try { Files.delete(itr.logFile.toPath()); } catch (NoSuchFileException e) { } } } finally { <START> close(itr); <END> if (raf != null) { raf.close(); } } }</code><technical_language>Do intentions for changing itr.logFile.delete() Files.delete(itr.logFile.toPath()) ? confused this: > Files.delete throw exception, this is useful for error reporting diagnosed a file deleted. - catch NoSuchFileException log</technical_language>

Target:
public void truncate(long zxid) throws IOException { FileTxnIterator itr = null; RandomAccessFile raf = null; try { itr = new FileTxnIterator(this.logDir, zxid); PositionInputStream input = itr.inputStream; if(input == null) { throw new IOException("No log files found to truncate! This could " + "happen if you still have snapshots from an old setup or " + "log files were deleted accidentally or dataLogDir was changed in zoo.cfg."); } long pos = input.getPosition(); raf = new RandomAccessFile(itr.logFile, "rw"); raf.setLength(pos); while(itr.goToNextLog()) { try { Files.delete(itr.logFile.toPath()); } catch (NoSuchFileException e) { LOG.info("An NoSuchFileException was thrown when delete file {}" + ", but will continue. Assume this file has been deleted successfully.", itr.logFile); } } } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { LOG.warn("Error closing RandomAccessFile {}, exception = ", raf, e); } } close(itr); } }
Source:
<code>public void testBoundarySignalProcessInstance() throws Exception { Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_BOUNDARY_SIGNAL_PROCESS); assertNotNull(processInstanceId); assertTrue(processInstanceId.longValue() > 0); try { <START> checkAvailableBoundarySignals(CONTAINER_ID, processInstanceId); <END> } catch (Exception e){ processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); e.printStackTrace(); fail(e.getMessage()); } }</code><technical_language>Please move abortProcessInstance final statement, done in case. please delete e.printStackTrace(); - bring value. please delete fail(e.getMessage()); - unexpected exceptions thrown out of test method, JUnit handle a failing test, printing exception stacktrace log</technical_language>

Target:
public void testBoundarySignalProcessInstance() throws Exception { Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_BOUNDARY_SIGNAL_PROCESS); assertNotNull(processInstanceId); assertTrue(processInstanceId.longValue() > 0); try { checkAvailableBoundarySignals(CONTAINER_ID, processInstanceId); } finally { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } }
Source:
<code>public static void validateTaskConfig(final PluginTask task) { String username = task.getUsername(); if (isNullOrEmpty(username)) { throw new ConfigException("Username or email could not be empty"); } String password = task.getPassword(); if (isNullOrEmpty(password)) { throw new ConfigException("Password could not be empty"); } String uri = task.getUri(); if (isNullOrEmpty(uri)) { throw new ConfigException("JIRA API endpoint could not be empty"); } try (CloseableHttpClient client = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(HTTP_TIMEOUT) .setConnectionRequestTimeout(HTTP_TIMEOUT) .setSocketTimeout(HTTP_TIMEOUT) .setCookieSpec(CookieSpecs.STANDARD) .build()) .build()) { <START> HttpGet request = new HttpGet(task.getUri()); <END> try (CloseableHttpResponse response = client.execute(request)) { response.getStatusLine().getStatusCode(); } } catch (IOException | IllegalArgumentException e) { throw new ConfigException("JIRA API endpoint is incorrect or not available"); } int retryInitialWaitSec = task.getInitialRetryIntervalMillis(); if (retryInitialWaitSec < 1) { throw new ConfigException("Initial retry delay should be equal or greater than 1"); } int retryLimit = task.getRetryLimit(); if (retryLimit < 0 || retryLimit > 10) { throw new ConfigException("Retry limit should between 0 and 10"); } }</code><technical_language>suggestion HttpGet request = new HttpGet(uri);</technical_language>

Target:
public static void validateTaskConfig(final PluginTask task) { String username = task.getUsername(); if (isNullOrEmpty(username)) { throw new ConfigException("Username or email could not be empty"); } String password = task.getPassword(); if (isNullOrEmpty(password)) { throw new ConfigException("Password could not be empty"); } String uri = task.getUri(); if (isNullOrEmpty(uri)) { throw new ConfigException("JIRA API endpoint could not be empty"); } try (CloseableHttpClient client = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(HTTP_TIMEOUT) .setConnectionRequestTimeout(HTTP_TIMEOUT) .setSocketTimeout(HTTP_TIMEOUT) .setCookieSpec(CookieSpecs.STANDARD) .build()) .build()) { HttpGet request = new HttpGet(uri); try (CloseableHttpResponse response = client.execute(request)) { response.getStatusLine().getStatusCode(); } } catch (IOException | IllegalArgumentException e) { throw new ConfigException("JIRA API endpoint is incorrect or not available"); } int retryInitialWaitSec = task.getInitialRetryIntervalMillis(); if (retryInitialWaitSec < 1) { throw new ConfigException("Initial retry delay should be equal or greater than 1"); } int retryLimit = task.getRetryLimit(); if (retryLimit < 0 || retryLimit > 10) { throw new ConfigException("Retry limit should between 0 and 10"); } }
Source:
<code>private RoutingAlgorithm createAlgo() { StopWatch sw = new StopWatch().start(); RoutingAlgorithm algo = algoFactory.createAlgo(queryGraph, algoOpts); <START> debug = ", algoInit:" + (sw.stop().getNanos() / 1000) + " micros"; <END> return algo; }</code><technical_language>I copied this, consistent. E.g. in Measurement instead of micros. mus :)</technical_language>

Target:
private RoutingAlgorithm createAlgo() { StopWatch sw = new StopWatch().start(); RoutingAlgorithm algo = algoFactory.createAlgo(queryGraph, algoOpts); debug = ", algoInit:" + (sw.stop().getNanos() / 1000) + " μs"; return algo; }
Source:
<code>@Override public void init(Context context) throws IOException { this.ctx = context; <START> return; <END> }</code><technical_language>nit: redundant</technical_language>

Target:
@Override public void init(Context context) throws IOException { this.ctx = context; }
Source:
<code>public List<Facility> getFacilities(PerunSession sess, Map<String, String> attributesWithSearchingValues) throws PrivilegeException, InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { <START> if (!AuthzResolver.authorizedInternal(sess, "getFacilities_Map<String, String>_policy", Collections.emptyList())) <END> throw new PrivilegeException(sess, "getFacilities"); return searcherBl.getFacilities(sess, attributesWithSearchingValues); }</code><technical_language>question ", " above</technical_language>

Target:
public List<Facility> getFacilities(PerunSession sess, Map<String, String> attributesWithSearchingValues) throws PrivilegeException, InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { if (!AuthzResolver.authorizedInternal(sess, "getFacilities_Map<String_String>_policy")) throw new PrivilegeException(sess, "getFacilities"); return searcherBl.getFacilities(sess, attributesWithSearchingValues); }
Source:
<code>public List<String> getExpectedBannedColumns() { List<String> bannedColumns = new ArrayList<String>(); bannedColumns.add(COL_ID_PROCESSNAME); <START> bannedColumns.add("Actions"); <END> return bannedColumns; }</code><technical_language>suggestion bannedColumns.add(COL_ID_ACTIONS);</technical_language>

Target:
public List<String> getExpectedBannedColumns() { List<String> bannedColumns = new ArrayList<String>(); bannedColumns.add(COL_ID_PROCESSNAME); bannedColumns.add(COL_ID_ACTIONS); return bannedColumns; }
Source:
<code>public Object java_switch() { String res; <START> switch (random) { <END> case 0: res = "zero"; break; default: res = "fallback"; } assert "zero".equals(res); return res; }</code><technical_language>testing binary branching, i.e. if. A switch is meant for more branches. java's switch linear binary search a lookup table. Javaslang's is linear. Please test properly</technical_language>

Target:
public Object java_switch() { String res; switch (random) { case 0: res = "0"; break; case 1: res = "1"; break; case 2: res = "2"; break; case 3: res = "3"; break; default: res = "error"; } assert String.valueOf(random).equals(res); return res; }
Source:
<code>public void onMessage(String messageType, JSONObject messagePayload) { try { String href = messagePayload.getString("href"); if (href.startsWith(" href = "https:" + href; } Log.d("Wikipedia", "Link clicked was " + href); if (href.startsWith("/wiki/")) { <START> bus.post(new NewWikiPageNavigationEvent(PageTitle.fromInternalLink(href, app.getPrimarySite()))); <END> } else { handleExternalLink(href); } } catch (JSONException e) { throw new RuntimeException(e); } }</code><technical_language>I feel this cleaner if call app.getPrimarySite().titleFromLink(href), asking PageTitle parse passing in a site</technical_language>

Target:
public void onMessage(String messageType, JSONObject messagePayload) { try { String href = messagePayload.getString("href"); if (href.startsWith(" href = "https:" + href; } Log.d("Wikipedia", "Link clicked was " + href); if (href.startsWith("/wiki/")) { bus.post(new NewWikiPageNavigationEvent(app.getPrimarySite().titleForInternalLink(href))); } else { handleExternalLink(href); } } catch (JSONException e) { throw new RuntimeException(e); } }
Source:
<code>public void showOfflineModeDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MaterialAlertDialogStyle); builder.setTitle("Offline Mode"); <START> builder.setMessage("You are in offline mode, Please go to Navigation drawer " + <END> "and switch to online mode. \n\n If you are trying to sync Groups" + " Please make sure your internet connection is working well"); builder.setPositiveButton("OK", null); builder.show(); }</code><technical_language>user hardcoded strings</technical_language>

Target:
public void showOfflineModeDialog() { new MaterialDialog.Builder().init(getActivity()) .setTitle(R.string.offline_mode) .setMessage(R.string.dialog_message_offline_sync_alert) .setPositiveButton(R.string.dialog_action_go_online, this) .setNegativeButton(R.string.dialog_action_cancel, this) .createMaterialDialog() .show(); }
Source:
<code>public void registerForPush(boolean clearFcmData){ boolean registerForPushAvailable = false; if (storageManagerPreferences != null) { if (allPushRegisterDataAvailable()) { new FcmConfigurationHandler(storageManagerPreferences, this).registerForPush(clearFcmData); registerForPushAvailable = true; } } if (!registerForPushAvailable) { if (isServiceAttached && listener != null) { <START> listener.onWarning(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING.ordinal(), RCClient.errorText(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING)); <END> } else { RCLogger.w(TAG, "RegisterForPush warning: " + RCClient.errorText(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING)); } } }</code><technical_language>I implementation thinking need do some more brainstorming this; I improve in some areas :D. In case, change this point, in action get full picture. If decide update do part of #767 is closely related in next sprint</technical_language>

Target:
public void registerForPush(boolean clearFcmData){ boolean registerForPushAvailable = false; if (storageManagerPreferences != null) { if (allPushRegisterDataAvailable()) { new FcmConfigurationHandler(storageManagerPreferences, this).registerForPush(clearFcmData); registerForPushAvailable = true; } } if (!registerForPushAvailable) { if (isServiceAttached && listener != null) { listener.onWarning(this, RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING.ordinal(), RCClient.errorText(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING)); } else { RCLogger.w(TAG, "RegisterForPush warning: " + RCClient.errorText(RCClient.ErrorCodes.ERROR_DEVICE_PUSH_PARAMETERS_MISSING)); } } }
Source:
<code>@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits, List<RelTraitSet> inTraits) { <START> if (TraitUtils.correlation(nodeTraits).correlated()) <END> return ImmutableList.of(); return ImmutableList.of(Pair.of(nodeTraits, Commons.transform(inTraits, t -> t.replace(CorrelationTrait.UNCORRELATED)))); }</code><technical_language>pass correlation in IgniteNestedLoopJoin</technical_language>

Target:
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits, List<RelTraitSet> inTraits) { return ImmutableList.of(Pair.of(nodeTraits, Commons.transform(inTraits, t -> t.replace(TraitUtils.correlation(nodeTraits))))); }
Source:
<code>private void initUserAnswers() { OrderedHashtable<String, QueryPrompt> queryPrompts = queryDatum.getUserQueryPrompts(); for (Enumeration en = queryPrompts.keys(); en.hasMoreElements(); ) { <START> String promptId = (String)en.nextElement(); <END> QueryPrompt prompt = queryPrompts.get(promptId); userAnswers.put(prompt.getKey(), ""); } }</code><technical_language>I this needs get updated this pr is included: <LINK_0> init behavior for query screen USH needs for performing de-dupe</technical_language>

Target:
private void initUserAnswers() throws XPathException { OrderedHashtable<String, QueryPrompt> queryPrompts = queryDatum.getUserQueryPrompts(); for (Enumeration en = queryPrompts.keys(); en.hasMoreElements(); ) { String promptId = (String)en.nextElement(); QueryPrompt prompt = queryPrompts.get(promptId); String defaultValue = ""; if(prompt.getDefaultValueExpr() != null) { defaultValue = FunctionUtils.toString(prompt.getDefaultValueExpr().eval(evaluationContext)); } userAnswers.put(prompt.getKey(), defaultValue); } }
Source:
<code>private void createAndLoadNativeAd(Context context, String placementID, NativeMediationAdRequest adRequest, Bundle mediationExtras) { <START> isNativeBanner = mediationExtras.getBoolean(NATIVE_BANNER); <END> if (isNativeBanner) { mNativeBannerAd = new NativeBannerAd(context, placementID); mNativeBannerAd.setAdListener(new NativeBannerListener(mNativeBannerAd, adRequest)); buildAdRequest(adRequest); mNativeBannerAd.loadAd(); } else { mMediaView = new MediaView(context); mNativeAd = new NativeAd(context, placementID); mNativeAd.setAdListener(new NativeListener(mNativeAd, adRequest)); buildAdRequest(adRequest); mNativeAd.loadAd(); } }</code><technical_language>This breaks API a NPE</technical_language>

Target:
private void createAndLoadNativeAd(Context context, String placementID, NativeMediationAdRequest adRequest, Bundle mediationExtras) { if (mediationExtras != null) { isNativeBanner = mediationExtras.getBoolean(NATIVE_BANNER); } if (isNativeBanner) { mNativeBannerAd = new NativeBannerAd(context, placementID); mNativeBannerAd.setAdListener(new NativeBannerListener(mNativeBannerAd, adRequest)); buildAdRequest(adRequest); mNativeBannerAd.loadAd(); } else { mMediaView = new MediaView(context); mNativeAd = new NativeAd(context, placementID); mNativeAd.setAdListener(new NativeListener(mNativeAd, adRequest)); buildAdRequest(adRequest); mNativeAd.loadAd(); } }
Source:
<code>public void shouldWriteInfoAboutManualBuildCause() throws Exception { <START> UserIdCause cause = Cause.UserIdCause.class.newInstance(); <END> FreeStyleBuild build = jenkins.createFreeStyleProject().scheduleBuild2(0, cause).get(); assertThat(build.getResult(), is(SUCCESS)); assertThat(build, withCause(BUILD_CAUSE, MANUAL_TRIGGER)); assertThat(build, withCause(ROOT_BUILD_CAUSE, MANUAL_TRIGGER)); assertThat(build, withCausesIsTrue(sub(BUILD_CAUSE, MANUAL_TRIGGER), sub(ROOT_BUILD_CAUSE, MANUAL_TRIGGER))); assertThat(build, withCause(USER_NAME, cause.getUserName())); }</code><technical_language>I work, username trigger build... If check works, is wrong matcher</technical_language>

Target:
public void shouldWriteInfoAboutManualBuildCause() throws Exception { Cause cause = Cause.UserCause.class.newInstance(); FreeStyleBuild build = jenkins.createFreeStyleProject().scheduleBuild2(0, cause).get(); assertThat(build.getResult(), is(SUCCESS)); assertThat(build, withCause(BUILD_CAUSE, MANUAL_TRIGGER)); assertThat(build, withCause(ROOT_BUILD_CAUSE, MANUAL_TRIGGER)); assertThat(build, withCausesIsTrue(sub(BUILD_CAUSE, MANUAL_TRIGGER), sub(ROOT_BUILD_CAUSE, MANUAL_TRIGGER))); }
Source:
<code>public void testGetEvent() { DropletCreation droplet = null; try { droplet = api.getDropletApi().create("eventtest", defaultImage.getId(), defaultSize.getId(), defaultRegion.getId()); Event event = api.getEventApi().get(droplet.getEventId()); <START> assertNotNull(event, "Droplet creation event shouold not be null"); <END> } finally { if (droplet != null) { waitForEvent(droplet.getEventId()); api.getDropletApi().destroy(droplet.getId(), true); } } }</code><technical_language>"should". check for ID > 0, do in mock tests</technical_language>

Target:
public void testGetEvent() { DropletCreation droplet = null; try { droplet = api.getDropletApi().create("eventtest", defaultImage.getId(), defaultSize.getId(), defaultRegion.getId()); Event event = api.getEventApi().get(droplet.getEventId()); assertNotNull(event, "Droplet creation event should not be null"); assertTrue(event.getId() > 0, "Event id should be > 0"); } finally { if (droplet != null) { waitForEvent(droplet.getEventId()); api.getDropletApi().destroy(droplet.getId(), true); } } }
Source:
<code>public void move(String newFilePath) throws IOException { if (newFilePath == null) { throw new IOException(); } if (newFilePath.equals(getFilePath())) { return; } final File currentTempFile = new File(getTempFilePath()); final File currentFilePath = new File(getFilePath()); setFilePath(newFilePath); final File targetTempFile = new File(getTempFilePath()); final File targetFilePath = new File(getFilePath()); <START> FileUtil.moveAndOverwrite(currentTempFile, targetTempFile); <END> FileUtil.moveAndOverwrite(currentFilePath, targetFilePath); }</code><technical_language>I TRY move update file path</technical_language>

Target:
public void move(String newFilePath) throws IOException { if (newFilePath == null) { throw new IOException(); } if (newFilePath.equals(getFilePath())) { return; } final File currentTempFile = new File(getTempFilePath()); final File currentFilePath = new File(getFilePath()); final File targetTempFile = new File(getTempFilePath(newFilePath)); final File targetFilePath = new File(newFilePath); FileUtil.moveAndOverwrite(currentTempFile, targetTempFile); try { FileUtil.moveAndOverwrite(currentFilePath, targetFilePath); } catch (final IOException ex) { FileUtil.moveAndOverwrite(targetTempFile, currentTempFile); throw ex; } setFilePath(newFilePath); }
Source:
<code>public WebcamRecorder(WebcamVideoConfiguration configuration) { Validate.notNull(configuration, "Video configuration is null!"); this.configuration = configuration; this.frameRate = configuration.getFrameRate(); <START> screenBounds = Toolkit.getDefaultToolkit().getScreenSize(); <END> }</code><technical_language>This assumes webcam res == screen size... case. height:width set in reporter</technical_language>

Target:
public WebcamRecorder(WebcamVideoConfiguration configuration) { Validate.notNull(configuration, "Video configuration is null!"); this.configuration = configuration; this.frameRate = configuration.getFrameRate(); if (this.configuration.getWidth() > 0 && this.configuration.getHeight() > 0) { screenBounds = new Dimension(this.configuration.getWidth(), this.configuration.getHeight()); } }
Source:
<code>public void run() { long microsLower = day * 1000; long microsUpper = (day * 1000) + TimeUnit.DAYS.toMicros(1) - 1; log.info( "Running Dependencies job for {}: ≤ Span.timestamp {}", dateStamp, microsLower, microsUpper); SparkContext sc = new SparkContext(conf); try { JavaRDD<DependencyLink> links = javaFunctions(sc) <START> .cassandraTable(keyspace, "span") <END> .map(CassandraRowToSpan.INSTANCE) .groupBy(Span::traceId) .flatMapValues(new SpansToDependencyLinks(logInitializer, microsLower, microsUpper)) .values() .mapToPair(link -> new Tuple2<>(new Tuple2<>(link.parent(), link.child()), link)) .reduceByKey((l, r) -> DependencyLink.newBuilder() .parent(l.parent()) .child(l.child()) .callCount(l.callCount() + r.callCount()) .errorCount(l.errorCount() + r.errorCount()) .build()) .values(); if (links.isEmpty()) { log.info("No spans found at {}/span", keyspace); } else { log.info("Saving dependency links to {}/dependency", keyspace); AddDayToDependencyLink converter = new AddDayToDependencyLink(day); javaFunctions(links.map(converter)) .writerBuilder(keyspace, "dependency", mapToRow(DependencyLinkWithDate.class)) .saveToCassandra(); } } finally { sc.stop(); } }</code><technical_language>a good performance improvement for folks lots of data. current spark job run in a realistic amount of time current dataset. Limiting a subset of data a big win. improvement for a time though</technical_language>

Target:
public void run() { long microsLower = day * 1000; long microsUpper = (day * 1000) + TimeUnit.DAYS.toMicros(1) - 1; log.info( "Running Dependencies job for {}: ≤ Span.timestamp {}", dateStamp, microsLower, microsUpper); SparkContext sc = new SparkContext(conf); try { JavaRDD<DependencyLink> links = flatMapToLinksByTraceId( javaFunctions(sc).cassandraTable(keyspace, "span"), microsUpper, microsLower, inTest ).values() .mapToPair(link -> new Tuple2<>(new Tuple2<>(link.parent(), link.child()), link)) .reduceByKey((l, r) -> DependencyLink.newBuilder() .parent(l.parent()) .child(l.child()) .callCount(l.callCount() + r.callCount()) .errorCount(l.errorCount() + r.errorCount()) .build()) .values(); if (links.isEmpty()) { log.info("No spans found at {}/span", keyspace); } else { log.info("Saving dependency links to {}/dependency", keyspace); AddDayToDependencyLink converter = new AddDayToDependencyLink(day); javaFunctions(links.map(converter)) .writerBuilder(keyspace, "dependency", mapToRow(DependencyLinkWithDate.class)) .saveToCassandra(); } } finally { sc.stop(); } }
Source:
<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"- " \"<LINK_0>\">"); email = request.getParameter("email"); password = request.getParameter("password"); BasicUserService basicUserService = new BasicUserService(new DbUserServices()); DatabaseBuilder builder = new DatabaseBuilder(new DatabaseConnector(), "DietTracker"); try { if(!builder.CheckIfDbExists()) { builder.CreateDatabase(); } } catch (DatabaseConnectorException e) { e.printStackTrace(); } try { if(!builder.CheckIfTableExists("USERS")) { builder.CreateUserTable(); } } catch (DatabaseConnectorException e) { <START> e.printStackTrace(); <END> } try { basicUserService.createUser(email, password); out.println("successfully created. You will now be directed back to login"); } catch (PersistanceUserServicesException e) { e.printStackTrace(out); } catch (DuplicateUserException e) { e.printStackTrace(out); } }</code><technical_language>clean exception handling too. (anywhere is a catch handle exception)</technical_language>

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"- " \"<LINK_0>\">"); email = request.getParameter("email"); password = request.getParameter("password"); UserService userService = ServiceFactory.getUserServiceInstance(); try { userService.createUser(email, password); } catch (UserServiceException e) { System.err.println("Error creating user"); e.printStackTrace(); } out.println("successfully created. You will now be directed back to login"); response.setHeader("Location", "./login.html"); }
Source:
<code>public void commitAndPushExperiment(Experiment experiment) throws KaramelException { <START> String owner = experiment.getGithubOwner(); <END> String repoName = experiment.getGithubRepo(); File f = Github.getRepoDirectory(repoName); boolean repoExists = Github.repoExists(owner, repoName); if (repoExists) { if (!f.exists()) { throw new KaramelException("Remote repository already exists. Load the experiment if it already exists."); } } else { if (f.exists()) { throw new KaramelException("The remote repo does not exist, however a conflicting local directory was found. " + "Remove the local directory in ~/.karamel/cookbook_designer first, then save again."); } else { initGithubRepo(Github.getUser(), owner, repoName, experiment.getDescription()); Github.scaffoldRepo(repoName); } } ChefExperimentExtractor.parseAttributesAddToGit(owner, repoName, experiment); ChefExperimentExtractor.parseRecipesAddToGit(owner, repoName, experiment); Github.commitPush(owner, repoName); }</code><technical_language>sense a ExperimentDesignerService move logic of this method next some more class</technical_language>

Target:
public void commitAndPushExperiment(Experiment experiment) throws KaramelException { String owner = experiment.getGithubOwner(); String repoName = experiment.getGithubRepo(); File f = GithubApi.getRepoDirectory(repoName); boolean repoExists = GithubApi.repoExists(owner, repoName); if (repoExists) { if (!f.exists()) { throw new KaramelException("Remote repository already exists. Load the experiment if it already exists."); } } else { if (f.exists()) { throw new KaramelException("The remote repo does not exist, however a conflicting local directory was found. " + "Remove the local directory in ~/.karamel/cookbook_designer first, then save again."); } else { initGithubRepo(GithubApi.getUser(), owner, repoName, experiment.getDescription()); GithubApi.scaffoldRepo(repoName); } } ChefExperimentExtractor.parseAttributesAddToGit(owner, repoName, experiment); ChefExperimentExtractor.parseRecipesAddToGit(owner, repoName, experiment); GithubApi.commitPush(owner, repoName); }
Source:
<code><START> public String toString() { <END> return "ZenossToken{" + "id='" + id + '\'' + ", expires=" + expires + '}'; }</code><technical_language>Tokens sensitive. want print them</technical_language>

Target:
public String toString() { return "ZenossToken{" + "id='********'" + ", expires=" + expires + '}'; }
Source:
<code>static Long callLongGetter(Method method, Object obj) { try { method.setAccessible(true); return (Long) method.invoke(obj); } catch (Exception e) { } for (Class<?> clazz : method.getDeclaringClass().getInterfaces()) { try { Method interfaceMethod = clazz.getMethod(method.getName(), method.getParameterTypes()); <START> Long result = callLongGetter(interfaceMethod, obj); <END> if (result != null) { return result; } } catch (NoSuchMethodException e) { } } return null; }</code><technical_language>This is recursive, do need worry infinite recursion</technical_language>

Target:
static Long callLongGetter(Method method, Object obj) throws InvocationTargetException { try { return (Long) method.invoke(obj); } catch (IllegalAccessException e) { } for (Class<?> clazz : method.getDeclaringClass().getInterfaces()) { try { Method interfaceMethod = clazz.getMethod(method.getName(), method.getParameterTypes()); Long result = callLongGetter(interfaceMethod, obj); if (result != null) { return result; } } catch (NoSuchMethodException e) { } } return null; }
Source:
<code>public SongMetadata moveNext(){ if(unPlayed.size() > 0){ played.add(unPlayed.get(0)); unPlayed.remove(0); } <START> if(unPlayed.size() > 0){ <END> return unPlayed.get(0); } else { return null; } }</code><technical_language>This is condition above... is this correct? Actually, I this is song play</technical_language>

Target:
public void moveNext(){ if(unPlayed.size() > 0){ played.add(unPlayed.get(0)); unPlayed.remove(0); } else { Log.i(TAG, "Cannot moveNext out of songs"); } }
Source:
<code>public String getURI(int index) { <START> return uris.elementAt(index).toString(); <END> }</code><technical_language>Do need toString() here</technical_language>

Target:
public String getURI(int index) { return uris.get(index); }
Source:
<code><START> boolean putData(String key, Object value) { <END> if (TextUtils.isEmpty(key)) { throw new IllegalArgumentException("Preference key value cannot be empty."); } return getStorage().put(key, value); }</code><technical_language>is putData private</technical_language>

Target:
private boolean putData(String key, Object value) { if (TextUtils.isEmpty(key)) { throw new IllegalArgumentException("Preference key value cannot be empty."); } return getStorage().put(key, value); }
Source:
<code>public void addAllReviewers(ChangeAttribute a, Change change) throws OrmException { List<PatchSetApproval> approvals = db.get().patchSetApprovals().byChange(change.getId()).toList(); <START> if (approvals.isEmpty()) { <END> return; } a.allReviewers = Lists.newArrayList(); Set<Account.Id> accountIdlist = Sets.newHashSet(); for (PatchSetApproval psa : approvals) { Account.Id accountId = psa.getAccountId(); if (!accountIdlist.contains(accountId)) { accountIdlist.add(accountId); a.allReviewers.add(asAccountAttribute(psa.getAccountId())); } } }</code><technical_language>I prefer this if (!approvals.isEmpty()) { ... } block lines 176-184 moved if-block, return statement. This is a style nit; insist if others OK this</technical_language>

Target:
public void addAllReviewers(ChangeAttribute a, Change change) throws OrmException { List<PatchSetApproval> approvals = db.get().patchSetApprovals().byChange(change.getId()).toList(); if (!approvals.isEmpty()) { a.allReviewers = Lists.newArrayList(); Set<Account.Id> seen = Sets.newHashSet(); for (PatchSetApproval psa : approvals) { Account.Id id = psa.getAccountId(); if (!seen.contains(id)) { seen.add(id); a.allReviewers.add(asAccountAttribute(id)); } } } }
Source:
<code>public synchronized ICommandResult executeCommand(ICommandInput command, IProgressMonitor monitor) throws ExecutionException { Map<String, ICommandResult> commands = fScenarioMap.get(fScenario); if (commands == null) { <START> throw new IllegalStateException(); <END> } String commandLine = command.toString(); String fullCommand = commandLine; Matcher matcher = LTTNG_LIST_SESSION_PATTERN.matcher(commandLine); if (matcher.matches() && !commandLine.matches(LTTNG_LIST_PROVIDER_PATTERN)) { String sessionName = matcher.group(1).trim(); Integer i = fSessionNameMap.get(sessionName); if (i != null) { i++; } else { i = 0; } fSessionNameMap.put(sessionName, i); fullCommand += String.valueOf(i); } if (commands.containsKey(fullCommand)) { return checkNotNull(commands.get(fullCommand)); } String[] output = new String[1]; output[0] = String.valueOf("Command not found"); ICommandResult result = createCommandResult(1, output, output); return result; }</code><technical_language>checkNotNull</technical_language>

Target:
public synchronized ICommandResult executeCommand(ICommandInput command, IProgressMonitor monitor) throws ExecutionException { Map<String, ICommandResult> commands = fScenarioMap.get(fScenario); commands = checkNotNull(commands); String commandLine = command.toString(); String fullCommand = commandLine; Matcher matcher = LTTNG_LIST_SESSION_PATTERN.matcher(commandLine); if (matcher.matches() && !commandLine.matches(LTTNG_LIST_PROVIDER_PATTERN)) { String sessionName = matcher.group(1).trim(); Integer i = fSessionNameMap.get(sessionName); if (i != null) { i++; } else { i = 0; } fSessionNameMap.put(sessionName, i); fullCommand += String.valueOf(i); } if (commands.containsKey(fullCommand)) { return checkNotNull(commands.get(fullCommand)); } String[] output = new String[1]; output[0] = String.valueOf("Command not found"); ICommandResult result = createCommandResult(1, output, output); return result; }
Source:
<code>public static void removeKeyFromMap( final Map<String, ?> params, final String key ) { if ( params == null || key == null ) { logger.debug( "Map or key are null, cannot remove." ); return; } params.remove( key ); <START> if ( KEY_MAP.keySet().contains( key ) ) { <END> params.remove( KEY_MAP.get( key ) ); } else if ( KEY_MAP.values().contains( key ) ) { final Iterator<Map.Entry<String, String>> keyMapIter = KEY_MAP.entrySet().iterator(); while ( keyMapIter.hasNext() ) { final Map.Entry<String, String> entry = keyMapIter.next(); final String keyMapKey = entry.getKey(); final String keyMapValue = entry.getValue(); if ( key.equals( keyMapValue ) ) { params.remove( keyMapKey ); break; } } } }</code><technical_language>reason for prefering KEY_MAP.keySet().contains KEY_MAP.containsKey()</technical_language>

Target:
public static void removeKeyFromMap( final Map<String, ?> params, final String key ) { if ( params == null || key == null ) { logger.debug( "Map or key are null, cannot remove." ); return; } params.remove( key ); if ( KEY_MAP.containsKey( key ) ) { params.remove( KEY_MAP.get( key ) ); } else if ( KEY_MAP.containsValue( key ) ) { final Iterator<Map.Entry<String, String>> keyMapIter = KEY_MAP.entrySet().iterator(); while ( keyMapIter.hasNext() ) { final Map.Entry<String, String> entry = keyMapIter.next(); final String keyMapKey = entry.getKey(); final String keyMapValue = entry.getValue(); if ( key.equals( keyMapValue ) ) { params.remove( keyMapKey ); break; } } } }
Source:
<code>protected InputStream getInitialContents() { boolean useNewCamelRoute = true; IProject project = getJavaProject().getProject(); String version = SwitchYardModelUtils.getSwitchYardProjectRuntimeVersion(project); if (version.startsWith("2.0") || version.startsWith("1")) { useNewCamelRoute = false; } String serviceName = getService().getName(); if (serviceName != null) { if (useNewCamelRoute) { <START> return new ByteArrayInputStream(getNewRouteStubText(serviceName).getBytes()); <END> } else { return getOldRouteStubText(); } } return null; }</code><technical_language>precise encoding in toBytes UTF-8 default instead of system java.nio.charset.StandardCharsets.UTF_8 is useful get UTF-8 charset</technical_language>

Target:
protected InputStream getInitialContents() { boolean useNewCamelRoute = true; IProject project = getJavaProject().getProject(); String version = SwitchYardModelUtils.getSwitchYardProjectRuntimeVersion(project); if (version.startsWith("2.0") || version.startsWith("1")) { useNewCamelRoute = false; } String serviceName = getService().getName(); if (serviceName != null) { if (useNewCamelRoute) { return new ByteArrayInputStream( getNewRouteStubText(serviceName).getBytes( java.nio.charset.StandardCharsets.UTF_8)); } else { return getOldRouteStubText(); } } return null; }
Source:
<code>public Block bingTileCoordinates(@SqlType(BingTileType.NAME) long input) { if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); BlockBuilder tileBlockBuilder = blockBuilder.beginBlockEntry(); BingTile tile = BingTile.decode(input); <START> INTEGER.writeLong(tileBlockBuilder, tile.getX()); <END> INTEGER.writeLong(tileBlockBuilder, tile.getY()); blockBuilder.closeEntry(); pageBuilder.declarePosition(); return BING_TILE_COORDINATES_ROW_TYPE.getObject(blockBuilder, blockBuilder.getPositionCount() - 1); }</code><technical_language>restructure code decode first, write entry (so worry inconsistent throw write)</technical_language>

Target:
public Block bingTileCoordinates(@SqlType(BingTileType.NAME) long input) { if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); BingTile tile = BingTile.decode(input); BlockBuilder tileBlockBuilder = blockBuilder.beginBlockEntry(); INTEGER.writeLong(tileBlockBuilder, tile.getX()); INTEGER.writeLong(tileBlockBuilder, tile.getY()); blockBuilder.closeEntry(); pageBuilder.declarePosition(); return BING_TILE_COORDINATES_ROW_TYPE.getObject(blockBuilder, blockBuilder.getPositionCount() - 1); }
Source:
<code><START> MockClientState getMockClientWithPreviousCaughtUpTasks(final Set<TaskId> statefulActiveTasks) { <END> if (!statefulTasks.containsAll(statefulActiveTasks)) { throw new IllegalArgumentException("Need to initialize stateful tasks set before creating mock clients"); } final Map<TaskId, Long> taskLags = new HashMap<>(); for (final TaskId task : statefulTasks) { if (statefulActiveTasks.contains(task)) { taskLags.put(task, 0L); } else { taskLags.put(task, Long.MAX_VALUE); } } final MockClientState client = new MockClientState(1, taskLags); client.addPreviousActiveTasks(statefulActiveTasks); return client; }</code><technical_language>suggestion private MockClientState getMockClientWithPreviousCaughtUpTasks(final Set<TaskId> statefulActiveTasks) {</technical_language>

Target:
private MockClientState getMockClientWithPreviousCaughtUpTasks(final Set<TaskId> statefulActiveTasks) { if (!statefulTasks.containsAll(statefulActiveTasks)) { throw new IllegalArgumentException("Need to initialize stateful tasks set before creating mock clients"); } final Map<TaskId, Long> taskLags = new HashMap<>(); for (final TaskId task : statefulTasks) { if (statefulActiveTasks.contains(task)) { taskLags.put(task, 0L); } else { taskLags.put(task, Long.MAX_VALUE); } } final MockClientState client = new MockClientState(1, taskLags); client.addPreviousActiveTasks(statefulActiveTasks); return client; }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> return true; if (o == null || getClass() != o.getClass()) return false; FieldOrMethod that = (FieldOrMethod) o; return ownerIsInterface == that.ownerIsInterface && Objects.equals(owner, that.owner) && Objects.equals(name, that.name) && Objects.equals(desc, that.desc); }</code><technical_language>please fix this</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldOrMethod that = (FieldOrMethod) o; return ownerIsInterface == that.ownerIsInterface && Objects.equals(owner, that.owner) && Objects.equals(name, that.name) && Objects.equals(desc, that.desc); }
Source:
<code>public void testFindIndexForSuffixes(final String dataFileSuffix, final String indexFileSuffix, final String expectIndexSuffix) throws IOException { final File dataFile = File.createTempFile("test", dataFileSuffix); dataFile.deleteOnExit(); Assert.assertNull(SamFiles.findIndex(dataFile)); Assert.assertNull(SamFiles.findIndex(dataFile.toPath())); File indexFile = null; if (indexFileSuffix != null) { indexFile = new File(dataFile.getAbsolutePath().replaceFirst("\\.\\S+$", indexFileSuffix)); indexFile.createNewFile(); indexFile.deleteOnExit(); } final File foundIndexFile = SamFiles.findIndex(dataFile); if (expectIndexSuffix == null) { Assert.assertNull(foundIndexFile); return; } Assert.assertNotNull(foundIndexFile); Assert.assertTrue(foundIndexFile.getName().endsWith(expectIndexSuffix)); final Path foundIndexPath = SamFiles.findIndex(dataFile.toPath()); if (expectIndexSuffix == null) { Assert.assertNull(foundIndexPath); <START> return; <END> } Assert.assertNotNull(foundIndexPath); Assert.assertTrue(foundIndexPath.getFileName().toString().endsWith(expectIndexSuffix)); }</code><technical_language>Refactor out return statements this test case, replacing if/else blocks (here well) -- expectIndexSuffix == null test File case Path case</technical_language>

Target:
public void testFindIndexForSuffixes(final String dataFileSuffix, final String indexFileSuffix, final String expectIndexSuffix) throws IOException { final File dataFile = File.createTempFile("test", dataFileSuffix); dataFile.deleteOnExit(); Assert.assertNull(SamFiles.findIndex(dataFile)); Assert.assertNull(SamFiles.findIndex(dataFile.toPath())); File indexFile = null; if (indexFileSuffix != null) { indexFile = new File(dataFile.getAbsolutePath().replaceFirst("\\.\\S+$", indexFileSuffix)); indexFile.createNewFile(); indexFile.deleteOnExit(); } final File foundIndexFile = SamFiles.findIndex(dataFile); if (expectIndexSuffix == null) { Assert.assertNull(foundIndexFile); } else { Assert.assertNotNull(foundIndexFile); Assert.assertTrue(foundIndexFile.getName().endsWith(expectIndexSuffix)); } final Path foundIndexPath = SamFiles.findIndex(dataFile.toPath()); if (expectIndexSuffix == null) { Assert.assertNull(foundIndexPath); } else { Assert.assertNotNull(foundIndexPath); Assert.assertTrue(foundIndexPath.getFileName().toString().endsWith(expectIndexSuffix)); } }
Source:
<code>private static Optional<Path> findDistribution(Path projectRootDirectory) { final Path distTargetDirectory = projectRootDirectory.resolve("flink-dist").resolve("target"); try { Collection<Path> paths = FileUtils.listFilesInDirectory(distTargetDirectory, p -> p.getFileName().toString().contains("flink-dist")); if (paths.size() == 0) { <START> return Optional.empty(); <END> } if (paths.size() > 1) { LOG.warn("Detected multiple distributions under flink-dist/target. It is recommended to explicitly" + " select the distribution by setting the '{}}' property.", DISTRIBUTION_DIRECTORY.getPropertyName()); } return Optional.of(paths.iterator().next().getParent().getParent()); } catch (IOException e) { LOG.error("Error while searching for distribution.", e); return Optional.empty(); } }</code><technical_language>flink-dist/target flink-dist_2.11-1.12-SNAPSHOT.jar? this is case for me. this a problem</technical_language>

Target:
private static Optional<Path> findDistribution(Path projectRootDirectory) { final Path distTargetDirectory = projectRootDirectory.resolve("flink-dist").resolve("target"); try { Collection<Path> paths = FileUtils.listFilesInDirectory( distTargetDirectory, LocalStandaloneFlinkResourceFactory::isDistribution); if (paths.size() == 0) { return Optional.empty(); } if (paths.size() > 1) { LOG.warn("Detected multiple distributions under flink-dist/target. It is recommended to explicitly" + " select the distribution by setting the '{}}' property.", DISTRIBUTION_DIRECTORY.getPropertyName()); } return Optional.of(paths.iterator().next().getParent().getParent()); } catch (IOException e) { LOG.error("Error while searching for distribution.", e); return Optional.empty(); } }