auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static File generateDefaultConfigFile(String workingDir) { checkArgument(workingDir != null, "working directory should not be null."); final File jaasConfFile; try { Path path = Paths.get(workingDir); if (Files.notExists(Paths.get(workingDir))) { Path parent = path.getParent().toRealPath(); Path resolvedPath = Paths.get(parent.toString(), path.getFileName().toString()); path = Files.createDirectories(resolvedPath); } Path jaasConfPath = Files.createTempFile(path, "jaas-", ".conf"); try (InputStream resourceStream = JaasModule.class.getClassLoader().getResourceAsStream(JAAS_CONF_RESOURCE_NAME)) { Files.copy(resourceStream, jaasConfPath, StandardCopyOption.REPLACE_EXISTING); } jaasConfFile = new File(workingDir, jaasConfPath.getFileName().toString()); jaasConfFile.deleteOnExit(); } catch (IOException e) { throw new RuntimeException("unable to generate a JAAS configuration file", e); } return jaasConfFile; }

Target:
private static File generateDefaultConfigFile(String workingDir) { checkArgument(workingDir != null, "working directory should not be null."); final File jaasConfFile; try { Path path = Paths.get(workingDir); if (Files.notExists(path)) { Path parent = path.getParent().toRealPath(); Path resolvedPath = Paths.get(parent.toString(), path.getFileName().toString()); path = Files.createDirectories(resolvedPath); } Path jaasConfPath = Files.createTempFile(path, "jaas-", ".conf"); try (InputStream resourceStream = JaasModule.class.getClassLoader().getResourceAsStream(JAAS_CONF_RESOURCE_NAME)) { Files.copy(resourceStream, jaasConfPath, StandardCopyOption.REPLACE_EXISTING); } jaasConfFile = new File(workingDir, jaasConfPath.getFileName().toString()); jaasConfFile.deleteOnExit(); } catch (IOException e) { throw new RuntimeException("unable to generate a JAAS configuration file", e); } return jaasConfFile; }
Source:
private List<Map<String, Object>> dedupeAndMergeLocations(Content episode, List<Map<String, Object>> existingLocations) { ImmutableSet<Location> locations = episode.getManifestedAs().stream() .filter(encoding -> encoding != null) .flatMap(encoding -> encoding.getAvailableAt().stream()) .filter(location -> location != null) .filter(location -> location.getPolicy() != null) .collect(MoreCollectors.toImmutableSet()); List<Map<String, Object>> nonNullExistingLocations = existingLocations != null ? existingLocations : ImmutableList.of(); Predicate<Policy> filter = createLocationNotPresentFilter( fromEsLocations(nonNullExistingLocations) ); ImmutableList<Map<String, Object>> newLocations = locations.stream() .filter(location -> filter.apply(location.getPolicy())) .map(location -> newLocationPolicyToMap(location.getPolicy())) .collect(MoreCollectors.toImmutableList()); return ImmutableList.<Map<String, Object>>builder() .addAll(nonNullExistingLocations) .addAll(newLocations) .build(); }

Target:
private List<Map<String, Object>> dedupeAndMergeLocations(Content episode, List<Map<String, Object>> existingLocations) { ImmutableSet<Location> locations = episode.getManifestedAs().stream() .filter(encoding -> encoding != null) .flatMap(encoding -> encoding.getAvailableAt().stream()) .filter(location -> location != null) .filter(location -> location.getPolicy() != null) .collect(MoreCollectors.toImmutableSet()); List<Map<String, Object>> nonNullExistingLocations = existingLocations != null ? existingLocations : ImmutableList.of(); Predicate<Policy> filter = createLocationNotPresentFilter( fromEsLocations(nonNullExistingLocations) ); ImmutableList<Map<String, Object>> newLocations = locations.stream() .filter(location -> filter.apply(location.getPolicy())) .map(EsLocation::toMap) .collect(MoreCollectors.toImmutableList()); return ImmutableList.<Map<String, Object>>builder() .addAll(nonNullExistingLocations) .addAll(newLocations) .build(); }
Source:
public static AccrualOnDefaultFormula of(String uniqueName) { ArgChecker.notNull(uniqueName, "uniqueName"); return valueOf(uniqueName.replace('-', '_').toUpperCase(Locale.ENGLISH)); }

Target:
public static AccrualOnDefaultFormula of(String uniqueName) { ArgChecker.notNull(uniqueName, "uniqueName"); String str = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName); if (str.endsWith("I_S_D_A")) { str = "ORIGINAL_ISDA"; } return valueOf(str); }
Source:
public static String getFirstReachableAddress(ComputeServiceContext context, NodeMetadata node) { SshClient client; try { client = context.utils().sshForNode().apply(node); } catch (Exception e) { throw new IllegalStateException("Unable to connect SshClient to "+node+"; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined", e); } return client.getHostAddress(); }

Target:
public static String getFirstReachableAddress(ComputeServiceContext context, NodeMetadata node) { SshClient client; try { client = context.utils().sshForNode().apply(node); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Unable to connect SshClient to "+node+"; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined", e); } return client.getHostAddress(); }
Source:
protected void assertNoRetryContextAfterScopeExecutions(int expectedExecutions) throws MuleException { final CoreEvent testEvent = eventBuilder(muleContext).message(of("queso")).build(); try { untilSuccessful.process(testEvent); fail(); } catch (Exception e) { MessagingException messagingException = (MessagingException) e; Map<String, Object> retryCtxContainer = ((InternalEvent) messagingException.getEvent()).getInternalParameter(RETRY_CTX_INTERNAL_PARAMETER_KEY); assertThat(retryCtxContainer.isEmpty(), is(true)); assertThat(targetMessageProcessor.eventCount, is(expectedExecutions)); } }

Target:
protected void assertNoRetryContextAfterScopeExecutions(int expectedExecutions) throws MuleException { final CoreEvent testEvent = eventBuilder(muleContext).message(of("queso")).build(); try { untilSuccessful.process(testEvent); fail("An exhaustion error was expected from an until successful scope"); } catch (Exception e) { MessagingException messagingException = (MessagingException) e; Map<String, Object> retryCtxContainer = ((InternalEvent) messagingException.getEvent()).getInternalParameter(RETRY_CTX_INTERNAL_PARAMETER_KEY); assertThat(retryCtxContainer.isEmpty(), is(true)); assertThat(targetMessageProcessor.eventCount, is(expectedExecutions)); } }
Source:
public void showAllImages(boolean enabled) { if(!enabled) { this.viewer.addFilter(hideDanglingImagesFilter); this.viewer.addFilter(hideIntermediateImagesFilter); this.form.setText(DVMessages.getFormattedString( connection.getName(), Integer.toString(connection.getContainers().size()))); } else { this.viewer.removeFilter(hideDanglingImagesFilter); this.viewer.removeFilter(hideIntermediateImagesFilter); this.form.setText(DVMessages.getFormattedString( connection.getName(), Integer.toString(connection.getContainers().size()))); } refreshViewTitle(); }

Target:
public void showAllImages(boolean enabled) { if(!enabled) { this.viewer.addFilter(hideDanglingImagesFilter); this.viewer.addFilter(hideIntermediateImagesFilter); } else { final List<ViewerFilter> filters = new ArrayList<>( Arrays.asList(this.viewer.getFilters())); for (Iterator<ViewerFilter> iterator = filters.iterator(); iterator .hasNext();) { ViewerFilter viewerFilter = iterator.next(); if (viewerFilter.equals(hideDanglingImagesFilter) || viewerFilter.equals(hideIntermediateImagesFilter)) { iterator.remove(); } } this.viewer.setFilters(filters.toArray(new ViewerFilter[0])); } refreshViewTitle(); }
Source:
protected void doExecute(ApplicationService applicationService) throws ApplicationServiceException { Application application = applicationService.getApplication(appName); if (application == null) { console.println("No application found with name " + appName); return; } ApplicationStatus appStatus = applicationService.getApplicationStatus(application); console.println(application.getName()); console.println("\nCurrent State is: " + appStatus.getState().toString()); console.println("\nFeatures Located within this Application:"); for (Feature curFeature : application.getFeatures()) { console.println("\t" + curFeature.getName()); } console.println("\nRequired Features Not Started"); if (appStatus.getErrorFeatures().isEmpty()) { console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString()); console.println("\tNONE"); console.print(Ansi.ansi().reset().toString()); } else { for (Feature curFeature : appStatus.getErrorFeatures()) { console.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); console.println("\t" + curFeature.getName()); console.print(Ansi.ansi().reset().toString()); } } console.println("\nRequired Bundles Not Started"); if (appStatus.getErrorBundles().isEmpty()) { console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString()); console.println("\tNONE"); console.print(Ansi.ansi().reset().toString()); } else { for (Bundle curBundle : appStatus.getErrorBundles()) { console.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); console.println("\t[" + curBundle.getBundleId() + "]\t" + curBundle.getSymbolicName()); console.print(Ansi.ansi().reset().toString()); } } }

Target:
protected void doExecute(ApplicationService applicationService) throws ApplicationServiceException { Application application = applicationService.getApplication(appName); if (application == null) { console.println("No application found with name " + appName); return; } ApplicationStatus appStatus = applicationService.getApplicationStatus(application); console.println(application.getName()); console.println("\nCurrent State is: " + appStatus.getState()); console.println("\nFeatures Located within this Application:"); for (Feature curFeature : application.getFeatures()) { console.println("\t" + curFeature.getName()); } console.println("\nRequired Features Not Started"); if (appStatus.getErrorFeatures().isEmpty()) { console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString()); console.println("\tNONE"); console.print(Ansi.ansi().reset().toString()); } else { for (Feature curFeature : appStatus.getErrorFeatures()) { console.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); console.println("\t" + curFeature.getName()); console.print(Ansi.ansi().reset().toString()); } } console.println("\nRequired Bundles Not Started"); if (appStatus.getErrorBundles().isEmpty()) { console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString()); console.println("\tNONE"); console.print(Ansi.ansi().reset().toString()); } else { for (Bundle curBundle : appStatus.getErrorBundles()) { console.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); console.println("\t[" + curBundle.getBundleId() + "]\t" + curBundle.getSymbolicName()); console.print(Ansi.ansi().reset().toString()); } } }
Source:
public static ResultHolder[] applyConstraintsToSpecifics(HaxeMethodModel model, ResultHolder[] specifics) { if (nonNull(model.getGenericParams())) { List<HaxeGenericParamModel> genericParams = model.getGenericParams(); if (genericParams != null) { Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { specifics[i] = nameAndConstraints.get(name); if (specifics[i].getClassType().isEnumValueClass()) { ResultHolder dynamicType = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); specifics[i] = wrapType(dynamicType, specifics[i].getElementContext(), true).createHolder(); } continue; } specifics[i] = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); } } } } return specifics; }

Target:
public static ResultHolder[] applyConstraintsToSpecifics(HaxeMethodModel model, ResultHolder[] specifics) { List<HaxeGenericParamModel> genericParams = model.getGenericParams(); if (nonNull(genericParams)) { Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { specifics[i] = nameAndConstraints.get(name); if (specifics[i].getClassType().isEnumValueClass()) { ResultHolder dynamicType = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); specifics[i] = wrapType(dynamicType, specifics[i].getElementContext(), true).createHolder(); } continue; } specifics[i] = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); } } } return specifics; }
Source:
public void startExport(Process process) throws DAOException, DataException, IOException { boolean exported = process.isExported(); process.setExported(true); ServiceManager.getProcessService().save(process); boolean exportSucessfull = startExport(process, (URI) null); if (exportSucessfull) { if (Objects.nonNull(process.getParent())) { startExport(process.getParent()); } } else { process.setExported(exported); } ServiceManager.getProcessService().save(process); }

Target:
public void startExport(Process process) throws DataException { boolean wasNotAlreadyExported = !process.isExported(); if (wasNotAlreadyExported) { process.setExported(true); ServiceManager.getProcessService().save(process); } boolean exportSucessfull = startExport(process, (URI) null); if (exportSucessfull) { if (Objects.nonNull(process.getParent())) { startExport(process.getParent()); } } else if (wasNotAlreadyExported) { process.setExported(false); ServiceManager.getProcessService().save(process); } }
Source:
public boolean isPublished() { Instant now = Instant.now(); Instant publishTime = this.resultsVisibleFromTime; if (publishTime.equals(Const.TIME_REPRESENTS_FOLLOW_VISIBLE)) { return isVisible(); } else if (publishTime.equals(Const.TIME_REPRESENTS_LATER)) { return false; } else if (publishTime.equals(Const.TIME_REPRESENTS_NEVER)) { return false; } else if (publishTime.equals(Const.TIME_REPRESENTS_NOW)) { return true; } else { return now.isAfter(publishTime) || now.equals(publishTime); } }

Target:
public boolean isPublished() { Instant publishTime = this.resultsVisibleFromTime; if (publishTime.equals(Const.TIME_REPRESENTS_FOLLOW_VISIBLE)) { return isVisible(); } if (publishTime.equals(Const.TIME_REPRESENTS_LATER) || publishTime.equals(Const.TIME_REPRESENTS_NEVER)) { return false; } if (publishTime.equals(Const.TIME_REPRESENTS_NOW)) { return true; } Instant now = Instant.now(); return now.isAfter(publishTime) || now.equals(publishTime); }
Source:
private List<Long> collectResumingTasksForResumeFailedMode(long attemptId) { List<ArchivedTask> tasks = sm .getSessionStore(getSiteId()) .getTasksOfAttempt(attemptId); List<Long> groupRetryErrorTaskIds = tasks.stream() .filter(task -> task.getState() == TaskStateCode.GROUP_ERROR && task.getStateParams().has("retry_count")) .map(task -> task.getId()) .collect(Collectors.toList()); List<Long> successTasks = tasks.stream() .filter(task -> !groupRetryErrorTaskIds.contains(task.getParentId().orNull())) .filter(task -> !task.getFullName().contains("^sub")) .filter(task -> task.getState() == TaskStateCode.SUCCESS) .map(task -> { if (!task.getParentId().isPresent()) { throw new IllegalArgumentException("Resuming successfully completed attempts is not supported"); } return task.getId(); }) .collect(Collectors.toList()); return ImmutableList.copyOf(successTasks); }

Target:
private List<Long> collectResumingTasksForResumeFailedMode(long attemptId) { List<ArchivedTask> tasks = sm .getSessionStore(getSiteId()) .getTasksOfAttempt(attemptId); List<Long> groupRetryErrorTaskIds = tasks.stream() .filter(task -> task.getState() == TaskStateCode.GROUP_ERROR && task.getStateParams().has("retry_count")) .map(task -> task.getId()) .collect(Collectors.toList()); List<Long> successTasks = tasks.stream() .filter(task -> !task.getFullName().contains("^sub")) .filter(task -> task.getState() == TaskStateCode.SUCCESS) .filter(task -> { if (!task.getParentId().isPresent()) { throw new IllegalArgumentException("Resuming successfully completed attempts is not supported"); } return !groupRetryErrorTaskIds.contains(task.getParentId().get()); }) .map(StoredTask::getId) .collect(Collectors.toList()); return ImmutableList.copyOf(successTasks); }
Source:
private void setTimeInterval(Criteria c, Calendar fromTime, Calendar toTime) { Calendar from = fromTime; if (from == null) { from = Calendar.getInstance(); from.setTimeInMillis(0); } Calendar to = toTime; if (to == null) { to = Calendar.getInstance(); to.setTimeInMillis(System.currentTimeMillis()); } if (to.after(from)) { c.add(Restrictions.between(TIME_FIELD_NAME, from, to)); } }

Target:
private void setTimeInterval(Criteria c, Calendar fromTime, Calendar toTime) { if (fromTime != null && toTime != null) { c.add(Restrictions.between(TIME_FIELD_NAME, fromTime, toTime)); } else if (fromTime != null) { c.add(Restrictions.ge(TIME_FIELD_NAME, fromTime)); } else if (toTime != null) { c.add(Restrictions.le(TIME_FIELD_NAME, toTime)); } }
Source:
private static boolean isSTDistance(RowExpression expression, FunctionManager functionManager) { if (expression instanceof CallExpression) { return functionManager.getFunctionMetadata(((CallExpression) expression).getFunctionHandle()).getName().equals(ST_DISTANCE); } return false; }

Target:
private static boolean isSTDistance(RowExpression expression, FunctionManager functionManager) { return expression instanceof CallExpression && functionManager.getFunctionMetadata(((CallExpression) expression).getFunctionHandle()).getName().equals(ST_DISTANCE); }
Source:
public List searchContentlets(String[] structureInodes, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, boolean filterUnpublish, boolean filterLocked, int page, int perPage,String orderBy, String modDateFrom, String modDateTo) throws DotStateException, DotDataException, DotSecurityException { String structureInodesJoined = String.join(",", structureInodes); return searchContentlets(structureInodesJoined, fields, categories, showDeleted, filterSystemHost, filterUnpublish, filterLocked, page, perPage, orderBy, modDateFrom, modDateTo); }

Target:
public List searchContentlets(String[] structureInodes, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, boolean filterUnpublish, boolean filterLocked, int page, int perPage,String orderBy, String modDateFrom, String modDateTo) throws DotStateException, DotDataException, DotSecurityException { String structureInodesJoined = String.join(CONTENT_TYPES_INODE_SEPARATOR, structureInodes); return searchContentlets(structureInodesJoined, fields, categories, showDeleted, filterSystemHost, filterUnpublish, filterLocked, page, perPage, orderBy, modDateFrom, modDateTo); }
Source:
private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); boolean realmFileIsBeingCreated = !configuration.realmExists(); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); OsSharedRealm sharedRealm = null; try { if (configuration.isSyncConfiguration()) { if (realmFileIsBeingCreated) { OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); if (ObjectServerFacade.getSyncFacadeIfPossible().isPartialRealm(configuration)) { sharedRealm = OsSharedRealm.getInstance(configuration, OsSharedRealm.VersionID.LIVE); try { ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); } catch (Throwable t) { sharedRealm.close(); sharedRealm = null; deleteRealmFileOnDisk(configuration); throw t; } } else { ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); } } } } finally { if (sharedRealm != null) { sharedRealm.close(); } } this.configuration = configuration; } else { validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, realmFileIsBeingCreated, version); } referenceCounter.incrementThreadCount(1); return (E) referenceCounter.getRealmInstance(); }

Target:
private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); boolean realmFileIsBeingCreated = !configuration.realmExists(); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); OsSharedRealm sharedRealm = null; try { if (configuration.isSyncConfiguration() && realmFileIsBeingCreated) { OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); if (ObjectServerFacade.getSyncFacadeIfPossible().isPartialRealm(configuration)) { sharedRealm = OsSharedRealm.getInstance(configuration, OsSharedRealm.VersionID.LIVE); try { ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); } catch (Throwable t) { sharedRealm.close(); sharedRealm = null; deleteRealmFileOnDisk(configuration); throw t; } } else { ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); } } } finally { if (sharedRealm != null) { sharedRealm.close(); } } this.configuration = configuration; } else { validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, realmFileIsBeingCreated, version); } referenceCounter.incrementThreadCount(1); return (E) referenceCounter.getRealmInstance(); }
Source:
private void saveVmDevicesToDb() { updateAllInTransaction(vmDeviceToSave.values(), getDbFacade().getVmDeviceDAO()); if (!removedDeviceIds.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().removeAll(removedDeviceIds); return null; } }); } if (!newVmDevices.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().saveAll(newVmDevices); return null; } }); } }

Target:
private void saveVmDevicesToDb() { List<VmDevice> list = new ArrayList<VmDevice>(vmDeviceToSave.values()); Collections.sort(list); updateAllInTransaction("UpdateVmDeviceRuntimeInfo", list, getDbFacade().getVmDeviceDAO()); if (!removedDeviceIds.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().removeAll(removedDeviceIds); return null; } }); } if (!newVmDevices.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().saveAll(newVmDevices); return null; } }); } }
Source:
public void allFieldsOfVariantShouldBeConverted(){ String chromosome = "12"; int start = 3; int end = 4; String reference = "A"; String alternate = "T"; Variant variant = buildVariant(chromosome, start, end, reference, alternate, fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(false, false, true, includeSrc); conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject files = (BasicDBObject) addToSet.get("files"); assertTrue(fileId.equals(files.get("fid"))); assertTrue(studyId.equals(files.get("sid"))); BasicDBObject setOnInsert = (BasicDBObject) dbObject.get("$setOnInsert"); assertTrue(String.format("%s_%s_%s_%s", chromosome, start, reference, alternate).equals(setOnInsert.get("_id"))); assertTrue(chromosome.equals(setOnInsert.get("chr"))); assertEquals(start, setOnInsert.get("start")); assertEquals(end, setOnInsert.get("end")); assertTrue(reference.equals(setOnInsert.get("ref"))); assertTrue(alternate.equals(setOnInsert.get("alt"))); }

Target:
public void allFieldsOfVariantShouldBeConverted() { String chromosome = "12"; int start = 3; int end = 4; String reference = "A"; String alternate = "T"; Variant variant = buildVariant(chromosome, start, end, reference, alternate, fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(false, false, true, includeSrc); conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject files = (BasicDBObject) addToSet.get("files"); assertEquals(fileId, files.get("fid")); assertEquals(studyId, files.get("sid")); BasicDBObject setOnInsert = (BasicDBObject) dbObject.get("$setOnInsert"); assertEquals(String.format("%s_%s_%s_%s", chromosome, start, reference, alternate), setOnInsert.get("_id")); assertEquals(chromosome, setOnInsert.get("chr")); assertEquals(start, setOnInsert.get("start")); assertEquals(end, setOnInsert.get("end")); assertEquals(reference, setOnInsert.get("ref")); assertEquals(alternate, setOnInsert.get("alt")); }
Source:
public static Properties getDatasourceProperties() { String propertiesNotFoundMessage = "Unable to load datasource properties [" + DATASOURCE_PROPERTIES + "]"; boolean propertiesNotFound = false; System.setProperty("h2.lobInDatabase", "true"); InputStream propsInputStream = PersistenceUtil.class.getResourceAsStream(DATASOURCE_PROPERTIES); assert propsInputStream != null : propertiesNotFoundMessage; Properties props = new Properties(); if (propsInputStream != null) { try { props.load(propsInputStream); } catch (IOException ioe) { propertiesNotFound = true; logger.warn("Unable to find properties, using default H2 properties: " + ioe.getMessage()); ioe.printStackTrace(); } } else { propertiesNotFound = true; } String password = props.getProperty("password"); if ("${maven.jdbc.password}".equals(password) || propertiesNotFound) { props = getDefaultProperties(); } return props; }

Target:
public static Properties getDatasourceProperties() { String propertiesNotFoundMessage = "Unable to load datasource properties [" + DATASOURCE_PROPERTIES + "]"; boolean propertiesNotFound = false; System.setProperty("h2.lobInDatabase", "true"); InputStream propsInputStream = PersistenceUtil.class.getResourceAsStream(DATASOURCE_PROPERTIES); if (propsInputStream == null) { throw new IllegalStateException(propertiesNotFoundMessage); } Properties props = new Properties(); try { props.load(propsInputStream); } catch (IOException ioe) { propertiesNotFound = true; logger.warn("Unable to find properties, using default H2 properties: " + ioe.getMessage()); ioe.printStackTrace(); } String password = props.getProperty("password"); if ("${maven.jdbc.password}".equals(password) || propertiesNotFound) { props = getDefaultProperties(); } return props; }
Source:
public synchronized void setInstanceStatus(InstanceStatus status) { InstanceStatus prev = instanceInfo.setStatus(status); if (prev != null) { for (StatusChangeListener listener : listeners.values()) { listener.notify(new StatusChangeEvent(prev, status)); } } }

Target:
public synchronized void setInstanceStatus(InstanceStatus status) { InstanceStatus prev = instanceInfo.setStatus(status); if (prev != null) { for (StatusChangeListener listener : listeners.values()) { try { listener.notify(new StatusChangeEvent(prev, status)); } catch (Exception e) { logger.warn("failed to notify listener: {}", listener.getId(), e); } } } }
Source:
protected Image addParents(Image image) { image.setStorageDomain(new StorageDomain()); image.getStorageDomain().setId(storageDomainId.toString()); return image; }

Target:
protected Image addParents(Image image) { StorageDomain sd = new StorageDomain(); sd.setId(storageDomainId.toString()); image.setStorageDomain(sd); return super.addParents(image); }
Source:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fListener); } }); }

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fFocusLostListener); } }); }
Source:
private void asyncInstall(License newLicense, UpdateCenter updateCenter) { try { Set<String> editionPluginKeys = newLicense.getPluginKeys(); Map<String, PluginInfo> pluginInfosByKeys = pluginRepository.getPluginInfosByKeys(); Set<String> pluginsToRemove = pluginsToRemove(editionPluginKeys, pluginInfosByKeys.values()); Set<String> pluginsToInstall = pluginsToInstall(editionPluginKeys, pluginInfosByKeys.keySet()); editionPluginDownloader.downloadEditionPlugins(pluginsToInstall, updateCenter); uninstallPlugins(pluginsToRemove); editionManagementState.automaticInstallReady(); } catch (Throwable t) { LOG.error("Failed to install edition with plugins {}", newLicense.getEditionKey(), newLicense.getPluginKeys(), t); editionManagementState.installFailed(t.getMessage()); } finally { semaphore.release(); } }

Target:
private void asyncInstall(License newLicense, UpdateCenter updateCenter) { try { Set<String> editionPluginKeys = newLicense.getPluginKeys(); Map<String, PluginInfo> pluginInfosByKeys = pluginRepository.getPluginInfosByKeys(); Set<String> pluginsToRemove = pluginsToRemove(editionPluginKeys, pluginInfosByKeys.values()); Set<String> pluginsToInstall = pluginsToInstall(editionPluginKeys, pluginInfosByKeys.keySet()); LOG.info("Installing edition '{}', download: {}, remove: {}", newLicense.getEditionKey(), pluginsToInstall, pluginsToRemove); editionPluginDownloader.downloadEditionPlugins(pluginsToInstall, updateCenter); uninstallPlugins(pluginsToRemove); editionManagementState.automaticInstallReady(); } catch (Throwable t) { LOG.error("Failed to install edition with plugins {}", newLicense.getEditionKey(), newLicense.getPluginKeys(), t); editionManagementState.installFailed(t.getMessage()); } finally { semaphore.release(); } }
Source:
public String toString() { return Objects.toStringHelper(this).add("public=", publicPort). add("private=", target+":"+privatePort).toString(); }

Target:
public String toString() { return Objects.toStringHelper(this).add("public=", publicPort). add("private", target+":"+privatePort).toString(); }
Source:
public Set<OperatorSpec> getAllOperatorSpecs() { Collection<InputStreamInternal> inputStreams = inStreams.values(); Set<OperatorSpec> operatorSpecs = new HashSet<>(); for (InputStreamInternal stream : inputStreams) { doGetOperatorSpecs((MessageStreamImpl) stream, operatorSpecs); } return operatorSpecs; }

Target:
public Collection<OperatorSpec> getAllOperatorSpecs() { Collection<InputStreamInternal> inputStreams = inStreams.values(); Set<OperatorSpec> operatorSpecs = new HashSet<>(); for (InputStreamInternal stream : inputStreams) { doGetOperatorSpecs((MessageStreamImpl) stream, operatorSpecs); } return operatorSpecs; }
Source:
@Override public E remove() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return null; } finally { lock.unlock(); } }

Target:
@Override public E remove() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
public void testEncode() { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); try { ReferencedEnvelope env = new ReferencedEnvelope( Double.valueOf(48.81752162), Double.valueOf(48.81915540), Double.valueOf(-3.47568429), Double.valueOf(-3.47261370), CRS.decode("EPSG:4326")); Filter bboxFilter = ff.bbox(ff.property("geom"), env); Encoder encoder = new Encoder(createConfiguration()); String encodedFilter = encoder.encodeAsString(bboxFilter, FES.Filter); Assert.assertTrue( encodedFilter.contains("<fes:ValueReference>geom</fes:ValueReference>")); Assert.assertTrue( encodedFilter.contains( "<gml:Envelope srsDimension=\"2\" srsName=\"urn:ogc:def:crs:EPSG::4326\">")); Assert.assertTrue( encodedFilter.contains( "<gml:lowerCorner>48.817522 -3.475684</gml:lowerCorner>")); Assert.assertTrue( encodedFilter.contains( "<gml:upperCorner>48.819155 -3.472614</gml:upperCorner>")); } catch (MismatchedDimensionException e) { Assert.fail(e.getMessage()); } catch (NoSuchAuthorityCodeException e) { Assert.fail(e.getMessage()); } catch (FactoryException e) { Assert.fail(e.getMessage()); } catch (IOException e) { Assert.fail(e.getMessage()); } }

Target:
public void testEncode() throws Exception { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); ReferencedEnvelope env = new ReferencedEnvelope( Double.valueOf(48.81752162), Double.valueOf(48.81915540), Double.valueOf(-3.47568429), Double.valueOf(-3.47261370), CRS.decode("EPSG:4326")); Filter bboxFilter = ff.bbox(ff.property("geom"), env); Encoder encoder = new Encoder(createConfiguration()); String encodedFilter = encoder.encodeAsString(bboxFilter, FES.Filter); Assert.assertTrue(encodedFilter.contains("<fes:ValueReference>geom</fes:ValueReference>")); Assert.assertTrue( encodedFilter.contains( "<gml:Envelope srsDimension=\"2\" srsName=\"urn:ogc:def:crs:EPSG::4326\">")); Assert.assertTrue( encodedFilter.contains("<gml:lowerCorner>48.817522 -3.475684</gml:lowerCorner>")); Assert.assertTrue( encodedFilter.contains("<gml:upperCorner>48.819155 -3.472614</gml:upperCorner>")); }
Source:
public void testListJobs() throws Exception { InspectGcsFile.inspectGcsFile(PROJECT_ID, GCS_PATH, PUB_SUB_TOPIC_ID, PUB_SUB_SUBSCRIPTION_ID); JobsList.listJobs(PROJECT_ID, "state=DONE", "INSPECT_JOB"); String output = bout.toString(); Matcher matcher = JOB_ID_PATTERN.matcher(bout.toString()); assertTrue("List must contain results.", matcher.find()); }

Target:
public void testListJobs() throws Exception { JobsList.listJobs(PROJECT_ID); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("DLP jobs found:")); }
Source:
public SecurityContext createSecurityContext(WithMockOidcUser withUser) { String userId = StringUtils.hasLength(withUser.name()) ? withUser .name() : withUser.value(); if (userId == null) { throw new IllegalArgumentException(withUser + " cannot have null userId on both userId and value properties"); } List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : withUser.authorities()) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } OidcUser principal = new DefaultOidcUser(grantedAuthorities, new OidcIdTokenFactory(userId, withUser.clientId(), withUser.nameTokenClaim()).build(), withUser.nameTokenClaim()); Authentication authentication = new OAuth2AuthenticationToken( principal, principal.getAuthorities(), withUser.clientId()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }

Target:
public SecurityContext createSecurityContext(WithMockOidcUser withUser) { String userId = StringUtils.hasLength(withUser.name()) ? withUser .name() : withUser.value(); if (userId == null) { Assert.notNull(userId, "@WithMockOidcUser cannot have null name on both name and value properties"); } Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (String authority : withUser.authorities()) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (grantedAuthorities.isEmpty()) { for (String scope : withUser.scopes()) { Assert.isTrue(!scope.startsWith("SCOPE_"), "scopes cannot start with SCOPE_ got " + scope); grantedAuthorities.add(new SimpleGrantedAuthority("SCOPE_" + scope)); } } grantedAuthorities.add(new OidcUserAuthority(getOidcTokenForUser(userId))); OidcUser principal = new DefaultOidcUser(grantedAuthorities, getOidcTokenForUser(userId)); Authentication authentication = new OAuth2AuthenticationToken( principal, principal.getAuthorities(), "client-id"); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
Source:
public void write(JsonGenerator jg, DocumentModel enriched) throws IOException { Collection<String> subtypes = enriched.getDocumentType().getAllowedSubtypes(); jg.writeFieldName(NAME); jg.writeStartArray(); for (String subtype : subtypes) { jg.writeStartObject(); jg.writeStringField("id", subtype); jg.writeEndObject(); } jg.writeEndArray(); }

Target:
public void write(JsonGenerator jg, DocumentModel enriched) throws IOException { Collection<String> subtypes = enriched.getDocumentType().getAllowedSubtypes(); jg.writeFieldName(NAME); jg.writeStartArray(); for (String subtype : subtypes) { jg.writeStartObject(); jg.writeStringField("type", subtype); jg.writeEndObject(); } jg.writeEndArray(); }
Source:
public DrawingData(final double dar, final double drawingWidth, final double drawingHeight, final DrawingDataDescriptor placementOption) { this.dar = dar; this.drawingWidth = drawingWidth; this.drawingHeight = drawingHeight; this.plaOpt = placementOption; calcAreaAspectRatioScaleMeasure(); }

Target:
public DrawingData(final double dar, final double drawingWidth, final double drawingHeight, final DrawingDataDescriptor placementOption) { this(dar, drawingWidth, drawingHeight, placementOption, 0.0, 0.0); }
Source:
public static Object deserializeState(final ByteBuffer byteBuffer) throws IOException, ClassNotFoundException { final byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){ try(ObjectInputStream o = new ObjectInputStream(b)){ return o.readObject(); } } }

Target:
private static Object deserializeState(final ByteBuffer byteBuffer) throws RuntimeException { final byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try { try (final ByteArrayInputStream b = new ByteArrayInputStream(bytes)) { try (final ObjectInputStream o = new ObjectInputStream(b)) { return o.readObject(); } } } catch (final Exception e) { LOG.log(Level.SEVERE, "An exception occured while deserializing the state."); e.printStackTrace(); throw new RuntimeException("Error while deserializing the operator state."); } }
Source:
public void setup() { filterBuilder = mock(FilterBuilder.class, RETURNS_DEEP_STUBS); when(workspaceMetacardFilter.filter(any())).thenReturn(true); workspaceServiceImpl = new WorkspaceServiceImpl( catalogFramework, workspaceTransformer, workspaceQueryBuilder, securityService, persistentStore, filterBuilder); workspaceServiceImpl.setMaxSubscriptions(100); }

Target:
public void setup() { when(workspaceMetacardFilter.filter(any())).thenReturn(true); workspaceServiceImpl = new WorkspaceServiceImpl( catalogFramework, workspaceTransformer, workspaceQueryBuilder, securityService, persistentStore, filterBuilder); workspaceServiceImpl.setMaxSubscriptions(100); }
Source:
private void show(final String graphUuid, final DomainObject domainObject) { final String domainObjectUUID = domainObject.getDomainObjectUUID(); final String domainObjectName = translationService.getTranslation(domainObject.getDomainObjectNameTranslationKey()); final Diagram<?, ?> diagram = formSessionHandler.getDiagram(); final Path diagramPath = diagram.getMetadata().getPath(); final RenderMode renderMode = formSessionHandler.getSession() instanceof EditorSession ? RenderMode.EDIT_MODE : RenderMode.READ_ONLY_MODE; formsContainer.render(graphUuid, domainObjectUUID, domainObject, diagramPath, (fieldName, newValue) -> { try { formSessionHandler.executeUpdateDomainObjectProperty(domainObject, fieldName, newValue); } catch (final Exception ex) { log(Level.SEVERE, "Something wrong happened refreshing the DomainObject '" + domainObject + "' for field '" + fieldName + "': " + ex.getCause()); } }, renderMode); propertiesOpenedEvent.fire(new FormPropertiesOpened(formSessionHandler.getSession(), domainObjectUUID, domainObjectName)); }

Target:
private void show(final String graphUuid, final DomainObject domainObject) { final String domainObjectUUID = domainObject.getDomainObjectUUID(); final String domainObjectName = translationService.getTranslation(domainObject.getDomainObjectNameTranslationKey()); final Diagram<?, ?> diagram = formSessionHandler.getDiagram(); if (Objects.isNull(diagram)) { return; } final Metadata metadata = diagram.getMetadata(); if (Objects.isNull(metadata)) { return; } final Path diagramPath = metadata.getPath(); final RenderMode renderMode = formSessionHandler.getSession() instanceof EditorSession ? RenderMode.EDIT_MODE : RenderMode.READ_ONLY_MODE; formsContainer.render(graphUuid, domainObjectUUID, domainObject, diagramPath, (fieldName, newValue) -> { try { formSessionHandler.executeUpdateDomainObjectProperty(domainObject, fieldName, newValue); } catch (final Exception ex) { log(Level.SEVERE, "Something wrong happened refreshing the DomainObject '" + domainObject + "' for field '" + fieldName + "': " + ex.getCause()); } }, renderMode); propertiesOpenedEvent.fire(new FormPropertiesOpened(formSessionHandler.getSession(), domainObjectUUID, domainObjectName)); }
Source:
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware()) { replicationFactor.set(calculateReplicationFactorForDC(allHostTokens, cpConfig.getLocalDataCenter())); } Set<String> remoteRacks = new HashSet<String>(); for (Host host : hPools.keySet()) { String rack = host.getRack(); if(localRack == null && rack != null) { remoteRacks.add(rack); } else if (localRack != null && !localRack.isEmpty() && rack != null && !rack.isEmpty() && !localRack.equals(rack)) { remoteRacks.add(rack); } } for (String rack : remoteRacks) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteRackSelectors.put(rack, remoteSelector); } remoteDCNames.swapWithList(remoteRackSelectors.keySet()); topology.set(createTokenPoolTopology(allHostTokens)); }

Target:
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware()) { replicationFactor.set(calculateReplicationFactorForDC(allHostTokens, cpConfig.getLocalDataCenter())); } Set<String> remoteRacks = hPools.keySet().stream().map(h -> h.getRack()).filter(rack -> rack != null && !rack.equals(localRack)).collect(Collectors.toSet()); for (String rack : remoteRacks) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteRackSelectors.put(rack, remoteSelector); } remoteDCNames.swapWithList(remoteRackSelectors.keySet()); topology.set(createTokenPoolTopology(allHostTokens)); }
Source:
public boolean getBindToAllInterfaces() { if (getNetworkInterface() != null || getHostAddress() != null) { return false; } else { return true; } }

Target:
public boolean getBindToAllInterfaces() { return !(getNetworkInterface() != null || getHostAddress() != null); }
Source:
public void blame(BlameInput input, BlameOutput output) { File basedir = input.fileSystem().baseDir(); try (Repository repo = buildRepository(basedir); Git git = Git.wrap(repo)) { File gitBaseDir = repo.getWorkTree(); if (gitBaseDir.toPath().resolve(".git/shallow").toFile().isFile()) { throw MessageException.of("Shallow clone detected, blame information may be incorrect. You can convert to non-shallow with: git fetch --unshallow"); } Stream<InputFile> stream = StreamSupport.stream(input.filesToBlame().spliterator(), true); ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), new GitThreadFactory(), null, false); forkJoinPool.submit(() -> stream.forEach(inputFile -> blame(output, git, gitBaseDir, inputFile))); try { forkJoinPool.shutdown(); forkJoinPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.info("Git blame interrupted"); } } }

Target:
public void blame(BlameInput input, BlameOutput output) { File basedir = input.fileSystem().baseDir(); try (Repository repo = buildRepository(basedir); Git git = Git.wrap(repo)) { File gitBaseDir = repo.getWorkTree(); if (Files.isRegularFile(gitBaseDir.toPath().resolve(".git/shallow"))) { throw MessageException.of("Shallow clone detected, blame information may be incorrect. " + "You can either convert to non-shallow with 'git fetch --unshallow', or disable the scm."); } Stream<InputFile> stream = StreamSupport.stream(input.filesToBlame().spliterator(), true); ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), new GitThreadFactory(), null, false); forkJoinPool.submit(() -> stream.forEach(inputFile -> blame(output, git, gitBaseDir, inputFile))); try { forkJoinPool.shutdown(); forkJoinPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.info("Git blame interrupted"); } } }