auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static int getFormatLength(String format) throws IllegalArgumentException { byte[] b = format.getBytes(Bytes.UTF8_CHARSET); int repeat = 0; char last = (char)b[0]; int length = b.length; for(int i=0; i<b.length+1; i++) { if (i != b.length && (char) b[i] == last) { repeat++; continue; } int r = repeat; char l = last; repeat = 1; if( i != b.length) last = (char) b[i]; if ((l == 'y' || l == 'u') && (r == 4 || r == 2)) continue; else if (r == 2 && "MmdHhs".indexOf(l) != -1 ) continue; else if (r == 3 && (l == 'e' || l == 'E')) continue; else if (l == 'S') continue; else if (r == 1) { if (l == 'a') { length++; continue; } if(" ,.-/:".indexOf(l) != -1) continue; } throw new IllegalArgumentException("not supported format \"" + format + "\": '" + l + "' can't be repeated " + r + " times"); } return length; }

Target:
public static int getFormatLength(String format) throws IllegalArgumentException { byte[] b = format.getBytes(Bytes.UTF8_CHARSET); int repeat = 0; char last = (char)b[0]; int length = b.length; for(int i=0; i<b.length+1; i++) { if (i != b.length && (char) b[i] == last) { repeat++; continue; } int r = repeat; char l = last; repeat = 1; if( i != b.length) last = (char) b[i]; if ((l == 'y' || l == 'u') && (r == 4 || r == 2)) continue; else if (r == 2 && "MmdHhs".indexOf(l) != -1 ) continue; else if (r == 3 && (l == 'e' || l == 'E')) continue; else if (l == 'S' && r <= 9) continue; else if (r == 1 && l == 'a') { length++; continue; } else if(" ,.-/:".indexOf(l) != -1) continue; throw new IllegalArgumentException("not supported format \"" + format + "\": '" + l + "' can't be repeated " + r + " times"); } return length; }
Source:
public String getCloseArgString() { return closeArg; }

Target:
public String getCloseArgString() { return this.closeArg; }
Source:
protected List<HostMetaData> getAllInstanceHostMetaDataForLinkedServices(final Map<Long, Account> accounts, final Set<Long> linkedServicesIds) { MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() { @Override protected HostMetaData map(List<Object> input) { Host host = (Host) input.get(0); IpAddress hostIp = (IpAddress) input.get(1); HostMetaData data = new HostMetaData(hostIp.getAddress(), host, accounts.get(host.getAccountId())); return data; } }; HostTable host = mapper.add(HOST, HOST.STATE); IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS); InstanceHostMapTable instanceHostMap = mapper.add(INSTANCE_HOST_MAP, INSTANCE_HOST_MAP.INSTANCE_ID, INSTANCE_HOST_MAP.HOST_ID); ServiceExposeMapTable exposeMap = mapper.add(SERVICE_EXPOSE_MAP, SERVICE_EXPOSE_MAP.INSTANCE_ID, SERVICE_EXPOSE_MAP.SERVICE_ID); return create() .select(mapper.fields()) .from(hostIpAddress) .join(HOST_IP_ADDRESS_MAP) .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID)) .join(host) .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID)) .join(instanceHostMap) .on(instanceHostMap.HOST_ID.eq(host.ID)) .join(exposeMap) .on(exposeMap.INSTANCE_ID.eq(instanceHostMap.INSTANCE_ID)) .where(host.REMOVED.isNull()) .and(exposeMap.REMOVED.isNull()) .and(instanceHostMap.REMOVED.isNull()) .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)) .and(hostIpAddress.REMOVED.isNull()) .and(exposeMap.SERVICE_ID.in(linkedServicesIds)) .fetch().map(mapper); }

Target:
protected List<HostMetaData> getAllInstanceHostMetaDataForLinkedServices(final Map<Long, Account> accounts, final Set<Long> linkedServicesIds) { MultiRecordMapper<HostMetaData> mapper = new MultiRecordMapper<HostMetaData>() { @Override protected HostMetaData map(List<Object> input) { Host host = (Host) input.get(0); IpAddress hostIp = (IpAddress) input.get(1); HostMetaData data = new HostMetaData(hostIp.getAddress(), host, accounts.get(host.getAccountId())); return data; } }; HostTable host = mapper.add(HOST); IpAddressTable hostIpAddress = mapper.add(IP_ADDRESS); InstanceHostMapTable instanceHostMap = mapper.add(INSTANCE_HOST_MAP, INSTANCE_HOST_MAP.INSTANCE_ID, INSTANCE_HOST_MAP.HOST_ID); ServiceExposeMapTable exposeMap = mapper.add(SERVICE_EXPOSE_MAP, SERVICE_EXPOSE_MAP.INSTANCE_ID, SERVICE_EXPOSE_MAP.SERVICE_ID); return create() .select(mapper.fields()) .from(hostIpAddress) .join(HOST_IP_ADDRESS_MAP) .on(HOST_IP_ADDRESS_MAP.IP_ADDRESS_ID.eq(hostIpAddress.ID)) .join(host) .on(host.ID.eq(HOST_IP_ADDRESS_MAP.HOST_ID)) .join(instanceHostMap) .on(instanceHostMap.HOST_ID.eq(host.ID)) .join(exposeMap) .on(exposeMap.INSTANCE_ID.eq(instanceHostMap.INSTANCE_ID)) .where(host.REMOVED.isNull()) .and(exposeMap.REMOVED.isNull()) .and(instanceHostMap.REMOVED.isNull()) .and(host.STATE.notIn(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED)) .and(hostIpAddress.REMOVED.isNull()) .and(exposeMap.SERVICE_ID.in(linkedServicesIds)) .fetch().map(mapper); }
Source:
public List<List<String>> getColumns(List<String> columns) { ArrayList<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); dataColumns.add(dataColumn); } return dataColumns; }

Target:
public List<List<String>> getColumns(List<String> columns) { List<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); dataColumns.add(dataColumn); } return dataColumns; }
Source:
private Optional<List<Map<String, String>>> readPartitionFromCatalogAndPrune( FlinkContext context, Catalog catalog, ObjectIdentifier tableIdentifier, List<String> allFieldNames, Seq<RexNode> partitionPredicate, Function<List<Map<String, String>>, List<Map<String, String>>> pruner) throws TableNotExistException, TableNotPartitionedException{ RexNodeToExpressionConverter converter = new RexNodeToExpressionConverter( allFieldNames.toArray(new String[0]), context.getFunctionCatalog(), context.getCatalogManager(), TimeZone.getTimeZone(context.getTableConfig().getLocalTimeZone())); ArrayList<Expression> partitionFilters = new ArrayList<>(); Option<ResolvedExpression> subExpr; for (RexNode node: JavaConversions.seqAsJavaList(partitionPredicate)) { subExpr = node.accept(converter); if (!subExpr.isEmpty()) { partitionFilters.add(subExpr.get()); } } ObjectPath tablePath = tableIdentifier.toObjectPath(); if (partitionFilters.size() > 0) { try { List<Map<String, String>> remainingPartitions = catalog.listPartitionsByFilter(tablePath, partitionFilters) .stream() .map(CatalogPartitionSpec::getPartitionSpec) .collect(Collectors.toList()); return Optional.of(remainingPartitions); } catch (UnsupportedOperationException e) { return readPartitionFromCatalogWithoutFilterAndPrune(catalog, tablePath, pruner); } } else { return readPartitionFromCatalogWithoutFilterAndPrune(catalog, tablePath, pruner); } }

Target:
private Optional<List<Map<String, String>>> readPartitionFromCatalogAndPrune( FlinkContext context, Catalog catalog, ObjectIdentifier tableIdentifier, List<String> allFieldNames, Seq<RexNode> partitionPredicate, Function<List<Map<String, String>>, List<Map<String, String>>> pruner) throws TableNotExistException, TableNotPartitionedException { ObjectPath tablePath = tableIdentifier.toObjectPath(); RexNodeToExpressionConverter converter = new RexNodeToExpressionConverter( allFieldNames.toArray(new String[0]), context.getFunctionCatalog(), context.getCatalogManager(), TimeZone.getTimeZone(context.getTableConfig().getLocalTimeZone())); ArrayList<Expression> partitionFilters = new ArrayList<>(); Option<ResolvedExpression> subExpr; for (RexNode node: JavaConversions.seqAsJavaList(partitionPredicate)) { subExpr = node.accept(converter); if (!subExpr.isEmpty()) { partitionFilters.add(subExpr.get()); } else { return readPartitionFromCatalogWithoutFilterAndPrune(catalog, tablePath, pruner); } } try { List<Map<String, String>> remainingPartitions = catalog.listPartitionsByFilter(tablePath, partitionFilters) .stream() .map(CatalogPartitionSpec::getPartitionSpec) .collect(Collectors.toList()); return Optional.of(remainingPartitions); } catch (UnsupportedOperationException e) { return readPartitionFromCatalogWithoutFilterAndPrune(catalog, tablePath, pruner); } }
Source:
public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer) throws Exception { MavenProperties mavenProperties = new MavenProperties(); mavenProperties.setRemoteRepositories(new HashMap<>(Collections.singletonMap("springRepo", new MavenProperties.RemoteRepository(repository)))); MavenResource resource = MavenResource.parse("io.spring.cloud:partitioned-batch-job:1.0.1.BUILD-SNAPSHOT", mavenProperties); DeployerPartitionHandler partitionHandler = new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep"); Map<String, String> environmentProperties = new HashMap<>(); environmentProperties.put("spring.profiles.active", "worker"); partitionHandler.setEnvironmentProperties(environmentProperties); partitionHandler.setMaxWorkers(2); return partitionHandler; }

Target:
public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer) throws Exception { Resource resource = delegatingResourceLoader.getResource("maven://io.spring.cloud:partitioned-batch-job:1.0.0.BUILD-SNAPSHOT"); DeployerPartitionHandler partitionHandler = new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep"); Map<String, String> environmentProperties = new HashMap<>(); environmentProperties.put("spring.profiles.active", "worker"); partitionHandler.setEnvironmentProperties(environmentProperties); partitionHandler.setMaxWorkers(2); return partitionHandler; }
Source:
private String getRequiredStorageUuid(String hostUuid, String psUuid){ if(psUuid == null){ return getMostFreeLocalStorageUuid(hostUuid); }else if(!Q.New(PrimaryStorageVO.class) .eq(PrimaryStorageVO_.type, LocalStorageConstants.LOCAL_STORAGE_TYPE) .eq(PrimaryStorageVO_.uuid, psUuid).isExists()){ throw new OperationFailureException(argerr(String.format("the type of primary storage[uuid:%s] cheesed is not local storage, " + "check if the resource can be created on other storage when cluster has attached local primary storage",psUuid))); }else if(Q.New(LocalStorageHostRefVO.class) .eq(LocalStorageHostRefVO_.primaryStorageUuid, psUuid) .eq(LocalStorageHostRefVO_.hostUuid, hostUuid).isExists()){ return psUuid; }else { return getMostFreeLocalStorageUuid(hostUuid); } }

Target:
private String getRequiredStorageUuid(String hostUuid, String psUuid){ if(psUuid == null){ return getMostFreeLocalStorageUuid(hostUuid); }else if(Q.New(LocalStorageHostRefVO.class) .eq(LocalStorageHostRefVO_.hostUuid, hostUuid) .eq(LocalStorageHostRefVO_.primaryStorageUuid, psUuid) .isExists()){ return psUuid; }else if(!Q.New(PrimaryStorageVO.class) .eq(PrimaryStorageVO_.uuid, psUuid) .eq(PrimaryStorageVO_.type, LocalStorageConstants.LOCAL_STORAGE_TYPE) .isExists()){ throw new OperationFailureException(argerr("the type of primary storage[uuid:%s] chosen is not local storage, " + "check if the resource can be created on other storage when cluster has attached local primary storage", psUuid)); }else { return getMostFreeLocalStorageUuid(hostUuid); } }
Source:
private void handleResponse(BranchCommitResponse response, IProgressMonitor monitor, Branch sourceBranch, Branch destinationBranch) throws OseeCoreException { TransactionRecord newTransaction = response.getTransaction(); AccessPolicy accessPolicy = ServiceUtil.getAccessPolicy(); accessPolicy.removePermissions(sourceBranch); if (sourceBranch.getAssociatedArtifactId() > 0) { TransactionManager.cacheCommittedArtifactTransaction(BranchManager.getAssociatedArtifact(sourceBranch), newTransaction); } BranchManager.getCache().reloadCache(); if (skipChecksAndEvents) { return; } Collection<Change> changes = new ArrayList<Change>(); IOperation operation = ChangeManager.comparedToPreviousTx(newTransaction, changes); doSubWork(operation, monitor, 1.0); handleArtifactEvents(newTransaction, changes); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Committed, sourceBranch.getGuid(), destinationBranch.getGuid())); }

Target:
private void handleResponse(BranchCommitResponse response, IProgressMonitor monitor, Branch sourceBranch, Branch destinationBranch) throws OseeCoreException { TransactionRecord newTransaction = response.getTransaction(); AccessPolicy accessPolicy = ServiceUtil.getAccessPolicy(); accessPolicy.removePermissions(sourceBranch); if (sourceBranch.getAssociatedArtifactId() > 0) { TransactionManager.cacheCommittedArtifactTransaction(BranchManager.getAssociatedArtifact(sourceBranch), newTransaction); } BranchManager.getCache().reloadCache(); if (!skipChecksAndEvents) { Collection<Change> changes = new ArrayList<Change>(); IOperation operation = ChangeManager.comparedToPreviousTx(newTransaction, changes); doSubWork(operation, monitor, 1.0); handleArtifactEvents(newTransaction, changes); OseeEventManager.kickBranchEvent(getClass(), new BranchEvent(BranchEventType.Committed, sourceBranch.getGuid(), destinationBranch.getGuid())); } }
Source:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory, projectName); configuration.setBuildNumber(buildNumber); configuration.setParallelTesting(parallelTesting); if (classifications != null) { for (Map.Entry<String, String> entry : classifications.entrySet()) { configuration.addClassifications(StringUtils.capitalise(entry.getKey()), entry.getValue()); } } ReportBuilder reportBuilder = new ReportBuilder(list, configuration); getLog().info("About to generate Cucumber report."); Reportable report = reportBuilder.generateReports(); if (checkBuildResult) { if (report == null) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }

Target:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory, projectName); configuration.setBuildNumber(buildNumber); configuration.setParallelTesting(parallelTesting); if (!MapUtils.isEmpty(classifications)) { for (Map.Entry<String, String> entry : classifications.entrySet()) { configuration.addClassifications(StringUtils.capitalise(entry.getKey()), entry.getValue()); } } ReportBuilder reportBuilder = new ReportBuilder(list, configuration); getLog().info("About to generate Cucumber report."); Reportable report = reportBuilder.generateReports(); if (checkBuildResult && report == null) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }
Source:
public InstructorFeedbackResultsNoResponsePanel getNoResponsePanel() { return new InstructorFeedbackResultsNoResponsePanel( bundle.responseStatus.getStudentsWhoDidNotRespondToAnyQuestion(), bundle.responseStatus.emailNameTable, bundle.responseStatus.emailTeamNameTable); }

Target:
public InstructorFeedbackResultsNoResponsePanel getNoResponsePanel() { return new InstructorFeedbackResultsNoResponsePanel(bundle.responseStatus); }
Source:
private static boolean prefixExists(Subfield subfieldPath, Collection<Subfield> subfieldPaths) { return subfieldPaths.stream() .filter(path -> path.isPrefix(subfieldPath)) .findAny() .isPresent(); }

Target:
private static boolean prefixExists(Subfield subfieldPath, Collection<Subfield> subfieldPaths) { return subfieldPaths.stream().anyMatch(path -> path.isPrefix(subfieldPath)); }
Source:
public void exceptionIfBoutNotFound() throws IOException { Messages messages = null; try { final String name = "testunread"; final Aliases aliases = new DyBase().user(new URN("urn:test:75066")).aliases(); final Alias alias = aliases.add(name); final Inbox inbox = alias.inbox(); final Bout bout = inbox.bout(inbox.start()); bout.messages().post(" 4 leading spaces retained "); final Friends friends = bout.friends(); friends.kick(name); messages = bout.messages(); } catch (IOException | URISyntaxException e) { fail(e.getMessage()); } messages.unread(); fail("Exception is not received"); }

Target:
public void exceptionIfBoutNotFound() throws Exception { try (final DyBase base = new DyBase()) { final String name = "testunread"; final Aliases aliases = base.user( new URN("urn:test:75066") ).aliases(); final Alias alias = aliases.add(name); final Inbox inbox = alias.inbox(); final Bout bout = inbox.bout(inbox.start()); bout.messages().post(" 4 leading spaces retained "); final Friends friends = bout.friends(); friends.kick(name); final Messages messages = bout.messages(); this.thrown.expect(HttpException.class); this.thrown.expectMessage(String.valueOf(bout.number())); messages.unread(); } }
Source:
public SystemViewLocal(GridKernalContext ctx, SystemView<R> sysView) { super(sqlName(sysView.name()), sysView.description(), ctx, indexes(sysView), columns(sysView)); this.sysView = sysView; attributeNames = new String[sysView.walker().count()]; sysView.walker().visitAll(new AttributeVisitor() { @Override public <T> void accept(int idx, String name, Class<T> clazz, boolean filtering) { attributeNames[idx] = name; } }); }

Target:
public SystemViewLocal(GridKernalContext ctx, SystemView<R> sysView) { this(ctx, sysView, null); }
Source:
public void send(String source, OutgoingMessageEnvelope envelope) { String msg = String.format("OutputStream:%s Key:%s Value:%s", envelope.getSystemStream(), envelope.getKey(), envelope.getMessage() != null ? new String((byte[]) envelope.getMessage()) : null); LOG.info(msg); System.out.println(String.format("Message %d :", messageCounter.incrementAndGet())); if (envelope.getKey() != null) { System.out.println(String.format("Key:%s Value:%s", envelope.getKey(), getFormattedValue(envelope))); } else { System.out.println(getFormattedValue(envelope)); } }

Target:
public void send(String source, OutgoingMessageEnvelope envelope) { String msg = String.format("OutputStream:%s Key:%s Value:%s", envelope.getSystemStream(), envelope.getKey(), new String((byte[]) envelope.getMessage())); LOG.info(msg); System.out.println(String.format("Message %d :", messageCounter.incrementAndGet())); if (envelope.getKey() != null) { System.out.println(String.format("Key:%s Value:%s", envelope.getKey(), getFormattedValue(envelope))); } else { System.out.println(getFormattedValue(envelope)); } }
Source:
public void testCreateInvalidConfigAEADWithAuthAndCrypt() throws Exception { IpSecConfig ipSecConfig = buildIpSecConfig(); IpSecAlgorithm authenticatedEncryptionAlgo = new IpSecAlgorithm(IpSecAlgorithm.AUTH_CRYPT_AES_GCM, CRYPT_KEY, 128); try { ipSecConfig.setAuthenticatedEncryption( IpSecTransform.DIRECTION_OUT, authenticatedEncryptionAlgo); fail( "IpSecService should have thrown an error on crypt/auth being" + " enabled with authenticated encryption for outbound"); } catch (IllegalArgumentException e) { } try { ipSecConfig.setAuthenticatedEncryption( IpSecTransform.DIRECTION_IN, authenticatedEncryptionAlgo); fail( "IpSecService should have thrown an error on crypt/auth being" + " enabled with authenticated encryption for inbound"); } catch (IllegalArgumentException e) { } }

Target:
public void testCreateInvalidConfigAEADWithAuthAndCrypt() throws Exception { IpSecConfig ipSecConfig = buildIpSecConfig(); IpSecAlgorithm authenticatedEncryptionAlgo = new IpSecAlgorithm(IpSecAlgorithm.AUTH_CRYPT_AES_GCM, CRYPT_KEY, 128); try { ipSecConfig.setAuthenticatedEncryption( IpSecTransform.DIRECTION_OUT, authenticatedEncryptionAlgo); fail( "IpSecService should have thrown an error on crypt/auth being" + " enabled with authenticated encryption for outbound"); } catch (IllegalArgumentException expected) { } try { ipSecConfig.setAuthenticatedEncryption( IpSecTransform.DIRECTION_IN, authenticatedEncryptionAlgo); fail( "IpSecService should have thrown an error on crypt/auth being" + " enabled with authenticated encryption for inbound"); } catch (IllegalArgumentException expected) { } }
Source:
extractMemberVariablesFromConfigurationFields(Field[] fields) { if (fields==null) return null; HashMap<String,String> retVal = new HashMap<String,String>(); String propRegex = "^[A-Za-z][A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)+$"; Pattern p = Pattern.compile(propRegex); int totalFields = 0; String value; for (Field f : fields) { if (configDebug) { System.out.println("Field: " + f); } if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isPublic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) { continue; } if (!f.getType().getName().equals("java.lang.String")) { continue; } try { value = (String) f.get(null); } catch (IllegalAccessException iaException) { continue; } if (configDebug) { System.out.println(" Value: " + value); } if (value == null) { continue; } if (value.endsWith(".xml") || value.endsWith(".") || value.endsWith("-")) continue; if (configurationPropsToSkipCompare != null) { if (configurationPropsToSkipCompare.contains(value)) { continue; } } boolean skipPrefix = false; if (configurationPrefixToSkipCompare != null) { for (String cfgPrefix : configurationPrefixToSkipCompare) { if (value.startsWith(cfgPrefix)) { skipPrefix = true; break; } } } if (skipPrefix) { continue; } Matcher m = p.matcher(value); if (!m.find()) { if (configDebug) { System.out.println(" Passes Regex: false"); } continue; } if (configDebug) { System.out.println(" Passes Regex: true"); } if (!retVal.containsKey(value)) { retVal.put(value,f.getName()); } else { if (configDebug) { System.out.println("ERROR: Already found key for property " + value); } } } return retVal; }

Target:
extractMemberVariablesFromConfigurationFields(Field[] fields) { if (fields==null) return null; HashMap<String,String> retVal = new HashMap<String,String>(); String propRegex = "^[A-Za-z][A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)+$"; Pattern p = Pattern.compile(propRegex); int totalFields = 0; String value; for (Field f : fields) { if (configDebug) { System.out.println("Field: " + f); } if (!Modifier.isStatic(f.getModifiers()) || !Modifier.isPublic(f.getModifiers()) || !Modifier.isFinal(f.getModifiers())) { continue; } if (!f.getType().getName().equals("java.lang.String")) { continue; } try { value = (String) f.get(null); } catch (IllegalAccessException iaException) { continue; } if (configDebug) { System.out.println(" Value: " + value); } if (value.endsWith(".xml") || value.endsWith(".") || value.endsWith("-")) continue; if (configurationPropsToSkipCompare != null) { if (configurationPropsToSkipCompare.contains(value)) { continue; } } boolean skipPrefix = false; if (configurationPrefixToSkipCompare != null) { for (String cfgPrefix : configurationPrefixToSkipCompare) { if (value.startsWith(cfgPrefix)) { skipPrefix = true; break; } } } if (skipPrefix) { continue; } Matcher m = p.matcher(value); if (!m.find()) { if (configDebug) { System.out.println(" Passes Regex: false"); } continue; } if (configDebug) { System.out.println(" Passes Regex: true"); } if (!retVal.containsKey(value)) { retVal.put(value,f.getName()); } else { if (configDebug) { System.out.println("ERROR: Already found key for property " + value); } } } return retVal; }
Source:
public void killAll(Map<String, String> modelEnvVars) throws InterruptedException { for( OSProcess p : this) { if(p.getPid()<10) continue; LOGGER.finest("Considering to kill "+p.getPid()); boolean matched; try { matched = p.hasMatchingEnvVars(modelEnvVars); } catch (WinpException e) { LOGGER.log(FINEST," Failed to check environment variable match",e); continue; } if (matched) { if (getVeto(p) == null) p.killRecursively(); } else LOGGER.finest("Environment variable didn't match"); } }

Target:
public void killAll(Map<String, String> modelEnvVars) throws InterruptedException { for( OSProcess p : this) { if(p.getPid()<10) continue; LOGGER.finest("Considering to kill "+p.getPid()); boolean matched; try { matched = p.hasMatchingEnvVars(modelEnvVars); } catch (WinpException e) { LOGGER.log(FINEST," Failed to check environment variable match",e); continue; } if(matched) p.killRecursively(); else LOGGER.finest("Environment variable didn't match"); } }
Source:
public void simplePhenotypeSearch() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype("GIST"); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response).isNotNull(); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().get(0)).isNotNull() ; }

Target:
public void simplePhenotypeSearch() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype(TestData.PHENOTYPE_NAME); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations()).isNotEmpty() ; }
Source:
public ParallelTransferOptions(Integer blockSize, Integer maxConcurrency, ProgressReceiver progressReceiver, Integer maxSingleUploadSize) { this.blockSize = blockSize; this.maxConcurrency = maxConcurrency; if (maxConcurrency != null) { StorageImplUtils.assertInBounds("numBuffers", maxConcurrency, 1, Integer.MAX_VALUE); } this.progressReceiver = progressReceiver; this.maxSingleUploadSize = maxSingleUploadSize; }

Target:
public ParallelTransferOptions(Integer blockSize, Integer maxConcurrency, ProgressReceiver progressReceiver, Integer maxSingleUploadSize) { this.blockSize = blockSize; this.maxConcurrency = maxConcurrency; if (maxConcurrency != null) { StorageImplUtils.assertInBounds("maxConcurrency", maxConcurrency, 1, Integer.MAX_VALUE); } this.progressReceiver = progressReceiver; this.maxSingleUploadSize = maxSingleUploadSize; }
Source:
private boolean multiMatchRune(int r) { int length = Math.min(runes.length, RUNES_LINER_SEARCH_SIZE); for (int j = 0; j < length; j += 2) { if (r < runes[j]) { return false; } if (r <= runes[j + 1]) { return true; } } for (int lo = 0, hi = (runes.length - RUNES_LINER_SEARCH_SIZE) / 2; lo < hi; ) { int m = lo + (hi - lo) / 2; int c = runes[2 * m + RUNES_LINER_SEARCH_SIZE]; if (c <= r) { if (r <= runes[2 * m + 1 + RUNES_LINER_SEARCH_SIZE]) { return true; } lo = m + 1; } else { hi = m; } } return false; }

Target:
private boolean multiMatchRune(int r) { int length = Math.min(runes.length, 10); for (int j = 0; j < length; j += 2) { if (r < runes[j]) { return false; } if (r <= runes[j + 1]) { return true; } } for (int lo = 0, hi = runes.length / 2; lo < hi; ) { int m = lo + (hi - lo) / 2; int c = runes[2 * m]; if (c <= r) { if (r <= runes[2 * m + 1]) { return true; } lo = m + 1; } else { hi = m; } } return false; }
Source:
private void loosen(ObjectDirectoryInserter inserter, ObjectReader reader, PackFile pack, HashSet<ObjectId> existing) throws IOException { for (PackIndex.MutableEntry entry : pack) { final ObjectId oid = entry.toObjectId(); if (!existing.contains(oid)) { existing.add(oid); try { ObjectLoader loader = reader.open(oid); inserter.insert(loader.getType(), loader.getSize(), loader.openStream(), true); } catch (MissingObjectException e) { throw new IOException(e); } } } }

Target:
private void loosen(ObjectDirectoryInserter inserter, ObjectReader reader, PackFile pack, HashSet<ObjectId> existing) throws IOException { for (PackIndex.MutableEntry entry : pack) { ObjectId oid = entry.toObjectId(); if (existing.contains(oid)) { continue; } existing.add(oid); ObjectLoader loader = reader.open(oid); inserter.insert(loader.getType(), loader.getSize(), loader.openStream(), true ); } }
Source:
private boolean applicableFile(File file, DepositBinConfiguration config) { if (!config.hasFileFilters()) return true; if (config.getFilePattern() != null && !config.getFilePattern().matcher(file.getName()).matches()) return false; return config.getMaxSize() == null || config.getMaxSize() == 0 || file.length() <= config.getMaxSize(); }

Target:
private boolean applicableFile(File file, DepositBinConfiguration config) { if (!config.hasFileFilters()) return true; boolean answer = config.getFilePattern() == null || config.getFilePattern().matcher(file.getName()).matches(); answer = answer && (config.getMaxBytesPerFilee() == null || config.getMaxBytesPerFilee() == 0 || file.length() <= config .getMaxBytesPerFilee()); if (answer) return true; log.warn("Non-applicable file found in bin {}", file.getAbsolutePath(), config.getName()); return false; }
Source:
private Boolean listElementStarts(List<String> aList, String charSeq) { for (String match : aList) { if (match.startsWith(match)){ return Boolean.TRUE; } } return Boolean.FALSE; }

Target:
private Boolean listElementStarts(List<String> aList, String charSeq) { for (String match : aList) { if (match.startsWith(charSeq)){ return Boolean.TRUE; } } return Boolean.FALSE; }
Source:
private static int countExternalReferences(PDOMBinding binding) throws Exception { IPDOMIterator<PDOMName> extRefs = binding.getExternalReferences(); assertNotNull(extRefs); int count = 0; for( ; extRefs.hasNext(); ++count) extRefs.next(); return count; }

Target:
private static int countExternalReferences(PDOMBinding binding) throws Exception { IPDOMIterator<PDOMName> extRefs = binding.getExternalReferences(); assertNotNull(extRefs); int count = 0; for( ; extRefs.hasNext(); extRefs.next()) ++count; return count; }
Source:
private RspListFuture processCalls(ReplicableCommand command, boolean broadcast, long timeout, RspFilter filter, List<Address> dests, ResponseMode mode, DeliverOrder deliverOrder) throws Exception { if (trace) log.tracef("Replication task sending %s to addresses %s with response mode %s", command, dests, mode); boolean rsvp = isRsvpCommand(command); Buffer buf = marshallCall(command); RequestOptions opts = constructRequestOptions(mode, rsvp, deliverOrder, timeout); Collection<Address> realDest = dests; if (deliverOrder == DeliverOrder.TOTAL) { opts.anycasting(true).useAnycastAddresses(true); } else if (broadcast || FORCE_MCAST) { opts.anycasting(false); realDest = null; } else { opts.anycasting(true).setUseAnycastAddresses(false); } opts.rspFilter(filter); GroupRequest<Response> request = cast(realDest, buf, opts, false); if (mode == ResponseMode.GET_NONE) return null; RspListFuture retval = new RspListFuture(request); if (request == null) { if (broadcast) { retval.complete(EMPTY_RESPONSES_LIST); } else { Map<Address, Rsp<Response>> rsps = new HashMap<>(dests.size()); for (Address dest : dests) { Rsp<Response> rsp = new Rsp<>(); rsp.setSuspected(); rsps.put(dest, rsp); } retval.complete(new RspList<>(rsps)); } } if (timeout > 0 && !retval.isDone()) { ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(retval, timeout, TimeUnit.MILLISECONDS); retval.setTimeoutFuture(timeoutFuture); } return retval; }

Target:
private CompletableFuture<Responses> processCalls(ReplicableCommand command, boolean broadcast, long timeout, RspFilter filter, List<Address> dests, ResponseMode mode, DeliverOrder deliverOrder) throws Exception { if (trace) log.tracef("Replication task sending %s to addresses %s with response mode %s", command, dests, mode); boolean rsvp = isRsvpCommand(command); Buffer buf = marshallCall(command); RequestOptions opts = constructRequestOptions(mode, rsvp, deliverOrder, timeout); Collection<Address> realDest = dests; if (deliverOrder == DeliverOrder.TOTAL) { opts.anycasting(true).useAnycastAddresses(true); } else if (broadcast || FORCE_MCAST) { opts.anycasting(false); realDest = null; } else { opts.anycasting(true).setUseAnycastAddresses(false); } opts.rspFilter(filter); GroupRequest<Response> request = cast(realDest, buf, opts, false); if (mode == ResponseMode.GET_NONE) return null; RspListFuture retval = new RspListFuture(request); if (timeout > 0 && !retval.isDone()) { ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(retval, timeout, TimeUnit.MILLISECONDS); retval.setTimeoutFuture(timeoutFuture); } return retval; }
Source:
public void triggerEvent(String channelId, String event) { if (getThing().getChannel(channelId) != null) { triggerChannel(getThing().getChannel(channelId).getUID(), event); return; } logger.warn("Event in thing does not exist, please recreate the thing", event, getThing().getUID()); }

Target:
public void triggerEvent(String channelId, String event) { if (getThing().getChannel(channelId) == null) { logger.warn("Event in thing does not exist, please recreate the thing", event, getThing().getUID()); return; } triggerChannel(getThing().getChannel(channelId).getUID(), event); }
Source:
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { if (result.containsKey(registration.getRegistrationId())) { throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); }

Target:
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { if (result.containsKey(registration.getRegistrationId())) { throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); }
Source:
private CommandImpl toWorkspaceCommand(Command devCommand, Action commandAction) { CommandImpl command = new CommandImpl(); command.setName(devCommand.getName()); command.setType(commandAction.getType()); command.setCommandLine(commandAction.getCommand()); if (commandAction.getWorkdir() != null) { command.getAttributes().put(WORKING_DIRECTORY_ATTRIBUTE, commandAction.getWorkdir()); } command.getAttributes().put(Constants.TOOL_NAME_COMMAND_ATTRIBUTE, commandAction.getTool()); if (devCommand.getAttributes() != null) { command.getAttributes().putAll(devCommand.getAttributes()); } return command; }

Target:
private CommandImpl toWorkspaceCommand(Command devCommand, Action commandAction) { CommandImpl command = new CommandImpl(); command.setName(devCommand.getName()); command.setType(commandAction.getType()); command.setCommandLine(commandAction.getCommand()); if (commandAction.getWorkdir() != null) { command.getAttributes().put(WORKING_DIRECTORY_ATTRIBUTE, commandAction.getWorkdir()); } command.getAttributes().put(Constants.TOOL_NAME_COMMAND_ATTRIBUTE, commandAction.getTool()); command.getAttributes().putAll(devCommand.getAttributes()); return command; }
Source:
public Object[] getElements(Object inputElement) { if(inputElement instanceof IBatchProperty){ return references.keySet().toArray(); }else if(inputElement instanceof IFile){ return references.get((IFile)inputElement).toArray(); } return null; }

Target:
public Object[] getElements(Object inputElement) { return getChildren(inputElement); }
Source:
public void performAction() { boolean isSinglePanelViewNow = mainFrame.toggleSinglePanel(); if (isSinglePanelViewNow) { previousRatio = mainFrame.getSplitPane().getSplitRatio(); hideInactivePanel(); } else { mainFrame.getSplitPane().setSplitRatio(previousRatio); showInactivePanel(); } MuConfigurations.getPreferences().setVariable(MuPreference.USE_SINGLE_PANEL_VIEW, isSinglePanelViewNow); }

Target:
public void performAction() { boolean isSinglePanelViewNow = mainFrame.toggleSinglePanel(); if (isSinglePanelViewNow) { previousRatio = mainFrame.getSplitPane().getSplitRatio(); hideInactivePanel(); } else { mainFrame.getSplitPane().setSplitRatio(previousRatio); showInactivePanel(); } MuConfigurations.getSnapshot().setVariable("", mainFrame.isSinglePanel()); }
Source:
@Override public String mimeType() { return "application/json; charset=" + encode; }

Target:
@Override public String mimeType() { return mimeType; }
Source:
private Collection<Slice> shardDeleteDelta(UUID oldShardUuid, Optional<UUID> oldDeltaDeleteShard, Optional<ShardInfo> newDeltaDeleteShard) { return ImmutableList.of(Slices.wrappedBuffer(SHARD_DELETE_DELTA_CODEC.toJsonBytes( new ShardDeleteDelta(oldShardUuid, oldDeltaDeleteShard, newDeltaDeleteShard)))); }

Target:
private static Collection<Slice> shardDeleteDelta(UUID oldShardUuid, Optional<UUID> oldDeltaDeleteShard, Optional<ShardInfo> newDeltaDeleteShard) { return ImmutableList.of(Slices.wrappedBuffer(SHARD_DELETE_DELTA_CODEC.toJsonBytes( new ShardDeleteDelta(oldShardUuid, new DeltaInfoPair(oldDeltaDeleteShard, newDeltaDeleteShard))))); }
Source:
public static Permissionable findParentPermissionable(String parent) throws DotDataException { Permissionable permissionableParent = null; try { User systemUser = APILocator.getUserAPI().getSystemUser(); Identifier iden = APILocator.getIdentifierAPI().find(parent); if(UtilMethods.isSet(iden) && UtilMethods.isSet(iden.getAssetType())){ if(iden.getAssetType().equals("folder")){ permissionableParent = APILocator.getFolderAPI().find(parent,systemUser,false); }else{ Contentlet contentlet; contentlet = APILocator.getContentletAPI().findContentletByIdentifier(parent, false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), systemUser, false); if (contentlet == null) { List<Contentlet> results = APILocator.getContentletAPI() .search("+identifier:" + parent + " +working:true", 1, 0, null, systemUser, false); if (!results.isEmpty()) { contentlet = results.get(0); } } if (contentlet.isHost()) { permissionableParent = contentlet; } else { permissionableParent = contentlet.getParentPermissionable(); } } } else { throw new DotDataException("Parent Identifier: " + parent + " does NOT exist."); } } catch (DotSecurityException | IndexOutOfBoundsException e) { Logger.error(Rule.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return permissionableParent; }

Target:
public static Permissionable findParentPermissionable(String parent) throws DotDataException { Permissionable permissionableParent = null; try { User systemUser = APILocator.getUserAPI().getSystemUser(); Identifier iden = APILocator.getIdentifierAPI().find(parent); if(UtilMethods.isSet(iden) && UtilMethods.isSet(iden.getAssetType())){ if(iden.getAssetType().equals("folder")){ permissionableParent = APILocator.getFolderAPI().find(parent,systemUser,false); }else{ Contentlet contentlet; contentlet = APILocator.getContentletAPI().findContentletByIdentifier(parent, false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), systemUser, false); if (contentlet == null) { List<Contentlet> results = APILocator.getContentletAPI() .search("+identifier:" + parent + " +working:true", 1, 0, null, systemUser, false); if (!results.isEmpty()) { contentlet = results.get(0); } } if (contentlet == null) { throw new DotDataException("Identifier: " + parent + " does not exist."); } if (contentlet.isHost()) { permissionableParent = contentlet; } else { permissionableParent = contentlet.getParentPermissionable(); } } } else { throw new DotDataException("Parent Identifier: " + parent + " does NOT exist."); } } catch (DotSecurityException | IndexOutOfBoundsException e) { Logger.error(Rule.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return permissionableParent; }
Source:
@Override public boolean remove(int element) { if (element < 0) throw new UnsupportedOperationException("Negative values are not supported!"); boolean alreadySet = bitSet.get(element); if (alreadySet) { bitSet.clear(element); size--; } return alreadySet; }

Target:
@Override public boolean remove(int element) { if (element < 0) return false; boolean alreadySet = bitSet.get(element); if (alreadySet) { bitSet.clear(element); size--; } return alreadySet; }
Source:
private <M extends Multimap<Long, String>> void testMultimapCollector(Class<? extends Multimap> erasedType, GenericType<M> genericType) { JdbiCollectors registry = dbRule.getJdbi().getConfig(JdbiCollectors.class); assertThat(registry.findElementTypeFor(genericType.getType())) .contains(new GenericType<Map.Entry<Long,String>>(){}.getType()); Collector<Map.Entry<Long,String>, ?, M> collector = (Collector<Map.Entry<Long, String>, ?, M>) registry .findFor(genericType.getType()) .orElseThrow(() -> new IllegalStateException("Missing collector for " + genericType)); M map = Stream.of(entry(1L, "foo"), entry(2L, "bar")).collect(collector); Assertions.assertThat(map) .isInstanceOf(erasedType) .containsAllEntriesOf(ImmutableMultimap.of(1L, "foo", 2L, "bar")); }

Target:
private <M extends Multimap<Long, String>> void testMultimapCollector(Class<? extends Multimap> erasedType, GenericType<M> genericType) { JdbiCollectors registry = dbRule.getJdbi().getConfig(JdbiCollectors.class); assertThat(registry.findElementTypeFor(genericType.getType())) .contains(new GenericType<Map.Entry<Long,String>>(){}.getType()); Collector<Map.Entry<Long,String>, ?, M> collector = (Collector<Map.Entry<Long, String>, ?, M>) registry .findFor(genericType.getType()) .orElseThrow(() -> new IllegalStateException("Missing collector for " + genericType)); M map = Stream.of(entry(1L, "foo"), entry(2L, "bar")).collect(collector); assertThat(map) .isInstanceOf(erasedType) .containsAllEntriesOf(ImmutableMultimap.of(1L, "foo", 2L, "bar")); }
Source:
private boolean hasSameLicense(Artifact license) throws MojoExecutionException, IOException { boolean sameLicense = false; if (license != null) { InputStream licenseInfo = getZipEntry(license.getFile(), "wlp/lafiles/LI_en"); if (licenseInfo == null) { log.warn("The license file may be corrupted"); return sameLicense; } File lic = new File(assemblyInstallDirectory, "wlp/lafiles/LI_en"); if (!lic.exists()) { return sameLicense; } FileInputStream installedLicenseInfo = new FileInputStream(lic); sameLicense = IOUtil.contentEquals(licenseInfo, installedLicenseInfo); licenseInfo.close(); installedLicenseInfo.close(); } return sameLicense; }

Target:
private boolean hasSameLicense(Artifact license) throws MojoExecutionException, IOException { boolean sameLicense = false; if (license != null) { InputStream licenseInfo = getZipEntry(license.getFile(), "wlp/lafiles/LI_en"); if (licenseInfo == null) { log.warn(MessageFormat.format(messages.getString("warn.install.license"), license.getArtifactId())); return sameLicense; } File lic = new File(assemblyInstallDirectory, "wlp/lafiles/LI_en"); if (!lic.exists()) { FileInputStream installedLicenseInfo = new FileInputStream(lic); sameLicense = IOUtil.contentEquals(licenseInfo, installedLicenseInfo); licenseInfo.close(); installedLicenseInfo.close(); } } return sameLicense; }
Source:
private List<Object> listOfArrays(SessionImplementor session, Iterator<Tuple> tuples) { List<Object> results = new ArrayList<Object>(); while ( tuples.hasNext() ) { Tuple tuple = tuples.next(); Object[] entry = null; if ( !customQuery.getCustomQueryReturns().isEmpty() ) { entry = new Object[customQuery.getCustomQueryReturns().size()]; int i = 0; for ( Return queryReturn : customQuery.getCustomQueryReturns() ) { ScalarReturn scalarReturn = (ScalarReturn) queryReturn; Type type = scalarReturn.getType(); if ( type != null ) { GridType gridType = typeTranslator.getType( type ); entry[i++] = gridType.nullSafeGet( tuple, scalarReturn.getColumnAlias(), session, null ); } else { entry[i++] = tuple.get( ( scalarReturn ).getColumnAlias() ); } } } else { entry = new Object[tuple.getColumnNames().size()]; int i = 0; for ( String column : tuple.getColumnNames() ) { entry[i++] = tuple.get( column ); } } if ( entry.length == 1 ) { results.add( entry[0] ); } else { results.add( entry ); } } return results; }

Target:
private List<Object> listOfArrays(SessionImplementor session, Iterator<Tuple> tuples) { List<Object> results = new ArrayList<Object>(); while ( tuples.hasNext() ) { Tuple tuple = tuples.next(); Object[] entry = null; if ( !customQuery.getCustomQueryReturns().isEmpty() ) { entry = new Object[customQuery.getCustomQueryReturns().size()]; int i = 0; for ( Return queryReturn : customQuery.getCustomQueryReturns() ) { ScalarReturn scalarReturn = (ScalarReturn) queryReturn; Type type = scalarReturn.getType(); if ( type != null ) { GridType gridType = typeTranslator.getType( type ); entry[i++] = gridType.nullSafeGet( tuple, scalarReturn.getColumnAlias(), session, null ); } else { entry[i++] = tuple.get( scalarReturn.getColumnAlias() ); } } } else { entry = new Object[tuple.getColumnNames().size()]; int i = 0; for ( String column : tuple.getColumnNames() ) { entry[i++] = tuple.get( column ); } } if ( entry.length == 1 ) { results.add( entry[0] ); } else { results.add( entry ); } } return results; }
Source:
private static String getStoreName(JSONObject arg0) { String storeName = arg0 != null ? arg0.optString(STORE_NAME, DEFAULT_STORE_NAME) : DEFAULT_STORE_NAME; return storeName==null?DEFAULT_STORE_NAME:storeName; }

Target:
private static String getStoreName(JSONObject arg0) { return arg0 != null ? arg0.optString(STORE_NAME, DEFAULT_STORE_NAME) : DEFAULT_STORE_NAME; }
Source:
public Factory saveFactory(Iterator<FileItem> formData, @Context UriInfo uriInfo) throws ForbiddenException, ConflictException, BadRequestException, ServerException, NotFoundException { try { final Set<FactoryImage> images = new HashSet<>(); Factory factory = null; while (formData.hasNext()) { final FileItem item = formData.next(); switch (item.getFieldName()) { case ("factory"): { try (InputStream factoryData = item.getInputStream()) { factory = factoryBuilder.build(factoryData); } catch (JsonSyntaxException e) { throw new BadRequestException("You have provided an invalid JSON. For more information, please visit: " + "<LINK_0>"); } break; } case ("image"): { try (InputStream imageData = item.getInputStream()) { final FactoryImage factoryImage = FactoryImage.createImage(imageData, item.getContentType(), NameGenerator.generate(null, 16)); if (factoryImage.hasContent()) { images.add(factoryImage); } } break; } } } if (factory == null) { LOG.warn("No factory information found in 'factory' section of multipart form-data."); throw new BadRequestException("No factory information found in 'factory' section of multipart/form-data."); } processDefaults(factory); createValidator.validateOnCreate(factory); final Factory storedFactory = factoryStore.getFactory(factoryStore.saveFactory(factory, images)); return storedFactory.withLinks(createLinks(storedFactory, images, uriInfo)); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new ServerException(e.getLocalizedMessage(), e); } }

Target:
public Factory saveFactory(Iterator<FileItem> formData, @Context UriInfo uriInfo) throws ForbiddenException, ConflictException, BadRequestException, ServerException, NotFoundException { try { final Set<FactoryImage> images = new HashSet<>(); Factory factory = null; while (formData.hasNext()) { final FileItem item = formData.next(); switch (item.getFieldName()) { case ("factory"): { try (InputStream factoryData = item.getInputStream()) { factory = factoryBuilder.build(factoryData); } catch (JsonSyntaxException e) { throw new BadRequestException("You have provided an invalid JSON. For more information, please visit: " + "<LINK_0>"); } break; } case ("image"): { try (InputStream imageData = item.getInputStream()) { final FactoryImage factoryImage = FactoryImage.createImage(imageData, item.getContentType(), NameGenerator.generate(null, 16)); if (factoryImage.hasContent()) { images.add(factoryImage); } } break; } default: } } if (factory == null) { LOG.warn("No factory information found in 'factory' section of multipart form-data."); throw new BadRequestException("No factory information found in 'factory' section of multipart/form-data."); } processDefaults(factory); createValidator.validateOnCreate(factory); final Factory storedFactory = factoryStore.getFactory(factoryStore.saveFactory(factory, images)); return storedFactory.withLinks(createLinks(storedFactory, images, uriInfo)); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new ServerException(e.getLocalizedMessage(), e); } }