auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void write(Batch batch) throws StageException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DataGenerator gen = null; try { gen = gcsTargetConfig.dataGeneratorFormatConfig.getDataGeneratorFactory().getGenerator(bOut); } catch (IOException e) { throw new StageException(Errors.GENERIC, e); } Iterator<Record> batchIterator = batch.getRecords(); while (batchIterator.hasNext()) { Record record = batchIterator.next(); try { gen.write(record); } catch (IOException e) { throw new StageException(Errors.GENERIC, e); } } try { gen.close(); } catch (IOException e) { throw new StageException(Errors.GENERIC, e); } if (bOut.size() > 0) { TimeEL.setCalendarInContext(elVars, calendar); TimeNowEL.setTimeNowInContext(elVars, new Date()); String partition = partitionEval.eval(elVars, gcsTargetConfig.partitionTemplate, String.class); String path = gcsTargetConfig.commonPrefix + partition + "/" + gcsTargetConfig.fileNamePrefix + UUID.randomUUID(); BlobId blobId = BlobId.of(gcsTargetConfig.bucketTemplate, path); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(getContentType()).build(); Blob blob = storage.create(blobInfo, bOut.toByteArray()); } }

Target:
public void write(Batch batch) throws StageException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); Iterator<Record> batchIterator = batch.getRecords(); while (batchIterator.hasNext()) { Record record = batchIterator.next(); DataGeneratorFactory generatorFactory = gcsTargetConfig.dataGeneratorFormatConfig.getDataGeneratorFactory(); try (DataGenerator gen = generatorFactory.getGenerator(bOut)) { gen.write(record); } catch (IOException e) { getContext().toError(record, Errors.GCS_00, e); } } if (bOut.size() > 0) { TimeEL.setCalendarInContext(elVars, calendar); TimeNowEL.setTimeNowInContext(elVars, calendar.getTime()); String partition = partitionEval.eval(elVars, gcsTargetConfig.partitionTemplate, String.class); String path = gcsTargetConfig.commonPrefix + partition + gcsTargetConfig.fileNamePrefix + UUID.randomUUID(); BlobId blobId = BlobId.of(gcsTargetConfig.bucketTemplate, path); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(getContentType()).build(); try { Blob blob = storage.create(blobInfo, bOut.toByteArray()); } catch(StorageException e) { batchIterator = batch.getRecords(); while (batchIterator.hasNext()) { getContext().toError(batchIterator.next(), e); } } } }
Source:
public void partialLoadingConceptApi() throws Exception { PageableCollectionResource<String[]> hits = new CodeSystemResourceRequest<>(CodeSystemURI.head(SnomedApiTestConstants.INT_CODESYSTEM), new RevisionIndexReadRequest<>( context -> { return SnomedRequests.prepareSearchConcept() .all() .setFields(SnomedRf2Headers.FIELD_ID, SnomedRf2Headers.FIELD_EFFECTIVE_TIME) .toRawSearch(String[].class) .build() .execute(context); } )).execute(ApplicationContext.getServiceForClass(Environment.class)); System.err.println(hits); hits.forEach(hit -> { assertNotNull(SnomedIdentifiers.create(hit[0])); assertNotNull(EffectiveTimes.parse(hit[1], DateFormats.SHORT)); }); }

Target:
public void partialLoadingConceptApi() throws Exception { PageableCollectionResource<String[]> hits = new CodeSystemResourceRequest<>(CodeSystemURI.head(SnomedApiTestConstants.INT_CODESYSTEM), new RevisionIndexReadRequest<>( context -> { return SnomedRequests.prepareSearchConcept() .all() .setFields(SnomedRf2Headers.FIELD_ID, SnomedRf2Headers.FIELD_EFFECTIVE_TIME) .toRawSearch(String[].class) .build() .execute(context); } )).execute(ApplicationContext.getServiceForClass(Environment.class)); hits.forEach(hit -> { assertNotNull(SnomedIdentifiers.create(hit[0])); assertNotNull(EffectiveTimes.parse(hit[1], DateFormats.SHORT)); }); }
Source:
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) { ex.setExceptionType(((BugsnagException) root).getType()); } return ex; }

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:
public Subscription get() { State oldState; State newState; do { oldState = state.get(); if (oldState.isUnsubscribed) { return Subscriptions.unsubscribed(); } else { newState = oldState.addChild(); } } while (!state.compareAndSet(oldState, newState)); return new InnerSubscription(this); }

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:
public void testFailureNumberedReconnectAttempts() throws Exception { try { AuditEndpoint endpoint = setupEndpointBadUdpReconnectAttempts(RECONNECT_NUMBER); } catch (IOException e) { assertEquals(e.getMessage(), "ELY11009: The maximum reconnect attempts of 10 was reached."); } }

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:
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 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); } } }

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:
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))); } return next.process(); }

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:
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 @ConfinedToDsfExecutor("fExecutor") 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)); } } }); }

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:
public ChannelFuture start() { bindFuture = bindServer(serverContext.getBossGroup(), serverContext.getWorkerGroup(), this::configureBootstrapOptions, serverContext, router, (String)serverContext.getServerConfig().get("--address"), (Integer)serverContext.getServerConfig().get("<port>")); return bindFuture.syncUninterruptibly(); }

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:
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 not 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())); } }

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:
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"); assertEquals(webhooks.size(), 0); } finally { server.shutdown(); } }

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:
public QueryResponse getFiles(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); return setQueryResponse(variantSourceEntityRepository.findAll()); }

Target:
public QueryResponse getFiles(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); return setQueryResponse(Utils.buildQueryResult(variantSourceEntityRepository.findAll())); }
Source:
public boolean isSameValue(ICPPTemplateArgument arg) { return arg.isTypeValue() && fType.isSameType(arg.getTypeValue()); }

Target:
public boolean isSameValue(ICPPTemplateArgument arg) { return fType.isSameType(arg.getTypeValue()); }
Source:
public boolean isOptional() { return optional; }

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

Target:
public void testToStringFormat() { final Status status = new Status("unknown code", "", ""); assertThat(status.toString(), matchesPattern(Status.class.getSimpleName() + "\\[.*\\]")); }
Source:
public DataCommandResult clear(Region region, String regionName) { DataPolicy policy = region.getAttributes().getDataPolicy(); 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); }

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:
public TripTimeShort(TripTimes tt, int i, Stop stop) { stopId = stop.getId(); stopTime = tt.getStopTimeByIndex(i); 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); }

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:
protected ListenableFuture<Table> modifyColumnAsync(TableName tableName, String columnName, 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); } }

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:
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(); String decision = AUTHZ_DECISION_PERMIT; final Evidence evidence = createEvidence(properties, subject); authDecisionStatements.add(OpenSAML2ComponentBuilder.getInstance().createAuthzDecisionStatement(resource, decision, AUTHZ_DECISION_ACTION_EXECUTE, evidence)); } return authDecisionStatements; }

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:
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(); if(!b) { 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(); }

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:
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) { throw capture[EXCEPTION_INDEX]; } return result; }

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:
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); out.flush(); return temp; }

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:
public int hashCode() { return Objects.hash(position, bases); }

Target:
public int hashCode() { int result = Objects.hash(position); result = 31 * result + Arrays.hashCode(bases); return result; }
Source:
private void relaunchActivityOpenJustSavedFile() { pocketMusicActivityRule.getActivity().finish(); List<SoundInfo> soundInfo = ProjectManager.getInstance().getCurrentSprite().getSoundList(); Intent pocketMusicDataIntent = null; if (soundInfo != null && !soundInfo.isEmpty()) { 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())); }

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:
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); get("/notification", this::getDataSharingNotificationForCurrentUser); }); }

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:
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); QuranSettings settings = QuranSettings.getInstance(activity); 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; }

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:
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) { } }

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:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly, boolean allowEmptyArchive) { this(artifacts, excludes, latestOnly, allowEmptyArchive, false, true); }

Target:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly, boolean allowEmptyArchive) { this(artifacts, excludes, latestOnly, allowEmptyArchive, false); }
Source:
public void putInRotation() { logger.warn("Putting host in rotation"); outOfRotation.set(false); for (ServiceRegistry serviceRegistry : serviceRegistries) { logger.info("registering with " + serviceRegistry); serviceRegistry.register(); } }

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:
protected void verifyAccesibleForSpecificUser(FeedbackSessionAttributes session) { InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); boolean isCreatorOnlyEnabled = false; 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"); } }

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:
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); assertTrue(isEqualCollection( command.getLunsToRemoveFromDb(lunsFromVgInfo, lunsFromDb), Collections.singletonList(lunFromDb))); }

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:
public boolean hasFeedbackResponseEntitiesForCourse(String courseId) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Query q = getPm().newQuery(FeedbackResponse.class); 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(); }

Target:
public boolean hasFeedbackResponseEntitiesForCourse(String courseId) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); return !getFeedbackResponseEntitiesForCourseWithinRange(courseId, 1).isEmpty(); }
Source:
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); }

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:
private double getVdsMemLimit(VDS curVds) { int computedMemoryOverCommit = (curVds.getVmCount() == 0) ? 100 : curVds.getMaxVdsMemoryOverCommit(); double vdsMemLimit = computedMemoryOverCommit * curVds.getPhysicalMemMb() / 100.0; return vdsMemLimit; }

Target:
private double getVdsMemLimit(VDS curVds) { int computedMemoryOverCommit = (curVds.getVmCount() == 0) ? 100 : curVds.getMaxVdsMemoryOverCommit(); return (computedMemoryOverCommit * curVds.getPhysicalMemMb() / 100.0); }
Source:
private boolean canItemBeCharged(ItemStack item) { 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; } }

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:
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))); 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); }

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:
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); verifyBlobPropertiesConstructionSuccess(headers); verifyUserMetadataConstructionSuccess(headers, userMetadata); }

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:
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 { ConfigService.getConfig(group).getProperty(key, null); } } return dubboConfig.getProperty(key, null); }

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:
public void example51(Vertx vertx) { NetServerOptions options = new NetServerOptions().setUseProxyProtocol(true); NetServer server = vertx.createNetServer(options); }

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:
protected QueryResult convert(List<RiakKvPB.TsGetResp> responses) { if (responses.size() > 1) { logger.error("Received responses when only one was expected.", responses.size()); } final RiakKvPB.TsGetResp response = responses.get(0); QueryResult result = TimeSeriesPBConverter.convertPbGetResp(response); return result; }

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

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:
public static String generateCorrelationId(){ return UUID.randomUUID().toString(); }

Target:
private static String generateCorrelationId(){ return UUID.randomUUID().toString(); }
Source:
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() .getBytes(Charset.defaultCharset()) ) ).toString() ) ); }

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() ) ) ); }
Source:
private void initNodeCommand(SensorContext context, File scriptFile) throws IOException { nodeCommandBuilder .outputConsumer(message -> { if (message.startsWith("DEBUG")) { LOG.debug(message.substring(5).trim()); } else { LOG.info(message); } }) .minNodeVersion(8) .configuration(context.config()) .script(scriptFile.getAbsolutePath()) .scriptArgs(String.valueOf(port)); context.config() .getInt(MAX_OLD_SPACE_SIZE_PROPERTY) .ifPresent(nodeCommandBuilder::maxOldSpaceSize); Optional<Path> typeScriptLocation = getTypeScriptLocation(context); if (typeScriptLocation.isPresent()) { LOG.debug("Using TypeScript at: '{}'", typeScriptLocation.get()); nodeCommandBuilder.addToNodePath(typeScriptLocation.get().toAbsolutePath()); } else { LOG.debug("TypeScript dependency was not found, TypeScript analysis might fail."); } nodeCommand = nodeCommandBuilder.build(); }

Target:
private void initNodeCommand(SensorContext context, File scriptFile) throws IOException { nodeCommandBuilder .outputConsumer(message -> { if (message.startsWith("DEBUG")) { LOG.debug(message.substring(5).trim()); } else { LOG.info(message); } }) .minNodeVersion(8) .configuration(context.config()) .script(scriptFile.getAbsolutePath()) .scriptArgs(String.valueOf(port)); context.config() .getInt(MAX_OLD_SPACE_SIZE_PROPERTY) .ifPresent(nodeCommandBuilder::maxOldSpaceSize); if (shouldDetectTypeScript(context.fileSystem())) { Optional<Path> typeScriptLocation = getTypeScriptLocation(context.fileSystem().baseDir()); if (typeScriptLocation.isPresent()) { LOG.info("Using TypeScript at: '{}'", typeScriptLocation.get()); nodeCommandBuilder.addToNodePath(typeScriptLocation.get().toAbsolutePath()); } else { LOG.info("TypeScript dependency was not found inside project directory, NodeJs will search TypeScript using " + "module resolution algorithm; analysis will fail without TypeScript."); } } nodeCommand = nodeCommandBuilder.build(); }