auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testZsetInboundConfigurationWithSingleScoreAndSynchronization() throws Exception{ RedisConnectionFactory jcf = this.getConnectionFactoryForTest(); this.prepareZset(jcf); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("zset-inbound-adapter.xml", this.getClass()); SourcePollingChannelAdapter zsetAdapterWithSingleScoreAndSynchronization = context.getBean("zsetAdapterWithSingleScoreAndSynchronization", SourcePollingChannelAdapter.class); SourcePollingChannelAdapter zsetAdapterNoScore = context.getBean("zsetAdapterNoScore", SourcePollingChannelAdapter.class); QueueChannel redisChannel = context.getBean("redisChannel", QueueChannel.class); QueueChannel otherRedisChannel = context.getBean("otherRedisChannel", QueueChannel.class); zsetAdapterNoScore.start(); Message<RedisZSet<Object>> message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(13, message.getPayload().size()); zsetAdapterNoScore.stop(); zsetAdapterWithSingleScoreAndSynchronization.start(); message = (Message<RedisZSet<Object>>) otherRedisChannel.receive(1000); assertNotNull(message); assertEquals(2, message.getPayload().rangeByScore(18, 18).size()); Thread.sleep(1000); zsetAdapterNoScore.start(); message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(11, message.getPayload().size()); zsetAdapterNoScore.stop(); context.close(); }

Target:
public void testZsetInboundConfigurationWithSingleScoreAndSynchronization() throws Exception{ RedisConnectionFactory jcf = this.getConnectionFactoryForTest(); this.prepareZset(jcf); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("zset-inbound-adapter.xml", this.getClass()); SourcePollingChannelAdapter zsetAdapterWithSingleScoreAndSynchronization = context.getBean("zsetAdapterWithSingleScoreAndSynchronization", SourcePollingChannelAdapter.class); SourcePollingChannelAdapter zsetAdapterNoScore = context.getBean("zsetAdapterNoScore", SourcePollingChannelAdapter.class); QueueChannel redisChannel = context.getBean("redisChannel", QueueChannel.class); QueueChannel otherRedisChannel = context.getBean("otherRedisChannel", QueueChannel.class); zsetAdapterNoScore.start(); Message<RedisZSet<Object>> message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(13, message.getPayload().size()); zsetAdapterNoScore.stop(); zsetAdapterWithSingleScoreAndSynchronization.start(); message = (Message<RedisZSet<Object>>) otherRedisChannel.receive(1000); assertNotNull(message); assertEquals(2, message.getPayload().rangeByScore(18, 18).size()); zsetAdapterNoScore.start(); message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); int n = 0; while(n++ < 100 && message.getPayload().size() != 11) { Thread.sleep(100); } assertTrue(n < 100); zsetAdapterNoScore.stop(); context.close(); }
Source:
public static void migrateRealm(final RealmConfiguration configuration, final RealmMigrationNeededException cause) throws FileNotFoundException { BaseRealm.migrateRealm(configuration, null, new MigrationCallback() { @Override public void migrationComplete() { } }, cause); }

Target:
private static void migrateRealm(final RealmConfiguration configuration, final RealmMigrationNeededException cause) throws FileNotFoundException { BaseRealm.migrateRealm(configuration, null, new MigrationCallback() { @Override public void migrationComplete() { } }, cause); }
Source:
protected Predicate<Trigger> matchTriggerFor(final TriggerEvent event) { DockerEvent dockerEvent = (DockerEvent) event; String account = dockerEvent.getContent().getAccount(); String repository = dockerEvent.getContent().getRepository(); return trigger -> trigger.getType().equals(TRIGGER_TYPE) && trigger.getRepository().equals(repository) && trigger.getAccount().equals(account) && triggerPatternMatches(trigger, dockerEvent.getContent().getTag()); }

Target:
protected Predicate<Trigger> matchTriggerFor(final TriggerEvent event) { return trigger -> isMatchingTrigger((DockerEvent)event, trigger); }
Source:
public void getExternalIdsFiltersSubstudyInExternalIdentifierInfo() { BridgeUtils.setRequestContext(new RequestContext.Builder() .withCallerSubstudies(ImmutableSet.of("substudyA", "substudyB")).build()); DynamoExternalIdentifier extId1 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId1"); extId1.setSubstudyId(null); DynamoExternalIdentifier extId2 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId2"); extId2.setSubstudyId("substudyA"); DynamoExternalIdentifier extId3 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId3"); extId3.setSubstudyId("substudyB"); DynamoExternalIdentifier extId4 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId4"); extId4.setSubstudyId("substudyC"); DynamoExternalIdentifier extId5 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId5"); extId5.setSubstudyId("substudyD"); setupQueryOfIds(ImmutableList.of(extId1, extId2, extId3, extId4, extId5)); ForwardCursorPagedResourceList<ExternalIdentifierInfo> externalIds = dao.getExternalIds(TEST_STUDY, null, 10, null, null); assertNull(externalIds.getItems().get(0).getSubstudyId()); assertEquals("substudyA", externalIds.getItems().get(1).getSubstudyId()); assertEquals("substudyB", externalIds.getItems().get(2).getSubstudyId()); assertNull(externalIds.getItems().get(3).getSubstudyId()); assertNull(externalIds.getItems().get(4).getSubstudyId()); }

Target:
public void getExternalIdsFiltersSubstudyInExternalIdentifierInfo() { BridgeUtils.setRequestContext(new RequestContext.Builder() .withCallerSubstudies(ImmutableSet.of("substudyA", "substudyB")).build()); DynamoExternalIdentifier extId1 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId1"); extId1.setSubstudyId(null); DynamoExternalIdentifier extId2 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId2"); extId2.setSubstudyId("substudyA"); DynamoExternalIdentifier extId3 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId3"); extId3.setSubstudyId("substudyB"); DynamoExternalIdentifier extId4 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId4"); extId4.setSubstudyId("substudyC"); DynamoExternalIdentifier extId5 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId5"); extId5.setSubstudyId("substudyD"); setupQueryOfIds(ImmutableList.of(extId1, extId2, extId3, extId4, extId5)); ForwardCursorPagedResourceList<ExternalIdentifierInfo> externalIds = dao.getExternalIds(TEST_STUDY, null, 10, null, null); assertExternalId(externalIds.getItems().get(0), "extId1", null); assertExternalId(externalIds.getItems().get(1), "extId2", "substudyA"); assertExternalId(externalIds.getItems().get(2), "extId3", "substudyB"); assertExternalId(externalIds.getItems().get(3), "extId4", null); assertExternalId(externalIds.getItems().get(4), "extId5", null); }
Source:
public static void createFromResourceUrl(Context context, final URL resourceUrl, final AuthenticationParamCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback"); } Logger.v(TAG, "createFromResourceUrl"); final Handler handler = new Handler(context.getMainLooper()); sThreadExecutor.submit(new Runnable() { @Override public void run() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON); HttpWebResponse webResponse = null; try { webResponse = sWebRequest.sendGet(resourceUrl, headers); try { onCompleted(null, parseResponse(webResponse)); } catch (ResourceAuthenticationChallengeException exc) { onCompleted(exc, null); } } catch (IOException e) { onCompleted(e, null); } } void onCompleted(final Exception exception, final AuthenticationParameters param) { handler.post(new Runnable() { @Override public void run() { callback.onCompleted(exception, param); return; } }); } }); }

Target:
public static void createFromResourceUrl(Context context, final URL resourceUrl, final AuthenticationParamCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback"); } Logger.v(TAG, "createFromResourceUrl"); final Handler handler = new Handler(context.getMainLooper()); sThreadExecutor.submit(new Runnable() { @Override public void run() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON); final HttpWebResponse webResponse; try { webResponse = sWebRequest.sendGet(resourceUrl, headers); try { onCompleted(null, parseResponse(webResponse)); } catch (ResourceAuthenticationChallengeException exc) { onCompleted(exc, null); } } catch (IOException e) { onCompleted(e, null); } } void onCompleted(final Exception exception, final AuthenticationParameters param) { handler.post(new Runnable() { @Override public void run() { callback.onCompleted(exception, param); return; } }); } }); }
Source:
public boolean matches(MethodParams params) { if (!params.match(parameters)) { return false; } @SuppressWarnings("unchecked") Class<? extends Message> firstParameter = (Class<? extends Message>) params.type(0); Optional<EntityVisibility> visibilityOption = EntityVisibility.of(firstParameter); if(!visibilityOption.isPresent()) { return false; } EntityVisibility visibility = visibilityOption.get(); if (visibility.canSubscribe()) { return true; } else { throw new InsufficientVisibilityError(TypeName.of(firstParameter), visibility); } }

Target:
public boolean matches(MethodParams params) { if (!params.match(criteria)) { return false; } @SuppressWarnings("unchecked") Class<? extends Message> firstParameter = (Class<? extends Message>) params.type(0); Optional<EntityVisibility> visibilityOption = EntityVisibility.of(firstParameter); if (!visibilityOption.isPresent()) { return false; } EntityVisibility visibility = visibilityOption.get(); if (visibility.canSubscribe()) { return true; } else { throw new InsufficientVisibilityError(TypeName.of(firstParameter), visibility); } }
Source:
public boolean requiresRedirect(RedirectionContext context, HttpClientResponse<O> response) { int statusCode = response.getStatus().code(); return statusCode >= 301 && statusCode <= 308; }

Target:
public boolean requiresRedirect(RedirectionContext context, HttpClientResponse<O> response) { int statusCode = response.getStatus().code(); return Arrays.binarySearch(REDIRECTABLE_STATUS_CODES, statusCode) >= 0; }
Source:
protected void done() { try { reportLaunchButton.setEnabled(true); reportToUser(get()); } catch (InterruptedException | ExecutionException exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error during html report generation : {}", exception.getMessage(), exception); } List<String> reportException = new ArrayList<>(); reportException.add(exception.getMessage()); reportToUser(reportException); } }

Target:
protected void done() { try { reportLaunchButton.setEnabled(true); reportToUser(get()); } catch (InterruptedException | ExecutionException exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error during html report generation: {}", exception.getMessage(), exception); } reportToUser(Arrays.asList(exception.getMessage())); } }
Source:
public void startLogin(Activity activity) { String phone = null; for (AuthUI.IdpConfig idpConfig : mFlowParameters.providerInfo) { if (idpConfig.getProviderId().equals(AuthUI.PHONE_VERIFICATION_PROVIDER)) { phone = idpConfig.getParams().getString(EXTRA_DEFAULT_PHONE); } } activity.startActivityForResult( PhoneVerificationActivity.createIntent(activity, mFlowParameters, phone), RC_PHONE_FLOW); }

Target:
public void startLogin(Activity activity) { String phone = null; for (AuthUI.IdpConfig idpConfig : mFlowParameters.providerInfo) { if (idpConfig.getProviderId().equals(AuthUI.PHONE_VERIFICATION_PROVIDER)) { phone = idpConfig.getParams().getString(AuthUI.EXTRA_DEFAULT_PHONE); } } activity.startActivityForResult( PhoneVerificationActivity.createIntent(activity, mFlowParameters, phone), RC_PHONE_FLOW); }
Source:
public void testServiceUnderMaintenance() throws Exception { MockWebServer server = mockWebServer(); for ( int i = 0; i <= MAX_RETRIES; i++ ) server.enqueue( new MockResponse().setResponseCode(503).setBody(payloadFromResource( "/maintenance-503.html" ))); ProfitBricksApi pbApi = api(server.getUrl("/")); DataCenterApi api = pbApi.dataCenterApi(); try { api.clearDataCenter("some-datacenter-id"); fail( "Request should have failed."); } catch (Exception ex){ assertTrue(ex instanceof RuntimeException, "Exception should be RuntimeException"); } finally { pbApi.close(); server.shutdown(); } }

Target:
public void testServiceUnderMaintenance() throws Exception { MockWebServer server = mockWebServer(); for (int i = 0; i <= MAX_RETRIES; i++) server.enqueue(new MockResponse().setResponseCode(503).setBody(payloadFromResource("/maintenance-503.html"))); ProfitBricksApi pbApi = api(server.getUrl("/")); DataCenterApi api = pbApi.dataCenterApi(); try { api.clearDataCenter("some-datacenter-id"); fail("Request should have failed."); } catch (Exception ex) { assertTrue(ex instanceof HttpResponseException, "Exception should be HttpResponseException"); } finally { pbApi.close(); server.shutdown(); } }
Source:
public boolean filterLog(Map<String, String> filters, String logLine) { if (filters == null) { return true; } boolean result = true; for (Entry<String, String> entry : filters.entrySet()) { if (!logLine.matches( String.format(".*\\[%s=%s\\].*", entry.getKey(), entry.getValue()))) { result = result & false; } } return result; }

Target:
public boolean filterLog(Map<String, String> filters, String logLine) { if (filters == null) { return true; } boolean result = true; for (Entry<String, String> entry : filters.entrySet()) { if (!logLine.matches( String.format(".*\\[%s=%s\\].*", entry.getKey(), entry.getValue()))) { return false; } } return true; }
Source:
static String createKey(Request data, StringBuilder builder) { if (data.uri != null) { String path = data.uri.toString(); builder.ensureCapacity(path.length() + KEY_PADDING); builder.append(path); } else { builder.ensureCapacity(KEY_PADDING); builder.append(data.resourceId); } builder.append('\n'); if (data.rotationDegrees != 0) { builder.append("rotation:").append(data.rotationDegrees); if (data.hasRotationPivot) { builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY); } builder.append('\n'); } if (data.targetWidth != 0) { builder.append("resize:").append(data.targetWidth).append('x').append(data.targetHeight); builder.append('\n'); } if (data.centerCrop) { builder.append("centerCrop\n"); } else if (data.centerInside) { builder.append("centerInside\n"); } if (data.transformations != null) { for (int i = 0, count = data.transformations.size(); i < count; i++) { builder.append(data.transformations.get(i).key()); builder.append('\n'); } } if (data.density != 0) { builder.append("density:").append(data.density); builder.append('\n'); } return builder.toString(); }

Target:
static String createKey(Request data, StringBuilder builder) { if (data.uri != null) { String path = data.uri.toString(); builder.ensureCapacity(path.length() + KEY_PADDING); builder.append(path); } else { builder.ensureCapacity(KEY_PADDING); builder.append(data.resourceId); } builder.append('\n'); if (data.rotationDegrees != 0) { builder.append("rotation:").append(data.rotationDegrees); if (data.hasRotationPivot) { builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY); } builder.append('\n'); } if (data.targetWidth != 0) { builder.append("resize:").append(data.targetWidth).append('x').append(data.targetHeight); builder.append('\n'); } if (data.centerCrop) { builder.append("centerCrop\n"); } else if (data.centerInside) { builder.append("centerInside\n"); } if (data.transformations != null) { for (int i = 0, count = data.transformations.size(); i < count; i++) { builder.append(data.transformations.get(i).key()); builder.append('\n'); } } if (data.originalDensity != 0) { builder.append("originalDensity:").append(data.originalDensity); builder.append('\n'); } return builder.toString(); }
Source:
public Guid getFirstQuotaForUserId(Guid storagePoolId, Guid adElementId) { List<Quota> quotas = getQuotaDao().getQuotaByAdElementId(adElementId, storagePoolId, false); if (quotas.isEmpty()) { return getDefaultQuotaId(storagePoolId); } return quotas.get(0).getId(); }

Target:
public Guid getFirstQuotaForUserId(Guid storagePoolId, Guid adElementId) { List<Quota> quotas = getQuotaDao().getQuotaByAdElementId(adElementId, storagePoolId, false); Guid defaultQuotaId = getDefaultQuotaId(storagePoolId); if (quotas.isEmpty()) { return defaultQuotaId; } for (Quota quota : quotas) { if (quota.getId().equals(defaultQuotaId)) { return defaultQuotaId; } } return quotas.get(0).getId(); }
Source:
private CompletableFuture<Void> runFailureDetectorTask(PollReport pollReport) { return CompletableFuture.runAsync(() -> { if (!pollReport.getClusterState().isReady()){ log.info("Cluster state is not ready: {}", pollReport.getClusterState()); return; } correctWrongEpochs(pollReport); try { if (pollReport.isCurrentLayoutSlotUnFilled()) { handleFailure(Collections.emptySet(), pollReport); return; } if (!pollReport.getWrongEpochs().isEmpty()) { return; } } catch (Exception ex) { log.error("Can't fill slot. Poll report: {}", pollReport, ex); } boolean handleFailure = handleFailure(pollReport); if (handleFailure) { return; } handleSequencer(serverContext.copyManagementLayout()); handleHealing(pollReport, serverContext.copyManagementLayout()); }, failureDetectorWorker); }

Target:
private CompletableFuture<DetectorTask> runFailureDetectorTask(PollReport pollReport) { if (!pollReport.getClusterState().isReady()) { log.info("Cluster state is not ready: {}", pollReport.getClusterState()); return DETECTOR_TASK_SKIPPED; } return CompletableFuture.supplyAsync(() -> { correctWrongEpochs(pollReport); try { if (pollReport.isCurrentLayoutSlotUnFilled()) { detectFailure(Collections.emptySet(), pollReport).get(); return DetectorTask.COMPLETED; } if (!pollReport.getWrongEpochs().isEmpty()) { log.debug("Wait for next iteration. Poll report contains wrong epochs: {}", pollReport.getWrongEpochs() ); return DetectorTask.COMPLETED; } } catch (Exception ex) { log.error("Can't fill slot. Poll report: {}", pollReport, ex); } DetectorTask healing = detectHealing(pollReport, serverContext.copyManagementLayout()); if (healing == DetectorTask.COMPLETED){ return DetectorTask.COMPLETED; } DetectorTask handleFailure = detectFailure(pollReport); if (handleFailure == DetectorTask.COMPLETED) { return DetectorTask.COMPLETED; } handleSequencer(serverContext.copyManagementLayout()); return DetectorTask.COMPLETED; }, failureDetectorWorker); }
Source:
public CompletableFuture<Void> visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } ctx.onReturn((ctx1, command1, rv, throwable) -> { if (throwable != null) throw throwable; if (rv == null) { return null; } if (needsUnboxing(ctx1)) { return CompletableFuture.completedFuture(converter.unboxValue(rv)); } return null; }); return ctx.continueInvocation(); }

Target:
public CompletableFuture<Void> visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { if (throwable != null) throw throwable; if (rv == null || !needsUnboxing(rCtx)) { return null; } return CompletableFuture.completedFuture(converter.unboxValue(rv)); }); }
Source:
private void recalculatePercent() { int percent = (int) (totalRead * 100 / size); if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }

Target:
private void recalculatePercent() { int percent = (int) (totalRead * 100 / size); if ( percent > 100 ) { percent = 100; } if ( percent < 0 ) { percent = 0; } if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }
Source:
protected void registerItems(RuntimeEngine runtime) { RegisterableItemsFactory factory = environment.getRegisterableItemsFactory(); KieSession ksession = ((InternalRuntimeEngine) runtime).internalGetKieSession(); Map<String, WorkItemHandler> handlers = factory.getWorkItemHandlers(runtime); for (Entry<String, WorkItemHandler> entry : handlers.entrySet()) { ksession.getWorkItemManager().registerWorkItemHandler(entry.getKey(), entry.getValue()); } Map<String, Object> globals = factory.getGlobals(runtime); for (Entry<String, Object> entry : globals.entrySet()) { ksession.setGlobal(entry.getKey(), entry.getValue()); } List<ProcessEventListener> processListeners = factory.getProcessEventListeners(runtime); for (ProcessEventListener listener : processListeners) { ksession.addEventListener(listener); } List<AgendaEventListener> agendaListeners = factory.getAgendaEventListeners(runtime); for (AgendaEventListener listener : agendaListeners) { ksession.addEventListener(listener); } if (factory instanceof SimpleRegisterableItemsFactory) { List<NotificationListener> additionalNotificationListener = ((SimpleRegisterableItemsFactory) factory).getNotificationListeners(runtime); NotificationListenerManager.get().registerAdditionalNotificationListener(additionalNotificationListener); } List<RuleRuntimeEventListener> wmListeners = factory.getRuleRuntimeEventListeners(runtime); for (RuleRuntimeEventListener listener : wmListeners) { ksession.addEventListener(listener); } }

Target:
protected void registerItems(RuntimeEngine runtime) { RegisterableItemsFactory factory = environment.getRegisterableItemsFactory(); KieSession ksession = ((InternalRuntimeEngine) runtime).internalGetKieSession(); Map<String, WorkItemHandler> handlers = factory.getWorkItemHandlers(runtime); for (Entry<String, WorkItemHandler> entry : handlers.entrySet()) { ksession.getWorkItemManager().registerWorkItemHandler(entry.getKey(), entry.getValue()); } Map<String, Object> globals = factory.getGlobals(runtime); for (Entry<String, Object> entry : globals.entrySet()) { ksession.setGlobal(entry.getKey(), entry.getValue()); } List<ProcessEventListener> processListeners = factory.getProcessEventListeners(runtime); for (ProcessEventListener listener : processListeners) { ksession.addEventListener(listener); } List<AgendaEventListener> agendaListeners = factory.getAgendaEventListeners(runtime); for (AgendaEventListener listener : agendaListeners) { ksession.addEventListener(listener); } List<RuleRuntimeEventListener> wmListeners = factory.getRuleRuntimeEventListeners(runtime); for (RuleRuntimeEventListener listener : wmListeners) { ksession.addEventListener(listener); } }
Source:
T resolve() { synchronized (m_lock) { if (m_unresolvedPath != null) { m_value = (T) getCatalog().m_operator.getItemForPath(m_unresolvedPath); m_unresolvedPath = null; } return m_value; } }

Target:
T resolve() { synchronized (m_lock) { if (m_unresolvedPath != null) { m_value = (T) getCatalog().getCatalogOperator().getItemForPath(m_unresolvedPath); m_unresolvedPath = null; } return m_value; } }
Source:
public void prepareTestProject() throws Exception { projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); runCompileCommand(); notifications.waitProgressPopupPanelClose(); consoles.dragConsolesInDefinePosition(VALUE_OF_SHIFTING_CONSOLES_ALONG_X_AXIS); }

Target:
public void prepareTestProject() throws Exception { CompileCommand compileCommand = new CompileCommand(); testCommandServiceClient.createCommand(DtoConverter.asDto(compileCommand), ws.getId()); projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); loader.waitOnClosed(); projectExplorer.waitItem(JUNIT4_PROJECT); try { runCompileCommandByPallete(compileCommand); } catch (TimeoutException ex) { fail("Known random failure <LINK_0>"); } notifications.waitProgressPopupPanelClose(); consoles.dragConsolesInDefinePosition(VALUE_OF_SHIFTING_CONSOLES_ALONG_X_AXIS); }
Source:
private <T> QueryRunner<T> makeRunner(Query<T> query, QueryRunner<T> baseClientRunner) { QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query); PostProcessingOperator<T> postProcessing = objectMapper.convertValue( query.<String>getContextValue("postProcessing"), new TypeReference<PostProcessingOperator<T>>() { } ); return new ResultLevelCachingQueryRunner<>( new FluentQueryRunnerBuilder<>(toolChest) .create( new SetAndVerifyContextQueryRunner( serverConfig, new RetryQueryRunner<>( baseClientRunner, retryConfig, objectMapper ) ) ) .applyPreMergeDecoration() .mergeResults() .applyPostMergeDecoration() .emitCPUTimeMetric(emitter) .postProcess(postProcessing), toolChest, query, objectMapper, cache, cacheConfig ); }

Target:
private <T> QueryRunner<T> makeRunner(Query<T> query, QueryRunner<T> baseClientRunner) { QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query); return new ResultLevelCachingQueryRunner<>(makeRunner(query, baseClientRunner, toolChest), toolChest, query, objectMapper, cache, cacheConfig); }
Source:
public void registerProtofiles(String...classPathResources) throws Exception { for(String classPathResource: classPathResources) { String fileName = Paths.get(classPathResource).getFileName().toString(); String contents = Util.read(this.getClass().getResourceAsStream(classPathResource)); clusterRegistry.put(REGISTRY_SCOPE, fileName, contents); } compile(); }

Target:
public void registerProtofiles(String... classPathResources) throws Exception { FileDescriptorSource fileDescriptorSource = getFileDescriptorSource(); for (String classPathResource : classPathResources) { String fileName = Paths.get(classPathResource).getFileName().toString(); String contents = Util.read(this.getClass().getResourceAsStream(classPathResource)); fileDescriptorSource.addProtoFile(fileName, contents); } clusterRegistry.put(REGISTRY_SCOPE, REGISTRY_KEY, fileDescriptorSource); }
Source:
public PersistentModelBuilder(PersistentModel previous) { this.previous = Preconditions.checkNotNull(previous); this.buildDir = previous.getBuildDir(); this.subprojectPaths = previous.getSubprojectPaths(); this.classpath = previous.getClasspath(); this.derivedResources = previous.getDerivedResources(); this.linkedResources = previous.getLinkedResources(); }

Target:
public PersistentModelBuilder(PersistentModel previous) { this.previous = Preconditions.checkNotNull(previous); if (previous.isPresent()) { this.buildDir = previous.getBuildDir(); this.subprojectPaths = previous.getSubprojectPaths(); this.classpath = previous.getClasspath(); this.derivedResources = previous.getDerivedResources(); this.linkedResources = previous.getLinkedResources(); } }
Source:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); if (vds.getVdsGroupSupportsGlusterService()) { List<String> serviceList = new ArrayList<>(); serviceList.add("glusterd"); runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), serviceList, "restart")); } }

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); if (vds.getVdsGroupSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); } }
Source:
public Map<String, R> resultFromBinary(byte[] binary) { Aggregation<P, R, T> agg = this.result.values().stream().findAny().orElse(null); if (agg == null) { return null; } ByteBuffer bb = ByteBuffer.wrap(binary); int mapSize = bb.getInt(); Map<String, R> resultMap = Maps.newHashMapWithExpectedSize(mapSize); for (int i = 0; i < mapSize; i++) { int keyLen = bb.getInt(); byte[] keyBytes = new byte[keyLen]; bb.get(keyBytes); String key = StringUtils.stringFromBinary(keyBytes); int valLen = bb.getInt(); byte[] valBytes = new byte[valLen]; bb.get(valBytes); R val = agg.resultFromBinary(valBytes); resultMap.put(key, val); } return resultMap; }

Target:
public Map<String, R> resultFromBinary(byte[] binary) { final Aggregation<P, R, T> agg = this.getHelperAggregation(); ByteBuffer bb = ByteBuffer.wrap(binary); int mapSize = bb.getInt(); Map<String, R> resultMap = Maps.newHashMapWithExpectedSize(mapSize); for (int i = 0; i < mapSize; i++) { int keyLen = bb.getInt(); byte[] keyBytes = new byte[keyLen]; bb.get(keyBytes); String key = StringUtils.stringFromBinary(keyBytes); int valLen = bb.getInt(); byte[] valBytes = new byte[valLen]; bb.get(valBytes); R val = agg.resultFromBinary(valBytes); resultMap.put(key, val); } return resultMap; }
Source:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (!fIsFlatList) { swapBetweenFlatViewOrHierarchicalView(); fIsFlatList = true; } } }; action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_HIERARCHICAL_VIEW)); action.setChecked(true); return action; }

Target:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (fIsFlatViewClicked) { switchView(fHierarchicalList); fIsFlatViewClicked = false; } } }; action.setChecked(true); return action; }
Source:
protected void initInput() { String treeID = getTreeID(); TmfStatisticsTreeNode statisticsTreeNode; if (TmfStatisticsTreeManager.containsTreeRoot(treeID)) { statisticsTreeNode = TmfStatisticsTreeManager.getStatTreeRoot(treeID); int numNodeTraces = statisticsTreeNode.getNbChildren(); Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(fTrace); int numTraces = traces.size(); if (numTraces == numNodeTraces) { boolean same = true; for (ITmfTrace trace : traces) { String traceName = trace.getName(); if (!statisticsTreeNode.containsChild(traceName)) { same = false; break; } } if (same) { fTreeViewer.setInput(statisticsTreeNode); return; } statisticsTreeNode.reset(); } } else { statisticsTreeNode = TmfStatisticsTreeManager.addStatsTreeRoot(treeID, getStatisticData()); } fTreeViewer.setInput(statisticsTreeNode); fPieChartModel = new TmfPieChartStatisticsModel(); fPieChartViewer.setModel(fPieChartModel); }

Target:
protected void initInput() { String treeID = getTreeID(); TmfStatisticsTreeNode statisticsTreeNode; if (TmfStatisticsTreeManager.containsTreeRoot(treeID)) { statisticsTreeNode = TmfStatisticsTreeManager.getStatTreeRoot(treeID); int numNodeTraces = statisticsTreeNode.getNbChildren(); Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(fTrace); int numTraces = traces.size(); if (numTraces == numNodeTraces) { boolean same = true; for (ITmfTrace trace : traces) { String traceName = trace.getName(); if (!statisticsTreeNode.containsChild(traceName)) { same = false; break; } } if (same) { fTreeViewer.setInput(statisticsTreeNode); return; } statisticsTreeNode.reset(); } } else { statisticsTreeNode = TmfStatisticsTreeManager.addStatsTreeRoot(treeID, getStatisticData()); } fTreeViewer.setInput(statisticsTreeNode); fPieChartViewer.setInput(getPieChartModel()); }
Source:
private boolean isTestExcludedFromLang(Method method) { String langFromConfig = System.getProperty("language") != null ? System.getProperty("language") : Configuration.getPropertyFromFile("language"); if (method.isAnnotationPresent(DontRun.class)) { String[] excludedLangs = method.getAnnotation(DontRun.class).language(); if (Arrays.stream(excludedLangs) .anyMatch(e -> Configuration.getWikiLanguage().contains(e) || langFromConfig.equals(e))) { return true; } } if (method.isAnnotationPresent(RunOnly.class)) { String[] includedLangs = method.getAnnotation(RunOnly.class).language(); if (hasOnlyDefaultValue(includedLangs)) { return false; } else if (Arrays.stream(includedLangs).anyMatch(e->Configuration.getWikiLanguage().contains(e))) { return false; } else { return true; } } return false; }

Target:
private boolean isTestExcludedFromLang(Method method) { String langFromConfig = System.getProperty("language") != null ? System.getProperty("language") : Configuration.getPropertyFromFile("language"); if (method.isAnnotationPresent(DontRun.class)) { String[] excludedLangs = method.getAnnotation(DontRun.class).language(); if (Arrays.stream(excludedLangs) .anyMatch(e -> Configuration.getWikiLanguage().contains(e) || langFromConfig.equals(e))) { return true; } } if (method.isAnnotationPresent(RunOnly.class)) { String[] includedLangs = method.getAnnotation(RunOnly.class).language(); if (hasOnlyDefaultValue(includedLangs)) { return false; } return !Arrays.stream(includedLangs).anyMatch(e->Configuration.getWikiLanguage().contains(e)); } return false; }
Source:
public void testUpdateSchema() { DefaultTableSchemaUpdater schemaUpdater = new DefaultTableSchemaUpdater(); Application app = mock(Application.class); Mockito.when(app.getApplicationContext()).thenReturn(context); TestTable testTable = new TestTable(app, DATABASE_NAME, TABLE_NAME, TABLE_VERSION, Arrays.asList(createColumn()), null, null, schemaUpdater); TestOnlineHelper onlineHelper = new TestOnlineHelper(context, null, null, TABLE_VERSION); SQLiteDatabase db = onlineHelper.getWritableDatabase(); schemaUpdater.updateSchema(db, testTable); assertEquals(true, TableExists(db)); }

Target:
public void testUpdateSchema() { DefaultTableSchemaUpdater schemaUpdater = new DefaultTableSchemaUpdater(); Application app = mock(Application.class); Context context = mock(Context.class); Mockito.when(app.getApplicationContext()).thenReturn(context); TestTable testTable = new TestTable(app, DATABASE_NAME, TABLE_NAME, TABLE_VERSION, Arrays.asList(createColumn()), null, null, schemaUpdater); TestOnlineHelper onlineHelper = new TestOnlineHelper(context, null, null, TABLE_VERSION); SQLiteDatabase db = onlineHelper.getWritableDatabase(); schemaUpdater.updateSchema(db, testTable); assertEquals(true, TableExists(db)); }
Source:
public void requestPulse(GlowBlock block) { ItemTable itemTable = ItemTable.instance(); BlockType type = itemTable.getBlock(block.getType()); if (type == null || type.getPulseTickSpeed() == null) { return; } requestPulse(block, type.getPulseTickSpeed(), type.isPulseOnce()); }

Target:
public void requestPulse(GlowBlock block) { requestPulse(block.getLocation()); }
Source:
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (target.startsWith("/test")) { String pkgId = target.substring(target.lastIndexOf("/") + 1); File pkgZip = new File(testStore, pkgId + ".zip"); if (pkgZip.exists()) { response.setContentLength((int) pkgZip.length()); try (ServletOutputStream os = response.getOutputStream()) { byte[] byteArray = FileUtils.readFileToByteArray(pkgZip); os.write(byteArray, 0, byteArray.length); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }

Target:
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (target.startsWith("/test")) { String pkgId = target.substring(target.lastIndexOf("/") + 1); File pkgZip = new File(testStore, pkgId + ".zip"); if (pkgZip.exists()) { response.setContentLength((int) pkgZip.length()); response.setStatus(HttpServletResponse.SC_OK); try (ServletOutputStream os = response.getOutputStream(); FileInputStream is = new FileInputStream(pkgZip)) { IOUtils.copy(is, os); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }
Source:
private void handleHangingStoppingRuntime(KubernetesInternalRuntime runtime) { RuntimeIdentity runtimeId = runtime.getContext().getIdentity(); try { eventPublisher.sendAbnormalStoppingEvent( runtimeId, WorkspaceStatus.STOPPING, "Workspace is not stopped in time. Trying to stop it forcibly"); runtime.internalStop(emptyMap()); runtime.markStopped(); eventPublisher.sendAbnormalStoppedEvent(runtimeId, "Workspace stop reached timeout"); LOG.info( "Runtime '{}:{}:{}' is not stopped in time. Stopped it forcibly", runtimeId.getWorkspaceId(), runtimeId.getEnvName(), runtimeId.getOwnerId()); } catch (InfrastructureException e) { LOG.error( "Error occurred during forcibly stopping of hanging runtime '{}:{}:{}'. Error: {}", runtimeId.getWorkspaceId(), runtimeId.getEnvName(), runtimeId.getOwnerId(), e.getMessage(), e); } }

Target:
private void handleHangingStoppingRuntime(KubernetesInternalRuntime runtime) { RuntimeIdentity runtimeId = runtime.getContext().getIdentity(); try { eventPublisher.sendAbnormalStoppingEvent( runtimeId, "Workspace is not stopped in time. Trying to stop it forcibly"); runtime.internalStop(emptyMap()); runtime.markStopped(); eventPublisher.sendAbnormalStoppedEvent(runtimeId, "Workspace stop reached timeout"); LOG.info( "Runtime '{}:{}:{}' is not stopped in time. Stopped it forcibly", runtimeId.getWorkspaceId(), runtimeId.getEnvName(), runtimeId.getOwnerId()); } catch (InfrastructureException e) { LOG.error( "Error occurred during forcibly stopping of hanging runtime '{}:{}:{}'. Error: {}", runtimeId.getWorkspaceId(), runtimeId.getEnvName(), runtimeId.getOwnerId(), e.getMessage(), e); } }
Source:
private void initReader() throws IOException { if (reader != null) { reader.close(); reader = null; } if (footersIterator.hasNext()) { Footer footer = footersIterator.next(); List<BlockMetaData> blocks = footer.getParquetMetadata().getBlocks(); if (filter.isPresent() && filter.get().isRight()) { blocks = ParquetInputFormat.applyRowGroupFilters(filter.get().asRight(), footer.getParquetMetadata().getFileMetaData().getSchema(), blocks); } reader = new InternalParquetRecordReader<T>(readSupport, filter); reader.initialize( readContext.getRequestedSchema(), globalMetaData.getSchema(), footer.getParquetMetadata().getFileMetaData().getKeyValueMetaData(), readContext.getReadSupportMetadata(), footer.getFile(), blocks, conf); } }

Target:
private void initReader() throws IOException { if (reader != null) { reader.close(); reader = null; } if (footersIterator.hasNext()) { Footer footer = footersIterator.next(); List<BlockMetaData> blocks = footer.getParquetMetadata().getBlocks(); List<BlockMetaData> filteredBlocks = RowGroupFilter.filterRowGroups(filter, blocks, footer.getParquetMetadata().getFileMetaData().getSchema()); reader = new InternalParquetRecordReader<T>(readSupport, filter); reader.initialize( readContext.getRequestedSchema(), globalMetaData.getSchema(), footer.getParquetMetadata().getFileMetaData().getKeyValueMetaData(), readContext.getReadSupportMetadata(), footer.getFile(), filteredBlocks, conf); } }
Source:
public void peoplewiththeirFirstNameIsJames() { List<Person> matches = this.personRepository.peopleWiththeirFirstNameIsJames(); assertThat("1940 and 1942", matches.size(), equalTo(2)); assertThat("1940 and 1942", matches, containsInAnyOrder(hasProperty("lastname", equalTo("Cagney")), hasProperty("lastname", equalTo("Stewart")))); }

Target:
public void peoplewiththeirFirstNameIsJames() { List<Person> matches = this.personRepository.peopleWithTheirFirstNameIsJames(); assertThat("1940 and 1942", matches.size(), equalTo(2)); assertThat("1940 and 1942", matches, containsInAnyOrder(hasProperty("lastname", equalTo("Cagney")), hasProperty("lastname", equalTo("Stewart")))); }
Source:
private void propagateTransit (int targetIndex) { TIntIntMap pointToStopDistanceTable = targets.pointToStopDistanceTables.get(targetIndex); if (pointToStopDistanceTable != null) { pointToStopDistanceTable.forEachEntry((stop, distanceMillimeters) -> { if (distanceMillimeters / speedMillimetersPerSecond <= egressLegTimeLimitSeconds) { for (int iteration = 0; iteration < nIterations; iteration++) { int timeAtStop = travelTimesToStop[stop][iteration]; if (timeAtStop > cutoffSeconds || timeAtStop > perIterationTravelTimes[iteration]) { continue; } int timeAtTarget = timeAtStop + distanceMillimeters / speedMillimetersPerSecond; if (timeAtTarget < cutoffSeconds && timeAtTarget < perIterationTravelTimes[iteration]) { perIterationTravelTimes[iteration] = timeAtTarget; if (calculateComponents) { Path[] pathsToStops = pathsToStopsForIteration.get(iteration); perIterationPaths[iteration] = pathsToStops[stop]; } } } } return true; }); } }

Target:
private void propagateTransit (int targetIndex) { TIntIntMap pointToStopLinkageCostTable = targets.pointToStopLinkageCostTables.get(targetIndex); StreetRouter.State.RoutingVariable unit = targets.linkageCostUnit; int egressLimit; if (unit == StreetRouter.State.RoutingVariable.DURATION_SECONDS) { egressLimit = egressLegTimeLimitSeconds; } else if (unit == StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS) { egressLimit = egressLegTimeLimitSeconds * speedMillimetersPerSecond; } else { throw new UnsupportedOperationException("Linkage costs have an unknown unit."); } if (pointToStopLinkageCostTable != null) { pointToStopLinkageCostTable.forEachEntry((stop, linkageCost) -> { if (linkageCost < egressLimit){ for (int iteration = 0; iteration < nIterations; iteration++) { int timeAtStop = travelTimesToStop[stop][iteration]; if (timeAtStop > cutoffSeconds || timeAtStop > perIterationTravelTimes[iteration]) { continue; } int secondsFromStopToTarget; if (unit == StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS) { secondsFromStopToTarget = linkageCost / speedMillimetersPerSecond; } else if (unit == StreetRouter.State.RoutingVariable.DURATION_SECONDS) { secondsFromStopToTarget = linkageCost; } else { throw new UnsupportedOperationException("Linkage costs have an unknown unit."); } int timeAtTarget = timeAtStop + secondsFromStopToTarget; if (timeAtTarget < cutoffSeconds && timeAtTarget < perIterationTravelTimes[iteration]) { perIterationTravelTimes[iteration] = timeAtTarget; if (calculateComponents) { Path[] pathsToStops = pathsToStopsForIteration.get(iteration); perIterationPaths[iteration] = pathsToStops[stop]; } } } } return true; }); } }
Source:
public void stop() { try { jmsConnectionFactory.closeConnection(connection); jmsConnectionFactory.closeSession(session); jmsConnectionFactory.closeMessageConsumer(messageConsumer); } catch (JMSServerConnectorException e) { logger.error("Error while closing the connection, session and consumer ", e); } }

Target:
public void stop() throws JMSServerConnectorException { closeAll(); }
Source:
public BinaryResult apply(final ProjectResource rsrc, final Input input) { return new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { PrintWriter writer = new PrintWriter( new OutputStreamWriter(out, UTF_8)) { @Override public void println() { write('\n'); } }; try { GarbageCollectionResult result = garbageCollectionFactory.create().run( Collections.singletonList(rsrc.getNameKey()), true, input.showProgress ? writer : null); String msg = "Garbage collection completed successfully."; if (result.hasErrors()) { for (GarbageCollectionResult.Error e : result.getErrors()) { switch (e.getType()) { case REPOSITORY_NOT_FOUND: msg = "Error: project \"" + e.getProjectName() + "\" not found."; break; case GC_ALREADY_SCHEDULED: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" was already scheduled."; break; case GC_FAILED: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" failed."; break; default: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" failed: " + e.getType() + "."; } } } writer.println(msg); } finally { writer.flush(); } } }.setContentType("text/plain") .setCharacterEncoding(UTF_8.name()) .disableGzip(); }

Target:
public BinaryResult apply(final ProjectResource rsrc, final Input input) { return new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { PrintWriter writer = new PrintWriter( new OutputStreamWriter(out, UTF_8)) { @Override public void println() { write('\n'); } }; try { GarbageCollectionResult result = garbageCollectionFactory.create().run( Collections.singletonList(rsrc.getNameKey()), input.aggressive, input.showProgress ? writer : null); String msg = "Garbage collection completed successfully."; if (result.hasErrors()) { for (GarbageCollectionResult.Error e : result.getErrors()) { switch (e.getType()) { case REPOSITORY_NOT_FOUND: msg = "Error: project \"" + e.getProjectName() + "\" not found."; break; case GC_ALREADY_SCHEDULED: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" was already scheduled."; break; case GC_FAILED: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" failed."; break; default: msg = "Error: garbage collection for project \"" + e.getProjectName() + "\" failed: " + e.getType() + "."; } } } writer.println(msg); } finally { writer.flush(); } } }.setContentType("text/plain") .setCharacterEncoding(UTF_8.name()) .disableGzip(); }