auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private long getCachedStartIndex(Path path) { Long startIndexForFile = startIndexMap.get(path); if (startIndexForFile == null) { try { FSDataInputStream fis = path.getFileSystem(conf).open(path); for (int j = 0; j < headerCount; j++) { fis.readLine(); startIndexForFile = fis.getPos() - 1; } } catch (IOException e) { startIndexForFile = 0L; } startIndexMap.put(path, startIndexForFile); } return startIndexForFile; }

Target:
private long getCachedStartIndex(Path path) throws IOException { if (headerCount == 0) { return 0; } Long startIndexForFile = startIndexMap.get(path); if (startIndexForFile == null) { FileSystem fileSystem; FSDataInputStream fis = null; fileSystem = path.getFileSystem(conf); try { fis = fileSystem.open(path); for (int j = 0; j < headerCount; j++) { if (fis.readLine() == null) { startIndexMap.put(path, Long.MAX_VALUE); return Long.MAX_VALUE; } } startIndexForFile = fis.getPos() - 1; } finally { if (fis != null) { fis.close(); } } startIndexMap.put(path, startIndexForFile); } return startIndexForFile; }
Source:
private static void invokeWithTimeoutWithNoExecutor( ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) { InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); long startTime = System.currentTimeMillis(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean notTimedout = true; try { Thread currentThread = Thread.currentThread(); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(realTimeOut); } catch (InterruptedException e) { } currentThread.interrupt(); }).start(); imr.run(); notTimedout = System.currentTimeMillis() <= startTime + realTimeOut; if (notTimedout) { testResult.setStatus(ITestResult.SUCCESS); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); testResult.setStatus(ITestResult.FAILURE); } } catch (Exception ex) { if (! notTimedout) { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); } else { testResult.setThrowable(ex.getCause()); } testResult.setStatus(ITestResult.FAILURE); } }

Target:
private static void invokeWithTimeoutWithNoExecutor( ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) { InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); long startTime = System.currentTimeMillis(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean notTimedout = true; try { Thread currentThread = Thread.currentThread(); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(realTimeOut); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } currentThread.interrupt(); }).start(); imr.run(); notTimedout = System.currentTimeMillis() <= startTime + realTimeOut; if (notTimedout) { testResult.setStatus(ITestResult.SUCCESS); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); testResult.setStatus(ITestResult.FAILURE); } } catch (Exception ex) { if (notTimedout) { testResult.setThrowable(ex.getCause()); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); } testResult.setStatus(ITestResult.FAILURE); } }
Source:
public Enum parseEnum(T object) { Error.push("parseEnum"); try { if (object != null) { String name = getStringProperty(object, STR_NAME); if (name == null) { throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_NAME); } Enum e = new Enum(name); List<String> values = getStringList(object, STR_VALUES); List<T> annotatedValues = getObjectList(object, STR_ANNOTATED_VALUES); Set<EnumValue> enumValues = new HashSet<EnumValue>(); if((values != null) && (annotatedValues != null)){ throw Error.get(MetadataConstants.ERR_INCOMPATIBLE_VALUE, STR_VALUES + " and " + STR_ANNOTATED_VALUES + " cannot both be defined."); } else if(values != null){ for(String string : values){ enumValues.add(new EnumValue(e.getName(), string, null)); } } else if(annotatedValues != null){ for(T value : annotatedValues){ EnumValue enumValue = new EnumValue(e.getName()); enumValue.setName(getRequiredStringProperty(value, STR_NAME)); enumValue.setDescription(getStringProperty(value, STR_DESCRIPTION)); enumValues.add(enumValue); } } if(enumValues.isEmpty()){ throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_VALUES); } e.setValues(enumValues); return e; } else { return null; } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, e.getMessage()); } finally { Error.pop(); } }

Target:
public Enum parseEnum(T object) { Error.push("parseEnum"); try { if (object != null) { String name = getStringProperty(object, STR_NAME); if (name == null) { throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_NAME); } Enum e = new Enum(name); List<String> values = getStringList(object, STR_VALUES); List<T> annotatedValues = getObjectList(object, STR_ANNOTATED_VALUES); Set<EnumValue> enumValues = new HashSet<EnumValue>(); if(annotatedValues != null){ for(T value : annotatedValues){ EnumValue enumValue = new EnumValue(); enumValue.setName(getRequiredStringProperty(value, STR_NAME)); enumValue.setDescription(getRequiredStringProperty(value, STR_DESCRIPTION)); enumValues.add(enumValue); } } else if(values != null){ for(String string : values){ enumValues.add(new EnumValue(string, null)); } } if(enumValues.isEmpty()){ throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_VALUES); } e.setValues(enumValues); return e; } else { return null; } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, e.getMessage()); } finally { Error.pop(); } }
Source:
private void factHandleSerialization(final boolean withOOPath) { final String str = "package org.kie.test\n" + "import java.util.concurrent.atomic.AtomicInteger\n" + "global java.util.List list\n" + "rule rule1\n" + "when\n" + (withOOPath ? " AtomicInteger($i: /intValue{this > 0})\n" : " $i: AtomicInteger(intValue > 0)\n") + "then\n" + " list.add( $i );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); List<?> list = new ArrayList<>(); ksession.setGlobal("list", list); final AtomicInteger value = new AtomicInteger(4); FactHandle atomicFH = ksession.insert(value); ksession.fireAllRules(); assertEquals(1, list.size()); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); assertEquals(2, list.size()); final String externalForm = atomicFH.toExternalForm(); ksession = KieServices.get().getStoreServices().loadKieSession(ksession.getIdentifier(), kbase, null, env); atomicFH = ksession.execute(CommandFactory.fromExternalFactHandleCommand(externalForm)); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); list = (List<?>) ksession.getGlobal("list"); assertEquals(3, list.size()); }

Target:
private void factHandleSerialization(final boolean withOOPath) { final String str = "package org.kie.test\n" + "import java.util.concurrent.atomic.AtomicInteger\n" + "global java.util.List list\n" + "rule rule1\n" + "when\n" + (withOOPath ? " AtomicInteger($i: /intValue{this > 0})\n" : " $i: AtomicInteger(intValue > 0)\n") + "then\n" + " list.add( $i );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); List<AtomicInteger> list = new ArrayList<>(); ksession.setGlobal("list", list); final AtomicInteger value = new AtomicInteger(4); FactHandle atomicFH = ksession.insert(value); ksession.fireAllRules(); assertThat(list).hasSize(1); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); assertThat(list).hasSize(2); final String externalForm = atomicFH.toExternalForm(); ksession = KieServices.get().getStoreServices().loadKieSession(ksession.getIdentifier(), kbase, null, env); atomicFH = ksession.execute(CommandFactory.fromExternalFactHandleCommand(externalForm)); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); list = (List<AtomicInteger>) ksession.getGlobal("list"); assertThat(list).hasSize(3); }
Source:
public QueueAsyncClient createQueue(String queueName) { return createQueue(queueName, null); }

Target:
public Mono<Response<QueueAsyncClient>> createQueue(String queueName) { return createQueue(queueName, null); }
Source:
public void refreshVdsRunTimeInfo() { boolean isVdsUpOrGoingToMaintenance = vds.getStatus() == VDSStatus.Up || vds.getStatus() == VDSStatus.PreparingForMaintenance || vds.getStatus() == VDSStatus.Error || vds.getStatus() == VDSStatus.NonOperational; try { if (isVdsUpOrGoingToMaintenance) { if (vdsManager.isTimeToRefreshStatistics() || vds.getStatus() == VDSStatus.PreparingForMaintenance) { refreshVdsStats(isVdsUpOrGoingToMaintenance); } else { refreshCommitedMemory(isVdsUpOrGoingToMaintenance); postProcessRefresh(); } } else { final AtomicBoolean processHardwareNeededAtomic = new AtomicBoolean(); vdsManager.refreshCapabilities( new RefreshCapabilitiesCallback(isVdsUpOrGoingToMaintenance, processHardwareNeededAtomic), processHardwareNeededAtomic, vds); } } catch (VDSRecoveringException e) { handleVDSRecoveringException(e); } catch (ClassCastException cce) { handleClassCastException(cce); } catch (Throwable t) { log.error("Failure to refresh host '{}' runtime info: {}", vds.getName(), t.getMessage()); log.debug("Exception", t); throw t; } if (isVdsUpOrGoingToMaintenance) { moveVDSToMaintenanceIfNeeded(); } }

Target:
public void refreshVdsRunTimeInfo() { boolean isVdsUpOrGoingToMaintenance = vds.getStatus() == VDSStatus.Up || vds.getStatus() == VDSStatus.PreparingForMaintenance || vds.getStatus() == VDSStatus.Error || vds.getStatus() == VDSStatus.NonOperational; try { if (isVdsUpOrGoingToMaintenance) { if (vdsManager.isTimeToRefreshStatistics() || vds.getStatus() == VDSStatus.PreparingForMaintenance) { refreshVdsStats(); } else { refreshCommitedMemory(true); postProcessRefresh(); } } else { final AtomicBoolean processHardwareNeededAtomic = new AtomicBoolean(); vdsManager.refreshCapabilities( new HostMonitoringRefreshCapabilitiesCallback(vds, vdsManager, this, processHardwareNeededAtomic), processHardwareNeededAtomic, vds); } } catch (VDSRecoveringException e) { handleVDSRecoveringException(e); } catch (ClassCastException cce) { handleClassCastException(cce); } catch (Throwable t) { log.error("Failure to refresh host '{}' runtime info: {}", vds.getName(), t.getMessage()); log.debug("Exception", t); throw t; } if (isVdsUpOrGoingToMaintenance) { moveVDSToMaintenanceIfNeeded(); } }
Source:
private static String getOffsetInStandardFormat(int offsetInMillis) { int hours = offsetInMillis / 1000 / 60 / 60; if (hours > 0) { return "+" + hours; } else if (hours == 0) { return "Z"; } else { return "" + hours; } }

Target:
public static String getOffsetInStandardFormat(int offsetInMillis) { int hours = offsetInMillis / 1000 / 60 / 60; String offsetStr; if (hours > 0) { offsetStr = "+" + intPad(hours, 2); } else if (hours == 0) { offsetStr = "Z"; } else { offsetStr = "-" + intPad(Math.abs(hours), 2); } int totalMinutes = offsetInMillis / 1000 / 60; int remainderMinutes = Math.abs(totalMinutes) % 60; if (remainderMinutes != 0) { offsetStr += (":" + intPad(remainderMinutes, 2)); } return offsetStr; }
Source:
public boolean hasOpenGraph() { boolean result = false; final WebElement openGraphContainer = getReplyCreatorWrapper() .findElement(By.className("og-container")); if (null != openGraphContainer) { result = null != openGraphContainer.findElement(By.className("og-texts")); } return result; }

Target:
public boolean hasOpenGraph() { boolean result = false; final WebElement openGraphContainer = getReplyCreatorWrapper() .findElement(getOpenGraphContainer()); if (null != openGraphContainer) { result = null != openGraphContainer.findElement(getOpenGraphText()); } return result; }
Source:
public void setUp() throws Exception { client = createClient(); }

Target:
public void setUp() throws Exception { LauncherFactory factory = mock(LauncherFactory.class); client = spy(new DifferentialClient( DUMMY_DIFF_ID, factory, DUMMY_CONDUIT_TOKEN, DUMMY_ARC_PATH )); }
Source:
public Object fromBody( TypedInput body, Type type ) throws ConversionException { try { if ( StringUtils.equals( body.mimeType(), BYTE_MIME_TYPE ) ) { return IOUtils.toByteArray( body.in() ); } JavaType javaType = objectMapper.getTypeFactory().constructType( type ); InputStream in = body.in(); if ( in.available() == 0 ) { return null; } return objectMapper.readValue( body.in(), javaType ); } catch ( IOException e ) { logger.error( "Unable to deserialize object of type from body with mime-type {}.", type, body.mimeType(), e ); throw new ConversionException( e ); } }

Target:
public Object fromBody( TypedInput body, Type type ) throws ConversionException { try ( InputStream in = body.in() ) { if ( StringUtils.equals( body.mimeType(), BYTE_MIME_TYPE ) ) { return IOUtils.toByteArray( in ); } JavaType javaType = objectMapper.getTypeFactory().constructType( type ); return objectMapper.readValue( body.in(), javaType ); } catch ( IOException e ) { logger.error( "Unable to deserialize object of type from body with mime-type {}.", type, body.mimeType(), e ); throw new ConversionException( e ); } }
Source:
public static void main(String[] args) throws Exception { LOG.info("Application started"); File configurationFile; if (args.length == 0) { configurationFile = new File(FileDropZoneMain.class.getClassLoader().getResource("file-drop-zone.properties").getPath()); } else if (args.length == 1) { configurationFile = new File(args[0]); } else { LOG.error("Too many arguments: {}", args.length); return; } PollingServiceManager pollingServiceManager = new PollingServiceManager(configurationFile); try { pollingServiceManager.initManager(); pollingServiceManager.initObservers(); } catch (IOException e) { LOG.error("Error during manager setup: {}", e.getMessage()); return; } LOG.info("Starting monitor"); pollingServiceManager.startMonitor(); Runtime.getRuntime().addShutdownHook(new Thread(new FileDropZoneShutdownTask(pollingServiceManager))); }

Target:
public static void main(String[] args) throws Exception { File configurationFile; if (args.length == 0) { LOG.info("Application started using default file: \"file-drop-zone.properties\""); configurationFile = new File(FileDropZoneMain.class.getClassLoader().getResource("file-drop-zone.properties").getPath()); } else { LOG.info("Application started using file: {}", args[0]); configurationFile = new File(args[0]); } PollingServiceManager pollingServiceManager = new PollingServiceManager(configurationFile); try { pollingServiceManager.initManager(); pollingServiceManager.initObservers(); } catch (IOException e) { LOG.error("Error during manager setup: {}", e); return; } LOG.info("Starting monitor"); pollingServiceManager.startMonitor(); Runtime.getRuntime().addShutdownHook(new Thread(new FileDropZoneShutdownTask(pollingServiceManager))); }
Source:
public LogTruncationException(Map<TopicPartition, OffsetAndMetadata> divergentOffsets) { super(Utils.transformMap(divergentOffsets, Function.identity(), OffsetAndMetadata::offset), "detected log truncation"); }

Target:
public LogTruncationException(Map<TopicPartition, OffsetAndMetadata> divergentOffsets) { super("Detected log truncation with diverging offsets " + divergentOffsets, Utils.transformMap(divergentOffsets, Function.identity(), OffsetAndMetadata::offset)); this.divergentOffsets = Collections.unmodifiableMap(divergentOffsets); }
Source:
public static PageRequest getPageRequest(QueryOptions queryOptions) { int limit = (int) queryOptions.get("limit"); int skip = (int) queryOptions.get("skip"); return getPageRequest(limit, skip); }

Target:
public static PageRequest getPageRequest(QueryOptions queryOptions) { int limit = (queryOptions.get("limit") == null) ? 10 : (int) queryOptions.get("limit"); int skip = (queryOptions.get("skip") == null) ? 0 : (int) queryOptions.get("skip"); return getPageRequest(limit, skip); }
Source:
public void tailsNonUtf() throws Exception { try ( final StartsDockerDaemon start = new StartsDockerDaemon(Profile.EMPTY) ) { Assume.assumeTrue( "true".equalsIgnoreCase(System.getProperty("run-docker-tests")) ); final PfShell sshd = start.shell(); final String clean = "some output"; new Shell.Plain( new SSH(sshd.host(), sshd.port(), sshd.login(), sshd.key()) ).exec(String.format("echo '%s\u00ea' > /tmp/stdout", clean)); final Talk talk = new Talk.InFile(); final String hash = "a1b5c3e3"; final String key = "id"; talk.modify( new Directives().xpath("/talk") .add("daemon") .attr(key, hash) .add("title").set("tail").up() .add("script").set("empty").up() .add("dir").set("/tmp").up() .add("code").set("-7").up() .add("started").set(new Time().iso()).up() .add("ended").set(new Time().iso()).up().up() .add("shell").attr(key, hash) .add("host").set(sshd.host()).up() .add("port").set(Integer.toString(sshd.port())).up() .add("login").set(sshd.login()).up() .add("key").set(sshd.key()).up().up() ); MatcherAssert.assertThat( IOUtils.toString( new Tail(talk.read(), hash).read(), Charsets.UTF_8 ), Matchers.is(String.format("%sê\n", clean)) ); } }

Target:
public void tailsNonUtf() throws Exception { Assume.assumeTrue( "true".equalsIgnoreCase(System.getProperty("run-docker-tests")) ); try ( final StartsDockerDaemon start = new StartsDockerDaemon(Profile.EMPTY) ) { final PfShell sshd = start.shell(); final String clean = "some output"; new Shell.Plain( new SSH(sshd.host(), sshd.port(), sshd.login(), sshd.key()) ).exec(String.format("echo '%s\u00ea' > /tmp/stdout", clean)); final Talk talk = new Talk.InFile(); final String hash = "a1b5c3e3"; final String key = "id"; talk.modify( new Directives().xpath("/talk") .add("daemon") .attr(key, hash) .add("title").set("tail").up() .add("script").set("empty").up() .add("dir").set("/tmp").up() .add("code").set("-7").up() .add("started").set(new Time().iso()).up() .add("ended").set(new Time().iso()).up().up() .add("shell").attr(key, hash) .add("host").set(sshd.host()).up() .add("port").set(Integer.toString(sshd.port())).up() .add("login").set(sshd.login()).up() .add("key").set(sshd.key()).up().up() ); MatcherAssert.assertThat( IOUtils.toString( new Tail(talk.read(), hash).read(), Charsets.UTF_8 ), Matchers.is(String.format("%sê\n", clean)) ); } }
Source:
public PollerFlux<CertificateOperation, KeyVaultCertificate> getCertificateOperation(String name) { return new PollerFlux<>(Duration.ofSeconds(1), null, createPollOperation(name), cancelOperation(name), fetchResultOperation(name)); }

Target:
public PollerFlux<CertificateOperation, KeyVaultCertificate> getCertificateOperation(String name) { return new PollerFlux<>(Duration.ofSeconds(1), (pollingContext) -> Mono.empty(), createPollOperation(name), cancelOperation(name), fetchResultOperation(name)); }
Source:
public List<UsagePriceOverride> getResolvedUsageOverrides(Usage[] usages, List<UsagePriceOverride> usagePriceOverrides) throws CatalogApiException{ List<UsagePriceOverride> resolvedUsageOverrides = new ArrayList<UsagePriceOverride>(); for (final Usage curUsage : usages) { final UsagePriceOverride curOverride = Iterables.tryFind(usagePriceOverrides, new Predicate<UsagePriceOverride>() { @Override public boolean apply(final UsagePriceOverride input) { return input.getName() != null && input.getName().equals(curUsage.getName()); } }).orNull(); if(curOverride != null) { List<TierPriceOverride> tierPriceOverrides = getResolvedTierOverrides(curUsage.getTiers(), curOverride.getTierPriceOverrides()); resolvedUsageOverrides.add(new DefaultUsagePriceOverride(curUsage.getName(), curUsage.getUsageType(),tierPriceOverrides)); } else resolvedUsageOverrides.add(null); } return resolvedUsageOverrides; }

Target:
public List<UsagePriceOverride> getResolvedUsageOverrides(Usage[] usages, List<UsagePriceOverride> usagePriceOverrides) throws CatalogApiException{ List<UsagePriceOverride> resolvedUsageOverrides = new ArrayList<UsagePriceOverride>(); for (final Usage curUsage : usages) { final UsagePriceOverride curOverride = Iterables.tryFind(usagePriceOverrides, new Predicate<UsagePriceOverride>() { @Override public boolean apply(final UsagePriceOverride input) { return input.getName() != null && input.getName().equals(curUsage.getName()); } }).orNull(); if(curOverride != null) { List<TierPriceOverride> tierPriceOverrides = getResolvedTierOverrides(curUsage.getTiers(), curOverride.getTierPriceOverrides()); resolvedUsageOverrides.add(new DefaultUsagePriceOverride(curUsage.getName(), curUsage.getUsageType(),tierPriceOverrides)); } else { resolvedUsageOverrides.add(null); } } return resolvedUsageOverrides; }
Source:
private void throwImmutableException() { throw new RuntimeException("PLANNING_USER: " + getEntityId() + " object can not be modified."); }

Target:
private void throwImmutableException() { throw new UnsupportedOperationException("PLANNING_USER: " + getEntityId() + " object can not be modified."); }
Source:
public void testAddedNotificationsContainTagsFromMetadata() { itemRegistry.addRegistryChangeListener(mockListener); prepareMetadata(ITEM_NAME, "hello"); prepareItem(ITEM_NAME); ArgumentCaptor<Item> captor = ArgumentCaptor.forClass(Item.class); verify(mockListener).added(captor.capture()); Item res = captor.getValue(); assertEquals(1, res.getTags().size()); assertEquals("hello", res.getTags().iterator().next()); StringItem item = new StringItem(ITEM_NAME); managedItemProvider.update(item); }

Target:
public void testAddedNotificationsContainTagsFromMetadata() { itemRegistry.addRegistryChangeListener(mockListener); prepareMetadata(ITEM_NAME, "hello"); prepareItem(ITEM_NAME); ArgumentCaptor<Item> captor = ArgumentCaptor.forClass(Item.class); verify(mockListener).added(captor.capture()); Item res = captor.getValue(); assertEquals(1, res.getTags().size()); assertEquals("hello", res.getTags().iterator().next()); }
Source:
public boolean getTaskGroupSuccess() { boolean childrenTasksSuccess = taskGroupSuccess; for (VdcActionParametersBase childParameters : getImagesParameters()) { childrenTasksSuccess &= childParameters.getTaskGroupSuccess(); } return childrenTasksSuccess; }

Target:
public boolean getTaskGroupSuccess() { boolean childrenTasksSuccess = taskGroupSuccess; for (VdcActionParametersBase childParameters : getImagesParameters()) { childrenTasksSuccess &= childParameters.getTaskGroupSuccess(); if (!childrenTasksSuccess) { break; } } return childrenTasksSuccess; }
Source:
public void actionPerformed(ActionEvent e) { Enum canOpen = etc.canOpen(); if (canOpen == EditorTopComponent.CanOpenState.SAVE_AND_OPEN) { etc.fileAction().saveFile(); this.setVisible(true); } else if (canOpen == EditorTopComponent.CanOpenState.OPEN) { this.setVisible(true); } }

Target:
public void actionPerformed(ActionEvent e) { FileActions fileAction = new FileActions(); switch (etc.canOpen()) { case SAVE_AND_OPEN: fileAction.saveFile(FileChooserService.DialogType.SAVE); this.setVisible(true); break; case OPEN: this.setVisible(true); break; default: break; } }
Source:
@Test public void multipleNamedArguments() { Map<String, Object> map = new HashMap<>(); map.put("pipe", System.class); map.put("text", "tacos"); CodeBlock block = CodeBlock.builder() .addNamed("$pipe:T.out.println(\"Let's eat some $text:L\");", map) .build(); assertThat(block.toString()).isEqualTo( "java.lang.System.out.println(\"Let's eat some tacos\");"); }

Target:
@Test public void multipleNamedArguments() { Map<String, Object> map = new LinkedHashMap<>(); map.put("pipe", System.class); map.put("text", "tacos"); CodeBlock block = CodeBlock.builder() .addNamed("$pipe:T.out.println(\"Let's eat some $text:L\");", map) .build(); assertThat(block.toString()).isEqualTo( "java.lang.System.out.println(\"Let's eat some tacos\");"); }
Source:
public void setup(OperatorContext context) { mode=context.getValue(context.PROCESSING_MODE); if(mode==ProcessingMode.EXACTLY_ONCE){ throw new RuntimeException("This operator only supports atmost once and atleast once processing modes"); } super.setup(context); }

Target:
public void setup(OperatorContext context) { mode=context.getValue(OperatorContext.PROCESSING_MODE); if(mode==ProcessingMode.EXACTLY_ONCE){ throw new RuntimeException("This operator only supports atmost once and atleast once processing modes"); } super.setup(context); }
Source:
UmiGraph(final DuplicateSet set, final String umiTag, final String molecularIdentifierTag, final boolean allowMissingUmis, final boolean duplexUmis) { this.umiTag = umiTag; this.molecularIdentifierTag = molecularIdentifierTag; this.allowMissingUmis = allowMissingUmis; this.duplexUmis = duplexUmis; records = set.getRecords(); for (final SAMRecord rec : records) { if (rec.getStringAttribute(umiTag) == null) { if (allowMissingUmis) { rec.setAttribute(umiTag, ""); } else { throw new PicardException("Read " + rec.getReadName() + " does not contain a UMI with the " + umiTag + " attribute."); } } } umiCounts = records.stream().collect(Collectors.groupingBy(p -> duplexUmis ? UmiUtil.getTopStrandNormalizedDuplexUMI(p, umiTag) : p.getStringAttribute(umiTag), counting())); numUmis = umiCounts.size(); umi = new String[numUmis]; duplicateSetID = IntStream.rangeClosed(0, numUmis-1).toArray(); int i = 0; for (final String key : umiCounts.keySet()) { umi[i] = key; i++; } }

Target:
UmiGraph(final DuplicateSet set, final String umiTag, final String molecularIdentifierTag, final boolean allowMissingUmis, final boolean duplexUmis) { this.umiTag = umiTag; this.molecularIdentifierTag = molecularIdentifierTag; this.allowMissingUmis = allowMissingUmis; this.duplexUmis = duplexUmis; records = set.getRecords(); for (final SAMRecord rec : records) { if (rec.getStringAttribute(umiTag) == null) { if (!allowMissingUmis) { throw new PicardException("Read " + rec.getReadName() + " does not contain a UMI with the " + umiTag + " attribute."); } rec.setAttribute(umiTag, ""); } } umiCounts = records.stream().collect(Collectors.groupingBy(p -> UmiUtil.getTopStrandNormalizedUmi(p, umiTag, duplexUmis), counting())); numUmis = umiCounts.size(); umi = new String[numUmis]; duplicateSetID = IntStream.rangeClosed(0, numUmis-1).toArray(); int i = 0; for (final String key : umiCounts.keySet()) { umi[i] = key; i++; } }
Source:
public void migrateOldConfiguration() throws Exception { String url = "<LINK_0>"; String oldConfiguration = "<hudson.plugins.jira.JiraProjectProperty_-DescriptorImpl>\n" + " <sites>\n" + " <hudson.plugins.jira.JiraSite>\n" + " <url>" + url + "</url>\n" + " <useHTTPAuth>false</useHTTPAuth>\n" + " <supportsWikiStyleComment>false</supportsWikiStyleComment>\n" + " <recordScmChanges>false</recordScmChanges>\n" + " <disableChangelogAnnotations>false</disableChangelogAnnotations>\n" + " <updateJiraIssueForAllStatus>false</updateJiraIssueForAllStatus>\n" + " <timeout>10</timeout>\n" + " <readTimeout>30</readTimeout>\n" + " <threadExecutorNumber>10</threadExecutorNumber>\n" + " <dateTimePattern></dateTimePattern>\n" + " <appendChangeTimestamp>false</appendChangeTimestamp>\n" + " </hudson.plugins.jira.JiraSite>\n" + " </sites>\n" + "</hudson.plugins.jira.JiraProjectProperty_-DescriptorImpl>"; XStream xstream = new XStream2(); JiraSite expected = new JiraSite(url); DescriptorImpl instance = (DescriptorImpl)xstream.fromXML(oldConfiguration); assertNotNull(instance); assertNull(instance.sites); JiraSite actual = JiraGlobalConfiguration.get().getSites().get(0); assertEquals(url, actual.getName()); r.assertEqualDataBoundBeans(expected, actual); }

Target:
public void migrateOldConfiguration() throws Exception { String url = "<LINK_0>"; XStream xstream = new XStream2(); JiraSite expected = new JiraSite(url); InputStream resource = getClass().getResourceAsStream("oldJiraProjectProperty.xml"); DescriptorImpl instance = (DescriptorImpl) xstream.fromXML(resource); assertNotNull(instance); assertNull(instance.sites); JiraSite actual = JiraGlobalConfiguration.get().getSites().get(0); assertEquals(url, actual.getName()); r.assertEqualDataBoundBeans(expected, actual); }
Source:
public MutableLiveData<String> getTitle() { return mTitle; }

Target:
public LiveData<String> getTitle() { return mTitle; }
Source:
public int hashCode() { int result = processId.hashCode(); result = 31 * result + processName.hashCode(); return result; }

Target:
public int hashCode() { int result = processId.hashCode(); result = ~~result; result = 31 * result + processName.hashCode(); result = ~~result; return result; }
Source:
private void create() throws SQLException { if(!validateDatabase(true)) throw new SchemaMigrationException("Target database is not empty, please consider executing with \"migrate\" option"); flyway.migrate(); }

Target:
private void create() throws SQLException { try (Connection connection = flyway.getDataSource().getConnection()) { if (!isDatabaseEmpty(connection)) throw new SchemaMigrationException("Please use an empty database or use \"migrate\" if you are already running a previous version."); } flyway.migrate(); }
Source:
public Ds3Element( final String name, final String type, final String componentType) { this.name = name; this.type = type; this.componentType = componentType; this.ds3Annotations = null; }

Target:
public Ds3Element( final String name, final String type, final String componentType) { this(name, type, componentType, null); }
Source:
public static FeedbackSessionAttributes getSoftDeletedSession(String feedbackSessionName, String instructorId) { Map<String, String[]> params = new HashMap<>(); params.put(Const.ParamsNames.ENTITY_TYPE, new String[] { Const.EntityType.INSTRUCTOR }); params.put(Const.ParamsNames.IS_IN_RECYCLE_BIN, new String[] { "true" }); params.put(Const.ParamsNames.USER_ID, new String[] { instructorId }); ResponseBodyAndCode response = executeGetRequest(Const.ResourceURIs.SESSIONS, params); if (response.responseCode == HttpStatus.SC_NOT_FOUND) { return null; } FeedbackSessionsData sessionsData = JsonUtils.fromJson(response.responseBody, FeedbackSessionsData.class); List<FeedbackSessionData> sessionsDataList = sessionsData.getFeedbackSessions(); for (FeedbackSessionData feedbackSession : sessionsDataList) { if (feedbackSession.getFeedbackSessionName().equals(feedbackSessionName)) { return FeedbackSessionAttributes .builder(feedbackSession.getCourseId(), feedbackSession.getFeedbackSessionName()) .build(); } } return null; }

Target:
public static FeedbackSessionAttributes getSoftDeletedSession(String feedbackSessionName, String instructorId) { Map<String, String[]> params = new HashMap<>(); params.put(Const.ParamsNames.ENTITY_TYPE, new String[] { Const.EntityType.INSTRUCTOR }); params.put(Const.ParamsNames.IS_IN_RECYCLE_BIN, new String[] { "true" }); params.put(Const.ParamsNames.USER_ID, new String[] { instructorId }); ResponseBodyAndCode response = executeGetRequest(Const.ResourceURIs.SESSIONS, params); if (response.responseCode == HttpStatus.SC_NOT_FOUND) { return null; } FeedbackSessionsData sessionsData = JsonUtils.fromJson(response.responseBody, FeedbackSessionsData.class); FeedbackSessionData feedbackSession = sessionsData.getFeedbackSessions() .stream() .filter(fs -> fs.getFeedbackSessionName().equals(feedbackSessionName)) .findFirst() .orElse(null); if (feedbackSession == null) { return null; } return FeedbackSessionAttributes .builder(feedbackSession.getCourseId(), feedbackSession.getFeedbackSessionName()) .build(); }
Source:
public List<StoragePoolVO> findZoneWideStoragePoolsByTags(long dcId, String[] tags) { if (tags == null || tags.length == 0) { QueryBuilder<StoragePoolVO> sc = QueryBuilder.create(StoragePoolVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); sc.and(sc.entity().getScope(), Op.EQ, ScopeType.ZONE); return sc.list(); } else { StringBuilder sql = new StringBuilder(ZoneWideTagsSqlPrefix); for (String tag : tags){ sql.append("(storage_pool_tags.tag='" + tag + "') OR "); } sql.delete(sql.length() - 4, sql.length()); sql.append(ZoneWideTagsSqlSuffix); TransactionLegacy txn = TransactionLegacy.currentTxn(); try (PreparedStatement pstmt = txn.prepareStatement(sql.toString());){ List<StoragePoolVO> pools = new ArrayList<StoragePoolVO>(); if (pstmt != null) { int i = 1; pstmt.setLong(i++, dcId); pstmt.setString(i++, ScopeType.ZONE.toString()); pstmt.setInt(i++, tags.length); try(ResultSet rs = pstmt.executeQuery();) { while (rs.next()) { pools.add(toEntityBean(rs, false)); } }catch (SQLException e) { throw new CloudRuntimeException("findZoneWideStoragePoolsByTags:Exception:" + e.getMessage(), e); } } return pools; } catch (SQLException e) { throw new CloudRuntimeException("findZoneWideStoragePoolsByTags:Exception:" + e.getMessage(), e); } } }

Target:
public List<StoragePoolVO> findZoneWideStoragePoolsByTags(long dcId, String[] tags) { if (tags == null || tags.length == 0) { QueryBuilder<StoragePoolVO> sc = QueryBuilder.create(StoragePoolVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); sc.and(sc.entity().getScope(), Op.EQ, ScopeType.ZONE); return sc.list(); } else { String sqlValues = getSqlValuesFromStorageTags(tags); String sql = getSqlPreparedStatement(ZoneWideTagsSqlPrefix, ZoneWideTagsSqlSuffix, sqlValues, null); return searchStoragePoolsPreparedStatement(sql, dcId, null, null, ScopeType.ZONE, tags.length); } }
Source:
private static Type resourceType(Tree resource) { if (resource instanceof VariableTree) { return ((VariableTree) resource).type().symbolType(); } return ((TypeTree) resource).symbolType(); }

Target:
private static Type resourceType(Tree resource) { if (resource.is(Tree.Kind.VARIABLE)) { return ((VariableTree) resource).type().symbolType(); } return ((TypeTree) resource).symbolType(); }
Source:
private void handleRemoveProject(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { final User user = session.getUser(); final String projectName = getParam(req, "project"); final Project project = this.projectManager.getProject(projectName); if (project == null) { this.setErrorMessageInCookie(resp, "Project " + projectName + " doesn't exist."); resp.sendRedirect(req.getContextPath()); return; } if (!hasPermission(project, user, Type.ADMIN)) { this.setErrorMessageInCookie(resp, "Cannot delete. User '" + user.getUserId() + "' is not an ADMIN."); resp.sendRedirect(req.getRequestURI() + "?project=" + projectName); return; } removeAssociatedSchedules(project); try { this.projectManager.removeProject(project, user); } catch (final ProjectManagerException e) { this.setErrorMessageInCookie(resp, e.getMessage()); resp.sendRedirect(req.getRequestURI() + "?project=" + projectName); return; } finally { try { if (this.enableQuartz) { this.scheduler.unscheduleAll(project); } } catch (final SchedulerException e) { this.setErrorMessageInCookie(resp, e.getMessage()); resp.sendRedirect(req.getRequestURI() + "?project=" + projectName); } } this.setSuccessMessageInCookie(resp, "Project '" + projectName + "' was successfully deleted and associated schedules are removed."); resp.sendRedirect(req.getContextPath()); }

Target:
private void handleRemoveProject(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { final User user = session.getUser(); final String projectName = getParam(req, "project"); final Project project = this.projectManager.getProject(projectName); if (project == null) { this.setErrorMessageInCookie(resp, "Project " + projectName + " doesn't exist."); resp.sendRedirect(req.getContextPath()); return; } if (!hasPermission(project, user, Type.ADMIN)) { this.setErrorMessageInCookie(resp, "Cannot delete. User '" + user.getUserId() + "' is not an ADMIN."); resp.sendRedirect(req.getRequestURI() + "?project=" + projectName); return; } removeAssociatedSchedules(project); try { this.projectManager.removeProject(project, user); } catch (final ProjectManagerException e) { this.setErrorMessageInCookie(resp, e.getMessage()); resp.sendRedirect(req.getRequestURI() + "?project=" + projectName); return; } this.setSuccessMessageInCookie(resp, "Project '" + projectName + "' was successfully deleted and associated schedules are removed."); resp.sendRedirect(req.getContextPath()); }
Source:
public void count(final String aspect, final long delta, final String... tags) { send(new StringBuilder(prefix).append(sanitiseAspect(aspect)).append(":").append(delta).append("|c").append(tagString(tags)).toString()); }

Target:
public void count(final String aspect, final long delta, final String... tags) { send(aspect, tags, Long.toString(delta), "|c"); }
Source:
public ConnectorPlanOptimizerProvider getConnectorPlanOptimizerProvider() { return new ConnectorPlanOptimizerProvider() { @Override public Set<ConnectorPlanOptimizer> getLogicalPlanOptimizers() { return ImmutableSet.of(planOptimizer); } @Override public Set<ConnectorPlanOptimizer> getPhysicalPlanOptimizers() { return ImmutableSet.of(); } }; }

Target:
public ConnectorPlanOptimizerProvider getConnectorPlanOptimizerProvider() { return new DruidPlanOptimizerProvider(planOptimizer); }
Source:
public Object visit(ASTPrimaryExpression node, Object data) { if (node.jjtGetNumChildren() > 3) { if (!"isEmpty".equals(node.jjtGetChild(node.jjtGetNumChildren() - 2).getImage())) { return data; } Node prevCall = node.jjtGetChild(node.jjtGetNumChildren() - 4); String target = prevCall.jjtGetNumChildren() > 0 ? prevCall.jjtGetChild(0).getImage() : prevCall.getImage(); if (target != null && target.indexOf("trim") != -1) { addViolation(data, node); } } return data; }

Target:
public Object visit(ASTPrimaryExpression node, Object data) { if (node.jjtGetNumChildren() > 3) { if (!"isEmpty".equals(node.jjtGetChild(node.jjtGetNumChildren() - 2).getImage())) { return data; } Node prevCall = node.jjtGetChild(node.jjtGetNumChildren() - 4); String target = prevCall.jjtGetNumChildren() > 0 ? prevCall.jjtGetChild(0).getImage() : prevCall.getImage(); if (target != null && "trim".equals(target) || target.endsWith(".trim")) { addViolation(data, node); } } return data; }
Source:
public boolean equals(Object o) { if (!(o instanceof CollectionKeys)) { return false; } CollectionKeys other = (CollectionKeys) o; return defaultKeyBundle.equals(other.defaultKeyBundle) && CollectionKeys.differences(this, other).isEmpty(); }

Target:
public boolean equals(Object o) { if (!(o instanceof CollectionKeys)) { return false; } CollectionKeys other = (CollectionKeys) o; try { return defaultKeyBundle().equals(other.defaultKeyBundle()) && CollectionKeys.differences(this, other).isEmpty(); } catch (NoCollectionKeysSetException e) { return false; } }
Source:
public void testJobQueueAddingJobsAtSametime() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1) .setJobPurgeInterval(-1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); System.out.println("before add jobs"); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobBuilders = new ArrayList<>(); _driver.waitToStop(queueName, 5000L); for (int i = 0; i < 5; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } _driver.enqueueJobs(queueName, jobNames, jobBuilders); _driver.resume(queueName); System.out.println("before poll to job state"); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }

Target:
public void testJobQueueAddingJobsAtSametime() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); List<String> jobNames = new ArrayList<>(); List<JobConfig.Builder> jobBuilders = new ArrayList<>(); _driver.waitToStop(queueName, 5000L); for (int i = 0; i < 5; i++) { jobNames.add("JOB" + i); jobBuilders.add(jobBuilder); } _driver.enqueueJobs(queueName, jobNames, jobBuilders); _driver.resume(queueName); _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }
Source:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); String attributeString = (String) arguments.get("columnOrder"); ArrayList<String> attributes = new ArrayList<String>(Arrays.asList((attributeString).split(","))); Appendable appendable = writeMetacardsToCsv( Collections.singletonList(metacard), new ArrayList<AttributeDescriptor>( metacard .getMetacardType() .getAttributeDescriptors() .stream() .filter(attr -> attributes.contains(attr.getName())) .collect(Collectors.toList())), aliases); return createResponse(appendable); }

Target:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); String attributeString = arguments.get("columnOrder") != null ? (String) arguments.get("columnOrder") : ""; List<String> attributes = Arrays.asList((attributeString).split(",")); List<AttributeDescriptor> allAttributes = new ArrayList<AttributeDescriptor>(metacard.getMetacardType().getAttributeDescriptors()); List<AttributeDescriptor> descriptors = CollectionUtils.isEmpty(attributes) ? allAttributes : allAttributes .stream() .filter(attr -> attributes.contains(attr.getName())) .collect(Collectors.toList()); Appendable appendable = writeMetacardsToCsv(Collections.singletonList(metacard), descriptors, aliases); return createResponse(appendable); }
Source:
public ConnectableDevice(JSONObject json) { this(); setId(json.optString(KEY_ID, null)); setLastKnownIPAddress(json.optString(KEY_LAST_IP, null)); setFriendlyName(json.optString(KEY_FRIENDLY, null)); setModelName(json.optString(KEY_MODEL_NAME, null)); setModelNumber(json.optString(KEY_MODEL_NUMBER, null)); setLastSeenOnWifi(json.optString(KEY_LAST_SEEN, null)); setLastConnected(json.optLong(KEY_LAST_CONNECTED, 0)); setLastDetection(json.optLong(KEY_LAST_DETECTED, 0)); try { JSONObject jsonServices = json.getJSONObject(KEY_SERVICES); Iterator<?> keys = jsonServices.keys(); if(keys!=null) { while (keys.hasNext()) { String key = (String) keys.next(); if (jsonServices.get(key) instanceof JSONObject) { JSONObject serviceObject = (JSONObject) jsonServices.get(key); DeviceService service = DeviceService.getService(serviceObject); addService(service); } } } } catch (JSONException e) { e.printStackTrace(); } }

Target:
public ConnectableDevice(JSONObject json) { this(); setId(json.optString(KEY_ID, null)); setLastKnownIPAddress(json.optString(KEY_LAST_IP, null)); setFriendlyName(json.optString(KEY_FRIENDLY, null)); setModelName(json.optString(KEY_MODEL_NAME, null)); setModelNumber(json.optString(KEY_MODEL_NUMBER, null)); setLastSeenOnWifi(json.optString(KEY_LAST_SEEN, null)); setLastConnected(json.optLong(KEY_LAST_CONNECTED, 0)); setLastDetection(json.optLong(KEY_LAST_DETECTED, 0)); JSONObject jsonServices = json.optJSONObject(KEY_SERVICES); if(jsonServices!=null) { Iterator<?> keys = jsonServices.keys(); if (keys != null) { while (keys.hasNext()) { String key = (String) keys.next(); JSONObject serviceObject = jsonServices.optJSONObject(key); if (serviceObject!=null) { DeviceService service = DeviceService.getService(serviceObject); addService(service); } } } } }
Source:
public boolean equals(Airport a){ if((this.name).equals(a.name)){ return true; } else return false; }

Target:
public boolean equals(Airport a){ return (this.name).equals(a.name); }
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) return false; PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }

Target:
public boolean setValue(T newValue) { if (!validate(newValue)) { return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }
Source:
public Geometry clip(Geometry g, boolean ensureValid) { if (g == null) { return null; } Envelope geomEnvelope = g.getEnvelopeInternal(); if (geomEnvelope.isNull()) { return null; } if (bounds.contains(geomEnvelope)) { return g; } else if (!bounds.intersects(geomEnvelope)) { return null; } if (g instanceof LineString) { return clipLineString((LineString) g); } else if (g instanceof Polygon) { Polygon polygon = (Polygon) g; if (ensureValid) { GeometryFactory gf = g.getFactory(); CoordinateSequenceFactory csf = gf.getCoordinateSequenceFactory(); Polygon fence = gf.createPolygon(buildBoundsString(gf, csf), null); return g.intersection(fence); } else { return clipPolygon((Polygon) g); } } else if (g instanceof GeometryCollection) { return clipCollection((GeometryCollection) g, ensureValid); } else { return g; } }

Target:
public Geometry clip(Geometry g, boolean ensureValid) { if (g == null) { return null; } Envelope geomEnvelope = g.getEnvelopeInternal(); if (geomEnvelope.isNull()) { return null; } if (bounds.contains(geomEnvelope)) { return g; } else if (!bounds.intersects(geomEnvelope)) { return null; } if (g instanceof LineString) { return clipLineString((LineString) g); } else if (g instanceof Polygon) { if (ensureValid) { GeometryFactory gf = g.getFactory(); CoordinateSequenceFactory csf = gf.getCoordinateSequenceFactory(); Polygon fence = gf.createPolygon(buildBoundsString(gf, csf), null); return g.intersection(fence); } else { return clipPolygon((Polygon) g); } } else if (g instanceof GeometryCollection) { return clipCollection((GeometryCollection) g, ensureValid); } else { return g; } }