auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EngineDriver(SqlEnvironment environment){ this.environment = environment; this.uuidGen=environment.getUUIDGenerator(); this.internalConnection=environment.getInternalConnection(); this.version=environment.getVersion(); this.config=environment.getConfiguration(); this.loadWatcher = environment.getLoadWatcher(); this.processorFactory = environment.getProcessorFactory(); this.olapClient = environment.getOlapClient(); this.propertyManager = environment.getPropertyManager(); this.exceptionFactory = environment.exceptionFactory(); this.dbAdmin = environment.databaseAdministrator(); this.sequencePool=CachedResourcePool.Builder.<SpliceSequence, SequenceKey>newBuilder() .expireAfterAccess(1,TimeUnit.MINUTES) .generator(new ResourcePool.Generator<SpliceSequence, SequenceKey>(){ @Override public SpliceSequence makeNew(SequenceKey refKey) throws Exception{ return refKey.makeNew(); } @Override public void close(SpliceSequence entity) throws Exception{ entity.close(); } }).build(); final AtomicLong count = new AtomicLong(0); ThreadPoolExecutor tpe = new ThreadPoolExecutor(0, config.getThreadPoolMaxSize(), 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), (runnable) -> { Thread t = new Thread(runnable, "SpliceThreadPool-" + count.getAndIncrement()); t.setDaemon(true); return t; }, new ThreadPoolExecutor.CallerRunsPolicy()); tpe.allowCoreThreadTimeOut(false); tpe.prestartAllCoreThreads(); this.threadPool = new ManagedThreadPool(tpe); }

Target:
public EngineDriver(SqlEnvironment environment){ this.environment = environment; this.uuidGen=environment.getUUIDGenerator(); this.internalConnection=environment.getInternalConnection(); this.version=environment.getVersion(); this.config=environment.getConfiguration(); this.loadWatcher = environment.getLoadWatcher(); this.processorFactory = environment.getProcessorFactory(); this.olapClient = environment.getOlapClient(); this.propertyManager = environment.getPropertyManager(); this.exceptionFactory = environment.exceptionFactory(); this.operationManager = environment.getOperationManager(); this.dbAdmin = environment.databaseAdministrator(); this.sequencePool=CachedResourcePool.Builder.<SpliceSequence, SequenceKey>newBuilder() .expireAfterAccess(1,TimeUnit.MINUTES) .generator(new ResourcePool.Generator<SpliceSequence, SequenceKey>(){ @Override public SpliceSequence makeNew(SequenceKey refKey) throws Exception{ return refKey.makeNew(); } @Override public void close(SpliceSequence entity) throws Exception{ entity.close(); } }).build(); final AtomicLong count = new AtomicLong(0); ThreadPoolExecutor tpe = new ThreadPoolExecutor(20, config.getThreadPoolMaxSize(), 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), (runnable) -> { Thread t = new Thread(runnable, "SpliceThreadPool-" + count.getAndIncrement()); t.setDaemon(true); return t; }, new ThreadPoolExecutor.CallerRunsPolicy()); tpe.allowCoreThreadTimeOut(false); tpe.prestartAllCoreThreads(); this.threadPool = new ManagedThreadPool(tpe); }
Source:
public void returnsNullForNoQuery() throws Exception { setUpBasicQueryData(); try { im.find(null); Assert.fail("find should throw QueryException"); } catch (QueryException qe) { ; } }

Target:
public void returnsNullForNoQuery() throws Exception { setUpBasicQueryData(); im.find(null); }
Source:
public boolean containsAll(final Collection<?> c) { for (final Object o : c) { final boolean b = contains(o); if (!b) return false; } return true; }

Target:
public boolean containsAll(final Collection<?> c) { for (final Object o : c) { if (!contains(o)) return false; } return true; }
Source:
public GetDeviceModelResponse dequeueGetDeviceModelResponse( final String correlationUid ) throws OsgpException { LOGGER.debug( "dequeueGetDeviceModelRequest called with correlation uid {}", correlationUid ); return (GetDeviceModelResponse) processResponse( correlationUid ); }

Target:
public GetDeviceModelResponse dequeueGetDeviceModelResponse(final String correlationUid) throws OsgpException { LOGGER.debug("dequeueGetDeviceModelResponse called with correlation uid {}", correlationUid); return (GetDeviceModelResponse) processResponse(correlationUid); }
Source:
public void start(final Map<String, String> props) { log.info("Starting JDBC Sink task"); config = new JdbcSinkConfig(props); initWriter(); remainingRetries = config.maxRetries; try { reporter = context.errantRecordReporter(); } catch (NoClassDefFoundError e) { reporter = null; } }

Target:
public void start(final Map<String, String> props) { log.info("Starting JDBC Sink task"); config = new JdbcSinkConfig(props); initWriter(); remainingRetries = config.maxRetries; try { reporter = context.errantRecordReporter(); } catch (NoSuchMethodError | NoClassDefFoundError e) { reporter = null; } }
Source:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String path = ((HttpServletRequest) request).getRequestURI(); if (path.contains("/sqlite/")) { super.doFilterInternal(request, response, filterChain); } else { filterChain.doFilter(request, response); } }

Target:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String path = request.getRequestURI(); if (path.contains("gwc/rest/sqlite/")) { super.doFilterInternal(request, response, filterChain); } else { filterChain.doFilter(request, response); } }
Source:
public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity.getId()); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); } else { instance = service.retrieve(ID, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (Exception e) { LOGGER.error("Unable to save object instance", e); throw new ObjectUpdateException(e); } }

Target:
public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = entityClass.newInstance(); } else { instance = service.retrieve(ID, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(); } } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject); if (newObject) { return service.create(instance); } else { return service.update(instance); } } catch (Exception e) { LOGGER.error("Unable to save object instance", e); throw new ObjectUpdateException(e); } }
Source:
public Object visit(ASTCompilationUnit node, Object data) { methodReportLevel = getProperty(METHOD_LEVEL_DESCRIPTOR); classReportLevel = getProperty(CLASS_LEVEL_DESCRIPTOR); if (cycloOptions == null) { cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); } super.visit(node, data); return data; }

Target:
public Object visit(ASTCompilationUnit node, Object data) { methodReportLevel = getProperty(METHOD_LEVEL_DESCRIPTOR); classReportLevel = getProperty(CLASS_LEVEL_DESCRIPTOR); cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); super.visit(node, data); return data; }
Source:
public void testQosError_performsFailover() throws Exception { server1.enqueue(new MockResponse().setResponseCode(UNAVAILABLE_RESPONSE_CODE)); server1.enqueue(new MockResponse().setBody("\"foo\"")); server2.enqueue(new MockResponse().setBody("\"bar\"")); assertThat(proxy.string(), is("bar")); }

Target:
public void testQosError_performsFailover() throws Exception { server1.enqueue(new MockResponse().setResponseCode(503)); server1.enqueue(new MockResponse().setBody("\"foo\"")); server2.enqueue(new MockResponse().setBody("\"bar\"")); assertThat(proxy.string(), is("bar")); }
Source:
public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); CTLogStore store = new CTLogStoreImpl(new CTLogInfo[] { new CTLogInfo(key, "Test Log", "foo") }); ctVerifier = new CTVerifier(store); }

Target:
public void setUp() throws Exception { ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem")); cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem")); certEmbedded = OpenSSLX509Certificate.fromX509PemInputStream( openTestFile("cert-ct-embedded.pem")); PublicKey key = OpenSSLKey.fromPublicKeyPemInputStream( openTestFile("ct-server-key-public.pem")).getPublicKey(); final CTLogInfo log = new CTLogInfo(key, "Test Log", "foo"); CTLogStore store = new CTLogStore() { public CTLogInfo getKnownLog(byte[] logId) { if (Arrays.equals(logId, log.getID())) { return log; } else { return null; } } }; ctVerifier = new CTVerifier(store); }
Source:
public void currentUser_throwsIfMultipleUsersLoggedIn() { AuthenticationServer originalAuthServer = SyncManager.getAuthServer(); AuthenticationServer authServer = Mockito.mock(AuthenticationServer.class); SyncManager.setAuthServerImpl(authServer); when(authServer.loginUser(any(SyncCredentials.class), any(URL.class))).thenAnswer(new Answer<AuthenticateResponse>() { @Override public AuthenticateResponse answer(InvocationOnMock invocationOnMock) throws Throwable { return getNewRandomUser(); } }); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); try { SyncUser.currentUser(); fail(); } catch (IllegalStateException ignore) { } finally { SyncManager.setAuthServerImpl(originalAuthServer); } }

Target:
public void currentUser_throwsIfMultipleUsersLoggedIn() { AuthenticationServer originalAuthServer = SyncManager.getAuthServer(); AuthenticationServer authServer = Mockito.mock(AuthenticationServer.class); SyncManager.setAuthServerImpl(authServer); try { when(authServer.loginUser(any(SyncCredentials.class), any(URL.class))).thenAnswer(new Answer<AuthenticateResponse>() { @Override public AuthenticateResponse answer(InvocationOnMock invocationOnMock) throws Throwable { return getNewRandomUser(); } }); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); SyncUser.login(SyncCredentials.facebook("foo"), "http:/test.realm.io/auth"); try { SyncUser.currentUser(); fail(); } catch (IllegalStateException ignore) { } } finally { SyncManager.setAuthServerImpl(originalAuthServer); } }
Source:
protected final AlarmManager getAlarmManager() { return getAlarmManager(this.getApplicationContext()); }

Target:
protected AlarmManager getAlarmManager() { return getAlarmManager(this.getApplicationContext()); }
Source:
protected synchronized void handleEvent(CoordinatorEvent event) { _log.info("START: Handle event " + event.getType() + ", Instance: " + _adapter.getInstanceName()); try { switch (event.getType()) { case LEADER_DO_ASSIGNMENT: handleLeaderDoAssignment(); break; case HANDLE_ASSIGNMENT_CHANGE: synchronized (_assignedDatastreamTasks) { handleAssignmentChange(false); } break; case HANDLE_DATASTREAM_CHANGE_WITH_UPDATE: synchronized (_assignedDatastreamTasks) { handleAssignmentChange(true); } break; case HANDLE_ADD_OR_DELETE_DATASTREAM: handleDatastreamAddOrDelete(); break; case HANDLE_INSTANCE_ERROR: handleInstanceError((CoordinatorEvent.HandleInstanceError) event); break; case HEARTBEAT: handleHeartbeat(); break; case LEADER_PARTITION_ASSIGNMENT: if (event.getEventMetadata() == null) { _log.error("Datastream group is not found when performing partition assignment, ignore the assignment"); } else { performPartitionAssignment((String) event.getEventMetadata()); } break; case LEADER_PARTITION_MOVEMENT: performPartitionMovement((Long) event.getEventMetadata()); break; case LEADER_DO_POST_BECOMING_LEADER: performTaskPostBecomingLeader(); break; default: String errorMessage = String.format("Unknown event type %s.", event.getType()); ErrorLogger.logAndThrowDatastreamRuntimeException(_log, errorMessage, null); break; } } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "handleEvent-" + event.getType(), NUM_ERRORS, 1); _log.error("ERROR: event + " + event + " failed.", e); } _log.info("END: Handle event " + event); }

Target:
protected synchronized void handleEvent(CoordinatorEvent event) { _log.info("START: Handle event " + event.getType() + ", Instance: " + _adapter.getInstanceName()); try { switch (event.getType()) { case LEADER_DO_ASSIGNMENT: handleLeaderDoAssignment(); break; case HANDLE_ASSIGNMENT_CHANGE: synchronized (_assignedDatastreamTasks) { handleAssignmentChange(false); } break; case HANDLE_DATASTREAM_CHANGE_WITH_UPDATE: synchronized (_assignedDatastreamTasks) { handleAssignmentChange(true); } break; case HANDLE_ADD_OR_DELETE_DATASTREAM: handleDatastreamAddOrDelete(); break; case HANDLE_INSTANCE_ERROR: handleInstanceError((CoordinatorEvent.HandleInstanceError) event); break; case HEARTBEAT: handleHeartbeat(); break; case LEADER_PARTITION_ASSIGNMENT: if (event.getEventMetadata() == null) { _log.error("Datastream group is not found when performing partition assignment, ignore the assignment"); } else { performPartitionAssignment((String) event.getEventMetadata()); } break; case LEADER_PARTITION_MOVEMENT: performPartitionMovement((Long) event.getEventMetadata()); break; case LEADER_DO_CLEANUP_POST_ELECTION: performCleanupTaskPostElection(); break; default: String errorMessage = String.format("Unknown event type %s.", event.getType()); ErrorLogger.logAndThrowDatastreamRuntimeException(_log, errorMessage, null); break; } } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "handleEvent-" + event.getType(), NUM_ERRORS, 1); _log.error("ERROR: event + " + event + " failed.", e); } _log.info("END: Handle event " + event); }
Source:
protected static void addDependencies(URL hpiResUrl, String fromPath, Set<URL> dependencySet) throws URISyntaxException, MalformedURLException { if (dependencySet.contains(hpiResUrl)) { return; } Manifest manifest = parsePluginManifest(hpiResUrl); String dependencySpec = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencySpec != null) { String[] dependencyTokens = dependencySpec.split(","); ServletContext context = Jenkins.getActiveInstance().servletContext; for (String dependencyToken : dependencyTokens) { if (dependencyToken.endsWith(";resolution:=optional")) { continue; } String[] artifactIdVersionPair = dependencyToken.split(":"); String artifactId = artifactIdVersionPair[0]; VersionNumber dependencyVersion = new VersionNumber(artifactIdVersionPair[1]); PluginManager manager = Jenkins.getActiveInstance().getPluginManager(); VersionNumber installedVersion = manager.getPluginVersion(manager.rootDir, artifactId); if (installedVersion != null && installedVersion.isNewerThan(dependencyVersion)) { continue; } URL dependencyURL = context.getResource(fromPath + "/" + artifactId + ".hpi"); if (dependencyURL == null) { dependencyURL = context.getResource(fromPath + "/" + artifactId + ".jpi"); } if (dependencyURL != null) { addDependencies(dependencyURL, fromPath, dependencySet); dependencySet.add(dependencyURL); } } } }

Target:
protected static void addDependencies(URL hpiResUrl, String fromPath, Set<URL> dependencySet) throws URISyntaxException, MalformedURLException { if (dependencySet.contains(hpiResUrl)) { return; } Manifest manifest = parsePluginManifest(hpiResUrl); String dependencySpec = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencySpec != null) { String[] dependencyTokens = dependencySpec.split(","); ServletContext context = Jenkins.getActiveInstance().servletContext; for (String dependencyToken : dependencyTokens) { if (dependencyToken.endsWith(";resolution:=optional")) { continue; } String[] artifactIdVersionPair = dependencyToken.split(":"); String artifactId = artifactIdVersionPair[0]; VersionNumber dependencyVersion = new VersionNumber(artifactIdVersionPair[1]); PluginManager manager = Jenkins.getActiveInstance().getPluginManager(); VersionNumber installedVersion = manager.getPluginVersion(manager.rootDir, artifactId); if (installedVersion != null && !installedVersion.isOlderThan(dependencyVersion)) { continue; } URL dependencyURL = context.getResource(fromPath + "/" + artifactId + ".hpi"); if (dependencyURL == null) { dependencyURL = context.getResource(fromPath + "/" + artifactId + ".jpi"); } if (dependencyURL != null) { addDependencies(dependencyURL, fromPath, dependencySet); dependencySet.add(dependencyURL); } } } }
Source:
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseRenewInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.renew(cancellationToken); }) .repeat(() -> { if (cancellationToken.isCancellationRequested()) { logger.info("Partition {}: renewer task stopped.", this.lease.getLeaseToken()); } return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { logger.warn("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } else { logger.error("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } return Mono.error(throwable); }); }

Target:
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseRenewInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.renew(cancellationToken); }) .repeat(() -> { if (cancellationToken.isCancellationRequested()) { logger.info("Partition {}: renewer task stopped.", this.lease.getLeaseToken()); } return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { if (throwable instanceof LeaseLostException) { logger.info("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } else { logger.error("Partition {}: renew lease loop failed.", this.lease.getLeaseToken(), throwable); } return Mono.error(throwable); }); }
Source:
private boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } if (env.getValue().contains("$".concat(env.getKey()))) { return true; } return false; }

Target:
private static boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } if (env.getValue().contains("$".concat(env.getKey()))) { return true; } return false; }
Source:
public void compactFully() throws Exception { FileReftableDatabase refDb = (FileReftableDatabase) db.getRefDatabase(); PersonIdent person = new PersonIdent("jane", "jane@invalid"); ObjectId aId = db.exactRef("refs/heads/a").getObjectId(); ObjectId bId = db.exactRef("refs/heads/b").getObjectId(); SecureRandom random = new SecureRandom(); List<String> strs = new ArrayList<>(); for (int i = 0; i < 1024; i++) { strs.add(String.format("%02x", random.nextInt(256))); } String randomStr = String.join("", strs); String refName = "branch"; for (long i = 0; i < 2; i++) { RefUpdate ru = refDb.newUpdate(refName, false); ru.setNewObjectId(i % 2 == 0 ? aId : bId); ru.setForceUpdate(true); ru.setRefLogMessage(i == 0 ? randomStr : "short", false); ru.setRefLogIdent(person); RefUpdate.Result res = ru.update(); assertTrue(res == Result.NEW || res == FORCED); } assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); refDb.compactFully(); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); }

Target:
public void compactFully() throws Exception { FileReftableDatabase refDb = (FileReftableDatabase) db.getRefDatabase(); PersonIdent person = new PersonIdent("jane", "jane@invalid"); ObjectId aId = db.exactRef("refs/heads/a").getObjectId(); ObjectId bId = db.exactRef("refs/heads/b").getObjectId(); SecureRandom random = new SecureRandom(); List<String> strs = new ArrayList<>(); for (int i = 0; i < 1024; i++) { strs.add(String.format("%02x", random.nextInt(256))); } String randomStr = String.join("", strs); String refName = "branch"; for (long i = 0; i < 2; i++) { RefUpdate ru = refDb.newUpdate(refName, false); ru.setNewObjectId(i % 2 == 0 ? aId : bId); ru.setForceUpdate(true); ru.setRefLogMessage(i == 0 ? randomStr : "short", false); ru.setRefLogIdent(person); RefUpdate.Result res = ru.update(); assertTrue(res == Result.NEW || res == FORCED); } assertEquals(refDb.exactRef(refName).getObjectId(), bId); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); refDb.compactFully(); assertEquals(refDb.exactRef(refName).getObjectId(), bId); assertTrue(randomStr.equals(refDb.getReflogReader(refName).getReverseEntry(1).getComment())); }
Source:
public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey(). environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); }

Target:
public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); }
Source:
private void swap(int fpos, int spos) { double tmpElement = elements[fpos]; double tmpWeight = weights[fpos]; elements[fpos] = elements[spos]; weights[fpos] = weights[spos]; elements[spos] = tmpElement; weights[spos] = tmpWeight; }

Target:
private void swap(int fpos, int spos) { double tmpElement = samples[fpos]; double tmpWeight = weights[fpos]; samples[fpos] = samples[spos]; weights[fpos] = weights[spos]; samples[spos] = tmpElement; weights[spos] = tmpWeight; }
Source:
public void moveToTrash() { Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_ACTION_MOVE_TO_TRASH_PROJECT_YA, getProjectName()); Ode.getInstance().getProjectService().moveToTrash(getProjectId(), new OdeAsyncCallback<UserProject>( MESSAGES.moveToTrashProjectError()) { @Override public void onSuccess(UserProject project) { if (project.getProjectId() == projectInfo.getProjectId()) { projectInfo.moveToTrash(); Ode.getInstance().getProjectManager().trashProjecct(getProjectId()); } } }); }

Target:
public void moveToTrash() { Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_ACTION_MOVE_TO_TRASH_PROJECT_YA, getProjectName()); Ode.getInstance().getProjectService().moveToTrash(getProjectId(), new OdeAsyncCallback<UserProject>( MESSAGES.moveToTrashProjectError()) { @Override public void onSuccess(UserProject project) { if (project.getProjectId() == projectInfo.getProjectId()) { projectInfo.moveToTrash(); Ode.getInstance().getProjectManager().trashProject(getProjectId()); } } }); }
Source:
public static TmfStateValue newValueString(@Nullable String strValue) { if (strValue == null) { return nullValue(); } for (char c : strValue.toCharArray()) { if (Character.isISOControl(c)) { Activator.getDefault().logError("Trying to use invalid string: " + strValue); throw new IllegalArgumentException(); } } StringStateValue tmfStateValue = STRING_CACHE.get(strValue); if (tmfStateValue == null) { tmfStateValue = new StringStateValue(strValue); STRING_CACHE.put(strValue, tmfStateValue); if (STRING_CACHE.size() > STRING_CACHE_SIZE) { STRING_CACHE.remove(STRING_CACHE.keySet().iterator().next()); } } return tmfStateValue; }

Target:
public static TmfStateValue newValueString(@Nullable String strValue) { if (strValue == null) { return nullValue(); } StringStateValue tmfStateValue = STRING_CACHE.get(strValue); if( tmfStateValue != null ) { return tmfStateValue; } for (char c : strValue.toCharArray()) { if (Character.isISOControl(c)) { Activator.getDefault().logError("Trying to use invalid string: " + strValue); throw new IllegalArgumentException(); } } tmfStateValue = new StringStateValue(strValue); STRING_CACHE.put(strValue, tmfStateValue); if (STRING_CACHE.size() > STRING_CACHE_SIZE) { STRING_CACHE.remove(STRING_CACHE.keySet().iterator().next()); } return tmfStateValue; }
Source:
public void download(User user, @RemainedPath String path, HttpServletResponse response) { path = decodePathWithUTF8(path); FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); throw new NGrinderRuntimeException("download requested file not exists in file entity " + path); } response.reset(); response.setContentType("application/octet-stream; charset=UTF-8"); ContentDisposition contentDisposition = ContentDisposition.builder("attachment") .filename(fileEntry.getFileName(), StandardCharsets.UTF_8) .build(); response.setHeader("Content-Disposition", contentDisposition.toString()); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); byte[] buffer = new byte[4096]; ByteArrayInputStream fis = null; OutputStream toClient = null; try { fis = new ByteArrayInputStream(fileEntry.getContentBytes()); toClient = new BufferedOutputStream(response.getOutputStream()); int readLength; while (((readLength = fis.read(buffer)) != -1)) { toClient.write(buffer, 0, readLength); } } catch (IOException e) { throw processException("error while download file", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }

Target:
public void download(User user, @RemainedPath String path, HttpServletResponse response) { FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); throw new NGrinderRuntimeException("download requested file not exists in file entity " + path); } response.reset(); response.setContentType("application/octet-stream; charset=UTF-8"); ContentDisposition contentDisposition = ContentDisposition.builder("attachment") .filename(fileEntry.getFileName(), StandardCharsets.UTF_8) .build(); response.setHeader("Content-Disposition", contentDisposition.toString()); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); try (ByteArrayInputStream fis = new ByteArrayInputStream(fileEntry.getContentBytes()); OutputStream os = new BufferedOutputStream(response.getOutputStream())) { IOUtils.copy(fis, os); } catch (IOException e) { throw processException("error while download file", e); } }
Source:
public Timeline2 getData() { String type = "all"; String midUrl; String url; Thread[] dataThreads = new Thread[3]; this.postList = new Timeline2(this.order); switch(type) { case "all": case "profile": midUrl = "profile/"; url = this.baseUrl + midUrl + this.query; dataThreads[0] = new ConcurrentScrape(url, "profile"); dataThreads[0].start(); if("profile".equals(type)) break; case "question": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=question"; dataThreads[1] = new ConcurrentScrape(url, "question"); dataThreads[1].start(); if("question".equals(type)) break; case "answer": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=answer"; dataThreads[2] = new ConcurrentScrape(url, "answer"); dataThreads[2].start(); if("answer".equals(type)) break; default: break; } try { for (int i=0; i<3; i++) { dataThreads[i].join(); } } catch(InterruptedException e) { DAO.severe("Couldn't complete all threads"); } return this.postList; }

Target:
public Timeline2 getData() { String type = "all"; String midUrl; String url; Thread[] dataThreads = new Thread[2]; this.postList = new Timeline2(this.order); switch(type) { case "all": case "user": midUrl = "profile/"; url = this.baseUrl + midUrl + this.query; dataThreads[0] = new ConcurrentScrape(url, "users"); dataThreads[0].start(); if("user".equals(type)) break; case "question": midUrl = "search/?q="; url = this.baseUrl + midUrl + this.query + "&type=question"; dataThreads[1] = new ConcurrentScrape(url, "question"); dataThreads[1].start(); if("question".equals(type)) break; default: break; } int i = 0; try { for (i = 0; i < dataThreads.length; i++) { dataThreads[i].join(); } } catch(InterruptedException e) { String stuck_at = ""; switch(i) { case 0: stuck_at = "users"; break; case 1: stuck_at = "question"; break; case 2: stuck_at = "answer"; break; default: stuck_at = "unknown, check the code"; } DAO.severe("Couldn't complete all threads, stuck at scraper: " + this.scraperName + " dataThread: " + stuck_at); } return this.postList; }
Source:
public List<StoredObject> getObjects(@Nonnull String query, int start, int size) { try (Stream<Path> stream = Files.list(file.toPath())) { return stream.skip(start) .map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .limit(size) .map(StoredObject::new) .collect(Collectors.toList()); } catch (IOException e) { throw Exceptions.createHandled().error(e).handle(); } }

Target:
public List<StoredObject> getObjects(@Nonnull String query, int start, int size) { try (Stream<Path> stream = Files.list(file.toPath())) { return stream.map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .skip(start) .limit(size) .map(StoredObject::new) .collect(Collectors.toList()); } catch (IOException e) { throw Exceptions.handle(e); } }
Source:
private void popMessageAndSend() { Message<Object> message = null; byte[] value = null; try { if (readFromLeft) { value = this.boundListOperations.leftPop( this.receiveTimeout, TimeUnit.MILLISECONDS); } else { value = this.boundListOperations.rightPop( this.receiveTimeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { this.listening = false; if (this.active) { logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e); this.publishException(e); this.sleepBeforeRecoveryAttempt(); } else { logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage()); } return; } if (value != null) { if (this.expectMessage) { try { message = (Message<Object>) this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } else { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } message = this.getMessageBuilderFactory().withPayload(payload).build(); } } if (message != null) { if (this.listening) { this.sendMessage(message); } else { if (readFromLeft) { this.boundListOperations.leftPush(value); } else { this.boundListOperations.rightPush(value); } } } }

Target:
private void popMessageAndSend() { Message<Object> message = null; byte[] value = null; try { if (this.rightPop) { value = this.boundListOperations.rightPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } else { value = this.boundListOperations.leftPop(this.receiveTimeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { this.listening = false; if (this.active) { logger.error("Failed to execute listening task. Will attempt to resubmit in " + this.recoveryInterval + " milliseconds.", e); this.publishException(e); this.sleepBeforeRecoveryAttempt(); } else { logger.debug("Failed to execute listening task. " + e.getClass() + ": " + e.getMessage()); } return; } if (value != null) { if (this.expectMessage) { try { message = (Message<Object>) this.serializer.deserialize(value); } catch (Exception e) { throw new MessagingException("Deserialization of Message failed.", e); } } else { Object payload = value; if (this.serializer != null) { payload = this.serializer.deserialize(value); } message = this.getMessageBuilderFactory().withPayload(payload).build(); } } if (message != null) { if (this.listening) { this.sendMessage(message); } else { if (this.rightPop) { this.boundListOperations.rightPush(value); } else { this.boundListOperations.leftPush(value); } } } }
Source:
public void unregisterConsumer(EventConsumer consumer, String publisherName) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug("unregisterConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = this.nameToPublisher.get(publisherName); if (publisher != null) { publisher.removeComsumer(consumer); } else { for (RegisteredConsumer regCon : this.danglingConsumers) { if (regCon.getConsumer().equals(consumer)) { this.danglingConsumers.remove(regCon); break; } } } } finally { regMgmtLock.unlock(); } }

Target:
public void unregisterConsumer(EventConsumer consumer, String publisherName) { if (consumer == null) { throw new InvalidParameterException("Consumer must not be null"); } regMgmtLock.lock(); try { log.debug("unregisterConsumer " + consumer.getClass().getCanonicalName() + " for " + publisherName); RegisteredPublisher publisher = this.nameToPublisher.get(publisherName); if (publisher != null) { publisher.removeComsumer(consumer); } else { removeDanglingConsumer(consumer); } } finally { regMgmtLock.unlock(); } }
Source:
public boolean failover(Guid currentCommandSpmId, Set<Guid> mTriedVdssList) { synchronized (syncObj) { mTriedVdssList.add(currentCommandSpmId); if (currentCommandSpmId.equals(mCurrentVdsId)) { if (getHasVdssForSpmSelection(mCurrentVdsId, mTriedVdssList)) { Guid vdsId = mCurrentVdsId; nullifyInternalProxies(); boolean performFailover = false; if (vdsId != null) { try { VDSReturnValue statusResult = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus, new SpmStatusVDSCommandParameters(vdsId, _storagePoolId)); if (statusResult != null && statusResult.getSucceeded() && (((SpmStatusResult) statusResult.getReturnValue()).getSpmStatus() == SpmStatus.SPM || ((SpmStatusResult) statusResult .getReturnValue()).getSpmStatus() == SpmStatus.Contend)) { performFailover = ResourceManager .getInstance() .runVdsCommand(VDSCommandType.SpmStop, new SpmStopVDSCommandParameters(vdsId, _storagePoolId)) .getSucceeded(); } else { performFailover = true; } } catch (Exception ex) { log.errorFormat("Could not get spm status on host {0} for spmStop.", vdsId); performFailover = true; } } if (performFailover) { log.infoFormat("Irs placed on server {0} failed. Proceed Failover", vdsId); mTriedVdssList.add(vdsId); return true; } else { log.errorFormat("IRS failover failed - cant allocate vds server"); return false; } } return false; } } return true; }

Target:
public boolean failover(Guid currentCommandSpmId, Set<Guid> mTriedVdssList) { synchronized (syncObj) { mTriedVdssList.add(currentCommandSpmId); if (currentCommandSpmId.equals(mCurrentVdsId)) { if (getHasVdssForSpmSelection(mCurrentVdsId, mTriedVdssList)) { Guid vdsId = mCurrentVdsId; nullifyInternalProxies(); boolean performFailover = false; try { VDSReturnValue statusResult = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus, new SpmStatusVDSCommandParameters(vdsId, _storagePoolId)); if (statusResult != null && statusResult.getSucceeded() && (((SpmStatusResult) statusResult.getReturnValue()).getSpmStatus() == SpmStatus.SPM || ((SpmStatusResult) statusResult .getReturnValue()).getSpmStatus() == SpmStatus.Contend)) { performFailover = ResourceManager .getInstance() .runVdsCommand(VDSCommandType.SpmStop, new SpmStopVDSCommandParameters(vdsId, _storagePoolId)) .getSucceeded(); } else { performFailover = true; } } catch (Exception ex) { log.errorFormat("Could not get spm status on host {0} for spmStop.", vdsId); performFailover = true; } if (performFailover) { log.infoFormat("Irs placed on server {0} failed. Proceed Failover", vdsId); return true; } else { log.errorFormat("IRS failover failed - cant allocate vds server"); return false; } } return false; } } return true; }
Source:
public static boolean tryLockIrsProxyData(Guid storagePoolId) { try { return _irsProxyData.get(storagePoolId).tryLockIrsProxyLockObject(); } catch (Exception e) { return false; } }

Target:
public static boolean tryLockIrsProxyData(Guid storagePoolId) { IrsProxyData proxyData = _irsProxyData.get(storagePoolId); if (proxyData != null) { _irsProxyData.get(storagePoolId).tryLockIrsProxyLockObject(); return true; } else { return false; } }
Source:
public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object value = e.getValue(); if (lifespan == null) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else if (e.getMetadata() == null) { if (value == null) { e.setExpired(true); return performRemove(e, ctx); } } else if ( e.getLifespan() == lifespan) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else { log.trace("Cannot remove entry as it's lifespan or value do not match"); } } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }

Target:
public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object value = e.getValue(); if (lifespan == null) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else if (e.getMetadata() == null) { if (value == null || valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else if (e.getLifespan() > 0 && e.getLifespan() == lifespan) { if (valueMatcher.matches(e, value, e.getValue(), valueEquivalence)) { e.setExpired(true); return performRemove(e, ctx); } } else { log.trace("Cannot remove entry as its lifespan or value do not match"); } } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }
Source:
public void close() { if(!isClosed){ isClosed = true; cipherRead = null; cipherWrite = null; cipherParams = null; underlyingThing.close(); } }

Target:
public void close() { if(!isClosed){ isClosed = true; underlyingThing.close(); } }
Source:
private void validateData(Run<?, ?> run, TaskListener listener, StorageAccountInfo storageAccount, String expContainerName) throws IOException, InterruptedException { if ( (run.getResult() == Result.FAILURE || run.getResult() == Result.ABORTED) && uploadArtifactsOnlyIfSuccessful) { listener.getLogger().println( Messages.WAStoragePublisher_build_failed_err()); } if (storageAccount == null) { listener.getLogger().println( Messages.WAStoragePublisher_storage_account_err()); run.setResult(Result.UNSTABLE); } if (Utils.isNullOrEmpty(filesPath)) { listener.getLogger().println( Messages.WAStoragePublisher_filepath_err()); run.setResult(Result.UNSTABLE); } if (getArtifactUploadType() == UploadType.INVALID) { listener.getLogger().println( Messages.WAStoragePublisher_uploadtype_invalid()); run.setResult(Result.UNSTABLE); } try { WAStorageClient.validateStorageAccount( storageAccount.getStorageAccName(), storageAccount.getStorageAccountKey(), storageAccount.getBlobEndPointURL()); } catch (Exception e) { listener.getLogger().println(Messages.Client_SA_val_fail()); listener.getLogger().println( "Storage Account name --->" + storageAccount.getStorageAccName() + "<----"); listener.getLogger().println( "Blob end point url --->" + storageAccount.getBlobEndPointURL() + "<----"); run.setResult(Result.UNSTABLE); } }

Target:
private boolean validateData(Run<?, ?> run, TaskListener listener, StorageAccountInfo storageAccount, String expContainerName) throws IOException, InterruptedException { if ((run.getResult() == Result.FAILURE || run.getResult() == Result.ABORTED) && uploadArtifactsOnlyIfSuccessful) { listener.getLogger().println( Messages.WAStoragePublisher_build_failed_err()); return false; } if (storageAccount == null) { listener.getLogger().println( Messages.WAStoragePublisher_storage_account_err()); return false; } if (Utils.isNullOrEmpty(filesPath)) { listener.getLogger().println( Messages.WAStoragePublisher_filepath_err()); return false; } if (getArtifactUploadType() == UploadType.INVALID) { listener.getLogger().println( Messages.WAStoragePublisher_uploadtype_invalid()); return false; } if (Utils.isNullOrEmpty(expContainerName)) { listener.getLogger().println("Container name is null or empty"); return false; } if (!Utils.validateContainerName(expContainerName)) { listener.getLogger().println("Container name contains invalid characters"); return false; } try { WAStorageClient.validateStorageAccount(storageAccount); } catch (Exception e) { listener.getLogger().println(Messages.Client_SA_val_fail()); listener.getLogger().println( "Storage Account name --->" + storageAccount.getStorageAccName() + "<----"); listener.getLogger().println( "Blob end point url --->" + storageAccount.getBlobEndPointURL() + "<----"); return false; } return true; }
Source:
public void classTearDown() throws IOException { generateResultAnalysis("StudentProfileLNPTest", 0.2, 10000); deleteTestData(JSON_DATA_PATH); deleteDataFiles(); }

Target:
public void classTearDown() throws IOException { deleteTestData(); deleteDataFiles(); }
Source:
public static DocumentBuilder createAndGetDocumentBuilder(Source schemaSource) throws SAXException, ParserConfigurationException, IOException { List<Source> schemaSources = new ArrayList<>(); schemaSources.add(new StreamSource(CORE_SCHEMA_URL.openStream())); schemaSources.add(schemaSource); return createAndGetDocumentBuilder(schemaSources); }

Target:
public static DocumentBuilder createAndGetDocumentBuilder(Source schemaSource) throws SAXException, ParserConfigurationException, IOException { List<Source> schemaSources = new ArrayList<>(2); schemaSources.add(new StreamSource(CORE_SCHEMA_URL.openStream())); schemaSources.add(schemaSource); return createAndGetDocumentBuilder(schemaSources); }
Source:
public void run() throws Exception { TChannel server = new TChannelServerBuilder("ping-server") .register("ping", new PingRequestHandler()) .port(this.port) .build(); server.start().channel().closeFuture().sync(); }

Target:
public void run() throws Exception { TChannel server = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .register("also-ping", new PingRequestHandler()) .setPort(this.port) .build(); server.start().channel().closeFuture().sync(); }
Source:
public static ExtMap generateQueryMap(Collection<String> ids, ExtUUID queryEntity) { ExtMap result = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, queryEntity); ExtKey key = queryEntity.equals(Authz.QueryEntity.GROUP) ? Authz.GroupRecord.ID : Authz.PrincipalRecord.ID; List<ExtMap> filter = new ArrayList<>(); for (String id : ids) { filter.add(createMapForKeyAndValue(key, id)); } result.mput( QueryFilterRecord.OPERATOR, QueryFilterOperator.OR ).mput( QueryFilterRecord.FILTER, filter ); return result; }

Target:
public static ExtMap generateQueryMap(Collection<String> ids, ExtUUID queryEntity) { ExtMap result = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, queryEntity); ExtKey key = queryEntity.equals(Authz.QueryEntity.GROUP) ? Authz.GroupRecord.ID : Authz.PrincipalRecord.ID; List<ExtMap> filter = ids.stream().map((id) -> createMapForKeyAndValue(key, id)).collect(Collectors.toList()); result.mput( QueryFilterRecord.OPERATOR, QueryFilterOperator.OR ).mput( QueryFilterRecord.FILTER, filter ); return result; }
Source:
public void run() { Iterator<String> it = spawn.getSpawnState().jobIdIterator(); List<String> jobIdsNotInCache = new LinkedList<>(); try { outputStream.write("{\"search\": [".getBytes()); while (it.hasNext()) { String jobId = it.next(); String expandedConfig = spawn.getCachedExpandedJob(jobId); if (expandedConfig == null) { jobIdsNotInCache.add(jobId); continue; } searchExpandedConfig(jobId, expandedConfig); } for (String jobId : jobIdsNotInCache) { try { searchExpandedConfig(jobId, spawn.getExpandedConfig(jobId)); } catch (ExecutionException e) { log.warn("failed to get expanded config", e); } } outputStream.write("]}".getBytes()); outputStream.flush(); } catch (IOException e) { log.warn("i/o exception in search thread", e); } finally { try { outputStream.close(); } catch (IOException e) { log.warn("failed to close jobsearcher", e); } } }

Target:
public void run() { Iterator<String> it = spawn.getSpawnState().jobIdIterator(); List<String> jobIdsNotInCache = new ArrayList<>(); try { outputStream.write("{\"search\": [".getBytes()); while (it.hasNext()) { String jobId = it.next(); String expandedConfig = spawn.getCachedExpandedJob(jobId); if (expandedConfig == null) { jobIdsNotInCache.add(jobId); continue; } searchExpandedConfig(jobId, expandedConfig); } for (String jobId : jobIdsNotInCache) { try { searchExpandedConfig(jobId, spawn.getExpandedConfig(jobId)); } catch (ExecutionException e) { log.warn("failed to get expanded config", e); } } outputStream.write("]}".getBytes()); outputStream.flush(); } catch (IOException e) { log.warn("i/o exception in search thread", e); } finally { try { outputStream.close(); } catch (IOException e) { log.warn("failed to close jobsearcher", e); } } }