auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void cancelNotOnMainThreadCrashes() throws Exception { doCallRealMethod().when(picasso).cancelRequest(any(ImageView.class)); doCallRealMethod().when(picasso).cancelRequest(any(Target.class)); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { new RequestCreator(picasso, null, 0).into(mockTarget()); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException ignored) { } finally { latch.countDown(); } } }).start(); latch.await(); }

Target:
public void cancelNotOnMainThreadCrashes() throws Exception { doCallRealMethod().when(picasso).cancelRequest(any(Target.class)); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { new RequestCreator(picasso, null, 0).into(mockTarget()); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException ignored) { } finally { latch.countDown(); } } }).start(); latch.await(); }
Source:
public static void main(String[] args) throws IOException { JobParameters params = new JobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); try (JavaSparkContext sc = JavaSparkContextFactory.withConfAndKryo(new SparkConf())) { HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputFaultPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); PatentMetadataParser parser = new OpsPatentMetadataXPathBasedParser(); JavaRDD<ImportedPatent> importedPatent = avroLoader.loadJavaRDD(sc, params.inputImportedPatentPath, ImportedPatent.class); JavaRDD<DocumentText> toBeProcessedContents = avroLoader.loadJavaRDD(sc, params.inputDocumentTextPath, DocumentText.class); JavaPairRDD<CharSequence, Tuple2<DocumentText, ImportedPatent>> pairedInput = toBeProcessedContents .mapToPair(x -> new Tuple2<CharSequence, DocumentText>(x.getId(), x)) .join(importedPatent.mapToPair(x -> new Tuple2<CharSequence, ImportedPatent>(x.getApplnNr(), x))); JavaRDD<PatentOrFault> parsedPatents = pairedInput.map(x -> parse(x._2._1, x._2._2, parser)); parsedPatents.cache(); Tuple2<JavaRDD<Patent>, JavaRDD<Fault>> splitPatentAndFault = splitPatentAndFault(parsedPatents); avroSaver.saveJavaRDD(splitPatentAndFault._1, Patent.SCHEMA$, params.outputPath); avroSaver.saveJavaRDD(splitPatentAndFault._2, Fault.SCHEMA$, params.outputFaultPath); avroSaver.saveJavaRDD(generateReportEntries(sc, splitPatentAndFault), ReportEntry.SCHEMA$, params.outputReportPath); } }

Target:
public static void main(String[] args) throws IOException { JobParameters params = new JobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); try (JavaSparkContext sc = JavaSparkContextFactory.withConfAndKryo(new SparkConf())) { HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputFaultPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); PatentMetadataParser parser = new OpsPatentMetadataXPathBasedParser(); JavaRDD<ImportedPatent> importedPatent = avroLoader.loadJavaRDD(sc, params.inputImportedPatentPath, ImportedPatent.class); JavaRDD<DocumentText> toBeProcessedContents = avroLoader.loadJavaRDD(sc, params.inputDocumentTextPath, DocumentText.class); JavaPairRDD<CharSequence, Tuple2<DocumentText, ImportedPatent>> pairedInput = toBeProcessedContents .mapToPair(x -> new Tuple2<>(x.getId(), x)) .join(importedPatent.mapToPair(x -> new Tuple2<>(x.getApplnNr(), x))); JavaRDD<Tuple2<Patent, Fault>> parsedPatentsWithFaults = pairedInput .map(x -> parse(x._2._1, x._2._2, parser)); JavaRDD<Patent> patents = parsedPatentsWithFaults.filter(e -> e._1 != null).map(e -> e._1); patents.cache(); JavaRDD<Fault> faults = parsedPatentsWithFaults.filter(e -> e._2 != null).map(e -> e._2); faults.cache(); avroSaver.saveJavaRDD(patents, Patent.SCHEMA$, params.outputPath); avroSaver.saveJavaRDD(faults, Fault.SCHEMA$, params.outputFaultPath); avroSaver.saveJavaRDD(generateReportEntries(sc, patents, faults), ReportEntry.SCHEMA$, params.outputReportPath); } }
Source:
private List<String> getImportClasspath(String localRepo) { List<String> classpath = new ArrayList<>(); if (localRepo.equals("")) { return classpath; } File repo = new File(localRepo); File[] files = repo.listFiles(); if (files == null) { return classpath; } for (File file : files) { if (!file.isDirectory()) { classpath.add(file.getAbsolutePath()); } } return classpath; }

Target:
private List<String> getImportClasspath(String localRepo) { List<String> classpath = new ArrayList<>(); if (localRepo.equals("")) { return classpath; } File repo = new File(localRepo); File[] files = repo.listFiles(); if (files == null) { return classpath; } for (File file : files) { if (file.isFile()) { classpath.add(file.getAbsolutePath()); } } return classpath; }
Source:
private Layer getLayerToActivate(DDiagram parentDiagram, final DDiagramElement ddiagramElement, DiagramMappingsManager mappingManager) { Collection<Layer> layers = mappingManager.getActiveParentLayers(ddiagramElement.getDiagramElementMapping()); List<Layer> allLayers = LayerHelper.getAllLayers(parentDiagram.getDescription()); Set<Layer> deactivatedLayers = allLayers.stream().filter(elmt -> !layers.contains(elmt)).collect(Collectors.toSet()); Collection<Layer> diagramElementLayers = LayerHelper.getParentLayers(ddiagramElement.getDiagramElementMapping()); Collection<Layer> keptElementLayers = new LinkedHashSet<>(); for (Layer deactivatedLayer : deactivatedLayers) { for (Layer diagramElementLayer : diagramElementLayers) { if (EqualityHelper.areEquals(deactivatedLayer, diagramElementLayer)) { keptElementLayers.add(deactivatedLayer); } } } if (keptElementLayers.size() > 0) { return keptElementLayers.iterator().next(); } return null; }

Target:
private Layer getLayerToActivate(DDiagram parentDiagram, final DDiagramElement ddiagramElement, DiagramMappingsManager mappingManager) { Collection<Layer> layers = mappingManager.getActiveParentLayers(ddiagramElement.getDiagramElementMapping()); List<Layer> allLayers = LayerHelper.getAllLayers(parentDiagram.getDescription()); Set<Layer> deactivatedLayers = allLayers.stream().filter(elmt -> !layers.contains(elmt)).collect(Collectors.toSet()); Collection<Layer> diagramElementLayers = LayerHelper.getParentLayers(ddiagramElement.getDiagramElementMapping()); Collection<Layer> keptElementLayers = new LinkedHashSet<>(); for (Layer deactivatedLayer : deactivatedLayers) { for (Layer diagramElementLayer : diagramElementLayers) { if (EqualityHelper.areEquals(deactivatedLayer, diagramElementLayer)) { keptElementLayers.add(deactivatedLayer); } } } if (!keptElementLayers.isEmpty()) { return keptElementLayers.iterator().next(); } return null; }
Source:
public void afterSLAViolated(SLAViolatedEvent event) { this.slaViolated = true; }

Target:
public void afterSLAViolated(SLAViolatedEvent event) { latch.countDown(); }
Source:
IndentedAppendable indent() { int s = size; String[] cache = CACHE; if (s >= 0 && s < cache.length) { buff.append(cache[s]); return this; } while (s-- > 0) { buff.append(' '); } return this; }

Target:
IndentedAppendable indent() { for (int i = 0; i < currentIndentation; i++) { stringBuilder.append(' '); } return this; }
Source:
protected static String buildFilePath(String path) throws IOException { if (StringUtils.isNotEmpty(path) && path.startsWith(RELATIVE_PATH_START_CHAR)) { File currentDirectory = new File(new File(RELATIVE_PATH_START_CHAR).getAbsolutePath()); path = currentDirectory.getCanonicalPath() + File.separator + path; } if (log.isDebugEnabled()) { log.debug("File path for KeyStore/TrustStore : " + path); } return path; }

Target:
private static String buildFilePath(String path) throws IOException { if (StringUtils.isNotEmpty(path) && path.startsWith(Constants.TenantConstants.RELATIVE_PATH_START_CHAR)) { File currentDirectory = new File(new File(Constants.TenantConstants.RELATIVE_PATH_START_CHAR) .getAbsolutePath()); path = currentDirectory.getCanonicalPath() + File.separator + path; } if (log.isDebugEnabled()) { log.debug("File path for KeyStore/TrustStore : " + path); } return path; }
Source:
private void init() { inflate(); bind(); FeedbackUtil.setToolbarButtonLongPressToast(bookmark); FeedbackUtil.setToolbarButtonLongPressToast(navigate); FeedbackUtil.setToolbarButtonLongPressToast(share); }

Target:
private void init() { inflate(); bind(); FeedbackUtil.setToolbarButtonLongPressToast(bookmark, navigate, share); }
Source:
private ListMultipartUploadsResult listIncompleteUploads(String bucketName, String keyMarker, String uploadIdMarker, String prefix, String delimiter, int maxUploads) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("uploads", ""); queryParamMap.put("max-uploads", Integer.toString(maxUploads < 0 || maxUploads > 1000 ? 1000 : maxUploads)); queryParamMap.put("prefix", prefix); queryParamMap.put("key-marker", keyMarker); queryParamMap.put("upload-id-marker", uploadIdMarker); queryParamMap.put("delimiter", delimiter); HttpResponse response = executeGet(bucketName, null, null, queryParamMap); ListMultipartUploadsResult result = new ListMultipartUploadsResult(); result.parseXml(response.body().charStream()); response.body().close(); return result; }

Target:
private ListMultipartUploadsResult listIncompleteUploads(String bucketName, String keyMarker, String uploadIdMarker, String prefix, String delimiter, int maxUploads) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { if (maxUploads < 0 || maxUploads > 1000) { maxUploads = 1000; } Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("uploads", ""); queryParamMap.put("max-uploads", Integer.toString(maxUploads)); queryParamMap.put("prefix", prefix); queryParamMap.put("key-marker", keyMarker); queryParamMap.put("upload-id-marker", uploadIdMarker); queryParamMap.put("delimiter", delimiter); HttpResponse response = executeGet(bucketName, null, null, queryParamMap); ListMultipartUploadsResult result = new ListMultipartUploadsResult(); result.parseXml(response.body().charStream()); response.body().close(); return result; }
Source:
public final void onInit() { if (!(this.executor instanceof ErrorHandlingTaskExecutor)) { ErrorHandler errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(this.getBeanFactory())); this.executor = new ErrorHandlingTaskExecutor(this.executor, errorHandler); } UnicastingDispatcher unicastingDispatcher = new UnicastingDispatcher(this.executor); unicastingDispatcher.setFailover(this.failover); if (this.maxSubscribers == null) { this.maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS, Integer.class); } unicastingDispatcher.setMaxSubscribers(this.maxSubscribers); if (this.loadBalancingStrategy != null) { unicastingDispatcher.setLoadBalancingStrategy(this.loadBalancingStrategy); } unicastingDispatcher.setMessageHandlingTaskDecorator(new MessageHandlingTaskDecorator() { @Override public Runnable decorate(MessageHandlingRunnable task) { return new MessageHandlingTask(task); } }); this.dispatcher = unicastingDispatcher; }

Target:
public final void onInit() { if (!(this.executor instanceof ErrorHandlingTaskExecutor)) { ErrorHandler errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(this.getBeanFactory())); this.executor = new ErrorHandlingTaskExecutor(this.executor, errorHandler); } UnicastingDispatcher unicastingDispatcher = new UnicastingDispatcher(this.executor); unicastingDispatcher.setFailover(this.failover); if (this.maxSubscribers == null) { this.maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS, Integer.class); } unicastingDispatcher.setMaxSubscribers(this.maxSubscribers); if (this.loadBalancingStrategy != null) { unicastingDispatcher.setLoadBalancingStrategy(this.loadBalancingStrategy); } unicastingDispatcher.setMessageHandlingTaskDecorator(new MessageHandlingTaskDecorator() { @Override public Runnable decorate(MessageHandlingRunnable task) { if (ExecutorChannel.this.executorInterceptorsSize > 0) { return new MessageHandlingTask(task); } else { return task; } } }); this.dispatcher = unicastingDispatcher; }
Source:
public void testRemoveModifiedFileWithSTRICT() throws Exception { try { runner.applyPatch(zippedPatch, ContentVerificationPolicy.STRICT); fail("Patch shouldn't be applied - ContentVerificationPolicy.STRICT"); } catch (ContentConflictsException e) { assertPatchHasNotBeenApplied(e, patch, fileRemoved.getItem(), env); assertFileExists(removedFile); assertArrayEquals(expectedModifiedHash, hashFile(removedFile)); } }

Target:
public void testRemoveModifiedFileWithSTRICT() throws Exception { try { runner.applyPatch(zippedPatch, ContentVerificationPolicy.STRICT); } catch (ContentConflictsException e) { assertPatchHasNotBeenApplied(e, patch, fileRemoved.getItem(), env); assertFileExists(removedFile); assertArrayEquals(expectedModifiedHash, hashFile(removedFile)); } }
Source:
CosmosPermissionProperties(String jsonString) { this.permission = new Permission(jsonString); this.permissionName = permission.getId(); this.permissionMode = permission.getPermissionMode(); this.resourcePartitionKey = permission.getResourcePartitionKey(); this.resourceToken = permission.getToken(); String[] parts = Utils.trimBeginningAndEndingSlashes(permission.getResourceLink()).split("/"); if (parts.length < 4) { throw new IllegalArgumentException("jsonString"); } this.databaseName = parts[1]; this.containerName = parts[3]; if (parts.length >= 6) { this.resourceName = parts[5]; if (Paths.DOCUMENTS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.ITEM; } else if (Paths.STORED_PROCEDURES_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.STORED_PROCEDURE; } else if (Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.USER_DEFINED_FUNCTION; } else if (Paths.TRIGGERS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.TRIGGER; } else { throw new IllegalArgumentException("jsonString"); } } }

Target:
CosmosPermissionProperties(String jsonString) { this.permission = new Permission(jsonString); this.permissionName = permission.getId(); this.permissionMode = permission.getPermissionMode(); this.resourcePartitionKey = permission.getResourcePartitionKey(); this.resourceToken = permission.getToken(); String[] parts = StringUtils.split(Utils.trimBeginningAndEndingSlashes(permission.getResourceLink()), "/"); if (parts.length < 4) { throw new IllegalArgumentException("jsonString"); } this.databaseName = parts[1]; this.containerName = parts[3]; if (parts.length >= 6) { this.resourceName = parts[5]; if (Paths.DOCUMENTS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.ITEM; } else if (Paths.STORED_PROCEDURES_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.STORED_PROCEDURE; } else if (Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.USER_DEFINED_FUNCTION; } else if (Paths.TRIGGERS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.TRIGGER; } else { throw new IllegalArgumentException("jsonString"); } } }
Source:
public LinkedList<StreamAppDefinition> getAppDefinitions() { if (this.applicationDefinitions == null || this.applicationDefinitions.isEmpty()) { return getAppDefinitions(this.name, this.dslText); } return this.applicationDefinitions; }

Target:
public LinkedList<StreamAppDefinition> getAppDefinitions() { if (CollectionUtils.isEmpty(this.applicationDefinitions)) { return getAppDefinitions(this.name, this.dslText); } return this.applicationDefinitions; }
Source:
protected void onPreExecute() { super.onPreExecute(); if (contextWeakReference.get() == null) { return; } String title = contextWeakReference.get().getString(R.string.please_wait); String message = contextWeakReference.get().getString(R.string.loading); progressDialog = ProgressDialog.show(contextWeakReference.get(), title, message); }

Target:
protected void onPreExecute() { Context context = contextWeakReference.get(); if (context == null) { return; } String title = context.getString(R.string.please_wait); String message = context.getString(R.string.loading); progressDialog = ProgressDialog.show(context, title, message); }
Source:
protected Properties addConnectionProperties(Properties properties) { Set<String> configKeys = config.values().keySet(); config.originalsWithPrefix("connection.").forEach((k,v) -> { if (!configKeys.contains("connection." + k)) { properties.put(k, v); } }); return properties; }

Target:
protected Properties addConnectionProperties(Properties properties) { Set<String> configKeys = config.values().keySet(); config.originalsWithPrefix(JdbcSourceConnectorConfig.CONNECTION_PREFIX).forEach((k,v) -> { if (!configKeys.contains(JdbcSourceConnectorConfig.CONNECTION_PREFIX + k)) { properties.put(k, v); } }); return properties; }
Source:
public Response createWorkflowInstance( @Valid @ApiParam(value = "Submitted workflow instance information", required = true) CreateWorkflowInstanceRequest req) { WorkflowInstance instance = createWorkflowConverter.convert(req); try { long id = workflowInstances.insertWorkflowInstance(instance); instance = workflowInstances.getWorkflowInstance(id, EnumSet.of(WorkflowInstanceInclude.CURRENT_STATE_VARIABLES), null); return created(URI.create(String.valueOf(id))).entity(createWorkflowConverter.convert(instance)).build(); } catch (StateVariableValueTooLongException e) { return status(BAD_REQUEST.getStatusCode(), e.getMessage()).build(); } }

Target:
public Response createWorkflowInstance( @Valid @ApiParam(value = "Submitted workflow instance information", required = true) CreateWorkflowInstanceRequest req) { WorkflowInstance instance = createWorkflowConverter.convert(req); long id = workflowInstances.insertWorkflowInstance(instance); instance = workflowInstances.getWorkflowInstance(id, EnumSet.of(WorkflowInstanceInclude.CURRENT_STATE_VARIABLES), null); return created(URI.create(String.valueOf(id))).entity(createWorkflowConverter.convert(instance)).build(); }
Source:
public static void initializeBeanInstance(Object instance) { Collection<Method> postConstructMethods = collectPostConstructMethods(instance.getClass()); for (Method method : postConstructMethods) { LOG.debug("invoking post-construct method {}", method); try { method.setAccessible(true); method.invoke(instance); } catch (Exception e) { throw translateException("Exception while invoking @PostConstruct method {}", e); } } Collection<Field> fields = collectInjectedFields(instance.getClass()); for (Field field : fields) { LOG.debug("injecting field {}", field); try { field.setAccessible(true); Object value = BEANS.get(field.getType()); field.set(instance, value); } catch (Exception e) { throw translateException("Exception while injecting field", e); } } }

Target:
public static void initializeBeanInstance(Object instance) { Collection<Field> fields = collectInjectedFields(instance.getClass()); for (Field field : fields) { LOG.debug("injecting field {}", field); try { field.setAccessible(true); Object value = BEANS.get(field.getType()); field.set(instance, value); } catch (Exception e) { throw translateException("Exception while injecting field", e); } } Collection<Method> initMethods = collectInjectedMethods(instance.getClass()); for (Method method : initMethods) { LOG.debug("invoking injected method {}", method); try { method.setAccessible(true); method.invoke(instance, BeanInstanceUtil.getInjectionArguments(method.getParameterTypes())); } catch (Exception e) { throw translateException("Exception while invoking @InjectBean method", e); } } Collection<Method> postConstructMethods = collectPostConstructMethods(instance.getClass()); for (Method method : postConstructMethods) { LOG.debug("invoking post-construct method {}", method); try { method.setAccessible(true); method.invoke(instance); } catch (Exception e) { throw translateException("Exception while invoking @PostConstruct method {}", e); } } }
Source:
abstract <S extends KeySpec> S getKeySpec(final Class<S> keySpecType) throws InvalidKeySpecException; abstract boolean verify(final char[] guess) throws InvalidKeyException; boolean verify(final char[] guess, Charset hashCharset) throws InvalidKeyException { throw new InvalidKeyException(); }

Target:
abstract <S extends KeySpec> S getKeySpec(final Class<S> keySpecType) throws InvalidKeySpecException; abstract boolean verify(final char[] guess) throws InvalidKeyException; boolean verify(final char[] guess, Charset hashCharset) throws InvalidKeyException { throw new UnsupportedOperationException(); }
Source:
public Hole(Element element) { super(element); this.sort = KSorts.KITEM; }

Target:
public Hole(Element element) { super(element); this.sort = Sort.KITEM; }
Source:
protected void autoFillNameTextField() { setAccountNameWithString(accountIdInputTextField.getText().trim()); }

Target:
protected void autoFillNameTextField() { setAccountNameWithString(accountIdInputTextField.getText()); }
Source:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { if(this.offHeapResourceIdentifiers.isEmpty()) { return responseFactory.failure( new IllegalStateException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource.") ); } try { switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(e); } }

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(e); } }
Source:
public void updateProgressBar(int id, int value) { super.updateProgressBar(id, value); switch (id) { case 0: inventory.fill = value != 0; ((GuiBase) ClientProxy.getOpenGui()).redraw(); break; case 1: if (value >= 0) inventory.tank.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.tank.getFluidAmount())); else inventory.tank.setFluid(null); break; case 2: if (value > 0 && inventory.tank.getFluid() != null) inventory.tank.setFluid(new FluidStack(inventory.tank.getFluid(), value)); else inventory.tank.setFluid(null); break; default: break; } }

Target:
public void updateProgressBar(int id, int value) { super.updateProgressBar(id, value); switch (id) { case 0: inventory.fill = value != 0; redrawOpenGui(); break; case 1: if (value >= 0) inventory.tank.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.tank.getFluidAmount())); else inventory.tank.setFluid(null); break; case 2: if (value > 0 && inventory.tank.getFluid() != null) inventory.tank.setFluid(new FluidStack(inventory.tank.getFluid(), value)); else inventory.tank.setFluid(null); break; default: break; } }
Source:
public ValidationResult validUseDefaultNetworkFilterFlag(boolean useDefaultNetworkFilterId) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_INVALID_VNIC_PROFILE_NETWORK_ID_CONFIGURATION, ReplacementUtils.createSetVariableString(VAR_VNIC_PROFILE_NAME, vnicProfile.getName()), ReplacementUtils.createSetVariableString(VAR_NETWORK_FILTER_ID, vnicProfile.getNetworkFilterId())) .when(useDefaultNetworkFilterId & vnicProfile.getNetworkFilterId() != null); }

Target:
public ValidationResult validUseDefaultNetworkFilterFlag(boolean useDefaultNetworkFilterId) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_INVALID_VNIC_PROFILE_NETWORK_ID_CONFIGURATION, ReplacementUtils.createSetVariableString(VAR_VNIC_PROFILE_NAME, vnicProfile.getName()), ReplacementUtils.createSetVariableString(VAR_NETWORK_FILTER_ID, vnicProfile.getNetworkFilterId())) .when(useDefaultNetworkFilterId && vnicProfile.getNetworkFilterId() != null); }
Source:
public void open() throws ConnectionException, XBeeDeviceException, TimeoutException { logger.info("Opening the connection interface..."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); logger.info("Connection interface open."); dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineConnectionMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException("Unsupported operating mode: AT."); } }

Target:
public void open() throws ConnectionException, XBeeDeviceException, TimeoutException { logger.info(toString() + "Opening the connection interface..."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); logger.info(toString() + "Connection interface open."); dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineConnectionMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } }
Source:
void updateResourcePermissionsById(String resourceId) throws UserStoreException { Connection dbConnection = null; ResultSet rs = null; PreparedStatement statement = null; try { PermissionTree tree = new PermissionTree(); tree.root = this.root; dbConnection = getDBConnection(); if (preserveCaseForResources) { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID_CASE_SENSITIVE); } else { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID); } statement.setInt(1, tenantId); statement.setInt(2, tenantId); statement.setString(3, resourceId); rs = statement.executeQuery(); write.lock(); try { while (rs.next()) { short allow = rs.getShort(3); String roleName = rs.getString(1); String domain = rs.getString(5); String roleWithDomain = UserCoreUtil.addDomainToName(roleName, domain); if (allow == UserCoreConstants.ALLOW) { tree.authorizeRoleInTree(roleWithDomain, rs.getString(2), rs.getString(4), false); } } } finally { write.unlock(); } write.lock(); try { this.root = tree.root; } finally { write.unlock(); } } catch (SQLException e) { throw new UserStoreException( "Error loading authorizations. Please check the database. Error message is " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, statement); } }

Target:
void updateResourcePermissionsById(String resourceId) throws UserStoreException { Connection dbConnection = null; ResultSet rs = null; PreparedStatement statement = null; try { PermissionTree tree = new PermissionTree(); tree.root = this.root; dbConnection = getDBConnection(); if (preserveCaseForResources) { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID_CASE_SENSITIVE); } else { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID); } statement.setInt(1, tenantId); statement.setInt(2, tenantId); statement.setString(3, resourceId); rs = statement.executeQuery(); write.lock(); try { while (rs.next()) { short allow = rs.getShort(3); String roleName = rs.getString(1); String domain = rs.getString(5); String roleWithDomain = UserCoreUtil.addDomainToName(roleName, domain); if (allow == UserCoreConstants.ALLOW) { tree.authorizeRoleInTree(roleWithDomain, rs.getString(2), rs.getString(4), false); } } } finally { this.root = tree.root; write.unlock(); } } catch (SQLException e) { throw new UserStoreException( "Error loading authorizations. Please check the database. Error message is " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, statement); } }
Source:
public List<Widget> getGroupWidgetsConfig(@PathVariable String uuid) { Optional<Group> group = repositoryService.getGroup(uuid); if (group.isPresent()) { return group.get().getWidgets(); } else { throw new SQCompanionException("Can't find requested group uuid: " + uuid); } }

Target:
public List<Widget> getGroupWidgetsConfig(@PathVariable String uuid) { return repositoryService.getGroup(uuid).map(Group::getWidgets).orElseThrow(() -> new SQCompanionException("Can't find requested group uuid: " + uuid)); }
Source:
public static FingerprintStorage get(){ String fingerprintStorageEngine = SystemProperties.getString("FingerprintStorageEngine", "jenkins.fingerprints.FileFingerprintStorage"); return ExtensionList.lookup(FingerprintStorage.class).getDynamic(fingerprintStorageEngine); }

Target:
public static FingerprintStorage get() { return ExtensionList.lookup(FingerprintStorage.class).get(0); }
Source:
public static void onKnockBack(LivingKnockBackEvent event) { if(event.getEntityLiving() instanceof EntitySheep) { event.setCanceled(true); } }

Target:
public static void onKnockBack(LivingKnockBackEvent event) { if(ENABLED) { if(event.getEntityLiving() instanceof EntitySheep) { event.setStrength(0.2F); } else if(event.getEntityLiving() instanceof EntityCow) { event.setCanceled(true); } } }
Source:
private XSSFRow getRow(XSSFSheet sheet,int index) { if(sheet.getRow(index)!=null) return sheet.getRow(index); else return sheet.createRow(index); }

Target:
private XSSFRow getRow(XSSFSheet sheet,int index){ if (sheet.getRow(index) != null) { return sheet.getRow(index); } else { return sheet.createRow(index); } }
Source:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; setShellStyle(getShellStyle() | SWT.RESIZE); }

Target:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; }
Source:
private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { if (validatorDir.canRead() && validatorDir.isDirectory()) { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); if (resourceTimestamps.get(f.getName()) == null || resourceTimestamps.get(f.getName()) != f.lastModified()) { reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { try { if (validatorLoader != null) { validatorLoader.close(); } } catch (IOException e) { logger.error("Cannot reload validator classloader."); throw new ValidatorManagerException(e); } validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }

Target:
private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { if (validatorDir.canRead() && validatorDir.isDirectory()) { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); if (resourceTimestamps.get(f.getName()) == null || resourceTimestamps.get(f.getName()) != f.lastModified()) { reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { try { if (validatorLoader != null) { validatorLoader.close(); } } catch (IOException e) { logger.error("Cannot reload validator classloader because failure " + "to close the validator classloader."); } validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }
Source:
public void register() { phaser.register(); try { noSafePoint.check(); } catch (InvalidAssumptionException e) { phaser.arriveAndAwaitAdvance(); try { noSafePoint.check(); } catch (InvalidAssumptionException e1) { phaser.arriveAndAwaitAdvance(); } } }

Target:
public void register() { phaser.register(); }
Source:
public static synchronized void removeIterator(final CtfTmfTrace trace, final CtfTmfContext ctx) { map.get(trace).removeIterator(ctx); }

Target:
public static synchronized void removeIterator(final CtfTmfTrace trace, final CtfTmfContext ctx) { CtfTraceManager traceManager = map.get(trace); if (traceManager != null) { traceManager.removeIterator(ctx); } }
Source:
public boolean releaseLock(String lockId) { log.warn("A following key are going to be released via external call, keyId : " + lockId); globalLock.lock(); try { InternalLockView lock = locks.get(lockId); if (lock == null) { log.warn("A lock with id : " + lockId + " is not exist and can not be release via external call"); return false; } if (lock.getExclusive()) { releaseExclusiveLock(lockId); } else { releaseSharedLock(lockId); } releasedLock.signal(); } finally { globalLock.unlock(); } log.warn("A following key was released via external call, keyId : " + lockId); return true; }

Target:
public boolean releaseLock(String lockId) { log.warnFormat("The following lock is going to be released via external call, lockId {0} ", lockId); globalLock.lock(); try { InternalLockView lock = locks.get(lockId); if (lock == null) { log.warnFormat("Lock with id {0} does not exist and can not be released via external call", lockId); return false; } if (lock.getExclusive()) { releaseExclusiveLock(lockId); } else { releaseSharedLock(lockId); } releasedLock.signal(); } finally { globalLock.unlock(); } log.warnFormat("Lock {0} was released via external call", lockId); return true; }
Source:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .AddMinutes((-1) * Config.<Integer> GetValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMAsyncTask task : _tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getaction_type().toString()); logable.addCustomValue("Dat)e", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { AuditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Stopping async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.stopTask(true); } else { AuditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Clearing async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.clearAsyncTask(true); } } } }

Target:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .AddMinutes((-1) * Config.<Integer> GetValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMAsyncTask task : _tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getaction_type().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { AuditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Stopping async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.stopTask(true); } else { AuditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Clearing async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.clearAsyncTask(true); } } } }
Source:
private boolean isDowngradeChangesFormats(List<StorageDomainStatic> poolDomains) { List<Object> problematicDomains = new LinkedList<>(); for (StorageDomainStatic domainStatic : poolDomains) { if (VersionStorageFormatUtil.getPreferredForVersion(getStoragePool().getcompatibility_version(), domainStatic.getStorageType()).compareTo( domainStatic.getStorageFormat()) < 0 ) { problematicDomains.add(domainStatic.getStorageName()); } } if (!problematicDomains.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DECREASING_COMPATIBILITY_VERSION_CAUSES_STORAGE_FORMAT_DOWNGRADING); addCanDoActionMessageListVariable("problematicDomains", problematicDomains); return true; } return false; }

Target:
private boolean isDowngradeChangesFormats(List<StorageDomainStatic> poolDomains) { List<String> problematicDomains = new LinkedList<>(); Version storagePoolVersion = getStoragePool().getcompatibility_version(); for (StorageDomainStatic domainStatic : poolDomains) { if (VersionStorageFormatUtil.getPreferredForVersion(storagePoolVersion, domainStatic.getStorageType()).compareTo( domainStatic.getStorageFormat()) < 0 ) { problematicDomains.add(domainStatic.getStorageName()); } } if (!problematicDomains.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DECREASING_COMPATIBILITY_VERSION_CAUSES_STORAGE_FORMAT_DOWNGRADING); getReturnValue().getCanDoActionMessages() .addAll(ReplacementUtils.replaceWith("problematicDomains", problematicDomains, ",")); return true; } return false; }
Source:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); VmTemplate originalTemplate = DbFacade.getInstance().getVmTemplateDao().get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }

Target:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BlankVmTemplateId.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = getVmTemplateDAO().get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }
Source:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); for (int i = start; i < start + length; i++) { blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }

Target:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); for (int i = 0; i < length; i++) { blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }
Source:
public static SetMultimap<ReviewerState, Account.Id> getReviewers( Iterable<PatchSetApproval> allApprovals) { PatchSetApproval first = null; SetMultimap<ReviewerState, Account.Id> reviewers = LinkedHashMultimap.create(); for (PatchSetApproval psa : allApprovals) { if (first == null) { first = psa; } else { checkArgument( first.getKey().getParentKey().getParentKey().equals( psa.getKey().getParentKey().getParentKey()), "multiple change IDs: %s, %s", first.getKey(), psa.getKey()); } Account.Id id = psa.getAccountId(); if (psa.getValue() > 0) { reviewers.put(ReviewerState.REVIEWER, id); reviewers.remove(ReviewerState.CC, id); } else if (!reviewers.containsEntry(ReviewerState.REVIEWER, id)) { reviewers.put(ReviewerState.CC, id); } } return Multimaps.unmodifiableSetMultimap(reviewers); }

Target:
public static SetMultimap<ReviewerState, Account.Id> getReviewers( Iterable<PatchSetApproval> allApprovals) { PatchSetApproval first = null; SetMultimap<ReviewerState, Account.Id> reviewers = LinkedHashMultimap.create(); for (PatchSetApproval psa : allApprovals) { if (first == null) { first = psa; } else { checkArgument( first.getKey().getParentKey().getParentKey().equals( psa.getKey().getParentKey().getParentKey()), "multiple change IDs: %s, %s", first.getKey(), psa.getKey()); } Account.Id id = psa.getAccountId(); if (psa.getValue() != 0) { reviewers.put(ReviewerState.REVIEWER, id); reviewers.remove(ReviewerState.CC, id); } else if (!reviewers.containsEntry(ReviewerState.REVIEWER, id)) { reviewers.put(ReviewerState.CC, id); } } return Multimaps.unmodifiableSetMultimap(reviewers); }
Source:
public void addExistingModelElements(EObject eObject, EReference eReference) { final Iterator<EObject> allElements = ItemPropertyDescriptor .getReachableObjectsOfType(eObject, eReference.getEType()) .iterator(); Set<EObject> elements = new LinkedHashSet<EObject>(); while (allElements.hasNext()) { elements.add(allElements.next()); } elements = new HashSet<EObject>(eobjectStrategy.collectExistingObjects(eObject, eReference, elements)); ECPControlHelper.removeExistingReferences(eObject, eReference, elements); final Set<EObject> addedElements = SelectModelElementWizardFactory .openModelElementSelectionDialog(elements, eReference.isMany()); switch (addedElements.size()) { case 0: break; case 1: addReference.addElementToReference(eObject, eReference, addedElements.iterator().next()); break; default: addReference.addElementsToReference(eObject, eReference, addedElements); break; } }

Target:
public void addExistingModelElements(EObject eObject, EReference eReference) { final Iterator<EObject> allElements = ItemPropertyDescriptor .getReachableObjectsOfType(eObject, eReference.getEType()) .iterator(); Set<EObject> elements = new LinkedHashSet<EObject>(); while (allElements.hasNext()) { elements.add(allElements.next()); } elements = new HashSet<EObject>(eobjectStrategy.collectExistingObjects(eObject, eReference, elements)); ECPControlHelper.removeExistingReferences(eObject, eReference, elements); final Set<EObject> addedElements = SelectModelElementWizardFactory .openModelElementSelectionDialog(elements, eReference.isMany()); switch (addedElements.size()) { case 0: break; case 1: addReference.addElementsToReference(eObject, eReference, singleton(addedElements.iterator().next())); break; default: addReference.addElementsToReference(eObject, eReference, addedElements); break; } }
Source:
public static void init() throws Exception { Main.LOCAL.main(args); NetworkAccess toPki = buildApi(args); Multihash pkiNodeId = toPki.dhtClient.id().get(); PublicKeyHash peergosId = PublicKeyHash.fromString(args.getArg("peergos.identity.hash")); nodes.add(toPki); int bootstrapSwarmPort = args.getInt("ipfs-config-swarm-port"); for (int i = 0; i < 2; i++) { int ipfsApiPort = 9000 + random.nextInt(8000); int ipfsGatewayPort = 9000 + random.nextInt(8000); int ipfsSwarmPort = 9000 + random.nextInt(8000); int peergosPort = 9000 + random.nextInt(8000); Args normalNode = UserTests.buildArgs() .with("useIPFS", "true") .with("port", "" + peergosPort) .with("pki-node-id", pkiNodeId.toBase58()) .with("peergos.identity.hash", peergosId.toString()) .with("ipfs-config-api-port", "" + ipfsApiPort) .with("ipfs-config-gateway-port", "" + ipfsGatewayPort) .with("ipfs-config-swarm-port", "" + ipfsSwarmPort) .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, "" + Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId)) .with("proxy-target", Main.getLocalMultiAddress(peergosPort).toString()) .with("ipfs-api-address", Main.getLocalMultiAddress(ipfsApiPort).toString()) .with("mutable-pointers-file", ":memory:") .with("social-sql-file", ":memory:"); Main.PEERGOS.main(normalNode); Thread.sleep(10_000); IPFS ipfs = new IPFS(Main.getLocalMultiAddress(ipfsApiPort)); ipfs.swarm.connect(Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId).toString()); nodes.add(buildApi(normalNode)); } }

Target:
public static void init() throws Exception { Main.PKI.main(args); NetworkAccess toPki = buildApi(args); Multihash pkiNodeId = toPki.dhtClient.id().get(); PublicKeyHash peergosId = PublicKeyHash.fromString(args.getArg("peergos.identity.hash")); nodes.add(toPki); int bootstrapSwarmPort = args.getInt("ipfs-config-swarm-port"); for (int i = 0; i < 2; i++) { int ipfsApiPort = 9000 + random.nextInt(8000); int ipfsGatewayPort = 9000 + random.nextInt(8000); int ipfsSwarmPort = 9000 + random.nextInt(8000); int peergosPort = 9000 + random.nextInt(8000); Args normalNode = UserTests.buildArgs() .with("useIPFS", "true") .with("port", "" + peergosPort) .with("pki-node-id", pkiNodeId.toBase58()) .with("peergos.identity.hash", peergosId.toString()) .with("ipfs-config-api-port", "" + ipfsApiPort) .with("ipfs-config-gateway-port", "" + ipfsGatewayPort) .with("ipfs-config-swarm-port", "" + ipfsSwarmPort) .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, "" + Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId)) .with("proxy-target", Main.getLocalMultiAddress(peergosPort).toString()) .with("ipfs-api-address", Main.getLocalMultiAddress(ipfsApiPort).toString()) .with("mutable-pointers-file", ":memory:") .with("social-sql-file", ":memory:"); Main.PEERGOS.main(normalNode); IPFS ipfs = new IPFS(Main.getLocalMultiAddress(ipfsApiPort)); ipfs.swarm.connect(Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId).toString()); nodes.add(buildApi(normalNode)); } }