auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testEmptyGrammar() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.State.OrderingInfo oinf2 = new Grammar.State.OrderingInfo(2); Grammar.State.OrderingInfo oinf3 = new Grammar.State.OrderingInfo(3); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, oinf2, stiend, oinf3); nt1.entryState.next.add(nt1.exitState); ParseState ps = new ParseState(""); Parser parser = new Parser(ps); Term result = parser.parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); assertEquals("Empty Grammar check: ", expected, result); assertEquals("Expected Nullable NTs", 1, NullabilityCheck.getReachableNullableNT(nt1).size()); }

Target:
public void testEmptyGrammar() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.State.OrderingInfo oinf2 = new Grammar.State.OrderingInfo(2); Grammar.State.OrderingInfo oinf3 = new Grammar.State.OrderingInfo(3); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, oinf2, stiend, oinf3); nt1.entryState.next.add(nt1.exitState); ParseState ps = new ParseState(""); Parser parser = new Parser(ps); Term result = parser.parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); Assert.assertEquals("Empty Grammar check: ", expected, result); Assert.assertEquals("Expected Nullable NTs", nt1, NullabilityCheck.getReachableNullableNT(nt1).iterator().next()); }
Source:
void recordMetaData(final SliceBAIMetadata sliceMetadata) { final int alignmentStart = sliceMetadata.getAlignmentStart(); if (alignmentStart == SAMRecord.NO_ALIGNMENT_START) { noCoordinateRecords += sliceMetadata.getRecordCount(); return; } final long start = sliceMetadata.getByteOffset(); final long end = sliceMetadata.getByteOffset() + sliceMetadata.getByteSize(); if (sliceMetadata.getAlignmentSpan() == SliceHeader.NO_ALIGNMENT_SPAN) { unAlignedRecords += sliceMetadata.getRecordCount(); } else { alignedRecords += sliceMetadata.getRecordCount(); } if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) { this.firstOffset = start; } if (BlockCompressedFilePointerUtil.compare(lastOffset, end) < 1) { this.lastOffset = end; } }

Target:
void recordMetaData(final SliceBAIMetadata sliceMetadata) { final int alignmentStart = sliceMetadata.getAlignmentStart(); if (alignmentStart == SAMRecord.NO_ALIGNMENT_START) { noCoordinateRecords += sliceMetadata.getRecordCount(); return; } final long start = sliceMetadata.getByteOffset(); final long end = start; if (sliceMetadata.getAlignmentSpan() == SliceHeader.NO_ALIGNMENT_SPAN) { unAlignedRecords += sliceMetadata.getRecordCount(); } else { alignedRecords += sliceMetadata.getRecordCount(); } if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) { this.firstOffset = start; } if (BlockCompressedFilePointerUtil.compare(lastOffset, end) < 1) { this.lastOffset = end; } }
Source:
private String extractWhat(final Audit note, final String methodName) { String what = note.action(); if (what.length() == 0) { boolean ccase = Character.isLowerCase(methodName.charAt(0)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < methodName.length(); i++) { char c = methodName.charAt(i); if (Character.isLowerCase(c) != ccase) { sb.append(' '); } sb.append(Character.toLowerCase(c)); } what = sb.toString(); } return what; }

Target:
private String extractWhat(final Audit note, final String methodName) { String what = note.action(); if (what.length() == 0) { boolean ccase = Character.isLowerCase(methodName.charAt(0)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < methodName.length(); i++) { char c = methodName.charAt(i); if (ccase && !Character.isLowerCase(c)) { sb.append(' '); } sb.append(Character.toLowerCase(c)); } what = sb.toString(); } return what; }
Source:
public Gff3BaseData(final String contig, final String source, final String type, final int start, final int end, final Double score, final Strand strand, final int phase, final Map<String, List<String>> attributes) { this.contig = contig; this.source = source; this.type = type; this.start = start; this.end = end; this.score = score; this.phase = phase; this.strand = strand; this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes)); this.id = Gff3Codec.extractSingleAttribute(attributes.get(ID_ATTRIBUTE_KEY)); this.name = Gff3Codec.extractSingleAttribute(attributes.get(NAME_ATTRIBUTE_KEY)); this.aliases = attributes.containsKey(ALIAS_ATTRIBUTE_KEY)? attributes.get(ALIAS_ATTRIBUTE_KEY) : Collections.emptyList(); this.hashCode = computeHashCode(); }

Target:
public Gff3BaseData(final String contig, final String source, final String type, final int start, final int end, final Double score, final Strand strand, final int phase, final Map<String, List<String>> attributes) { this.contig = contig; this.source = source; this.type = type; this.start = start; this.end = end; this.score = score; this.phase = phase; this.strand = strand; this.attributes = copyAttributesSafely(attributes); this.id = Gff3Codec.extractSingleAttribute(attributes.get(ID_ATTRIBUTE_KEY)); this.name = Gff3Codec.extractSingleAttribute(attributes.get(NAME_ATTRIBUTE_KEY)); this.aliases = attributes.getOrDefault(ALIAS_ATTRIBUTE_KEY, Collections.emptyList()); this.hashCode = computeHashCode(); }
Source:
public boolean verify() throws ConstructorException { try { HttpUrl url = this.makeUrl("v1/verify"); Builder builder = this.makeAuthorizedRequestBuilder(); Request request = builder .url(url) .get() .build(); Response response = clientWithRetry.newCall(request).execute(); getResponseBody(response); return true; } catch (Exception exception) { throw new ConstructorException(exception); } }

Target:
public boolean verify() throws ConstructorException { try { HttpUrl url = this.makeUrl("v1/verify"); Request request = this.makeAuthorizedRequestBuilder() .url(url) .get() .build(); Response response = clientWithRetry.newCall(request).execute(); getResponseBody(response); return true; } catch (Exception exception) { throw new ConstructorException(exception); } }
Source:
void setFailed() { done = true; }

Target:
void setFailed() { done = true; succeeded = false; }
Source:
private void putlightDimmer(String message) { coapClient.setURI( "coap://" + COAP_SERVER_IP_ADDRESS + ":" + COAP_SERVER_PORT + "/InternetOfTiny/actuators/actuator1"); StringBuilder coapLightSwitch = new StringBuilder(); coapLightSwitch.append(",1,pp," + message + ","); CoapResponse clientResponse = coapClient.put(coapLightSwitch.toString(), TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); }

Target:
private void putlightDimmer(String message) { coapClient .setURI("coap://" + coapServerIpAddress + ":" + coapServerPort + "/InternetOfTiny/actuators/actuator1"); StringBuilder coapLightSwitch = new StringBuilder(); coapLightSwitch.append(",1,pp,").append(message).append(","); CoapResponse clientResponse = coapClient.put(coapLightSwitch.toString(), TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); }
Source:
public void load(final List<String> entryIds, boolean periodic) { boolean setLastUpdatedAt = periodic || lastUpdatedCuePoint == 0; KalturaCuePointFilter filter = new KalturaCuePointFilter(); filter.entryIdEqual = StringUtils.join(entryIds); filter.statusEqual = KalturaCuePointStatus.READY; filter.triggeredAtGreaterThanOrEqual = 1; if(periodic){ filter.updatedAtGreaterThanOrEqual = lastUpdatedCuePoint; } filter.orderBy = KalturaCuePointOrderBy.UPDATED_AT_ASC.hashCode; KalturaFilterPager pager = new KalturaFilterPager(); pager.pageIndex = 1; pager.pageSize = 100; Timer timer; TimerTask timerTask; Date date = new Date(); try{ while(true){ KalturaCuePointListResponse CuePointsList = client.getCuePointService().list(filter , pager); if(CuePointsList.objects.size() == 0){ break; } for(final KalturaCuePoint cuePoint : CuePointsList.objects){ if(setLastUpdatedAt){ lastUpdatedCuePoint = Math.max(lastUpdatedCuePoint, cuePoint.updatedAt); } long scheduledTime = (cuePoint.triggeredAt / 1000) - 30000; if (scheduledTime < 0) { logger.error("Cue-point was set with illegal triggered at time " + cuePoint.triggeredAt + ", setting time to zero" ); scheduledTime =0 ; } date.setTime(scheduledTime); timerTask = new TimerTask(){ @Override public void run() { createSyncPoint(cuePoint.entryId); } }; timer = new Timer(true); timer.schedule(timerTask, date); } } } catch (KalturaApiException e) { logger.error("Failed to list entries cue-points: " + e.getMessage()); } }

Target:
public void load(final List<String> entryIds, boolean periodic) { boolean setLastUpdatedAt = periodic || lastUpdatedCuePoint == 0; KalturaCuePointFilter filter = new KalturaCuePointFilter(); filter.entryIdEqual = StringUtils.join(entryIds); filter.statusEqual = KalturaCuePointStatus.READY; filter.triggeredAtGreaterThanOrEqual = 1; if(periodic){ filter.updatedAtGreaterThanOrEqual = lastUpdatedCuePoint; } filter.orderBy = KalturaCuePointOrderBy.UPDATED_AT_ASC.hashCode; KalturaFilterPager pager = new KalturaFilterPager(); pager.pageIndex = 1; pager.pageSize = 100; Timer timer; TimerTask timerTask; Date date = new Date(); try{ while(true){ KalturaCuePointListResponse CuePointsList = client.getCuePointService().list(filter , pager); if(CuePointsList.objects.size() == 0){ break; } for(final KalturaCuePoint cuePoint : CuePointsList.objects){ if(setLastUpdatedAt){ lastUpdatedCuePoint = Math.max(lastUpdatedCuePoint, cuePoint.updatedAt); } long scheduledTime = (cuePoint.triggeredAt / 1000) - 30000; if (scheduledTime < 0) { logger.error("Cue-point was set with illegal triggered at time " + cuePoint.triggeredAt + ", seems that the filter does not work" ); } date.setTime(scheduledTime); timerTask = new TimerTask(){ @Override public void run() { createSyncPoint(cuePoint.entryId); } }; timer = new Timer(true); timer.schedule(timerTask, date); } } } catch (KalturaApiException e) { logger.error("Failed to list entries cue-points: " + e.getMessage()); } }
Source:
public long getSessionId() { long sessionId = -1; if (isConnected()) { try { sessionId = getZooKeeper().getSessionId(); } catch (Exception e) { } } return sessionId; }

Target:
public long getSessionId() { long sessionId = -1; if (isConnected()) { try { ZooKeeper zk = zooKeeper.getZooKeeper(); if (zk != null) { sessionId = zk.getSessionId(); } } catch (Exception e) { } } return sessionId; }
Source:
public Collection<EPackage> getPackagesToImport() { Collection<EPackage> superResult = super.getPackagesToImport(); superResult.add(DiagramPackage.eINSTANCE); return superResult; }

Target:
public Collection<EPackage> getPackagesToImport() { Collection<EPackage> superResult = super.getPackagesToImport(); superResult.add(DiagramPackage.eINSTANCE); superResult.add(DescriptionPackage.eINSTANCE); superResult.add(StylePackage.eINSTANCE); superResult.add(org.eclipse.sirius.diagram.description.tool.ToolPackage.eINSTANCE); superResult.add(FilterPackage.eINSTANCE); superResult.add(ConcernPackage.eINSTANCE); return superResult; }
Source:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); referenceGenome.setId(1L); return referenceGenome; }

Target:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); return referenceGenome; }
Source:
default List<String> getNewFieldNames( final String[] incomingFieldNames ) { final Set<String> fieldNamesInTable = new HashSet<>(); for ( int i = 0; i < getFieldsTable().table.getItemCount(); i++ ) { final TableItem item = getFieldsTable().table.getItem( i ); int fieldNameIndex = getFieldsTable().hasIndexColumn() ? 1 : 0; fieldNamesInTable.add( item.getText( fieldNameIndex ) ); } return Arrays .stream( incomingFieldNames ) .filter( fieldName -> !fieldNamesInTable.contains( fieldName ) ) .collect( Collectors.toList() ); }

Target:
default List<String> getNewFieldNames( final String[] incomingFieldNames ) { final Set<String> fieldNamesInTable = new HashSet<>(); for ( int i = 0; i < getFieldsTable().getTable().getItemCount(); i++ ) { final TableItem item = getFieldsTable().getTable().getItem( i ); int fieldNameIndex = getFieldsTable().hasIndexColumn() ? 1 : 0; fieldNamesInTable.add( item.getText( fieldNameIndex ) ); } return Arrays .stream( incomingFieldNames ) .filter( fieldName -> !fieldNamesInTable.contains( fieldName ) ) .collect( Collectors.toList() ); }
Source:
public static void loadTextures() { Image brickTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_brick.png"); BRICK.setDiffuseMap(brickTexture); Image mossTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_moss.png"); MOSS.setDiffuseMap(mossTexture); Image crackTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_crack.png"); CRACK.setDiffuseMap(crackTexture); Image floorTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_cobblestone.png"); FLOOR.setDiffuseMap(floorTexture); Image coinTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_coin.png"); COIN.setDiffuseMap(coinTexture); Image woodTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_wood.png"); WOOD.setDiffuseMap(woodTexture); Image pillarTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_pillar.png"); PILLAR.setDiffuseMap(pillarTexture); Image fenceTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_fence.png"); FENCE.setDiffuseMap(fenceTexture); Image playerTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_player.png"); PLAYER.setDiffuseMap(playerTexture); }

Target:
public static void loadTextures() { String path = "nl/tudelft/ti2206/group9/gui/"; Image brickTexture = new Image(path + "texture_brick.png"); BRICK.setDiffuseMap(brickTexture); Image mossTexture = new Image(path + "texture_moss.png"); MOSS.setDiffuseMap(mossTexture); Image crackTexture = new Image(path + "texture_crack.png"); CRACK.setDiffuseMap(crackTexture); Image floorTexture = new Image(path + "texture_cobblestone.png"); FLOOR.setDiffuseMap(floorTexture); Image coinTexture = new Image(path + "texture_coin.png"); COIN.setDiffuseMap(coinTexture); Image woodTexture = new Image(path + "texture_wood.png"); WOOD.setDiffuseMap(woodTexture); Image pillarTexture = new Image(path + "texture_pillar.png"); PILLAR.setDiffuseMap(pillarTexture); Image fenceTexture = new Image(path + "texture_fence.png"); FENCE.setDiffuseMap(fenceTexture); Image playerTexture = new Image(path + "texture_player.png"); PLAYER.setDiffuseMap(playerTexture); }
Source:
public synchronized ProcessingResult insert(Beacon block) { ValidationResult vRes; if ((vRes = beaconValidator.validateAndLog(block)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); Beacon parent = pullParent(block); BeaconState currentState = pullState(parent); if ((vRes = proposerValidator.validateAndLog(block, parent, currentState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); if ((vRes = attestationsValidator.validateAndLog(block, parent, currentState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); BeaconState newState = transitionFunction.applyBlock(block, currentState); if ((vRes = stateValidator.validateAndLog(block, newState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); BigInteger blockScore = scoreFunction.apply(block, newState); BigInteger chainScore = store.getChainScore(parent.getHash()).add(blockScore); ScoredChainHead newHead = new ScoredChainHead(block, chainScore, newState); beaconDbFlusher.commit(() -> { repository.insert(newHead.state); repository.commit(); store.save(newHead.block, newHead.score, canonicalHead.isParentOf(newHead)); if (canonicalHead.shouldReorgTo(newHead)) { store.reorgTo(newHead.block); } if (canonicalHead.isParentOf(newHead) || canonicalHead.shouldReorgTo(newHead)) { canonicalHead = newHead; } }); ProcessingResult res = canonicalHead.equals(newHead) ? ProcessingResult.Best : ProcessingResult.NotBest; publish(onBeaconBlock(block, newState, res == ProcessingResult.Best)); logger.info("Process block {}, status: {}", block.toString(), res); return res; }

Target:
public synchronized ProcessingResult insert(Beacon block) { ValidationResult vRes; if ((vRes = beaconValidator.validateAndLog(block)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); Beacon parent = pullParent(block); BeaconState currentState = pullState(parent); BeaconState newState = transitionFunction.applyBlock(block, currentState); if ((vRes = stateValidator.validateAndLog(block, newState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); BigInteger chainScore = scoreFunction.apply(block, newState); ScoredChainHead newHead = new ScoredChainHead(block, chainScore, newState); beaconDbFlusher.commit(() -> { repository.insert(newHead.state); repository.commit(); store.save(newHead.block, newHead.score, canonicalHead.isParentOf(newHead)); if (canonicalHead.shouldReorgTo(newHead)) { store.reorgTo(newHead.block); } if (canonicalHead.isParentOf(newHead) || canonicalHead.shouldReorgTo(newHead)) { canonicalHead = newHead; } }); ProcessingResult res = canonicalHead.equals(newHead) ? ProcessingResult.Best : ProcessingResult.NotBest; publish(onBeaconBlock(block, newState, res == ProcessingResult.Best)); logger.info("Process block {}, status: {}", block.toString(), res); return res; }
Source:
private VView loadView(IPath path) { final ResourceSet resourceSet = new ResourceSetImpl(); final Resource resource = resourceSet .createResource(URI.createPlatformResourceURI(path.toOSString(), true)); try { resource.load(null); return (VView) resource.getContents().get(0); } catch (final IOException ex) { throw new IllegalArgumentException(ex); } }

Target:
private VView loadView(IPath path) { final ResourceSet resourceSet = new ResourceSetImpl(); final Resource resource = resourceSet .createResource(URI.createPlatformResourceURI(path.toOSString(), true)); try { resource.load(null); final EObject eObject = resource.getContents().get(0); if (!VView.class.isInstance(eObject)) { throw new IllegalArgumentException( "The provided path " + path.toString() + " doesn't contain a VView."); } return (VView) eObject; } catch (final IOException ex) { throw new IllegalArgumentException(ex); } }
Source:
private void setWatchAction(UserFeed feed) { int seriesNumber = feed.getEpisodes(); String showName = feed.getShow(); String actionText; if (seriesNumber == 1) { setWatchOneSeriesAction(feed, showName); } else { int pluralsId = feed.getGender() == Gender.FEMALE ? R.plurals.f_watch_series : R.plurals.m_watch_series; actionText = itemView.getResources().getQuantityString(pluralsId, seriesNumber, seriesNumber, showName); setShowActionText(actionText, feed); } }

Target:
private void setWatchAction(UserFeed feed) { Spannable spannable = feed.getEpisodes() == 1 ? getOneEpisodeSpannable(feed) : getManyEpisodeSpannable(feed); action.setText(spannable, TextView.BufferType.SPANNABLE); }
Source:
public void testNonPartition() throws Exception { tEnv().executeSql("CREATE TABLE sink_table (a int, b string, c string) with (" + options() + ")"); tEnv().executeSql("insert into sink_table select * from my_table").await(); List<Row> results = toListAndClose(tEnv().executeSql("select * from sink_table").collect()); results.sort(Comparator.comparingInt(o -> (Integer) o.getField(0))); assertEquals(rows, results); File[] files = new File(URI.create(resultPath)).listFiles( (dir, name) -> name.startsWith("compacted-part-")); assertEquals(Arrays.toString(files), 1, files.length); String fileName = files[0].getName(); assertTrue(fileName, fileName.startsWith("compacted-part-")); }

Target:
public void testNonPartition() throws Exception { tEnv().executeSql("CREATE TABLE sink_table (a int, b string, c string) with (" + options() + ")"); tEnv().executeSql("insert into sink_table select * from my_table").await(); assertIterator(tEnv().executeSql("select * from sink_table").collect()); assertFiles(new File(URI.create(resultPath)).listFiles(), false); }
Source:
private void emit() { if (isUnsubscribed()) { last = null; return; } synchronized (this) { if (last != ABSENT) { T t = last; last = null; child.onNext(t); } } if (!isUnsubscribed()) child.onCompleted(); }

Target:
private void emit() { if (isUnsubscribed()) { last = null; return; } T t = last; last = null; if (t != ABSENT) { try { child.onNext(t); } catch (Throwable e) { child.onError(e); return; } } if (!isUnsubscribed()) child.onCompleted(); }
Source:
public void testParsingHPOOBO() throws Exception { OboParser parser = new OboParser(); InputStream inStream = parser.getClass().getResourceAsStream("/ontology/hp.obo"); Assert.assertNotNull(inStream); BufferedReader oboFile = new BufferedReader ( new InputStreamReader ( inStream ) ); Ontology ontology; ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set<Term> keys = ontology.getTerms(); Assert.assertTrue(keys.size() > 4000); }

Target:
public void testParsingHPOOBO() throws Exception { OboParser parser = new OboParser(); InputStream inStream = parser.getClass().getResourceAsStream("/ontology/hp.obo"); Assert.assertNotNull(inStream); BufferedReader oboFile = new BufferedReader ( new InputStreamReader ( inStream ) ); Ontology ontology; ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set<Term> keys = ontology.getTerms(); Iterator iter = keys.iterator(); while (iter.hasNext()){ Term term = (Term) iter.next(); if(term.getName().equals("HP:0000057")) { Annotation anno = term.getAnnotation(); Assert.assertTrue(anno.containsProperty("replaced_by")); Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); } } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlueprintConfigurations that = (BlueprintConfigurations) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) return false; return propertyAttributes != null ? propertyAttributes.equals(that.propertyAttributes) : that.propertyAttributes == null; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlueprintConfigurations that = (BlueprintConfigurations) o; return Objects.equals(properties, that.properties) && Objects.equals(propertyAttributes, that.propertyAttributes); }
Source:
public Set<Firmware> getFirmwares(final ThingTypeUID thingTypeUID, Locale locale) { Preconditions.checkArgument(thingTypeUID != null); if (locale == null) { locale = Locale.getDefault(); } final Locale myLocale = locale; Path thingTypePath = Paths.get(rootPath, thingTypeUID.getBindingId(), thingTypeUID.getId()); final Set<Firmware> firmwareSet = new HashSet<>(); try { Files.walkFileTree(thingTypePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (PROPERTY_FILE_MATCHER.matches(file)) { FirmwareUID firmwareUID = getFirmwareUIDFromFileName(thingTypeUID, getBaseName(file.getFileName().toString())); if (firmwareUID != null) { Firmware firmware = getFirmware(firmwareUID, myLocale); if (firmware != null) { firmwareSet.add(firmware); } } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { logger.error("Error searching firmwares for thing type " + thingTypeUID, e); } return firmwareSet; }

Target:
public Set<Firmware> getFirmwares(final ThingTypeUID thingTypeUID, Locale locale) { Preconditions.checkArgument(thingTypeUID != null); if (locale == null) { locale = Locale.getDefault(); } final Locale myLocale = locale; Path thingTypePath = Paths.get(rootPath, thingTypeUID.getBindingId(), thingTypeUID.getId()); final Set<Firmware> firmwareSet = new HashSet<>(); try { Files.walkFileTree(thingTypePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (PROPERTY_FILE_MATCHER.matches(file)) { FirmwareUID firmwareUID = getFirmwareUIDFromFileName(thingTypeUID, getBaseName(file.getFileName().toString())); if (firmwareUID != null) { Firmware firmware = getFirmware(firmwareUID, myLocale); if (firmware != null) { firmwareSet.add(firmware); } } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { logger.debug("Cannot find firmwares for thing type " + thingTypeUID); } return firmwareSet; }
Source:
public void postCollectionSubmittersGroupCreateSubmittersGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); }

Target:
public void postCollectionSubmittersGroupCreateSubmittersGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isNoContent()); }
Source:
public static ColumnType parseColumnType(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { if (entityDictionary.attributeOrRelationAnnotationExists(cls, dimensionField, Id.class)) { return ColumnType.PRIMARY_KEY; } else { return ColumnType.FIELD; } }

Target:
public static ColumnType parseColumnType(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { if (entityDictionary.getIdFieldName(cls).equals(dimensionField)) { return ColumnType.PRIMARY_KEY; } else { return ColumnType.FIELD; } }
Source:
private IterableResponse<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new IterableResponse<ConfigurationSetting>(client.listSettingRevisions(selector, context)); }

Target:
public PagedIterable<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedIterable<>(client.listSettingRevisions(selector, context)); }
Source:
protected void endWithFailure() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(false); Backend.getInstance().endAction(VdcActionType.CreateImageTemplate, p, cloneContext().withoutCompensationContext().withoutExecutionContext().withoutLock()); } if (getVmTemplate() != null) { DbFacade.getInstance().getVmTemplateDao().remove(getVmTemplateId()); removeNetwork(); } if (!getVmId().equals(Guid.Empty) && getVm() != null) { VmHandler.unLockVm(getVm()); } setSucceeded(true); }

Target:
protected void endWithFailure() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(false); Backend.getInstance().endAction(VdcActionType.CreateImageTemplate, p, cloneContextAndDetachFromParent()); } if (getVmTemplate() != null) { DbFacade.getInstance().getVmTemplateDao().remove(getVmTemplateId()); removeNetwork(); } if (!getVmId().equals(Guid.Empty) && getVm() != null) { VmHandler.unLockVm(getVm()); } setSucceeded(true); }
Source:
public Object cors() throws Exception { return getOrApply(new CorsConfigurer<HttpSecurity>()); }

Target:
public CorsConfigurer<HttpSecurity> cors() throws Exception { return getOrApply(new CorsConfigurer<HttpSecurity>()); }
Source:
public CoupleMbusDeviceByChannelAsyncResponse coupleMbusDeviceByChannel( @OrganisationIdentification final String organisationIdentification, @RequestPayload final CoupleMbusDeviceByChannelRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime, @ResponseUrl final String responseUrl) throws OsgpException { final String deviceIdentification = request.getDeviceIdentification(); final short channel = request.getCoupleMbusDeviceByChannelRequestData().getChannel(); LOGGER.info("Incoming CoupleMbusDeviceByChannellRequest for meter: and channel {}.", deviceIdentification, channel); CoupleMbusDeviceByChannelAsyncResponse response = null; try { response = new CoupleMbusDeviceByChannelAsyncResponse(); final String correlationUid = this.installationService.enqueueCoupleMbusDeviceByChannelRequest( organisationIdentification, deviceIdentification, MessagePriorityEnum.getMessagePriority(messagePriority), this.installationMapper.map(scheduleTime, Long.class), channel); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(deviceIdentification); this.saveResponseUrlIfNeeded(correlationUid, responseUrl); } catch (final Exception e) { LOGGER.error("Exception while coupling on channel: for device: for organisation {}.", channel, deviceIdentification, organisationIdentification, e); this.handleException(e); } return response; }

Target:
public CoupleMbusDeviceByChannelAsyncResponse coupleMbusDeviceByChannel( @OrganisationIdentification final String organisationIdentification, @RequestPayload final CoupleMbusDeviceByChannelRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime, @ResponseUrl final String responseUrl) throws OsgpException { final String deviceIdentification = request.getDeviceIdentification(); final short channel = request.getCoupleMbusDeviceByChannelRequestData().getChannel(); LOGGER.info("Incoming CoupleMbusDeviceByChannelRequest for device: and channel {}.", deviceIdentification, channel); CoupleMbusDeviceByChannelAsyncResponse response = null; try { response = new CoupleMbusDeviceByChannelAsyncResponse(); final String correlationUid = this.installationService.enqueueCoupleMbusDeviceByChannelRequest( organisationIdentification, deviceIdentification, MessagePriorityEnum.getMessagePriority(messagePriority), this.installationMapper.map(scheduleTime, Long.class), channel); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(deviceIdentification); this.saveResponseUrlIfNeeded(correlationUid, responseUrl); } catch (final Exception e) { LOGGER.error("Exception while coupling on channel: for device: for organisation {}.", channel, deviceIdentification, organisationIdentification, e); this.handleException(e); } return response; }
Source:
protected void run() throws Failure { if (all && projectNames.size() > 0) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); } ReplicationState state = new ReplicationState(ReplicationType.COMMAND, this); Future<?> future = null; if (all) { future = pushAllFactory.create(urlMatch, state).schedule(0, TimeUnit.SECONDS); } else { for (String name : projectNames) { Project.NameKey key = new Project.NameKey(name); if (projectCache.get(key) != null) { replication.scheduleFullSync(key, urlMatch, state); } else { writeStdErrSync("error: '" + name + "': not a Gerrit project"); } } state.markAllPushTasksScheduled(); } if (wait) { if (future != null) { try { future.get(); } catch (InterruptedException e) { log.warn("Thread was interrupted while waiting for PushAll operation to finish", e); } catch (ExecutionException e) { log.warn("An exception was thrown in PushAll operation", e); } } if (state.hasPushTask()) { state.waitForReplication(); } else { writeStdOutSync("Nothing to replicate"); } } }

Target:
protected void run() throws Failure { if (all && projectNames.size() > 0) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); } ReplicationState state = new ReplicationState(ReplicationType.COMMAND, this); Future<?> future = null; if (all) { future = pushAllFactory.create(urlMatch, state).schedule(0, TimeUnit.SECONDS); } else { for (String name : projectNames) { Project.NameKey key = new Project.NameKey(name); if (projectCache.get(key) != null) { replication.scheduleFullSync(key, urlMatch, state); } else { writeStdErrSync("error: '" + name + "': not a Gerrit project"); } } state.markAllPushTasksScheduled(); } if (wait) { if (future != null) { try { future.get(); } catch (InterruptedException e) { wrappedLog.error("Thread was interrupted while waiting for PushAll operation to finish", e, state); } catch (ExecutionException e) { wrappedLog.error("An exception was thrown in PushAll operation", e, state); } } if (state.hasPushTask()) { try { state.waitForReplication(); } catch (InterruptedException e) { wrappedLog.error("We are interrupted while waiting replication to complete", state); } } else { writeStdOutSync("Nothing to replicate"); } } }
Source:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; setHeaderHeight(timeGraphScale.getBounds().height); }

Target:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; }
Source:
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); Map<String, Path> paths = swagger.getPaths(); for (String pathKey : paths.keySet()) { Map<HttpMethod, Operation> operationsMap = paths.get(pathKey).getOperationMap(); for (Map.Entry<HttpMethod, Operation> entry : operationsMap.entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getVendorExtensions(); if (extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) { Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER); extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER); extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier); } operation.setVendorExtensions(extensions); entry.setValue(operation); operationsMap.put(entry.getKey(), operation); } paths.put(pathKey, paths.get(pathKey)); } swagger.setPaths(paths); return getSwaggerJsonString(swagger); }

Target:
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); Map<String, Path> paths = swagger.getPaths(); for (String pathKey : paths.keySet()) { Map<HttpMethod, Operation> operationsMap = paths.get(pathKey).getOperationMap(); for (Map.Entry<HttpMethod, Operation> entry : operationsMap.entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getVendorExtensions(); if (extensions != null && extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) { Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER); extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER); extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier); } } } return getSwaggerJsonString(swagger); }
Source:
public void shouldNotRecordSuccessTestExecutionByDefault() { final String oldMode = updateRecorderToDefaultOption(); Description desc = description("shouldNotRecordSuccessTestExecutionByDefault"); TestRecorderRule testRecorderRule = rule(desc); testRecorderRule.starting(desc); System.out.println("Hello World"); testRecorderRule.succeeded(desc); testRecorderRule.finished(desc); File outputFile = outputFile(desc); assertThat(outputFile.exists(), is(false)); outputFile.delete(); restoreRecorderOption(oldMode); }

Target:
public void shouldNotRecordSuccessTestExecutionByDefault() { final String oldMode = updateRecorderToDefaultOption(); try { Description desc = description("shouldNotRecordSuccessTestExecutionByDefault"); TestRecorderRule testRecorderRule = rule(desc); testRecorderRule.starting(desc); System.out.println("Hello World"); testRecorderRule.succeeded(desc); testRecorderRule.finished(desc); File outputFile = outputFile(desc); assertThat(outputFile.exists(), is(false)); outputFile.delete(); } finally { restoreRecorderOption(oldMode); } }
Source:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); checkFalse(loadFactor <= 0 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; }

Target:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); checkFalse(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; }
Source:
public void setUp() throws Exception { world = new PhysicsWorld(1920, 1600); sprite = new SingleSprite("TestSprite"); physicsObject = world.getPhysicsObject(sprite); physicsLook = new PhysicsLook(sprite, world); }

Target:
public void setUp() throws Exception { Sprite sprite = mock(Sprite.class); physicsObject = mock(PhysicsObject.class); physicsWorldSpy = Mockito.spy(new PhysicsWorld(1920, 1600)); when(physicsWorldSpy.getPhysicsObject(sprite)).thenReturn(physicsObject); physicsLook = new PhysicsLook(sprite, physicsWorldSpy); }
Source:
public void removePublicLink(OCShare share) { Log_OC.d(TAG, "Unsharing " + share.getName()); mListener.removeShare(share); }

Target:
public void removePublicLink(OCShare share) { Log_OC.d(TAG, "Removing public share " + share.getName()); mListener.removeShare(share); }
Source:
public void readJournalListFromResource(String resourceFileName) { try { InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); readJournalList(new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))); } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } }

Target:
public void readJournalListFromResource(String resourceFileName) { try (InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { readJournalList(reader); } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } }
Source:
public void should_create_job_with_description() { String jobName = "MyJob"; String jobDescription = "My sample despription"; String jobDslScript = String.format("job('%s') { description('%s') }", jobName, jobDescription); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); job.open(); WebElement descriptionElement = job.find(by.xpath(" assertEquals(descriptionElement.getText(), jobDescription); }

Target:
public void should_create_job_with_description() { String jobName = "MyJob"; String jobDescription = "My sample despription"; String jobDslScript = String.format("job('%s') { description('%s') }", jobName, jobDescription); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); job.open(); assertThat(job.getDescription(), containsString(jobDescription)); }
Source:
protected static Set<Cache> getRunningCaches(EmbeddedCacheManager cacheContainer) { Set<Cache> running = new HashSet<Cache>(); if (cacheContainer == null || !cacheContainer.getStatus().allowInvocations()) return running; for (String cacheName : cacheContainer.getCacheNames()) { if (cacheContainer.isRunning(cacheName)) { Cache c = cacheContainer.getCache(cacheName); if (c.getStatus().allowInvocations()) running.add(c); } } Cache defaultCache = cacheContainer.getCache(EmbeddedCacheManager.DEFAULT_CACHE_NAME); if (defaultCache != null) { if (defaultCache.getStatus().allowInvocations()) running.add(defaultCache); } return running; }

Target:
protected static Set<Cache> getRunningCaches(EmbeddedCacheManager cacheContainer) { Set<Cache> running = new HashSet<Cache>(); if (cacheContainer == null || !cacheContainer.getStatus().allowInvocations()) return running; for (String cacheName : cacheContainer.getCacheNames()) { if (cacheContainer.isRunning(cacheName)) { Cache c = cacheContainer.getCache(cacheName, false); if (c != null && c.getStatus().allowInvocations()) { running.add(c); } } } if (cacheContainer.isDefaultRunning()) { Cache defaultCache = cacheContainer.getCache(EmbeddedCacheManager.DEFAULT_CACHE_NAME, false); if (defaultCache != null && defaultCache.getStatus().allowInvocations()) { running.add(defaultCache); } } return running; }
Source:
public InputStreamWithFilename extractJudgmentContent(File archiveFile, String judgmentSourceId) { if (FilenameUtils.getExtension(archiveFile.getName()).equals("zip")) { ZipInputStream inputStream = null; try { inputStream = new ZipInputStream(new FileInputStream(archiveFile)); ZipEntry entry = inputStream.getNextEntry(); while(true) { if (entry == null) { break; } if (FilenameUtils.getBaseName(entry.getName()).equals(judgmentSourceId)) { return new InputStreamWithFilename(inputStream, entry.getName()); } entry = inputStream.getNextEntry(); } throw new ImportException("Content for judgment with sourceId " + judgmentSourceId + " not found in file " + archiveFile.getName()); } catch (IOException e) { IOUtils.closeQuietly(inputStream); throw new ImportException(e); } } throw new ImportException("File " + archiveFile.getName() + " is of type that is not supported"); }

Target:
public InputStreamWithFilename extractJudgmentContent(File archiveFile, String judgmentSourceId) throws IOException { if (FilenameUtils.getExtension(archiveFile.getName()).equals("zip")) { ZipInputStream inputStream = null; try { inputStream = new ZipInputStream(new FileInputStream(archiveFile)); ZipEntry entry = inputStream.getNextEntry(); while(true) { if (entry == null) { break; } if (FilenameUtils.getBaseName(entry.getName()).equals(judgmentSourceId)) { return new InputStreamWithFilename(inputStream, entry.getName()); } entry = inputStream.getNextEntry(); } throw new ImportException("Content for judgment with sourceId " + judgmentSourceId + " not found in file " + archiveFile.getName()); } catch (IOException | ImportException e) { if (inputStream != null) { inputStream.close(); } throw e; } } throw new ImportException("File " + archiveFile.getName() + " is of type that is not supported"); }
Source:
public void markCertificatesDirtyForPoolsWithProducts(Owner owner, Collection<String> productIds) { if (productIds.size() <= MAX_IN_CLAUSE_VALUES) { markCertificatesDirtyForPoolsWithNormalProducts(owner, productIds); markCertificatesDirtyForPoolsWithProvidedProducts(owner, productIds); } else { Iterator<String> productIdIter = productIds.iterator(); List<String> batch = new ArrayList<String>(); while (productIdIter.hasNext()) { batch.add(productIdIter.next()); if (batch.size() == MAX_IN_CLAUSE_VALUES) { markCertificatesDirtyForPoolsWithProducts(owner, batch); batch.clear(); } } if (batch.size() > 0) { markCertificatesDirtyForPoolsWithProducts(owner, batch); } } }

Target:
public void markCertificatesDirtyForPoolsWithProducts(Owner owner, Collection<String> productIds) { for (List<String> batch : Iterables.partition(productIds, IN_OPERATOR_BLOCK_SIZE)) { markCertificatesDirtyForPoolsWithNormalProducts(owner, batch); markCertificatesDirtyForPoolsWithProvidedProducts(owner, batch); } }
Source:
public <T> T construct(Class<T> componentType) { if (!configuration.transaction().transactionMode().isTransactional()) { return null; } TransactionManager transactionManager = null; if (transactionManager == null) { TransactionManagerLookup lookup = configuration.transaction().transactionManagerLookup(); try { if (lookup != null) { componentRegistry.wireDependencies(lookup); transactionManager = lookup.getTransactionManager(); } } catch (Exception e) { log.couldNotInstantiateTransactionManager(e); } } if (transactionManager == null && configuration.invocationBatching().enabled()) { log.usingBatchModeTransactionManager(); transactionManager = BatchModeTransactionManager.getInstance(); } if (transactionManager == null) { throw new CacheException("This is transactional cache but no transaction manager could be found. " + "Configure the transaction manager lookup properly."); } return componentType.cast(transactionManager); }

Target:
public <T> T construct(Class<T> componentType) { if (!configuration.transaction().transactionMode().isTransactional()) { return null; } TransactionManager transactionManager = null; TransactionManagerLookup lookup = configuration.transaction().transactionManagerLookup(); try { if (lookup != null) { componentRegistry.wireDependencies(lookup); transactionManager = lookup.getTransactionManager(); } } catch (Exception e) { log.couldNotInstantiateTransactionManager(e); } if (transactionManager == null && configuration.invocationBatching().enabled()) { log.usingBatchModeTransactionManager(); transactionManager = BatchModeTransactionManager.getInstance(); } if (transactionManager == null) { throw new CacheException("This is transactional cache but no transaction manager could be found. " + "Configure the transaction manager lookup properly."); } return componentType.cast(transactionManager); }
Source:
private GeometryCollection standardizeGeometryCollection(GeometryCollection geometryCollection) { ArrayList<Geometry> geometries = new ArrayList<>(); for (int i = 0; i < geometryCollection.getNumGeometries(); i++) { Geometry geometry = standardizeGeometry(geometryCollection.getGeometryN(i)); geometries.add(geometry); } if (geometryCollection.getClass() == MultiPoint.class) { return GEOMETRY_FACTORY.createMultiPoint(geometries.toArray(new Point[0])); } if (geometryCollection.getClass() == MultiLineString.class) { return GEOMETRY_FACTORY.createMultiLineString(geometries.toArray(new LineString[0])); } if (geometryCollection.getClass() == MultiPolygon.class) { return GEOMETRY_FACTORY.createMultiPolygon(geometries.toArray(new Polygon[0])); } return GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); }

Target:
private GeometryCollection standardizeGeometryCollection(GeometryCollection geometryCollection) { ArrayList<Geometry> geometries = new ArrayList<>(); for (int i = 0; i < geometryCollection.getNumGeometries(); i++) { Geometry geometry = standardizeGeometry(geometryCollection.getGeometryN(i)); geometries.add(geometry); } if (geometryCollection instanceof MultiPoint) { return GEOMETRY_FACTORY.createMultiPoint(geometries.toArray(new Point[0])); } if (geometryCollection instanceof MultiLineString) { return GEOMETRY_FACTORY.createMultiLineString(geometries.toArray(new LineString[0])); } if (geometryCollection instanceof MultiPolygon) { return GEOMETRY_FACTORY.createMultiPolygon(geometries.toArray(new Polygon[0])); } return GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); }
Source:
public static List<Overlay> convert(MapView map, File file) throws Exception { ValidationPreferences pref = new ValidationPreferences(); pref.setMaxNumberOfPointsPerShape(200000); return convert(map, file, pref); }

Target:
public static List<Overlay> convert(MapView map, File file) throws Exception { return convert(map, file, getDefaultValidationPreferences()); }