auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Exceptions readExceptions(Configuration config, JsonReader reader) throws IOException { reader.beginArray(); Throwable root = null; while (reader.hasNext()) { Throwable exc = readException(reader); if (root == null) { root = exc; } else { Throwable throwable = root; while (throwable.getCause() != null) { throwable = throwable.getCause(); } throwable.initCause(exc); } } reader.endArray(); Exceptions ex = new Exceptions(config, root); if (root != null) { <START> ex.setExceptionType(((BugsnagException) root).getType()); <END> } return ex; }</code><technical_language>I example means this cast</technical_language>

Target:
private static Exceptions readExceptions(Configuration config, JsonReader reader) throws IOException { reader.beginArray(); BugsnagException root = readException(reader); Throwable ref = root; while (reader.hasNext()) { Throwable exc = readException(reader); ref.initCause(exc); ref = exc; } reader.endArray(); Exceptions ex = new Exceptions(config, root); if (root != null) { ex.setExceptionType(root.getType()); } return ex; }
Source:
<code>public Subscription get() { State oldState; State newState; do { <START> oldState = state.get(); <END> if (oldState.isUnsubscribed) { return Subscriptions.unsubscribed(); } else { newState = oldState.addChild(); } } while (!state.compareAndSet(oldState, newState)); return new InnerSubscription(this); }</code><technical_language>field state read a local variable loop</technical_language>

Target:
public Subscription get() { State oldState; State newState; final AtomicReference<State> localState = this.state; do { oldState = localState.get(); if (oldState.isUnsubscribed) { return Subscriptions.unsubscribed(); } else { newState = oldState.addChild(); } } while (!localState.compareAndSet(oldState, newState)); return new InnerSubscription(this); }
Source:
<code>public void testFailureNumberedReconnectAttempts() throws Exception { try { AuditEndpoint endpoint = setupEndpointBadUdpReconnectAttempts(RECONNECT_NUMBER); } catch (IOException e) { <START> assertEquals(e.getMessage(), "ELY11009: The maximum reconnect attempts of 10 was reached."); <END> } }</code><technical_language>Assert.fail call this line test fails if exception is thrown</technical_language>

Target:
public void testFailureNumberedReconnectAttempts() throws Exception { Assume.assumeFalse("Test does not run on Windows Server", SystemUtils.OS_NAME.contains("Windows Server")); try { AuditEndpoint endpoint = setupEndpointBadUdpReconnectAttempts(RECONNECT_NUMBER); Assert.fail("No error was thrown while attempting to log to a bad IP with UDP."); } catch (IOException e) { assertCorrectError(e, new String[] {"ELY12001", Integer.toString(RECONNECT_NUMBER)}); } }
Source:
<code>public void removeIdleConnections() { ArrayList<ConnectionListener> destroy = null; long timeout = System.currentTimeMillis() - (poolConfiguration.getIdleTimeoutMinutes() * 1000L * 60); while (true) { synchronized (cls) { if (cls.size() == 0) break; ConnectionListener cl = cls.get(0); if (cl.isTimedOut(timeout) && (shouldRemove() || !isRunning())) { if (statistics.isEnabled()) statistics.deltaTimedOut(); cls.remove(0); if (destroy == null) destroy = new ArrayList<ConnectionListener>(1); destroy.add(cl); } else { break; } } } if (destroy != null) <START> { <END> for (ConnectionListener cl : destroy) { log.tracef("Destroying connection %s", cl); cl.destroy(); cl = null; } if (isRunning()) { boolean emptyManagedConnectionPool = false; if ((poolConfiguration.isPrefill() || poolConfiguration.isStrictMin()) && pool instanceof PrefillPool) { if (poolConfiguration.getMinSize() > 0) { PoolFiller.fillPool(this); } else { emptyManagedConnectionPool = true; } } else { emptyManagedConnectionPool = true; } if (emptyManagedConnectionPool && isEmpty()) pool.emptyManagedConnectionPool(this); } } }</code><technical_language>log message is here... other branch a message, I add this difference in log messages realizing it, in original commit</technical_language>

Target:
public void removeIdleConnections() { ArrayList<ConnectionListener> destroy = null; long timeout = System.currentTimeMillis() - (poolConfiguration.getIdleTimeoutMinutes() * 1000L * 60); while (true) { synchronized (cls) { if (cls.size() == 0) break; ConnectionListener cl = cls.get(0); if (cl.isTimedOut(timeout) && (shouldRemove() || !isRunning())) { if (statistics.isEnabled()) statistics.deltaTimedOut(); cls.remove(0); if (destroy == null) destroy = new ArrayList<ConnectionListener>(1); destroy.add(cl); } else { break; } } } if (destroy != null) { for (ConnectionListener cl : destroy) { log.tracef("Destroying timedout connection %s", cl); cl.destroy(); cl = null; } if (isRunning()) { boolean emptyManagedConnectionPool = false; if ((poolConfiguration.isPrefill() || poolConfiguration.isStrictMin()) && pool instanceof PrefillPool) { if (poolConfiguration.getMinSize() > 0) { PoolFiller.fillPool(this); } else { emptyManagedConnectionPool = true; } } else { emptyManagedConnectionPool = true; } if (emptyManagedConnectionPool && isEmpty()) pool.emptyManagedConnectionPool(this); } } }
Source:
<code>private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); <START> } <END> return next.process(); }</code><technical_language>This belong in a cleanseHeaders method. rename refactor</technical_language>

Target:
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); }
Source:
<code>public void getCPUs(final IHardwareTargetDMContext dmc, final DataRequestMonitor<ICPUDMContext[]> rm) { if (!getSessionInitializationComplete()) { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_STATE, "Debug session not initialized yet", null)); return; } getResourcesInformation(dmc, CPUResourceClass, new DataRequestMonitor<IResourcesInformation>(getExecutor(), rm) { @Override <START> @ConfinedToDsfExecutor("fExecutor") <END> protected void handleCompleted() { if (isSuccess()) { ICoreInfo[] cores = new CoreList(getData()).getCoreList(); rm.done(parseCoresInfoForCPUs(dmc, cores)); } else { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Operation not supported", null)); } } }); }</code><technical_language>Replace fExecutor (which exist) getExecutor()</technical_language>

Target:
public void getCPUs(final IHardwareTargetDMContext dmc, final DataRequestMonitor<ICPUDMContext[]> rm) { if (!getSessionInitializationComplete()) { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_STATE, "Debug session not initialized yet", null)); return; } if (coreListCache != null) { rm.done(parseCoresInfoForCPUs(dmc, coreListCache)); return; } getResourcesInformation(dmc, CPUResourceClass, new DataRequestMonitor<IResourcesInformation>(getExecutor(), rm) { @Override @ConfinedToDsfExecutor("getExecutor()") protected void handleCompleted() { if (isSuccess()) { coreListCache = new CoreList(getData()).getCoreList(); rm.done(parseCoresInfoForCPUs(dmc, coreListCache)); } else { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Operation not supported", null)); } } }); }
Source:
<code>public ChannelFuture start() { bindFuture = bindServer(serverContext.getBossGroup(), serverContext.getWorkerGroup(), this::configureBootstrapOptions, serverContext, router, (String)serverContext.getServerConfig().get("--address"), <START> (Integer)serverContext.getServerConfig().get("<port>")); <END> return bindFuture.syncUninterruptibly(); }</code><technical_language>I this work. user passes a String. need cast a string parse Integer. tests failing. need change ServerContextBuilder instead leave this is</technical_language>

Target:
public ChannelFuture start() { bindFuture = bindServer(serverContext.getBossGroup(), serverContext.getWorkerGroup(), this::configureBootstrapOptions, serverContext, router, (String)serverContext.getServerConfig().get("--address"), Integer.parseInt((String)serverContext.getServerConfig().get("<port>"))); return bindFuture.syncUninterruptibly(); }
Source:
<code>public ConfigBasedUplink make(Extension config) { String url = config.get("url").asString(); String domain = config.get("domain").asString(); String user = config.get("user").asString(); String password = config.get("password").asString(); try { if (Strings.isFilled(user)) { if (Strings.isEmpty(domain)) { <START> throw new IllegalArgumentException("A user has been specified but not domain was given!"); <END> } return new CIFSRoot(config, new SmbFile(url, new NtlmPasswordAuthentication(domain, user, password))); } else { return new CIFSRoot(config, new SmbFile(url)); } } catch (MalformedURLException e) { throw new IllegalArgumentException(Strings.apply("An invalid url (%s) was given: %s", url, e.getMessage())); } }</code><technical_language>suggestion throw new IllegalArgumentException("A user domain given!");</technical_language>

Target:
public ConfigBasedUplink make(Extension config) { String url = config.get("url").asString(); String domain = config.get("domain").asString(); String user = config.get("user").asString(); String password = config.get("password").asString(); try { if (Strings.isFilled(user)) { if (Strings.isEmpty(domain)) { throw new IllegalArgumentException("A user has been specified but no domain was given!"); } return new CIFSRoot(config, new SmbFile(url, new NtlmPasswordAuthentication(domain, user, password))); } else { return new CIFSRoot(config, new SmbFile(url)); } } catch (MalformedURLException e) { throw new IllegalArgumentException(Strings.apply("An invalid url (%s) was given: %s", url, e.getMessage())); } }
Source:
<code>public void testListWebhooksFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhook_list_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.list(); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", "/v1.0/888888/groups/1234567890/policies/321456/webhooks"); <START> assertEquals(webhooks.size(), 0); <END> } finally { server.shutdown(); } }</code><technical_language>assertTrue(webhooks.isEmpty(), "Expected webhooks was: " + webhooks), that</technical_language>

Target:
public void testListWebhooksFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhook_list_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.list(); assertAuthentication(server); assertRequest(server.takeRequest(), "GET", "/v1.0/888888/groups/1234567890/policies/321456/webhooks"); assertTrue(webhooks.isEmpty(), "Expected no webhooks, but was: " + webhooks); } finally { server.shutdown(); } }
Source:
<code>public QueryResponse getFiles(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); <START> return setQueryResponse(variantSourceEntityRepository.findAll()); <END> }</code><technical_language>I variantSourceMongoDbAdaptor.getAllSources returned a QueryResult, this is returning a list of VariantSourceEntity. Utils.buildQueryResult</technical_language>

Target:
public QueryResponse getFiles(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); return setQueryResponse(Utils.buildQueryResult(variantSourceEntityRepository.findAll())); }
Source:
<code>public boolean isSameValue(ICPPTemplateArgument arg) { <START> return arg.isTypeValue() && fType.isSameType(arg.getTypeValue()); <END> }</code><technical_language>answer question: I so. I legitimate reasons compare type non-type template arguments. Thinking of example is tricky, this: template <typename T> void foo(); // Overload template parameter kind. valid. template <int I> void foo(); template <typename T> auto bar() -> decltype(foo<T>()); // Declaration matching code need compare // template argument lists <T> <T()> determine // if this is a redeclaration overload. template <typename T> auto bar() -> decltype(foo<T()>());</technical_language>

Target:
public boolean isSameValue(ICPPTemplateArgument arg) { return fType.isSameType(arg.getTypeValue()); }
Source:
<code>public boolean isOptional() { <START> return optional; <END> }</code><technical_language>this</technical_language>

Target:
public boolean isOptional() { return this.optional; }
Source:
<code>public void testToStringFormat() { final Status status = new Status("unknown code", "", ""); final Pattern pattern = Pattern.compile(Status.class.getSimpleName() + "\\[.*\\]"); <START> assertThat(pattern.matcher(status.toString()).matches(), CoreMatchers.is(true)); <END> }</code><technical_language>consider MatchesPattern matcher</technical_language>

Target:
public void testToStringFormat() { final Status status = new Status("unknown code", "", ""); assertThat(status.toString(), matchesPattern(Status.class.getSimpleName() + "\\[.*\\]")); }
Source:
<code>public DataCommandResult clear(Region region, String regionName) { <START> DataPolicy policy = region.getAttributes().getDataPolicy(); <END> region.clear(); if (logger.isDebugEnabled()) { logger.debug("Cleared all keys in the region - {}", regionName); } return DataCommandResult.createRemoveInfoResult(null, null, null, CliStrings.format(CliStrings.REMOVE__MSG__CLEARED_ALL_KEYS, regionName), true); }</code><technical_language>This variable is used</technical_language>

Target:
public DataCommandResult clear(Region region, String regionName) { region.clear(); if (logger.isDebugEnabled()) { logger.debug("Cleared all keys in the region - {}", regionName); } return DataCommandResult.createRemoveInfoResult(null, null, null, CliStrings.format(CliStrings.CLEAR_REGION_CLEARED_ALL_KEYS, regionName), true); }
Source:
<code>public TripTimeShort(TripTimes tt, int i, Stop stop) { stopId = stop.getId(); stopTime = tt.getStopTimeByIndex(i); <START> stopIndex = i; <END> stopCount = tt.getNumStops(); scheduledArrival = tt.getScheduledArrivalTime(i); realtimeArrival = tt.getArrivalTime(i); arrivalDelay = tt.getArrivalDelay(i); scheduledDeparture = tt.getScheduledDepartureTime(i); realtimeDeparture = tt.getDepartureTime(i); departureDelay = tt.getDepartureDelay(i); timepoint = tt.isTimepoint(i); realtime = !tt.isScheduled(); realtimeState = tt.getRealTimeState(); blockId = tt.trip.getBlockId(); headsign = tt.getHeadsign(i); }</code><technical_language>Remove stopTime ..</technical_language>

Target:
public TripTimeShort(TripTimes tt, int i, Stop stop) { stopId = stop.getId(); stopIndex = i; stopCount = tt.getNumStops(); scheduledArrival = tt.getScheduledArrivalTime(i); realtimeArrival = tt.getArrivalTime(i); arrivalDelay = tt.getArrivalDelay(i); scheduledDeparture = tt.getScheduledDepartureTime(i); realtimeDeparture = tt.getDepartureTime(i); departureDelay = tt.getDepartureDelay(i); timepoint = tt.isTimepoint(i); realtime = !tt.isScheduled(); realtimeState = tt.getRealTimeState(); blockId = tt.trip.getBlockId(); headsign = tt.getHeadsign(i); }
Source:
<code><START> protected ListenableFuture<Table> modifyColumnAsync(TableName tableName, String columnName, <END> String modificationType, Modification.Builder modification) throws IOException { ModifyColumnFamiliesRequest.Builder modifyColumnBuilder = ModifyColumnFamiliesRequest .newBuilder().addModifications(modification).setName(toBigtableName(tableName)); try { return bigtableTableAdminClient.modifyColumnFamilyAsync(modifyColumnBuilder.build()); } catch (Throwable throwable) { throw new IOException( String.format( "Failed to %s column '%s' in table '%s'", modificationType, columnName, tableName.getNameAsString()), throwable); } }</code><technical_language>Please this return a CompletableFuture<Void> callers repeat translation over</technical_language>

Target:
protected CompletableFuture<Void> modifyColumnAsync(TableName tableName, String columnName, String modificationType, Modification.Builder modification) { ModifyColumnFamiliesRequest.Builder modifyColumnBuilder = ModifyColumnFamiliesRequest .newBuilder().addModifications(modification).setName(toBigtableName(tableName)); return FutureUtils.toCompletableFuture( bigtableTableAdminClient.modifyColumnFamilyAsync(modifyColumnBuilder.build())) .thenApply(r -> null); }
Source:
<code>public List<AuthzDecisionStatement> createAuthorizationDecisionStatements(final CallbackProperties properties, final Subject subject) { final List<AuthzDecisionStatement> authDecisionStatements = new ArrayList<>(); final Boolean hasAuthzStmt = properties.getAuthorizationStatementExists(); if (hasAuthzStmt) { final String resource = properties.getAuthorizationResource(); <START> String decision = AUTHZ_DECISION_PERMIT; <END> final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, decision, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; }</code><technical_language>Unneeded local variable, put constant method a couple lines below</technical_language>

Target:
public List<AuthzDecisionStatement> createAuthorizationDecisionStatements(final CallbackProperties properties, final Subject subject) { final List<AuthzDecisionStatement> authDecisionStatements = new ArrayList<>(); final Boolean hasAuthzStmt = properties.getAuthorizationStatementExists(); if (hasAuthzStmt) { final String resource = properties.getAuthorizationResource(); final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, AUTHZ_DECISION_PERMIT, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; }
Source:
<code>public static ACE fromId(String aceId) { if (aceId == null) { return null; } ArrayList<String> tokenList = new ArrayList<>(); Pattern p = Pattern.compile("^(.+):([^:]+):([^:]+):([^:]*):([^:]*):([^:]*)$"); Matcher m = p.matcher(aceId); boolean b = m.matches(); <START> if(!b) { <END> throw new IllegalArgumentException(String.format("Invalid ACE id: %s", aceId)); } for(int i=1; i <= m.groupCount(); i++) { tokenList.add(m.group(i)); } String[] parts = new String[tokenList.size()]; parts = tokenList.toArray(new String[]{}); String username = parts[0]; String permission = parts[1]; boolean isGranted = Boolean.valueOf(parts[2]); ACEBuilder builder = ACE.builder(username, permission).isGranted(isGranted); if (parts.length >= 4 && StringUtils.isNotBlank(parts[3])) { builder.creator(parts[3]); } if (parts.length >= 5 && StringUtils.isNotBlank(parts[4])) { Calendar begin = new GregorianCalendar(); begin.setTimeInMillis(Long.valueOf(parts[4])); builder.begin(begin); } if (parts.length >= 6 && StringUtils.isNotBlank(parts[5])) { Calendar end = new GregorianCalendar(); end.setTimeInMillis(Long.valueOf(parts[5])); builder.end(end); } return builder.build(); }</code><technical_language>Add space if (. need for a separate b variable, do if (!m.matches())</technical_language>

Target:
public static ACE fromId(String aceId) { if (aceId == null) { return null; } Matcher m = ID_PATTERN.matcher(aceId); if (!m.matches()) { throw new IllegalArgumentException(String.format("Invalid ACE id: %s", aceId)); } String[] parts = new String[m.groupCount()]; for (int i = 1; i <= m.groupCount(); i++) { parts[i - 1] = m.group(i); } String username = parts[0]; String permission = parts[1]; boolean isGranted = Boolean.valueOf(parts[2]); ACEBuilder builder = ACE.builder(username, permission).isGranted(isGranted); if (parts.length >= 4 && StringUtils.isNotBlank(parts[3])) { builder.creator(parts[3]); } if (parts.length >= 5 && StringUtils.isNotBlank(parts[4])) { Calendar begin = new GregorianCalendar(); begin.setTimeInMillis(Long.valueOf(parts[4])); builder.begin(begin); } if (parts.length >= 6 && StringUtils.isNotBlank(parts[5])) { Calendar end = new GregorianCalendar(); end.setTimeInMillis(Long.valueOf(parts[5])); builder.end(end); } return builder.build(); }
Source:
<code>private Object getConfigurationValueException(String fieldName) throws IOException { final IOException[] capture = new IOException[1]; final int EXCEPTION_INDEX = 0; Object result = env.syncReadConfiguration(configuration -> { try { return ClassUtil.getFieldValue(configuration, fieldName); } catch (IOException ex) { capture[EXCEPTION_INDEX] = ex; return null; } }); if (capture[EXCEPTION_INDEX] != null) { <START> throw capture[EXCEPTION_INDEX]; <END> } return result; }</code><technical_language>exception is translated throw new WebApplicationException(e, Response.Status.BAD_REQUEST) thro remove try block in caller</technical_language>

Target:
private Object getConfigurationValueException(String fieldName) throws WebApplicationException { final IOException[] capture = new IOException[1]; final int IOE_INDEX = 0; Object result = env.syncReadConfiguration(configuration -> { try { return ClassUtil.getFieldValue(configuration, fieldName); } catch (IOException ex) { capture[IOE_INDEX] = ex; return null; } }); if (capture[IOE_INDEX] != null) { throw new WebApplicationException(capture[IOE_INDEX], Response.Status.BAD_REQUEST); } return result; }
Source:
<code>protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); Process chmodProcess = Runtime.getRuntime().exec("chmod 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); <START> out.flush(); <END> return temp; }</code><technical_language>for catching this before, need "out.close()", leak file descriptor</technical_language>

Target:
protected File createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); Process chmodProcess = Runtime.getRuntime().exec("chmod 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.flush(); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { } } } return temp; }
Source:
<code>public int hashCode() { <START> return Objects.hash(position, bases); <END> }</code><technical_language>this memory location of bases instead of base values</technical_language>

Target:
public int hashCode() { int result = Objects.hash(position); result = 31 * result + Arrays.hashCode(bases); return result; }
Source:
<code>private void relaunchActivityOpenJustSavedFile() { pocketMusicActivityRule.getActivity().finish(); List<SoundInfo> soundInfo = ProjectManager.getInstance().getCurrentSprite().getSoundList(); Intent pocketMusicDataIntent = null; <START> if (soundInfo != null && !soundInfo.isEmpty()) { <END> pocketMusicDataIntent = new Intent(); pocketMusicDataIntent.putExtra("FILENAME", soundInfo.get(0).getSoundFileName()); pocketMusicDataIntent.putExtra("TITLE", soundInfo.get(0).getTitle()); } pocketMusicActivityRule.launchActivity(pocketMusicDataIntent); onView(withId(android.R.id.content)).check(matches(isDisplayed())); }</code><technical_language>i guess test calling this fail if this is null, for ease of debugging if breaks wouldnt nicer do like: assertNotNull(soundInfo) assertFalse(soundInfo.isEmpty()); instead of if(...)</technical_language>

Target:
private void relaunchActivityOpenJustSavedFile() { pocketMusicActivityRule.getActivity().finish(); List<SoundInfo> soundInfo = ProjectManager.getInstance().getCurrentSprite().getSoundList(); assertNotNull("Soundinfo not found", soundInfo); assertFalse("Soundinfo not found", soundInfo.isEmpty()); Intent pocketMusicDataIntent = new Intent(); pocketMusicDataIntent.putExtra("FILENAME", soundInfo.get(0).getSoundFileName()); pocketMusicDataIntent.putExtra("TITLE", soundInfo.get(0).getTitle()); pocketMusicActivityRule.launchActivity(pocketMusicDataIntent); onView(withId(android.R.id.content)).check(matches(isDisplayed())); }
Source:
<code>public void setupRoutes() { path(controllerPath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", this::verifyContentType); before("/*", this::verifyContentType); before("", mimeType, apiAuthenticationHelper::checkUserAnd403); before("", mimeType, this::checkAdminUserAnd403OnlyForPatch); before("/notification", mimeType, apiAuthenticationHelper::checkUserAnd403); get("", this::getDataSharingSettings); patch("", mimeType, this::patchDataSharingSettings); <START> get("/notification", this::getDataSharingNotificationForCurrentUser); <END> }); }</code><technical_language>endpoint reads /go/api/data_sharing/settings/notification impression of API returning settings notification. Whereas, API answers authorization for showing notification. /go/api/data_sharing/settings/notification_auth</technical_language>

Target:
public void setupRoutes() { path(controllerPath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", this::verifyContentType); before("/*", this::verifyContentType); before("", mimeType, apiAuthenticationHelper::checkUserAnd403); before("", mimeType, this::checkAdminUserAnd403OnlyForPatch); before("/notification_auth", mimeType, apiAuthenticationHelper::checkUserAnd403); get("", this::getDataSharingSettings); patch("", mimeType, this::patchDataSharingSettings); get("/notification_auth", this::getDataSharingNotificationForCurrentUser); }); }
Source:
<code>private QuranRow[] getSuraList() { int next; int pos = 0; int sura = 1; QuranRow[] elements = new QuranRow[SURAS_COUNT + JUZ2_COUNT]; Activity activity = getActivity(); boolean wantPrefix = activity.getResources().getBoolean(R.bool.show_surat_prefix); <START> QuranSettings settings = QuranSettings.getInstance(activity); <END> boolean wantTranslation = settings.isShowSuraTranslatedName(); for (int juz = 1; juz <= JUZ2_COUNT; juz++) { final String headerTitle = activity.getString(R.string.juz2_description, QuranUtils.getLocalizedNumber(activity, juz)); final QuranRow.Builder headerBuilder = new QuranRow.Builder() .withType(QuranRow.HEADER) .withText(headerTitle) .withPage(quranInfo.getStartingPageForJuz(juz)); elements[pos++] = headerBuilder.build(); next = (juz == JUZ2_COUNT) ? numberOfPages + 1 : quranInfo.getStartingPageForJuz(juz + 1); while ((sura <= SURAS_COUNT) && (quranInfo.getPageNumberForSura(sura) < next)) { final QuranRow.Builder builder = new QuranRow.Builder() .withText(quranDisplayData.getSuraName(activity, sura, wantPrefix, wantTranslation)) .withMetadata(quranDisplayData.getSuraListMetaString(activity, sura)) .withSura(sura) .withPage(quranInfo.getPageNumberForSura(sura)); elements[pos++] = builder.build(); sura++; } } return elements; }</code><technical_language>replace with: @Inject QuranSettings quranSettings; field top</technical_language>

Target:
private QuranRow[] getSuraList() { int next; int pos = 0; int sura = 1; QuranRow[] elements = new QuranRow[SURAS_COUNT + JUZ2_COUNT]; Activity activity = getActivity(); boolean wantPrefix = activity.getResources().getBoolean(R.bool.show_surat_prefix); boolean wantTranslation = quranSettings.isShowSuraTranslatedName(); for (int juz = 1; juz <= JUZ2_COUNT; juz++) { final String headerTitle = activity.getString(R.string.juz2_description, QuranUtils.getLocalizedNumber(activity, juz)); final QuranRow.Builder headerBuilder = new QuranRow.Builder() .withType(QuranRow.HEADER) .withText(headerTitle) .withPage(quranInfo.getStartingPageForJuz(juz)); elements[pos++] = headerBuilder.build(); next = (juz == JUZ2_COUNT) ? numberOfPages + 1 : quranInfo.getStartingPageForJuz(juz + 1); while ((sura <= SURAS_COUNT) && (quranInfo.getPageNumberForSura(sura) < next)) { final QuranRow.Builder builder = new QuranRow.Builder() .withText(quranDisplayData.getSuraName(activity, sura, wantPrefix, wantTranslation)) .withMetadata(quranDisplayData.getSuraListMetaString(activity, sura)) .withSura(sura) .withPage(quranInfo.getPageNumberForSura(sura)); elements[pos++] = builder.build(); sura++; } } return elements; }
Source:
<code>public void TopicPublisher() throws AxisFault { try { MqttClient mqttClient = new MqttClient(SERVER_URL, CLIENT_ID); MqttConnectOptions clientOptions = new MqttConnectOptions(); mqttClient.setCallback(new SampleMqttCallBack()); mqttClient.connect(clientOptions); if (mqttClient.isConnected()) { System.out.println("Mqtt client connected successfully..."); MqttTopic topic = mqttClient.getTopic("esb.test2"); MqttMessage message = new MqttMessage(); message.setPayload(PAYLOAD.getBytes()); message.setRetained(true); } mqttClient.disconnect(); MqttClient mqttClient1 = new MqttClient(SERVER_URL,CLIENT_ID); MqttConnectOptions cleintOptions = new MqttConnectOptions(); mqttClient.setCallback(new SampleMqttCallBack()); mqttClient.connect(cleintOptions); if (mqttClient1.isConnected()) { System.out.println("Mqtt client connected successfully..."); MqttTopic topic = mqttClient.getTopic("esb.test2"); mqttClient1.subscribe(topic.toString()); } } catch(Exception e) <START> { <END> } }</code><technical_language>add a log statement</technical_language>

Target:
public void TopicPublisher() throws AxisFault { try { MqttClient mqttClient = new MqttClient(SERVER_URL, CLIENT_ID); MqttConnectOptions clientOptions = new MqttConnectOptions(); mqttClient.setCallback(new SampleMqttCallBack()); mqttClient.connect(clientOptions); if (mqttClient.isConnected()) { log.info("Mqtt client connected successfully..."); MqttTopic topic = mqttClient.getTopic("esb.test2"); MqttMessage message = new MqttMessage(); message.setPayload(PAYLOAD.getBytes()); message.setRetained(true); } mqttClient.disconnect(); MqttClient mqttClient1 = new MqttClient(SERVER_URL,CLIENT_ID); MqttConnectOptions cleintOptions = new MqttConnectOptions(); mqttClient.setCallback(new SampleMqttCallBack()); mqttClient.connect(cleintOptions); if (mqttClient1.isConnected()) { log.info("Mqtt client connected successfully..."); MqttTopic topic = mqttClient.getTopic("esb.test2"); mqttClient1.subscribe(topic.toString()); } } catch(Exception e) { log.error("Error in connecting to client"); } }
Source:
<code>public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly, boolean allowEmptyArchive) { <START> this(artifacts, excludes, latestOnly, allowEmptyArchive, false, true); <END> }</code><technical_language>this change</technical_language>

Target:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly, boolean allowEmptyArchive) { this(artifacts, excludes, latestOnly, allowEmptyArchive, false); }
Source:
<code>public void putInRotation() { logger.warn("Putting host in rotation"); outOfRotation.set(false); for (ServiceRegistry serviceRegistry : serviceRegistries) { <START> logger.info("registering with " + serviceRegistry); <END> serviceRegistry.register(); } }</code><technical_language>Registering ServiceRegistry more explicit (also, SLF4J form, instead of concatenation)</technical_language>

Target:
public void putInRotation() { logger.warn("Putting host in rotation"); outOfRotation.set(false); for (ServiceRegistry serviceRegistry : serviceRegistries) { logger.info("Registering ServiceRegistry {}", serviceRegistry); try { serviceRegistry.register(); } catch (RuntimeException e) { logger.warn("Failed to register ServiceRegistry {}. Exception: {}", serviceRegistry, e); } } }
Source:
<code>protected void verifyAccesibleForSpecificUser(FeedbackSessionAttributes session) { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); <START> boolean isCreatorOnlyEnabled = false; <END> gateKeeper.verifyAccessible(instructor, session, isCreatorOnlyEnabled); boolean shouldEnableSubmit = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS); if (!shouldEnableSubmit && instructor.isAllowedForPrivilegeAnySection(session.getFeedbackSessionName(), Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS)) { shouldEnableSubmit = true; } if (!shouldEnableSubmit) { throw new UnauthorizedAccessException("Feedback session [" + session.getFeedbackSessionName() + "] is not accessible to instructor [" + instructor.email + "] for this purpose"); } }</code><technical_language>isEnabledForCreatorOnly sounds</technical_language>

Target:
protected void verifyAccesibleForSpecificUser(FeedbackSessionAttributes session) { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); boolean isCreatorOnly = false; gateKeeper.verifyAccessible(instructor, session, isCreatorOnly); boolean shouldEnableSubmit = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS); if (!shouldEnableSubmit && instructor.isAllowedForPrivilegeAnySection(session.getFeedbackSessionName(), Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS)) { shouldEnableSubmit = true; } if (!shouldEnableSubmit) { throw new UnauthorizedAccessException("Feedback session [" + session.getFeedbackSessionName() + "] is not accessible to instructor [" + instructor.email + "] for this purpose"); } }
Source:
<code>public void testGetLunsToRemoveFromDb() { lunFromVg.setLUNId(Guid.newGuid().toString()); lunFromDb.setLUNId(Guid.newGuid().toString()); LUNs dummyLun = new LUNs(); dummyLun.setId(BusinessEntitiesDefinitions.DUMMY_LUN_ID_PREFIX + Guid.newGuid().toString()); List<LUNs> lunsFromVgInfo = Collections.singletonList(lunFromVg); List<LUNs> lunsFromDb = Arrays.asList(lunFromDb, dummyLun); <START> assertTrue(isEqualCollection( command.getLunsToRemoveFromDb(lunsFromVgInfo, lunsFromDb), Collections.singletonList(lunFromDb))); <END> }</code><technical_language>a simple assertEquals do here</technical_language>

Target:
public void testGetLunsToRemoveFromDb() { lunFromVg.setLUNId(Guid.newGuid().toString()); lunFromDb.setLUNId(Guid.newGuid().toString()); LUNs dummyLun = new LUNs(); dummyLun.setId(BusinessEntitiesDefinitions.DUMMY_LUN_ID_PREFIX + Guid.newGuid().toString()); List<LUNs> lunsFromVgInfo = Collections.singletonList(lunFromVg); List<LUNs> lunsFromDb = Arrays.asList(lunFromDb, dummyLun); assertEquals(command.getLunsToRemoveFromDb(lunsFromVgInfo, lunsFromDb), Collections.singletonList(lunFromDb)); }
Source:
<code>public boolean hasFeedbackResponseEntitiesForCourse(String courseId) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); <START> Query q = getPm().newQuery(FeedbackResponse.class); <END> q.declareParameters("String courseIdParam"); q.setFilter("courseId == courseIdParam"); q.setRange(0, 1); @SuppressWarnings("unchecked") List<FeedbackResponse> responses = (List<FeedbackResponse>) q.execute(courseId); return !responses.isEmpty(); }</code><technical_language>this portion (line 701 -707) extracted getFeedbackResponseEntitiesForCourseWithinRange, method reused in future</technical_language>

Target:
public boolean hasFeedbackResponseEntitiesForCourse(String courseId) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); return !getFeedbackResponseEntitiesForCourseWithinRange(courseId, 1).isEmpty(); }
Source:
<code>public <K, V> CompletionStage<KeyValueStore<K, V>> getKeyValueStore(String name, KeyValueStoreConfig config) { return CompletableFuture.supplyAsync(() -> { addProtobufSchema(config); RemoteCache<K, V> cache = cacheManager.getCache(name, false); RemoteCache<K, V> cacheWithReturnValues = cacheManager.getCache(name, true); <START> return new KeyValueStoreImpl(cache, cacheWithReturnValues); <END> }, asyncExecutorService); }</code><technical_language><> missing</technical_language>

Target:
public <K, V> CompletionStage<KeyValueStore<K, V>> getKeyValueStore(String name, KeyValueStoreConfig config) { return CompletableFuture.supplyAsync(() -> { addProtobufSchema(config); RemoteCache<K, V> cache = cacheManager.getCache(name, false); RemoteCache<K, V> cacheWithReturnValues = cacheManager.getCache(name, true); return new KeyValueStoreImpl<>(cache, cacheWithReturnValues); }, asyncExecutorService); }
Source:
<code>private double getVdsMemLimit(VDS curVds) { int computedMemoryOverCommit = (curVds.getVmCount() == 0) ? 100 : curVds.getMaxVdsMemoryOverCommit(); <START> double vdsMemLimit = computedMemoryOverCommit * curVds.getPhysicalMemMb() / 100.0; <END> return vdsMemLimit; }</code><technical_language>variable left outuua</technical_language>

Target:
private double getVdsMemLimit(VDS curVds) { int computedMemoryOverCommit = (curVds.getVmCount() == 0) ? 100 : curVds.getMaxVdsMemoryOverCommit(); return (computedMemoryOverCommit * curVds.getPhysicalMemMb() / 100.0); }
Source:
<code>private boolean canItemBeCharged(ItemStack item) { <START> if (item.getItem() instanceof ISteamChargable) { <END> return ((ISteamChargable) item.getItem()).canCharge(item); } else { if (CrossMod.TINKERS_CONSTRUCT && item.getItem() instanceof ToolCore) { NBTTagCompound nbt = item.getTagCompound(); return nbt.getCompoundTag("InfiTool").hasKey("Steam"); } return item.getItem() == SteamcraftItems.steamcellEmpty; } }</code><technical_language>item != null &&</technical_language>

Target:
private boolean canItemBeCharged(ItemStack item) { if (item == null) { return false; } if (item.getItem() instanceof ISteamChargable) { return ((ISteamChargable) item.getItem()).canCharge(item); } else { if (CrossMod.TINKERS_CONSTRUCT && item.getItem() instanceof ToolCore) { NBTTagCompound nbt = item.getTagCompound(); return nbt.getCompoundTag("InfiTool").hasKey("Steam"); } return item.getItem() == SteamcraftItems.steamcellEmpty; } }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Project project = call.rel(1); if (RexOver.containsOver(project.getProjects(), null)) { return; } RexNode newCondition = RelOptUtil.pushPastProject(filter.getCondition(), project); final RelBuilder relBuilder = call.builder(); RelNode newFilterRel; if (copyFilter) { final RelNode input = project.getInput(); final RelTraitSet traitSet = filter.getTraitSet() .replaceIfs(RelCollationTraitDef.INSTANCE, <START> () -> Collections.singletonList( <END> input.getTraitSet().getTrait(RelCollationTraitDef.INSTANCE))); newFilterRel = filter.copy(traitSet, input, simplifyFilterCondition(newCondition, call)); } else { newFilterRel = relBuilder.push(project.getInput()).filter(newCondition).build(); } RelNode newProjRel = copyProject ? project.copy(project.getTraitSet(), newFilterRel, project.getProjects(), project.getRowType()) : relBuilder.push(newFilterRel) .project(project.getProjects(), project.getRowType().getFieldNames()) .build(); call.transformTo(newProjRel); }</code><technical_language>RelDistribution trait? problem</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Project project = call.rel(1); if (RexOver.containsOver(project.getProjects(), null)) { return; } RexNode newCondition = RelOptUtil.pushPastProject(filter.getCondition(), project); final RelBuilder relBuilder = call.builder(); RelNode newFilterRel; if (copyFilter) { final RelNode input = project.getInput(); final RelTraitSet traitSet = filter.getTraitSet() .replaceIfs(RelCollationTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelCollationTraitDef.INSTANCE))) .replaceIfs(RelDistributionTraitDef.INSTANCE, () -> Collections.singletonList( input.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE))); newFilterRel = filter.copy(traitSet, input, simplifyFilterCondition(newCondition, call)); } else { newFilterRel = relBuilder.push(project.getInput()).filter(newCondition).build(); } RelNode newProjRel = copyProject ? project.copy(project.getTraitSet(), newFilterRel, project.getProjects(), project.getRowType()) : relBuilder.push(newFilterRel) .project(project.getProjects(), project.getRowType().getFieldNames()) .build(); call.transformTo(newProjRel); }
Source:
<code>public void getUserMetadataGoodInputTest() throws Exception { JSONObject headers = new JSONObject(); setAmbryHeaders(headers, Long.toString(RANDOM.nextInt(10000)), Long.toString(RANDOM.nextInt(10000)), Boolean.toString(RANDOM.nextBoolean()), generateRandomString(10), "image/gif", generateRandomString(10)); Map<String, List<String>> userMetadata = new HashMap<String, List<String>>(); userMetadata.put(RestUtils.Headers.UserMetaData_Header_Prefix + "key1", new ArrayList<String>(Arrays.asList("value1_1", "value1_2"))); userMetadata.put(RestUtils.Headers.UserMetaData_Header_Prefix + "key2", new ArrayList<String>(Arrays.asList("value2_1", "value2_2"))); RestUtils.setAmbryHeaders(headers, userMetadata); <START> verifyBlobPropertiesConstructionSuccess(headers); <END> verifyUserMetadataConstructionSuccess(headers, userMetadata); }</code><technical_language>do need this setAmbryHeaders()? leave out checking of blob properties right (it is checked in another function)</technical_language>

Target:
public void getUserMetadataGoodInputTest() throws Exception { JSONObject headers = new JSONObject(); setAmbryHeaders(headers, Long.toString(RANDOM.nextInt(10000)), Long.toString(RANDOM.nextInt(10000)), Boolean.toString(RANDOM.nextBoolean()), generateRandomString(10), "image/gif", generateRandomString(10)); Map<String, String> userMetadata = new HashMap<String, String>(); userMetadata.put(RestUtils.Headers.UserMetaData_Header_Prefix + "key1", "value1"); userMetadata.put(RestUtils.Headers.UserMetaData_Header_Prefix + "key2", "value2"); setUserMetadataHeaders(headers, userMetadata); verifyBlobPropertiesConstructionSuccess(headers); verifyUserMetadataConstructionSuccess(headers, userMetadata); }
Source:
<code>public String getConfig(String key, String group, long timeout) throws IllegalStateException { if (StringUtils.isNotEmpty(group)) { if (group.equals(url.getParameter(Constants.APPLICATION_KEY))) { return ConfigService.getAppConfig().getProperty(key, null); } else { <START> ConfigService.getConfig(group).getProperty(key, null); <END> } } return dubboConfig.getProperty(key, null); }</code><technical_language>need add return statement here</technical_language>

Target:
public String getConfig(String key, String group, long timeout) throws IllegalStateException { if (StringUtils.isNotEmpty(group)) { if (group.equals(url.getParameter(APPLICATION_KEY))) { return ConfigService.getAppConfig().getProperty(key, null); } else { return ConfigService.getConfig(group).getProperty(key, null); } } return dubboConfig.getProperty(key, null); }
Source:
<code>public void example51(Vertx vertx) { NetServerOptions options = new NetServerOptions().setUseProxyProtocol(true); <START> NetServer server = vertx.createNetServer(options); <END> }</code><technical_language>I add: java server.connectHandler(so -> { // Print actual client address provided HA proxy protocol instead of proxy address System.out.println(so.remoteAddress()); });</technical_language>

Target:
public void example51(Vertx vertx) { NetServerOptions options = new NetServerOptions().setUseProxyProtocol(true); NetServer server = vertx.createNetServer(options); server.connectHandler(so -> { System.out.println(so.remoteAddress()); System.out.println(so.localAddress()); }); }
Source:
<code>protected QueryResult convert(List<RiakKvPB.TsGetResp> responses) { if (responses.size() > 1) { <START> logger.error("Received responses when only one was expected.", responses.size()); <END> } final RiakKvPB.TsGetResp response = responses.get(0); QueryResult result = TimeSeriesPBConverter.convertPbGetResp(response); return result; }</code><technical_language>This check is a good candidate moved PBFutureOperation generalize behavior</technical_language>

Target:
protected QueryResult convert(List<RiakKvPB.TsGetResp> responses) { final RiakKvPB.TsGetResp response = checkAndGetSingleResponse(responses); return TimeSeriesPBConverter.convertPbGetResp(response); }
Source:
<code><START> public String getTopicUuid(){ <END> String topicId = ""; try { topicId = getAsString(ForumsXPath.inReplyTo); } catch (Exception e) if(StringUtil.isEmpty(topicId)){ topicId = topicUuid; } return extractForumUuid(topicId); }</code><technical_language>API doc needed</technical_language>

Target:
public String getTopicUuid(){ String topicId = ""; try { topicId = getAsString(ForumsXPath.inReplyTo); } catch (Exception e) if(StringUtil.isEmpty(topicId)){ topicId = (String) fields.get("topicUuid"); } return extractForumUuid(topicId); }
Source:
<code><START> public static String generateCorrelationId(){ <END> return UUID.randomUUID().toString(); }</code><technical_language>public static [](start = 4, length = 14) public? if needed in a helper/utility class instead</technical_language>

Target:
private static String generateCorrelationId(){ return UUID.randomUUID().toString(); }
Source:
<code>public void addsCookieToResponse() throws IOException { final String msg = "hey, how are you?"; MatcherAssert.assertThat( new RsPrint( new RsFlash(msg) ).print(), Matchers.containsString( new StringBuilder("Set-Cookie: RsFlash=") .append( DatatypeConverter.printBase64Binary( new StringBuilder( Level.INFO.getName() ) .append('/') .append(msg) .toString() <START> .getBytes(Charset.defaultCharset()) <END> ) ).toString() ) ); }</code><technical_language>@dmzaytsev utf-8 idea here</technical_language>

Target:
public void addsCookieToResponse() throws IOException { final String msg = "hey, how are you?"; MatcherAssert.assertThat( new RsPrint( new RsFlash(msg) ).print(), Matchers.containsString( String.format( "Set-Cookie: RsFlash=%s/%s", URLEncoder.encode( msg, Charset.defaultCharset().name() ), Level.INFO.getName() ) ) ); }