auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void start(ComponentContext context) { super.start(context); jsonFactoryManager = Framework.getService(JsonFactoryManager.class); codecs = new ObjectCodecService(jsonFactoryManager.getJsonFactory()); List<CodecDescriptor> descriptors = getDescriptors(XP_CODECS); descriptors.forEach(d -> { try { <START> codecs.addCodec(d.klass.newInstance()); <END> } catch (ReflectiveOperationException e) { getLog().error(e); } }); codecs.postInit(); }</code><technical_language>add getDeclaredConstructor</technical_language>

Target:
public void start(ComponentContext context) { super.start(context); jsonFactoryManager = Framework.getService(JsonFactoryManager.class); codecs = new ObjectCodecService(jsonFactoryManager.getJsonFactory()); List<CodecDescriptor> descriptors = getDescriptors(XP_CODECS); descriptors.forEach(d -> { try { codecs.addCodec(d.klass.getDeclaredConstructor().newInstance()); } catch (ReflectiveOperationException e) { getLog().error(e,e); } }); codecs.postInit(); }
Source:
<code>public DefaultTier(Tier in, TierPriceOverride override, Currency currency) { this.limits = (DefaultLimit[])in.getLimits(); this.blocks = new DefaultTieredBlock[in.getTieredBlocks().length]; for (int i = 0; i < in.getTieredBlocks().length; i++) { <START> if(override != null && override.getTieredBlockPriceOverrides().get(i)!=null) <END> blocks[i] = new DefaultTieredBlock(in.getTieredBlocks()[i], override.getTieredBlockPriceOverrides().get(i), currency) ; else blocks[i] = (DefaultTieredBlock) in.getTieredBlocks()[i]; } }</code><technical_language>remark ordering (we replacing entry i matches before)</technical_language>

Target:
public DefaultTier(Tier in, TierPriceOverride override, Currency currency) { this.limits = (DefaultLimit[])in.getLimits(); this.blocks = new DefaultTieredBlock[in.getTieredBlocks().length]; for (int i = 0; i < in.getTieredBlocks().length; i++) { if(override != null && override.getTieredBlockPriceOverrides() != null) { final TieredBlock curTieredBlock = in.getTieredBlocks()[i]; final TieredBlockPriceOverride overriddenTierBlock = Iterables.tryFind(override.getTieredBlockPriceOverrides(), new Predicate<TieredBlockPriceOverride>() { @Override public boolean apply(final TieredBlockPriceOverride input) { return (input != null && input.getUnitName().equals(curTieredBlock.getUnit().getName()) && Double.compare(input.getSize(), curTieredBlock.getSize()) == 0 && Double.compare(input.getMax(), curTieredBlock.getMax()) == 0); } }).orNull(); blocks[i] = (overriddenTierBlock != null) ? new DefaultTieredBlock(in.getTieredBlocks()[i], overriddenTierBlock, currency) : (DefaultTieredBlock) in.getTieredBlocks()[i]; } else { blocks[i] = (DefaultTieredBlock) in.getTieredBlocks()[i]; } } }
Source:
<code>public boolean barrierAnnouncement( InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) throws IOException { <START> inputs[channelInfo.getGateIdx()].convertToPriorityEvent(channelInfo.getInputChannelIdx(), sequenceNumber); <END> return false; }</code><technical_language>prioritizing savepoint barriers here? guarded NO_ALIGNMENT_TIME_OUT creation</technical_language>

Target:
public void barrierAnnouncement( InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) throws IOException { inputs[channelInfo.getGateIdx()].convertToPriorityEvent( channelInfo.getInputChannelIdx(), sequenceNumber); }
Source:
<code>public void theDeviceDebugInformationShouldBeDisabled() throws Throwable { <START> final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(PROPERTIES_MAP.put( <END> Keys.KEY_DEVICE_IDENTIFICATION, ScenarioContext.Current().get(Keys.KEY_DEVICE_IDENTIFICATION) .toString())); assertFalse("Debug mode", device.isInDebugMode()); }</code><technical_language>Is PROPERTIES_MAP.put() needed in this step? get device identification ScenarioContext? split this line increase readability</technical_language>

Target:
public void theDeviceDebugInformationShouldBeDisabled() throws Throwable { final DlmsDevice device = dlmsDeviceRepository.findByDeviceIdentification(ScenarioContext.Current() .get(Keys.KEY_DEVICE_IDENTIFICATION).toString()); assertFalse("Debug mode", device.isInDebugMode()); }
Source:
<code>public Result<Void> create(final EventTypeBase eventType) { final TopicRepository topicRepository = timelineService.getDefaultTopicRepository(); try { validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); final String topicName = topicRepository.createTopic( partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); eventType.setTopic(topicName); eventTypeRepository.saveEventType(eventType); return Result.ok(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | <START> DuplicatedEventTypeNameException e) { <END> LOG.debug("Failed to create EventType.", e); if (null != eventType.getTopic()) { try { topicRepository.deleteTopic(eventType.getTopic()); } catch (final TopicDeletionException ex) { LOG.warn("failed to delete topic for event type that failed to be created", ex); } } return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return Result.problem(e.asProblem()); } }</code><technical_language>please change log in line "113/115" error this is leaving system in inconsistent state, i.e. orphan topic in Kafka event type in DB</technical_language>

Target:
public Result<Void> create(final EventTypeBase eventType) { final TopicRepository topicRepository = timelineService.getDefaultTopicRepository(); try { validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); final String topicName = topicRepository.createTopic( partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); eventType.setTopic(topicName); boolean eventTypeCreated = false; try { eventTypeRepository.saveEventType(eventType); eventTypeCreated = true; } finally { if (!eventTypeCreated) { try { topicRepository.deleteTopic(eventType.getTopic()); } catch (final TopicDeletionException ex) { LOG.error("failed to delete topic for event type that failed to be created", ex); } } } return Result.ok(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return Result.problem(e.asProblem()); } }
Source:
<code>public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) { return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId)) <START> .isEmpty() <END> .flatMap(empty -> { if (empty) { logger.warnf("Attempt to update status of non-exist job with id %s", jobId); return Observable.empty(); } else { return session.execute(updateStatus.bind((byte) 1, timeSlice, jobId)) .doOnError(t -> logger .warnf("There was an error updating the status to finished for %s in time " + "slice [%s]", jobId, timeSlice.getTime())); } }); }</code><technical_language>switchIfEmpty(Observable.empty().doOnComplete(() -> logger.info("Nothing found!"))</technical_language>

Target:
public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) { return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId)) .flatMap(jobRow -> session.execute(updateStatus.bind((byte) 1, timeSlice, jobId)) .doOnError(t -> logger .warnf("There was an error updating the status to finished for %s in time " + "slice [%s]", jobId, timeSlice.getTime())) ) .switchIfEmpty(Observable.<ResultSet>empty().doOnCompleted(() -> logger.warnf( "Attempt to update the status of a non-exist job [%s] " + "in time slice [%s]", jobId, timeSlice.getTime()))); }
Source:
<code>public Trigger(Trigger trigger) { if (trigger == null) { throw new IllegalArgumentException("trigger must be not null"); } this.tenantId = trigger.getTenantId(); this.id = trigger.getId(); this.name = trigger.getName(); this.context = new HashMap<>(trigger.getContext()); this.tags = new HashMap<>(trigger.getTags()); this.actions = new HashSet<>(); for (TriggerAction action : trigger.getActions()) { this.actions.add(new TriggerAction(action)); } this.autoDisable = trigger.isAutoDisable(); this.autoEnable = trigger.isAutoEnable(); this.autoResolve = trigger.isAutoResolve(); this.autoResolveAlerts = trigger.isAutoResolveAlerts(); this.autoResolveMatch = trigger.getAutoResolveMatch(); this.dataIdMap = new HashMap<>(trigger.getDataIdMap() != null ? trigger.getDataIdMap() : new HashMap<>()); this.eventCategory = trigger.getEventCategory(); this.eventText = trigger.getEventText(); this.eventType = trigger.getEventType(); this.memberOf = trigger.getMemberOf(); this.description = trigger.getDescription(); this.enabled = trigger.isEnabled(); this.firingMatch = trigger.getFiringMatch(); this.type = trigger.getType(); this.source = trigger.getSource(); this.severity = trigger.getSeverity(); <START> this.match = trigger.getMatch() != null ? trigger.getMatch() : Match.ALL; <END> this.mode = trigger.getMode() != null ? trigger.getMode() : Mode.FIRING; }</code><technical_language>I this be: this.mode = trigger.getMode() != null ? trigger.getMode() : Mode.FIRING this.match = trigger.getMode() == Mode.FIRING ? trigger.getFiringMatch() : trigger.getAutoResolveMatch();</technical_language>

Target:
public Trigger(Trigger trigger) { if (trigger == null) { throw new IllegalArgumentException("trigger must be not null"); } this.tenantId = trigger.getTenantId(); this.id = trigger.getId(); this.name = trigger.getName(); this.context = new HashMap<>(trigger.getContext()); this.tags = new HashMap<>(trigger.getTags()); this.actions = new HashSet<>(); for (TriggerAction action : trigger.getActions()) { this.actions.add(new TriggerAction(action)); } this.autoDisable = trigger.isAutoDisable(); this.autoEnable = trigger.isAutoEnable(); this.autoResolve = trigger.isAutoResolve(); this.autoResolveAlerts = trigger.isAutoResolveAlerts(); this.autoResolveMatch = trigger.getAutoResolveMatch(); this.dataIdMap = new HashMap<>(trigger.getDataIdMap() != null ? trigger.getDataIdMap() : new HashMap<>()); this.eventCategory = trigger.getEventCategory(); this.eventText = trigger.getEventText(); this.eventType = trigger.getEventType(); this.memberOf = trigger.getMemberOf(); this.description = trigger.getDescription(); this.enabled = trigger.isEnabled(); this.firingMatch = trigger.getFiringMatch(); this.type = trigger.getType(); this.source = trigger.getSource(); this.severity = trigger.getSeverity(); this.mode = trigger.getMode() != null ? trigger.getMode() : Mode.FIRING; this.match = trigger.getMode() == Mode.FIRING ? trigger.getFiringMatch() : trigger.getAutoResolveMatch(); }
Source:
<code>public List<T> values(final int state) { final int size = sharedList.size(); final ArrayList<T> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { <START> T entry = sharedList.get(i); <END> if (entry.getState() == state) { list.add(entry); } } return list; }</code><technical_language>This is inherently dangerous. sharedList is a CopyOnWriteArrayList is _safe for iteration_ while is modified. However, abandon iterator, is for sharedList size decrease while in loop, sharedList.get(i) generate ArrayIndexOutOfBounds exception</technical_language>

Target:
public List<T> values(final int state) { final ArrayList<T> list = new ArrayList<>(sharedList.size()); for (final T reference : sharedList) { if (reference.getState() == state) { list.add(reference); } } return list; }
Source:
<code>private List<Config> fetchRows(TDJobOperator job) { Config resultState = state.getNestedOrSetEmpty(RESULT); try { List<String> columnNames = job.getResultColumnNames(); return job.getResult(ite -> { List<Config> rows = new ArrayList<>(); while (ite.hasNext()) { rows.add(row(columnNames, ite.next().asArrayValue())); if (rows.size() > Limits.maxWorkflowTasks()) { TaskLimitExceededException cause = new TaskLimitExceededException("Too many tasks. Limit: " + Limits.maxWorkflowTasks()); throw new TaskExecutionException(cause, TaskExecutionException.buildExceptionErrorConfig(cause)); } } return rows; }); } catch (UncheckedIOException | TDClientException e) { if (isDeterministicClientException(e)) { throw new TaskExecutionException(e, TaskExecutionException.buildExceptionErrorConfig(e)); } int retry = resultState.get(RETRY, int.class, 0); <START> resultState.set(RETRY, retry + 1); <END> int interval = (int) Math.min(INITIAL_RETRY_INTERVAL * Math.pow(2, retry), MAX_RETRY_INTERVAL); logger.warn("Failed to download result of job '{}', retrying in seconds", job.getJobId(), interval, e); throw TaskExecutionException.ofNextPolling(interval, ConfigElement.copyOf(state)); } }</code><technical_language>[minor] reduce duplicated logics later</technical_language>

Target:
private List<Config> fetchRows(TDJobOperator job) { Config resultState = state.getNestedOrSetEmpty(RESULT); try { List<String> columnNames = job.getResultColumnNames(); List<Config> result = job.getResult(ite -> { List<Config> rows = new ArrayList<>(); while (ite.hasNext()) { rows.add(row(columnNames, ite.next().asArrayValue())); if (rows.size() > Limits.maxWorkflowTasks()) { TaskLimitExceededException cause = new TaskLimitExceededException("Too many tasks. Limit: " + Limits.maxWorkflowTasks()); throw new TaskExecutionException(cause, TaskExecutionException.buildExceptionErrorConfig(cause)); } } return rows; }); resultState.remove(RETRY); return result; } catch (UncheckedIOException | TDClientException e) { if (isDeterministicClientException(e)) { throw new TaskExecutionException(e, TaskExecutionException.buildExceptionErrorConfig(e)); } int retry = resultState.get(RETRY, int.class, 0); resultState.set(RETRY, retry + 1); int interval = (int) Math.min(INITIAL_RETRY_INTERVAL * Math.pow(2, retry), MAX_RETRY_INTERVAL); logger.warn("Failed to download result of job '{}', retrying in seconds", job.getJobId(), interval, e); throw TaskExecutionException.ofNextPolling(interval, ConfigElement.copyOf(state)); } }
Source:
<code>private void restoreState(final Machine machine) { machineServiceClient.getProcesses(machine.getWorkspaceId(), machine.getId()).then(new Operation<List<MachineProcessDto>>() { @Override public void apply(List<MachineProcessDto> arg) throws OperationException { for (MachineProcessDto machineProcessDto : arg) { <START> if (machineProcessDto.getCommandLine() != null && !machineProcessDto.getCommandLine().isEmpty() <END> && machineProcessDto.getCommandLine().startsWith("#hidden")) { continue; } final CommandDto commandDto = dtoFactory.createDto(CommandDto.class) .withName(machineProcessDto.getName()) .withAttributes(machineProcessDto.getAttributes()) .withCommandLine(machineProcessDto.getCommandLine()) .withType(machineProcessDto.getType()); final CommandType type = commandTypeRegistry.getCommandTypeById(commandDto.getType()); if (type != null) { final CommandConfiguration configuration = type.getConfigurationFactory().createFromDto(commandDto); final CommandOutputConsole console = commandConsoleFactory.create(configuration, machine); console.listenToOutput(machineProcessDto.getOutputChannel()); console.attachToProcess(machineProcessDto); addCommandOutput(machine.getId(), console); } } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { notificationManager.notify(localizationConstant.failedToGetProcesses(machine.getId())); } }); }</code><technical_language>Please, Strings.isNullOrEmpty() (from Guava library)</technical_language>

Target:
private void restoreState(final Machine machine) { machineServiceClient.getProcesses(machine.getWorkspaceId(), machine.getId()).then(new Operation<List<MachineProcessDto>>() { @Override public void apply(List<MachineProcessDto> arg) throws OperationException { for (MachineProcessDto machineProcessDto : arg) { if (!Strings.isNullOrEmpty(machineProcessDto.getCommandLine()) && machineProcessDto.getCommandLine().startsWith("#hidden")) { continue; } final CommandDto commandDto = dtoFactory.createDto(CommandDto.class) .withName(machineProcessDto.getName()) .withAttributes(machineProcessDto.getAttributes()) .withCommandLine(machineProcessDto.getCommandLine()) .withType(machineProcessDto.getType()); final CommandType type = commandTypeRegistry.getCommandTypeById(commandDto.getType()); if (type != null) { final CommandConfiguration configuration = type.getConfigurationFactory().createFromDto(commandDto); final CommandOutputConsole console = commandConsoleFactory.create(configuration, machine); console.listenToOutput(machineProcessDto.getOutputChannel()); console.attachToProcess(machineProcessDto); addCommandOutput(machine.getId(), console); } } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { notificationManager.notify(localizationConstant.failedToGetProcesses(machine.getId())); } }); }
Source:
<code>private static void startBootMicroservices() throws IOException, InterruptedException, ExecutionException { if (!(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.isSet() && PASchedulerProperties.SCHEDULER_HOME.isSet())) return; String paHome = PASchedulerProperties.getAbsolutePath(System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey())); <START> String microservicesPath = PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.getValueAsString(); <END> Process iamProcess = IAMStarter.INSTANCE.start(paHome, microservicesPath); bootMicroservicesProcesses.add(iamProcess); }</code><technical_language>Change this to: String paHome = PASchedulerProperties.SCHEDULER_HOME.getValueAsString() String microservicesPath = PASchedulerProperties.getAbsolutePath( PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.getValueAsString())</technical_language>

Target:
private static void startBootMicroservices() throws IOException, InterruptedException, ExecutionException { if (!(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.isSet() && PASchedulerProperties.SCHEDULER_HOME.isSet())) return; String paHome = PASchedulerProperties.SCHEDULER_HOME.getValueAsString(); String bootMicroservicesPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_BOOT_MICROSERVICES_PATH.getValueAsString()); String bootConfigurationPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_BOOT_CONFIGURATION_PATH.getValueAsString()); Process iamProcess = IAMStarter.start(paHome, bootMicroservicesPath, bootConfigurationPath); bootMicroservicesProcesses.add(iamProcess); }
Source:
<code><START> public long getFreeMemory() throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException { <END> return (long) mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize"); }</code><technical_language>instead of throwing types of checked exceptions I sense catch in return -1 failure wdyt</technical_language>

Target:
public long getFreeMemory() { try { return (long) mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize"); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("An exception occurred during memory check", e); } } return -1; }
Source:
<code>public void transform(StructuredRecord structuredRecord, Emitter<StructuredRecord> emitter) throws Exception { outputSchema = outputSchema == null ? buildOutputSchema(structuredRecord.getSchema()) : outputSchema; <START> StringBuilder executableCommand = new StringBuilder(); <END> if (!Strings.isNullOrEmpty(config.fieldsToProcess)) { for (String inputField : Splitter.on(',').trimResults().split(config.fieldsToProcess)) { Schema inputFieldSchema = structuredRecord.getSchema().getField(inputField).getSchema(); Schema.Type inputFieldType = inputFieldSchema.isNullable() ? inputFieldSchema.getNonNullable().getType() : inputFieldSchema.getType(); if ((inputFieldType.equals(Schema.Type.STRING)) && ((String) (structuredRecord.get(inputField))).contains(" ")) { executableCommand.append("\""); executableCommand.append(structuredRecord.get(inputField)); executableCommand.append("\""); } else { executableCommand.append(structuredRecord.get(inputField)); } executableCommand.append(" "); } } if (!Strings.isNullOrEmpty(config.fixedArguments)) { executableCommand.append(config.fixedArguments); } SettableFuture<String> completion = SettableFuture.create(); executor.submit(executableCommand.toString().trim(), completion, emitter, structuredRecord, outputSchema); }</code><technical_language>This variable name is misleading. is executable command, a string representation of structure record is send external process. call structuredRecordStr</technical_language>

Target:
public void transform(StructuredRecord structuredRecord, Emitter<StructuredRecord> emitter) throws Exception { outputSchema = outputSchema == null ? buildOutputSchema(structuredRecord.getSchema()) : outputSchema; StringBuilder executableInputs = new StringBuilder(); for (String inputField : inputFieldsToProcess) { Schema inputFieldSchema = structuredRecord.getSchema().getField(inputField).getSchema(); Schema.Type inputFieldType = inputFieldSchema.isNullable() ? inputFieldSchema.getNonNullable().getType() : inputFieldSchema.getType(); if ((inputFieldType.equals(Schema.Type.STRING)) && ((String) (structuredRecord.get(inputField))).contains(" ")) { executableInputs.append("\""); executableInputs.append(structuredRecord.get(inputField)); executableInputs.append("\""); } else { executableInputs.append(structuredRecord.get(inputField)); } executableInputs.append(" "); } if (!Strings.isNullOrEmpty(config.fixedInputs)) { executableInputs.append(config.fixedInputs); } executor.submit(executableInputs.toString().trim(), emitter, structuredRecord, outputSchema); }
Source:
<code>private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build()); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(leaderElectionService); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); environment.jersey().register(new NotCurrentLeaderExceptionMapper()); <START> environment.jersey().register(new TooManyRequestsExceptionMapper()); <END> }</code><technical_language>Hmm, this bit rate limiting configuration, relevant leader election service</technical_language>

Target:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build()); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(leaderElectionService); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); environment.jersey().register(new NotCurrentLeaderExceptionMapper()); }
Source:
<code>void drawWidget (long id, NSGraphicsContext context, NSRect rect) { if (id != paintView().id) return; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return; <START> if (ignorePaint) { if (++ignorePaintCount > 1) return; } <END> GCData data = new GCData (); data.paintRect = rect; GC gc = GC.cocoa_new (this, data); Event event = new Event (); event.gc = gc; event.x = (int)rect.x; event.y = (int)rect.y; event.width = (int)rect.width; event.height = (int)rect.height; sendEvent (SWT.Paint, event); event.gc = null; gc.dispose (); }</code><technical_language>/* Allow paint event caused NSView.cacheDisplayInRect(), required for custom controls captured correctly. */ if (ignorePaint && !firstPaintEvent) { return; } firstPaintEvent = false;</technical_language>

Target:
void drawWidget (long id, NSGraphicsContext context, NSRect rect) { if (id != paintView().id) return; if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return; if (ignorePaint) { if (!firstPaint) return; firstPaint = false; } GCData data = new GCData (); data.paintRect = rect; GC gc = GC.cocoa_new (this, data); Event event = new Event (); event.gc = gc; event.x = (int)rect.x; event.y = (int)rect.y; event.width = (int)rect.width; event.height = (int)rect.height; sendEvent (SWT.Paint, event); event.gc = null; gc.dispose (); }
Source:
<code>private void <START> updateLogViewer(List<LogEntry> <END> entries) { elements.clear(); groups.clear(); group(entries); limitEntriesCount(); String titleSummary = getTitleSummary(); getDisplay().asyncExec(() -> { setContentDescription(titleSummary); if (fFilteredTree != null && !fFilteredTree.isDisposed()) { fFilteredTree.getViewer().refresh(); fFilteredTree.setEnabled(true); } }); }</code><technical_language>If I read right, enter this code asynchronously. Means, work line needed / lead some errors</technical_language>

Target:
private void updateLogViewer(List<LogEntry> entries) { elements.clear(); groups.clear(); group(entries); limitEntriesCount(); String titleSummary = getTitleSummary(); getDisplay().asyncExec(() -> { if (fFilteredTree == null || fFilteredTree.isDisposed()) { return; } setContentDescription(titleSummary); fFilteredTree.getViewer().refresh(); fFilteredTree.setEnabled(true); }); }
Source:
<code>public void rightClickBlock(GlowPlayer player, GlowBlock target, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { <START> if (placeAs != null) { <END> placeAs.rightClickBlock(player, target, face, holding, clickedLoc, hand); } }</code><technical_language>a check for if context is AIR, this more verbose check in case more contexts in future</technical_language>

Target:
public void rightClickBlock(GlowPlayer player, GlowBlock target, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { if (placeAs != null) { Context context = placeAs.getContext(); if ((context == Context.ANY || context == Context.BLOCK)) { placeAs.rightClickBlock(player, target, face, holding, clickedLoc, hand); } } }
Source:
<code>public void commitBlock(long sessionId, long blockId, boolean pinOnCreate) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { <START> LOG.debug("commitBlock: sessionId={}, blockId={}", sessionId, blockId); <END> long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { BlockStoreLocation loc = commitBlockInternal(sessionId, blockId, pinOnCreate); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onCommitBlock(sessionId, blockId, loc); } } } finally { mLockManager.unlockBlock(lockId); } }</code><technical_language>add pinOnCreate</technical_language>

Target:
public void commitBlock(long sessionId, long blockId, boolean pinOnCreate) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { LOG.debug("commitBlock: sessionId={}, blockId={}, pinOnCreate={}", sessionId, blockId, pinOnCreate); long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { BlockStoreLocation loc = commitBlockInternal(sessionId, blockId, pinOnCreate); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onCommitBlock(sessionId, blockId, loc); } } } finally { mLockManager.unlockBlock(lockId); } }
Source:
<code>public DecorateBiomeEvent(World world, Random rand, BlockPos pos) { this.world = world; this.rand = rand; this.pos = pos; <START> chunkPos = new BlockPos((pos.getX()/16)*16, (pos.getY()/16)*16, (pos.getZ()/16)*16); <END> }</code><technical_language>This calculation is accurate, pos is a random position in 4 chunks, is true origin chunk pos here. I leave chunkPos null in this case getter @Nullable. In 1.13 remove this constructor</technical_language>

Target:
public DecorateBiomeEvent(World world, Random rand, BlockPos pos) { this.world = world; this.rand = rand; this.pos = pos; this.chunkPos = new ChunkPos(pos); }
Source:
<code>public String getHibernateVersion() { if (launchConfiguration.exists()){ return getAttribute(IConsoleConfigurationLaunchConstants.HIBERNATE_VERSION, "3.5"); } <START> return null; <END> }</code><technical_language>return null, caller methods affected NPEs</technical_language>

Target:
public String getHibernateVersion() { String defaultVersion = "3.5"; if (launchConfiguration.exists()){ return getAttribute(IConsoleConfigurationLaunchConstants.HIBERNATE_VERSION, defaultVersion); } return defaultVersion; }
Source:
<code><START> public long executeLargeUpdate() throws SQLException { <END> internalExecuteUpdate(); return getLargeUpdateCount(); }</code><technical_language>please co-locate this method int executeUpdate</technical_language>

Target:
public long executeLargeUpdate() throws SQLException { executeWithFlags(QueryExecutor.QUERY_NO_RESULTS); checkNoResultUpdate(); return getLargeUpdateCount(); }
Source:
<code>protected ICommand getCallEventCommand(Classifier targetClassifier, Operation operation) { ICommand command = null; if (!callEventExist(targetClassifier.eContainer(), operation)) { try { TransactionalEditingDomain domain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(targetClassifier); CreateElementRequest createElementRequest = new CreateElementRequest(domain, targetClassifier.eContainer(), UMLElementTypes.CallEvent_2084); createElementRequest.setParameter(OWNED_OPERATION, operation); IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetClassifier); if <START> (provider != null) { <END> ICommand createCommand = provider.getEditCommand(createElementRequest); if (null != createCommand) { command = createCommand; } } } catch (ServiceException e) { Activator.log.error(e); } } return command; }</code><technical_language>constant variable</technical_language>

Target:
protected ICommand getCallEventCommand(Classifier targetClassifier, Operation operation) { ICommand command = null; if (!callEventExist(targetClassifier.eContainer(), operation)) { try { TransactionalEditingDomain domain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(targetClassifier); CreateElementRequest createElementRequest = new CreateElementRequest(domain, targetClassifier.eContainer(), UMLElementTypes.CallEvent_2084); createElementRequest.setParameter(OWNED_OPERATION, operation); IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetClassifier); if (null != provider) { ICommand createCommand = provider.getEditCommand(createElementRequest); if (null != createCommand) { command = createCommand; } } } catch (ServiceException e) { Activator.log.error(e); } } return command; }
Source:
<code>public String generateFieldInfoInputs(Class<?> cls) { java.lang.reflect.Field[] fields = cls.getDeclaredFields(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field f = fields[i]; Class<?> c = ClassUtils.primitiveToWrapper(f.getType()); sb.append(f.getName() + FIELD_SEPARATOR + f.getName() + FIELD_SEPARATOR + c.getSimpleName().toUpperCase() + RECORD_SEPARATOR); } <START> return sb.substring(0, sb.length() - 1).toString(); <END> }</code><technical_language>toString() needed</technical_language>

Target:
private String generateFieldInfoInputs(Class<?> cls) { java.lang.reflect.Field[] fields = cls.getDeclaredFields(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field f = fields[i]; Class<?> c = ClassUtils.primitiveToWrapper(f.getType()); sb.append(f.getName()).append(FIELD_SEPARATOR).append(f.getName()).append(FIELD_SEPARATOR) .append(c.getSimpleName().toUpperCase()).append(RECORD_SEPARATOR); } return sb.substring(0, sb.length() - 1); }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); <START> builder.append("\n"); <END> builder.append(super.toString()); builder.append("\n"); ObjectDescriptor.toStringBuilder(checkpointsUuids, builder); ObjectDescriptor.toStringBuilder(error, builder); return builder.toString(); }</code><technical_language>Newline beginning of string? For readability</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append(super.toString()); builder.append("\n"); ObjectDescriptor.toStringBuilder(checkpointsIds, builder); ObjectDescriptor.toStringBuilder(error, builder); return builder.toString(); }
Source:
<code><START> protected AbstractSerialPort(String port, int baudRate, int receiveTimeout) { <END> this.port = port; this.baudRate = baudRate; this.receiveTimeout = receiveTimeout; }</code><technical_language>Do want do this in constructor connect() method handle exception stuff</technical_language>

Target:
protected AbstractSerialPort(String port, int baudRate, int receiveTimeout) { this(port, new SerialPortParameters(baudRate, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY, DEFAULT_FLOW_CONTROL), receiveTimeout); }
Source:
<code>private void verifyRevenueScheduleTypeWithInvalidValue( String invalidValue ){ Subscription subscription = new Subscription(); try{ subscription.setRevenueScheduleType( invalidValue ); <START> assertEquals(true, false ); <END> } catch( IllegalArgumentException iae ){ } }</code><technical_language>Nit: assertFail() instead</technical_language>

Target:
private void verifyRevenueScheduleTypeWithInvalidValue( String invalidValue ){ Subscription subscription = new Subscription(); try{ subscription.setRevenueScheduleType( invalidValue ); Assert.fail(); } catch( IllegalArgumentException iae ){ } }
Source:
<code>public void testComposedStreamThatIsItselfDeployable() throws IOException { FileSink sink = newFileSink(); HttpSource httpSource = newHttpSource(); String streamName = getRandomStreamName(); stream().createDontDeploy(streamName, "%s | filter --expression=payload.contains('${word:foo}') | %s", httpSource, sink); <START> stream().create(getRandomStreamName(), streamName); <END> httpSource.postData("foobar"); httpSource.postData("hello"); httpSource.postData("custardfoo"); httpSource.postData("whisk"); assertThat(sink, eventually(hasContentsThat(equalTo("foobar\ncustardfoo\n")))); }</code><technical_language>this is missing final 'sink' argument</technical_language>

Target:
public void testComposedStreamThatIsItselfDeployable() throws IOException { FileSink sink = newFileSink(); HttpSource httpSource = newHttpSource(); String streamName = getStreamName(); stream().createDontDeploy(streamName, "%s | filter --expression=payload.contains('${word:foo}') | %s", httpSource, sink); stream().create(getStreamName(), streamName); httpSource.postData("foobar"); httpSource.postData("hello"); httpSource.postData("custardfoo"); httpSource.postData("whisk"); assertThat(sink, eventually(hasContentsThat(equalTo("foobar\ncustardfoo\n")))); }
Source:
<code>public void testMultipleUpdates() throws Exception { Subscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }); <START> Thread.sleep(1000); <END> Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertNotNull(ref); ObjectId master = triggerUpdate("refs/heads/master"); ObjectId branch1 = createRef( "refs/heads/master", "refs/heads/branch1"); branch1 = triggerUpdate("refs/heads/branch1"); master = triggerUpdate("refs/heads/master"); Thread.sleep(1000); ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(master, ref.getObjectId()); ref = r.getRef("refs/pubsub/origin/heads/branch1"); assertEquals(branch1, ref.getObjectId()); }</code><technical_language>Thread.sleep</technical_language>

Target:
public void testMultipleUpdates() throws Exception { setUpPublisher(1); TestSubscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }, 5); connectLatch.await(); ObjectId master = triggerUpdate("refs/heads/master"); ObjectId branch1 = createBranch( "refs/heads/master", "refs/heads/branch1"); branch1 = triggerUpdate("refs/heads/branch1"); master = triggerUpdate("refs/heads/master"); client1.await(); Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(master, ref.getObjectId()); ref = r.getRef("refs/pubsub/origin/heads/branch1"); assertEquals(branch1, ref.getObjectId()); }
Source:
<code>private boolean executeCommand(String command) { <START> ICommandService commandService = getCommandService(); <END> IHandlerService handlerService = getHandlerService(); if (commandService == null || handlerService == null) { CheatSheetPlugin.logError( "Could not get ICommandService or IHandlerService while trying to execute: " + command, null); return false; } try { ParameterizedCommand pCommand = commandService.deserialize(command); handlerService.executeCommand(pCommand, null); return true; } catch (CommandException e) { CheatSheetPlugin.logError("Could not execute command: " + command, e); return false; } }</code><technical_language>IWorkbench.getService(ICommandService.class)</technical_language>

Target:
private boolean executeCommand(String command) { ICommandService commandService = PlatformUI.getWorkbench().getService(ICommandService.class); IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); if (commandService == null || handlerService == null) { CheatSheetPlugin.logError( "Could not get ICommandService or IHandlerService while trying to execute: " + command, null); return false; } try { ParameterizedCommand pCommand = commandService.deserialize(command); handlerService.executeCommand(pCommand, null); return true; } catch (CommandException e) { CheatSheetPlugin.logError("Could not execute command: " + command, e); return false; } }
Source:
<code>public ConnectionType setNetworkConnection( ConnectionType type) { <START> Map<String, Integer> mode = ImmutableMap.of("type", type.getBitMask()); <END> return new ConnectionType(((Number) executeMethod.execute(DriverCommand.SET_NETWORK_CONNECTION, ImmutableMap .of("parameters", mode))) .intValue()); }</code><technical_language>change this instead type.toString() expose getBitMask in enum. (Alternatively type.hashCode() feel nice)</technical_language>

Target:
public ConnectionType setNetworkConnection( ConnectionType type) { Map<String, ConnectionType> mode = ImmutableMap.of("type", type); return new ConnectionType(((Number) executeMethod.execute(DriverCommand.SET_NETWORK_CONNECTION, ImmutableMap .of("parameters", mode))) .intValue()); }
Source:
<code>public List<String> getGroupNamesForUser(String userName) { if (userName == null) { <START> return new ArrayList<>(); <END> } AuthUser user = getUser(userName); if (user == null) { return new ArrayList<>(); } return user.getGroupNames(); }</code><technical_language>construct a list return Collections.emptyList() ImmutableList.of();</technical_language>

Target:
public List<String> getGroupNamesForUser(String userName) { if (userName == null) { return Collections.emptyList(); } AuthUser user = getUser(userName); if (user == null) { return Collections.emptyList(); } return user.getGroupNames(); }
Source:
<code><START> private String generateName(BaseArtifactType artifact) { <END> String name = ""; String artifactId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID); String version = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION); String snapshotId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID); String classifier = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_CLASSIFIER); String type = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_TYPE); if (artifact.getName().contains(artifactId)) { name += artifactId; if (version.contains("SNAPSHOT")) { if (StringUtils.isNotBlank(snapshotId)) { name += MAVEN_SEPARATOR + version.substring(0, version.indexOf("SNAPSHOT")) + snapshotId; } else { name += MAVEN_SEPARATOR + version; } } else { name += MAVEN_SEPARATOR + version; } if (classifier != null) { name += MAVEN_SEPARATOR + classifier; } name += MAVEN_FILE_EXTENSION_SEPARATOR + type; return name; } else { return artifact.getName(); } }</code><technical_language>Please StringBuilder instead of String concats</technical_language>

Target:
private String generateName(BaseArtifactType artifact) { String artifactId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID); String version = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION); String snapshotId = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID); String classifier = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_CLASSIFIER); String type = SrampModelUtils.getCustomProperty(artifact, JavaModel.PROP_MAVEN_TYPE); if (artifact.getName().contains(artifactId)) { StringBuilder name = new StringBuilder(""); name.append(artifactId); if (version.contains("SNAPSHOT")) { if (StringUtils.isNotBlank(snapshotId)) { name.append(MAVEN_SEPARATOR).append(version.substring(0, version.indexOf("SNAPSHOT"))).append(snapshotId); } else { name.append(MAVEN_SEPARATOR).append(version); } } else { name.append(MAVEN_SEPARATOR).append(version); } if (classifier != null) { name.append(MAVEN_SEPARATOR).append(classifier); } name.append(MAVEN_FILE_EXTENSION_SEPARATOR).append(type); return name.toString(); } else { return artifact.getName(); } }
Source:
<code>public <V extends DirectiveValue, T extends Directive<V>> void addDirective(@Nonnull T d) { Directive<? extends DirectiveValue> directive = this.directives.get(d.getClass()); if (directive == null) { this.directives.put(d.getClass(), d); this.expandDefaultSrc(); this.resolveSelf(); this.optimise(); } else { <START> throw new IllegalArgumentException( <END> "Policy contains more than one " + directive.getName() + " directive. All but the first instance will be ignored."); } }</code><technical_language>This throwing allowed spec. warning handled parser</technical_language>

Target:
public <V extends DirectiveValue, T extends Directive<V>> void addDirective(@Nonnull T d) { Directive<? extends DirectiveValue> directive = this.directives.get(d.getClass()); if (directive == null) { this.directives.put(d.getClass(), d); this.expandDefaultSrc(); this.resolveSelf(); this.optimise(); } }
Source:
<code>public void putAll(Map<? extends String, ? extends List<Object>> map) { for (Map.Entry<? extends String, ? extends List<Object>> entry : map.entrySet()) { List<Object> objs = entry.getValue(); <START> putResponseHeader(entry.getKey(), objs.get(0)); END> for (int i=1; i < objs.size(); i++) { add(entry.getKey(), objs.get(i)); } } }</code><technical_language>This is fail in case get empty list (yes, edge case, still... a check size safe). empty list a special meaning</technical_language>

Target:
public void putAll(Map<? extends String, ? extends List<Object>> map) { for (Map.Entry<? extends String, ? extends List<Object>> entry : map.entrySet()) { List<Object> objs = entry.getValue(); if (!objs.isEmpty()) { putResponseHeader(entry.getKey(), objs.get(0)); for (int i = 1; i < objs.size(); i++) { add(entry.getKey(), objs.get(i)); } } } }
Source:
<code>public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new SourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fSourceViewer.setEditable(false); Control sourceViewerControl= fSourceViewer.getControl(); sourceViewerControl.setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)); IPreferenceStore preferenceStore= EditorsUI.getPreferenceStore(); Color bg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, sourceViewerControl.getDisplay()); <START> Color fg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, sourceViewerControl.getDisplay()); <END> sourceViewerControl.setBackground(bg); sourceViewerControl.setForeground(fg); disposeColors(); fForegroundColor= fg; fBackgroundColor= bg; sourceViewerControl.addDisposeListener(e -> disposeColors()); fPane.setContent(sourceViewerControl); }</code><technical_language>selection foreground background</technical_language>

Target:
public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new SourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fSourceViewer.setEditable(false); Control sourceViewerControl= fSourceViewer.getControl(); sourceViewerControl.setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)); IPreferenceStore preferenceStore= EditorsUI.getPreferenceStore(); Color bg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, sourceViewerControl.getDisplay()); Color fg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, sourceViewerControl.getDisplay()); Color selBg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND, sourceViewerControl.getDisplay()); Color selFg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND, sourceViewerControl.getDisplay()); sourceViewerControl.setBackground(bg); sourceViewerControl.setForeground(fg); if (sourceViewerControl instanceof StyledText) { StyledText styledText = (StyledText) sourceViewerControl; styledText.setSelectionBackground(selBg); styledText.setSelectionForeground(selFg); } disposeColors(); fForegroundColor= fg; fBackgroundColor= bg; fSelectionForegroundColor= selFg; fSelectionBackgroundColor= selBg; sourceViewerControl.addDisposeListener(e -> disposeColors()); fPane.setContent(sourceViewerControl); }
Source:
<code>protected ReferencedEnvelope calculateBounds() { ReferencedEnvelope extent = ReferencedEnvelope.create( getSchema().getCoordinateReferenceSystem() ); for( SimpleFeature feature : list ){ <START> if( feature == null ) <END> continue; ReferencedEnvelope bbox = ReferencedEnvelope.reference( feature.getBounds() ); if( bbox == null || bbox.isEmpty() || bbox.isNull() ) continue; extent.expandToInclude( bbox ); } return extent; }</code><technical_language>tend braces placing a statement a seperate line, check developers guide for sun-java-conventions + 100 cols</technical_language>

Target:
protected ReferencedEnvelope calculateBounds() { ReferencedEnvelope extent = ReferencedEnvelope.create( getSchema().getCoordinateReferenceSystem() ); for( SimpleFeature feature : list ){ if( feature == null ) { continue; } ReferencedEnvelope bbox = ReferencedEnvelope.reference( feature.getBounds() ); if( bbox == null || bbox.isEmpty() || bbox.isNull() ) { continue; } extent.expandToInclude( bbox ); } return extent; }