auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ZKDatabase(FileTxnSnapLog snapLog) { dataTree = createDataTree(); sessionsWithTimeouts = new ConcurrentHashMap<Long, Integer>(); this.snapLog = snapLog; try { snapshotSizeFactor = Double.parseDouble( System.getProperty(SNAPSHOT_SIZE_FACTOR, Double.toString(DEFAULT_SNAPSHOT_SIZE_FACTOR))); if (snapshotSizeFactor > 1) { snapshotSizeFactor = DEFAULT_SNAPSHOT_SIZE_FACTOR; LOG.warn("The configured is invalid, going to use " + "the default {}", SNAPSHOT_SIZE_FACTOR, DEFAULT_SNAPSHOT_SIZE_FACTOR); } } catch (NumberFormatException e) { LOG.error("Error parsing {}, using default value {}", SNAPSHOT_SIZE_FACTOR, DEFAULT_SNAPSHOT_SIZE_FACTOR); snapshotSizeFactor = DEFAULT_SNAPSHOT_SIZE_FACTOR; } LOG.info("{} = {}", SNAPSHOT_SIZE_FACTOR, snapshotSizeFactor); try { commitLogCount = Integer.parseInt( System.getProperty(COMMIT_LOG_COUNT, Integer.toString(DEFAULT_COMMIT_LOG_COUNT))); if (commitLogCount < DEFAULT_COMMIT_LOG_COUNT) { commitLogCount = DEFAULT_COMMIT_LOG_COUNT; LOG.warn("The configured " + COMMIT_LOG_COUNT + " is less than the recommended " + DEFAULT_COMMIT_LOG_COUNT + ", going to use the recommended one"); } } catch (NumberFormatException e) { LOG.error("Error parsing " + COMMIT_LOG_COUNT + " - use default value " + DEFAULT_COMMIT_LOG_COUNT); commitLogCount = DEFAULT_COMMIT_LOG_COUNT; } LOG.info(COMMIT_LOG_COUNT + "=" + commitLogCount); }

Target:
public ZKDatabase(FileTxnSnapLog snapLog) { dataTree = createDataTree(); sessionsWithTimeouts = new ConcurrentHashMap<Long, Integer>(); this.snapLog = snapLog; try { snapshotSizeFactor = Double.parseDouble( System.getProperty(SNAPSHOT_SIZE_FACTOR, Double.toString(DEFAULT_SNAPSHOT_SIZE_FACTOR))); if (snapshotSizeFactor > 1) { snapshotSizeFactor = DEFAULT_SNAPSHOT_SIZE_FACTOR; LOG.warn("The configured is invalid, going to use the default {}", SNAPSHOT_SIZE_FACTOR, DEFAULT_SNAPSHOT_SIZE_FACTOR); } } catch (NumberFormatException e) { LOG.error("Error parsing {}, using default value {}", SNAPSHOT_SIZE_FACTOR, DEFAULT_SNAPSHOT_SIZE_FACTOR); snapshotSizeFactor = DEFAULT_SNAPSHOT_SIZE_FACTOR; } LOG.info("{} = {}", SNAPSHOT_SIZE_FACTOR, snapshotSizeFactor); try { commitLogCount = Integer.parseInt( System.getProperty(COMMIT_LOG_COUNT, Integer.toString(DEFAULT_COMMIT_LOG_COUNT))); if (commitLogCount < DEFAULT_COMMIT_LOG_COUNT) { commitLogCount = DEFAULT_COMMIT_LOG_COUNT; LOG.warn("The configured commitLogCount is less than the recommended {}" + ", going to use the recommended one", COMMIT_LOG_COUNT, DEFAULT_COMMIT_LOG_COUNT); } } catch (NumberFormatException e) { LOG.error("Error parsing - use default value {}", COMMIT_LOG_COUNT, DEFAULT_COMMIT_LOG_COUNT); commitLogCount = DEFAULT_COMMIT_LOG_COUNT; } LOG.info("{}={}", COMMIT_LOG_COUNT, commitLogCount); }
Source:
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException { super.populateModel(context, operation, resource); DataSourceStatisticsService.registerStatisticsResources(resource); boolean enabled = ! operation.hasDefined(ENABLED.getName()) || ENABLED.resolveModelAttribute(context, resource.getModel()).asBoolean(); if (enabled) { context.addStep(new DataSourceEnable(this instanceof XaDataSourceAdd), OperationContext.Stage.MODEL); } }

Target:
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException { DataSourceStatisticsService.registerStatisticsResources(resource); super.populateModel(context, operation, resource); }
Source:
private void initGC(StyledText textWidget, Color color, GC gc) { gc.setForeground(color); gc.setBackground(textWidget.getBackground()); FontRegistry fontRegistry= JFaceResources.getFontRegistry(); Font font= fontRegistry.get("org.eclipse.ui.editors.codemining"); gc.setFont(font); }

Target:
private void initGC(StyledText textWidget, Color color, GC gc) { gc.setForeground(color); gc.setBackground(textWidget.getBackground()); FontRegistry fontRegistry= JFaceResources.getFontRegistry(); Font font= fontRegistry.get("org.eclipse.ui.editors.codemining"); if (font != null) { gc.setFont(font); } else { gc.setFont(textWidget.getFont()); } }
Source:
protected Event doTake() throws InterruptedException { type = TransactionType.TAKE; try { if (!transFailoverController.get().uuid.equals(channelUUID)) { transFailoverController.remove(); LOGGER.info("UUID mismatch, creating new transFailoverController"); } } catch (Exception ex) { LOGGER.warn("Error while get multi message", ex); } if (!events.isPresent()) { events = Optional.of(new LinkedList<Event>()); } Event e; if (!transFailoverController.get().failedEvents.isEmpty()) { e = transFailoverController.get().failedEvents.removeFirst(); } else { try { long startTime = System.nanoTime(); String message = redisDao.rpop(queue_key); while (message == null || message.isEmpty()) { Thread.sleep(1000); message = redisDao.rpop(queue_key); } long endTime = System.nanoTime(); counter.addToRedisEventGetTimer((endTime - startTime) / (1000 * 1000)); if (parseAsFlumeEvent) { ByteArrayInputStream in = new ByteArrayInputStream( message.getBytes()); decoder = DecoderFactory.get().directBinaryDecoder(in, decoder); if (!reader.isPresent()) { reader = Optional .of(new SpecificDatumReader<AvroFlumeEvent>( AvroFlumeEvent.class)); } AvroFlumeEvent event = reader.get().read(null, decoder); e = EventBuilder.withBody(event.getBody().array(), toStringMap(event.getHeaders())); } else { e = EventBuilder.withBody(message.getBytes(), Collections.EMPTY_MAP); } } catch (Exception ex) { LOGGER.warn("Error while getting events from redis", ex); throw new ChannelException( "Error while getting events from redis", ex); } } eventTaken = true; events.get().add(e); return e; }

Target:
protected Event doTake() throws InterruptedException { type = TransactionType.TAKE; try { if (!transFailoverController.get().uuid.equals(channelUUID)) { transFailoverController.remove(); LOGGER.info("UUID mismatch, creating new transFailoverController"); } } catch (Exception ex) { LOGGER.warn("Error while get multi message", ex); } Event e; if (!transFailoverController.get().failedEvents.isEmpty()) { e = transFailoverController.get().failedEvents.removeFirst(); } else { try { long startTime = System.nanoTime(); Long queueLength = redisOperator.llen(queue_key); while (queueLength == null || queueLength == 0) { Thread.sleep(1000); queueLength = redisOperator.llen(queue_key); } long endTime = System.nanoTime(); counter .addToRedisEventGetTimer((endTime - startTime) / (1000 * 1000)); String message = redisOperator.rpop(queue_key); if (parseAsFlumeEvent) { ByteArrayInputStream in = new ByteArrayInputStream( message.getBytes()); decoder = DecoderFactory.get().directBinaryDecoder(in, decoder); AvroFlumeEvent event = reader.read(null, decoder); e = EventBuilder.withBody(event.getBody().array(), toStringMap(event.getHeaders())); } else { e = EventBuilder.withBody(message.getBytes(), Collections.EMPTY_MAP); } } catch (Exception ex) { LOGGER.warn("Error while getting events from redis", ex); throw new ChannelException("Error while getting events from redis", ex); } } eventTaken = true; events.add(e); return e; }
Source:
private GroupRepresentation getOrCreateOTPRoleInGroup() { try { return testRealmResource().groups().groups("otp_group",0,1).get(0); } catch (NotFoundException | IndexOutOfBoundsException ex ) { GroupRepresentation group = new GroupRepresentation(); group.setName("otp_group"); RoleRepresentation role = getOrCreateOTPRole(); testRealmResource().groups().add(group); GroupRepresentation groupRep = testRealmResource().groups().groups("otp_group",0,1).get(0); testRealmResource().groups().group(groupRep.getId()).roles().realmLevel().add(Arrays.asList(role)); return testRealmResource().groups().groups("otp_group",0,1).get(0); } }

Target:
private GroupRepresentation getOrCreateOTPRoleInGroup() { GroupRepresentation group = new GroupRepresentation(); group.setName("otp_group"); RoleRepresentation role = getOrCreateOTPRole(); testRealmResource().groups().add(group); GroupRepresentation groupRep = testRealmResource().groups().groups("otp_group",0,1).get(0); testRealmResource().groups().group(groupRep.getId()).roles().realmLevel().add(Arrays.asList(role)); return testRealmResource().groups().groups("otp_group",0,1).get(0); }
Source:
private static Predicate<MetricName> withTagIsCurrentSuspectedLeader(boolean currentLeader) { return metricName -> Optional.ofNullable(metricName.safeTags().get(AtlasDbMetricNames.TAG_CURRENT_SUSPECTED_LEADER)) .filter(x -> x.equals(String.valueOf(currentLeader))) .isPresent(); }

Target:
private static Predicate<MetricName> withTagIsCurrentSuspectedLeader(boolean currentLeader) { return metricName -> Optional.ofNullable(metricName.safeTags().get(AtlasDbMetricNames.TAG_CURRENT_SUSPECTED_LEADER)) .filter(String.valueOf(currentLeader)::equals) .isPresent(); }
Source:
public static SharedPackageListingsSettings instance() { RequestResolver resolver = resolvers.values() .stream() .filter(RequestResolver::isActive) .findFirst() .orElse(null); if (resolver != null) { return instance(resolver.resolve()); } return null; }

Target:
public static SharedPackageListingsSettings instance() { return resolvers.values() .stream() .filter(RequestResolver::isActive) .findFirst() .map(RequestResolver::resolve) .map(SharedPackageListingsSettings::instance) .orElse(null); }
Source:
protected static String getPopulatedErrorMessage(String messageTemplate, String userInput, String fieldName, String errorReason, int maxLength) throws Exception { return (String) invokeMethod(FieldValidator.class, "getPopulatedErrorMessage", new Class<?>[] { String.class, String.class, String.class, String.class, int.class }, null, new Object[] { messageTemplate, userInput, fieldName, errorReason, maxLength }); }

Target:
protected static String getPopulatedErrorMessage(String messageTemplate, String userInput, String fieldName, String errorReason, int maxLength) throws ReflectiveOperationException { return (String) invokeMethod(FieldValidator.class, "getPopulatedErrorMessage", new Class<?>[] { String.class, String.class, String.class, String.class, int.class }, null, new Object[] { messageTemplate, userInput, fieldName, errorReason, maxLength }); }
Source:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (formats) { stime = YEAR_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }

Target:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (YEAR_FORMAT) { stime = YEAR_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }
Source:
public void test() { assertEquals( "HHH000485: Illegally attempted to associate a proxy for entity [org.hibernate.session.AssociateEntityWithTwoSessionsTest$Location] with id [1] with two open sessions.", triggerable.triggerMessage() ); }

Target:
public void test() { assertEquals( "HHH000490: Using JtaPlatform implementation: [org.hibernate.testing.jta.TestingJtaPlatformImpl]", triggerable.triggerMessage() ); }
Source:
private io.github.resilience4j.bulkhead.BulkheadConfig buildBulkheadConfig(io.github.resilience4j.bulkhead.BulkheadConfig.Builder builder, InstanceProperties instanceProperties) { if (instanceProperties.getMaxConcurrentCalls() != null) { builder.maxConcurrentCalls(instanceProperties.getMaxConcurrentCalls()); } if (instanceProperties.getMaxWaitTime() != null) { builder.maxWaitTime(instanceProperties.getMaxWaitTime()); } if (instanceProperties.getMaxWaitDuration() != null) { builder.maxWaitTime(instanceProperties.getMaxWaitDuration().toMillis()); } return builder.build(); }

Target:
private io.github.resilience4j.bulkhead.BulkheadConfig buildBulkheadConfig(io.github.resilience4j.bulkhead.BulkheadConfig.Builder builder, InstanceProperties instanceProperties) { if (instanceProperties.getMaxConcurrentCalls() != null) { builder.maxConcurrentCalls(instanceProperties.getMaxConcurrentCalls()); } if (instanceProperties.getMaxWaitDuration() != null) { builder.maxWaitTimeDuration(instanceProperties.getMaxWaitDuration()); } return builder.build(); }
Source:
public boolean performFinish() { try { final IFile modelFile = newFileCreationPage.getModelFile(); WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor progressMonitor) { try { ResourceSet resourceSet = new ResourceSetImpl(); URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true); Resource resource = resourceSet.createResource(fileURI); CyberPhysicalSystem rootObject = createModel(); resource.getContents().add(rootObject); Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); resource.save(options); } catch (Exception exception) { log(exception); } finally { progressMonitor.done(); } } }; getContainer().run(false, false, operation); BasicNewResourceWizard.selectAndReveal(modelFile, workbench.getActiveWorkbenchWindow()); if (constraintPage.shouldOpenModel()) IDE.openEditor(workbench.getActiveWorkbenchWindow().getActivePage(), modelFile, true); return true; } catch (Exception exception) { log(exception); return false; } }

Target:
public boolean performFinish() { try { final IFile modelFile = ResourcesPlugin.getWorkspace().getRoot().getFile(newFileCreationPage.getModelRelativePath()); WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor progressMonitor) throws CoreException { try { ResourceSet resourceSet = new ResourceSetImpl(); URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true); Resource resource = resourceSet.createResource(fileURI); CyberPhysicalSystem rootObject = createModel(); resource.getContents().add(rootObject); Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); resource.save(options); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, CPSApplicationUIPlugin.PLUGIN_ID, "Error creating file " + modelFile.getName(), e)); } finally { progressMonitor.done(); } } }; getContainer().run(false, false, operation); BasicNewResourceWizard.selectAndReveal(modelFile, workbench.getActiveWorkbenchWindow()); if (constraintPage.shouldOpenModel()) IDE.openEditor(workbench.getActiveWorkbenchWindow().getActivePage(), modelFile, true); return true; } catch (InvocationTargetException e) { log(e); MessageDialog.openError(getShell(), "Error creating file", e.getTargetException().getMessage()); return false; } catch (Exception e) { log(e); MessageDialog.openError(getShell(), "Error creating file", e.getMessage()); return false; } }
Source:
public Long save(GlobalId globalId) { Long lookup = getIfExists(globalId); if (lookup != null) { return lookup; } return insert(globalId); }

Target:
public long save(GlobalId globalId) { Optional<Long> lookup = getIfExists(globalId); if(lookup.isEmpty()){ return insert(globalId); } return lookup.get(); }
Source:
public Builder() { super(new int[]{1, 1, 1}, new int[]{1, 1, 1}, new int[]{0, 0, 0}, new int[]{0, 0, 0}); }

Target:
public Builder() { super(new int[]{2, 2, 2}, new int[]{1, 1, 1}, new int[]{0, 0, 0}, new int[]{1, 1, 1}, 3); }
Source:
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; return this; }

Target:
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis); return this; }
Source:
void verifyData(HashMap<ConflictTxStream, Long> recordMap, SequencerServerCache cache) { for (ConflictTxStream oldKey : recordMap.keySet()) { long oldAddress = oldKey.txVersion; if (oldAddress < cache.firstAddress()) continue; ConflictTxStream key = new ConflictTxStream(oldKey.getStreamId(), oldKey.getConflictParam(), 0); log.debug("address " + cache.getIfPresent(key) + " expected " + oldAddress); assertThat(cache.getIfPresent(key) == oldAddress); } }

Target:
void verifyData(HashMap<ConflictTxStream, Long> recordMap, SequencerServerCache cache) { for (ConflictTxStream oldKey : recordMap.keySet()) { long oldAddress = oldKey.txVersion; if (oldAddress < cache.firstAddress()) { continue; } ConflictTxStream key = new ConflictTxStream(oldKey.getStreamId(), oldKey.getConflictParam(), 0); log.debug("address " + cache.get(key) + " expected " + oldAddress); assertThat(cache.get(key) == oldAddress); } }
Source:
public void testList() { appliances = serverApplianceApi().list(); currentAppliance = appliances.get(0); Assert.assertTrue(appliances.size() > 0); }

Target:
public void testList() { appliances = serverApplianceApi().list(); Assert.assertTrue(appliances.size() > 0); currentAppliance = appliances.get(0); }
Source:
public boolean handle(String[] args) throws RandoopTextuiException { try { String[] nonargs = foptions.parse(args); if (nonargs.length > 0) { throw new Options.ArgException("Unrecognized arguments: " + Arrays.toString(nonargs)); } } catch (Options.ArgException ae) { usage("while parsing command-line arguments: %s", ae.getMessage()); } if (Minimize.suitepath == null) { System.out.println("You must specify an input file path."); System.out.println("Use the --suitepath option."); System.exit(1); } else if (Minimize.testsuitetimeout <= 0) { System.out.println("You must specify a positive timeout value."); System.exit(1); } return mainMinimize(suitepath, suiteclasspath, testsuitetimeout); }

Target:
public boolean handle(String[] args) throws RandoopTextuiException { try { String[] nonargs = foptions.parse(args); if (nonargs.length > 0) { throw new Options.ArgException("Unrecognized arguments: " + Arrays.toString(nonargs)); } } catch (Options.ArgException ae) { usage("while parsing command-line arguments: %s", ae.getMessage()); } if (Minimize.suitepath == null) { System.out.println("You must specify an input file path."); System.out.println("Use the --suitepath option."); System.exit(1); } if (!FilenameUtils.getExtension(Minimize.suitepath).equals("java")) { System.out.println("The input file must be a Java file."); System.exit(1); } if (Minimize.testsuitetimeout <= 0) { System.out.println("You must specify a positive timeout value."); System.exit(1); } return mainMinimize(suitepath, suiteclasspath, testsuitetimeout, verboseminimizer); }
Source:
public Set<Type> thrownExceptions() { if (visitedUnknown || thrownExceptions.stream().anyMatch(Type::isUnknown)) { return null; } if (methodTree.is(Tree.Kind.CONSTRUCTOR) && !visitedOtherConstructor) { Optional<Symbol.MethodSymbol> constructor = getImplicitlyCalledConstructor(methodTree); constructor.ifPresent(c -> thrownExceptions.addAll(c.thrownTypes())); } return thrownExceptions; }

Target:
public Set<Type> thrownExceptions() { if (visitedUnknown || thrownExceptions.stream().anyMatch(Type::isUnknown)) { return null; } if (methodTree.is(Tree.Kind.CONSTRUCTOR) && !visitedOtherConstructor) { getImplicitlyCalledConstructor(methodTree) .map(Symbol.MethodSymbol::thrownTypes) .ifPresent(thrownExceptions::addAll); } return thrownExceptions; }
Source:
public Response getHeaders( @PathParam("sourceid") String sourceid, @PathParam("id") String id, @Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) { try { Response.ResponseBuilder responseBuilder; String filename = null; final BinaryContent content = catalogService.getHeaders( sourceid, id, uriInfo.getAbsolutePath(), uriInfo.getQueryParameters()); if (content == null) { return Response.status(Status.NOT_FOUND) .entity("<pre>Unable to retrieve requested metacard.</pre>") .type(MediaType.TEXT_HTML) .build(); } responseBuilder = Response.noContent(); responseBuilder.header(HEADER_ACCEPT_RANGES, BYTES); if (content instanceof Resource) { filename = ((Resource) content).getName(); } else { String fileExtension = catalogService.getFileExtensionForMimeType(content.getMimeTypeValue()); if (StringUtils.isNotBlank(fileExtension)) { filename = id + fileExtension; } } if (StringUtils.isNotBlank(filename)) { LOGGER.debug("filename: {}", filename); responseBuilder.header(HEADER_CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); } long size = content.getSize(); if (size > 0) { responseBuilder.header(HEADER_CONTENT_LENGTH, size); } return responseBuilder.build(); } catch (CatalogServiceException e) { return createBadRequestResponse(e.getMessage()); } }

Target:
public Response getHeaders( @PathParam("sourceid") String sourceid, @PathParam("id") String id, @Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) { try { Response.ResponseBuilder responseBuilder; final BinaryContent content = catalogService.getHeaders( sourceid, id, uriInfo.getAbsolutePath(), uriInfo.getQueryParameters()); if (content == null) { return Response.status(Status.NOT_FOUND) .entity("<pre>Unable to retrieve requested metacard.</pre>") .type(MediaType.TEXT_HTML) .build(); } responseBuilder = Response.noContent(); responseBuilder.header(HEADER_ACCEPT_RANGES, BYTES); setFileNameOnResponseBuilder(id, content, responseBuilder); long size = content.getSize(); if (size > 0) { responseBuilder.header(HEADER_CONTENT_LENGTH, size); } return responseBuilder.build(); } catch (CatalogServiceException e) { return createBadRequestResponse(e.getMessage()); } }
Source:
public void testDeleteMarkerForCellsWithLowerOrEqualTimestamp() { long timestamp = 10000L; List<Cell> cells = Lists.newArrayList( HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp), HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp - 1), HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp + 1)); Predicate<Cell> predicate = predicateMaker.apply( HBaseCellUtils.deleteMarkerForCellsWithLowerOrEqualTimestamp( ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp)); assertEquals(Sets.newHashSet(cells.subList(0, 2)), Sets.newHashSet(Iterables.filter(cells, predicate))); predicate = predicateMaker.apply( HBaseCellUtils.deleteMarkerForCellsWithLowerOrEqualTimestamp( ROW_KEY, COLUMN_FAMILY, ANOTHER_QUALIFIER, timestamp)); assertTrue(Iterables.isEmpty(Iterables.filter(cells, predicate))); }

Target:
public void testDeleteMarkerForCellsWithLowerOrEqualTimestamp() { long timestamp = 10000L; List<Cell> cells = Lists.newArrayList( HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp), HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp - 1), HBaseCellUtils.createDataCell(ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp + 1)); Predicate<Cell> predicate = predicateMaker.apply( HBaseCellUtils.deleteMarkerForCellsWithLowerOrEqualTimestamp( ROW_KEY, COLUMN_FAMILY, QUALIFIER, timestamp)); assertEquals(Sets.newHashSet(cells.get(0), cells.get(1)), Sets.newHashSet(Iterables.filter(cells, predicate))); predicate = predicateMaker.apply( HBaseCellUtils.deleteMarkerForCellsWithLowerOrEqualTimestamp( ROW_KEY, COLUMN_FAMILY, ANOTHER_QUALIFIER, timestamp)); assertTrue(Iterables.isEmpty(Iterables.filter(cells, predicate))); }
Source:
private void discontinueExistingOrdersIfNecessary(Order order, Boolean isRetrospective) { if (DISCONTINUE != order.getAction()) { return; } Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { stopOrder(previousOrder, aMomentBefore(order.getDateActivated()), isRetrospective); return; } Date asOfDate = null; if (isRetrospective) asOfDate = order.getDateActivated(); List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getOrderType(), order.getCareSetting(), asOfDate); boolean isDrugOrderAndHasADrug = DrugOrder.class.isAssignableFrom(getActualType(order)) && (((DrugOrder) order).getDrug() != null || ((DrugOrder) order).isNonCodedDrug()); Order orderToBeDiscontinued = null; for (Order activeOrder : orders) { if (!getActualType(order).equals(getActualType(activeOrder))) { continue; } if (isDrugOrderAndHasADrug) { Order existing = order.hasSameOrderableAs(activeOrder) ? activeOrder : null; if (existing != null) { if (orderToBeDiscontinued == null) { orderToBeDiscontinued = existing; } else { throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } } else if (activeOrder.getConcept().equals(order.getConcept())) { if (orderToBeDiscontinued == null) { orderToBeDiscontinued = activeOrder; } else { throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } } if (orderToBeDiscontinued != null) { order.setPreviousOrder(orderToBeDiscontinued); stopOrder(orderToBeDiscontinued, aMomentBefore(order.getDateActivated()), isRetrospective); } }

Target:
private void discontinueExistingOrdersIfNecessary(Order order, Boolean isRetrospective) { if (DISCONTINUE != order.getAction()) { return; } Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { stopOrder(previousOrder, aMomentBefore(order.getDateActivated()), isRetrospective); return; } Date asOfDate = null; if (isRetrospective) { asOfDate = order.getDateActivated(); } List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getOrderType(), order.getCareSetting(), asOfDate); boolean isDrugOrderAndHasADrug = DrugOrder.class.isAssignableFrom(getActualType(order)) && (((DrugOrder) order).getDrug() != null || ((DrugOrder) order).isNonCodedDrug()); Order orderToBeDiscontinued = null; for (Order activeOrder : orders) { if (!getActualType(order).equals(getActualType(activeOrder))) { continue; } if (isDrugOrderAndHasADrug) { Order existing = order.hasSameOrderableAs(activeOrder) ? activeOrder : null; if (existing != null) { if (orderToBeDiscontinued == null) { orderToBeDiscontinued = existing; } else { throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } } else if (activeOrder.getConcept().equals(order.getConcept())) { if (orderToBeDiscontinued == null) { orderToBeDiscontinued = activeOrder; } else { throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } } if (orderToBeDiscontinued != null) { order.setPreviousOrder(orderToBeDiscontinued); stopOrder(orderToBeDiscontinued, aMomentBefore(order.getDateActivated()), isRetrospective); } }
Source:
private void checkForStageCompleted() { synchronized (this.stageCompletionCheckLock) { if (ingestMode == IngestJob.Mode.BATCH) { if (IngestJobPipeline.taskScheduler.currentTasksAreCompleted(this)) { switch (this.stage) { case FIRST: this.finishFirstStage(); break; case SECOND: this.finish(); break; } } } else { System.out.println("IngestJobPipeline.checkForStageCompleted() - current stage: " + this.stage.toString()); if (IngestJobPipeline.taskScheduler.currentTasksAreCompleted(this)) { System.out.println("IngestJobPipeline.checkForStageCompleted() - current tasks are completed"); switch (this.stage) { case STREAMING_FILE_INGEST: System.out.println("IngestJobPipeline.checkForStageCompleted() - do nothing"); break; case STREAMING_FIRST_STAGE_DATA_SOURCE_INGEST: System.out.println("IngestJobPipeline.checkForStageCompleted() - finishFirstStage"); this.finishFirstStage(); break; case SECOND: System.out.println("IngestJobPipeline.checkForStageCompleted() - finish"); this.finish(); break; } } else { System.out.println("IngestJobPipeline.checkForStageCompleted() - current tasks are not complete"); } } } }

Target:
private void checkForStageCompleted() { if (ingestMode == IngestJob.Mode.BATCH) { checkForStageCompletedBatch(); } else { checkForStageCompletedStreaming(); } }
Source:
public void blackCorner5x5BoardTest() { GoCounting gocounting = new GoCounting(board5x5); Set<Point> territory = new HashSet<>(); territory.add(new Point(0, 0)); territory.add(new Point(0, 1)); territory.add(new Point(1, 0)); assertEquals(gocounting.BLACK, gocounting.getTerritoryOwner(0, 1)); assertEquals(territory, gocounting.getTerritory(0, 1)); }

Target:
public void blackCorner5x5BoardTest() { GoCounting gocounting = new GoCounting(board5x5); Set<Point> territory = new HashSet<>(); territory.add(new Point(0, 0)); territory.add(new Point(0, 1)); territory.add(new Point(1, 0)); assertEquals(Player.BLACK, gocounting.getTerritoryOwner(0, 1)); assertEquals(territory, gocounting.getTerritory(0, 1)); }
Source:
public void run() { while (true) { PooledByteBufAllocatorMetric metric = PooledByteBufAllocator.DEFAULT.metric(); numDirectArenas = metric.numDirectArenas(); numHeapArenas = metric.numHeapArenas(); numThreadLocalCaches = metric.numThreadLocalCaches(); usedHeapMemory = metric.usedHeapMemory(); usedDirectMemory = metric.usedDirectMemory(); List<PoolArenaMetric> heapArenaMetrics = metric.heapArenas(); List<PoolArenaMetric> directArenaMetrics = metric.directArenas(); numHeapTotalAllocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numAllocations).sum(); numHeapTotalDeallocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numDeallocations).sum(); numHeapTotalActiveAllocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(); numDirectTotalAllocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numAllocations).sum(); numDirectTotalDeallocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numDeallocations).sum(); numDirectTotalActiveAllocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(); try { Thread.sleep(config.nettyMetricsRefreshIntervalSeconds * 1000); } catch (InterruptedException e) { stopLatch.countDown(); return; } } }

Target:
public void run() { PooledByteBufAllocatorMetric metric = PooledByteBufAllocator.DEFAULT.metric(); numDirectArenas = metric.numDirectArenas(); numHeapArenas = metric.numHeapArenas(); numThreadLocalCaches = metric.numThreadLocalCaches(); usedHeapMemory = metric.usedHeapMemory(); usedDirectMemory = metric.usedDirectMemory(); List<PoolArenaMetric> heapArenaMetrics = metric.heapArenas(); List<PoolArenaMetric> directArenaMetrics = metric.directArenas(); numHeapTotalAllocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numAllocations).sum(); numHeapTotalDeallocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numDeallocations).sum(); numHeapTotalActiveAllocations = heapArenaMetrics.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(); numDirectTotalAllocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numAllocations).sum(); numDirectTotalDeallocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numDeallocations).sum(); numDirectTotalActiveAllocations = directArenaMetrics.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum(); }
Source:
public Expr apply(final List<Expr> args) { if (args.size() < 1 || args.size() > 3) { throw new IAE("Function[%s] must have 1 to 3 arguments", name()); } final Expr arg = args.get(0); final String formatString = args.size() > 1 ? (String) args.get(1).getLiteralValue() : null; final DateTimeZone timeZone; if (args.size() > 2 && args.get(2).getLiteralValue() != null) { timeZone = DateTimeZone.forID((String) args.get(2).getLiteralValue()); } else { timeZone = DateTimeZone.UTC; } final DateTimes.UtcFormatter formatter = DateTimes.wrapFormatter( formatString == null ? ISODateTimeFormat.dateTimeParser() : DateTimeFormat.forPattern(formatString).withZone(timeZone) ); class TimestampParseExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { try { return ExprEval.of(formatter.parse(arg.eval(bindings).asString()).getMillis()); } catch (IllegalArgumentException e) { return ExprEval.of(null); } } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampParseExpr(); }

Target:
public Expr apply(final List<Expr> args) { if (args.size() < 1 || args.size() > 3) { throw new IAE("Function[%s] must have 1 to 3 arguments", name()); } final Expr arg = args.get(0); final String formatString = args.size() > 1 ? (String) args.get(1).getLiteralValue() : null; final DateTimeZone timeZone; if (args.size() > 2 && args.get(2).getLiteralValue() != null) { timeZone = DateTimeZone.forID((String) args.get(2).getLiteralValue()); } else { timeZone = DateTimeZone.UTC; } final DateTimes.UtcFormatter formatter = formatString == null ? DateTimes.ISO_DATE_OR_TIME : DateTimes.wrapFormatter(DateTimeFormat.forPattern(formatString).withZone(timeZone)); class TimestampParseExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { try { return ExprEval.of(formatter.parse(arg.eval(bindings).asString()).getMillis()); } catch (IllegalArgumentException e) { return ExprEval.of(null); } } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampParseExpr(); }
Source:
public void createContainerWithoutShmVolume() { try ( BrowserWebDriverContainer webDriverContainer = (BrowserWebDriverContainer) new BrowserWebDriverContainer() .withSharedMemorySize(512 * FileUtils.ONE_MB) ) { webDriverContainer.start(); assertEquals("Shared memory size is configured", 512 * FileUtils.ONE_MB, webDriverContainer.getShmSize()); assertEquals("No mounts present", webDriverContainer.getContainerInfo().getMounts().size(), 0); } }

Target:
public void createContainerWithoutShmVolume() { try ( BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer<>() .withSharedMemorySize(512 * FileUtils.ONE_MB) ) { webDriverContainer.start(); assertEquals("Shared memory size is configured", 512 * FileUtils.ONE_MB, webDriverContainer.getShmSize()); final long shmMountCount = webDriverContainer.getContainerInfo().getMounts() .stream() .filter(m -> "/dev/shm".equals(m.getSource())) .count(); assertEquals("No shm mounts present", shmMountCount, 0L); } }
Source:
public void scan() { Stats.incCounter("domxss.scan.count"); ArrayList<String> attackVectors = new ArrayList<String>(); int numberOfAttackStrings; switch (this.getAttackStrength()) { case LOW: numberOfAttackStrings = 3; break; case MEDIUM: default: numberOfAttackStrings = 5; break; case HIGH: numberOfAttackStrings = 7; break; case INSANE: numberOfAttackStrings = ATTACK_STRINGS.length; break; } for (int i=0; i < numberOfAttackStrings; i++) { attackVectors.add(ATTACK_STRINGS[i]); } ArrayList<WebDriverWrapper> drivers = new ArrayList<WebDriverWrapper>(); WebDriverWrapper fxDriver; try { fxDriver = this.getFirefoxDriver(); } catch (Exception e) { getLog().warn("Skipping scanner, failed to start Firefox: " + e.getMessage()); getParent().pluginSkipped(this, Constant.messages.getString("domxss.skipped.reason.browsererror")); return; } drivers.add(fxDriver); try { for(String attackVector : attackVectors) { if (scan(drivers, attackVector)) { if (!Plugin.AlertThreshold.LOW.equals( this.getAlertThreshold())) { break; } } } } finally { this.returnFirefoxDriver(fxDriver); } super.scan(); }

Target:
public void scan() { Stats.incCounter("domxss.scan.count"); ArrayList<String> attackVectors = new ArrayList<String>(); int numberOfAttackStrings; switch (this.getAttackStrength()) { case LOW: numberOfAttackStrings = 3; break; case MEDIUM: default: numberOfAttackStrings = 5; break; case HIGH: numberOfAttackStrings = 7; break; case INSANE: numberOfAttackStrings = ATTACK_STRINGS.length; break; } for (int i=0; i < numberOfAttackStrings; i++) { attackVectors.add(ATTACK_STRINGS[i]); } try { driver = TestDomXSS.getFirefoxDriver(); } catch (Exception e) { getLog().warn("Skipping scanner, failed to start Firefox: " + e.getMessage()); getParent().pluginSkipped(this, Constant.messages.getString("domxss.skipped.reason.browsererror")); return; } try { for(String attackVector : attackVectors) { if (scan(attackVector, getBaseMsg().getRequestHeader().getURI().toString() + attackVector)) { if (!Plugin.AlertThreshold.LOW.equals( this.getAlertThreshold())) { break; } } } super.scan(); } finally { this.returnFirefoxDriver(driver); } }
Source:
public static String generateHmacSha256Hash(String key, String valueToEncrypt) { try { return Base64.getEncoder().encodeToString(generateHmacSha256Bytes(key, valueToEncrypt)); } catch (RuntimeException e) { throw new RuntimeException("CommunityCommons::EncodeHmacSha256::Unable to encode: " + e.getMessage(), e); } }

Target:
public static String generateHmacSha256Hash(String key, String valueToEncrypt) { try { return Base64.getEncoder().encodeToString(generateHmacSha256Bytes(key, valueToEncrypt)); } catch (UnsupportedEncodingException | IllegalStateException | InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException("CommunityCommons::generateHmacSha256Hash::Unable to encode: " + e.getMessage(), e); } }
Source:
public static boolean directmime(String mime) { if ( mime != null && ( mime.equals(HTTPResource.MP4_TYPEMIME) || mime.equals(HTTPResource.WEBM_TYPEMIME) || mime.equals(HTTPResource.OGG_TYPEMIME) || mime.equals(HTTPResource.AUDIO_OGA_TYPEMIME) || mime.equals(HTTPResource.AUDIO_MP3_TYPEMIME) || mime.equals(HTTPResource.PNG_TYPEMIME) || mime.equals(HTTPResource.JPEG_TYPEMIME) || mime.equals(HTTPResource.GIF_TYPEMIME) || mime.equals(HTTPResource.TIFF_TYPEMIME) ) ) { return true; } return false; }

Target:
public static boolean directmime(String mime) { if ( mime != null && ( mime.equals(HTTPResource.MP4_TYPEMIME) || mime.equals(HTTPResource.WEBM_TYPEMIME) || mime.equals(HTTPResource.OGG_TYPEMIME) || mime.equals(HTTPResource.AUDIO_OGA_TYPEMIME) || mime.equals(HTTPResource.AUDIO_MP3_TYPEMIME) || mime.equals(HTTPResource.PNG_TYPEMIME) || mime.equals(HTTPResource.JPEG_TYPEMIME) || mime.equals(HTTPResource.GIF_TYPEMIME) ) ) { return true; } return false; }
Source:
public static ILaunchConfiguration[] filterConfigs(ILaunchConfiguration[] configurations) { IWorkbenchActivitySupport activitySupport = PlatformUI.getWorkbench().getActivitySupport(); if (activitySupport == null) { return configurations; } List<ILaunchConfiguration> filteredConfigs = new ArrayList<>(); ILaunchConfigurationType type = null; LaunchConfigurationTypeContribution contribution = null; ILaunchConfiguration configuration = null; for (ILaunchConfiguration configuration2 : configurations) { configuration = configuration2; try { type = configuration.getType(); contribution = new LaunchConfigurationTypeContribution(type); if (DebugUIPlugin.doLaunchConfigurationFiltering(configuration) & !WorkbenchActivityHelper.filterItem(contribution)) { filteredConfigs.add(configuration); } } catch (CoreException e) {DebugUIPlugin.log(e.getStatus());} } return filteredConfigs.toArray(new ILaunchConfiguration[filteredConfigs.size()]); }

Target:
public static ILaunchConfiguration[] filterConfigs(ILaunchConfiguration[] configurations) { IWorkbenchActivitySupport activitySupport = PlatformUI.getWorkbench().getActivitySupport(); if (activitySupport == null) { return configurations; } List<ILaunchConfiguration> filteredConfigs = new ArrayList<>(); for (ILaunchConfiguration configuration : configurations) { try { ILaunchConfigurationType type = configuration.getType(); LaunchConfigurationTypeContribution contribution = new LaunchConfigurationTypeContribution(type); if (DebugUIPlugin.doLaunchConfigurationFiltering(configuration) & !WorkbenchActivityHelper.filterItem(contribution)) { filteredConfigs.add(configuration); } } catch (CoreException e) {DebugUIPlugin.log(e.getStatus());} } return filteredConfigs.toArray(new ILaunchConfiguration[filteredConfigs.size()]); }
Source:
public void testCall() { GetDiffCommand diff = new GetDiffCommand(fGerrit.getRepository(), change_id, commit_id, "/COMMIT_MSG"); try { DiffInfo di = diff.call(); System.out.println(di); } catch (EGerritException e) { e.printStackTrace(); } }

Target:
public void testCall() throws EGerritException { GetDiffCommand diff = new GetDiffCommand(fGerrit.getRepository(), change_id, commit_id, "/COMMIT_MSG", 2); diff.call(); }
Source:
protected void init() { if (getVm() == null) { return; } super.init(); if (getParameters().getCustomCpuName() != null) { getVm().setUseHostCpuFlags(false); getVm().setCustomCpuName(getParameters().getCustomCpuName()); } if (getParameters().getCustomEmulatedMachine() != null) { getVm().setEmulatedMachine(getParameters().getCustomEmulatedMachine()); } if (getParameters().getBootMenuEnabled() != null) { getVm().setBootMenuEnabled(getParameters().getBootMenuEnabled()); } if (getParameters().getSpiceFileTransferEnabled() != null) { getVm().setSpiceFileTransferEnabled(getParameters().getSpiceFileTransferEnabled()); } if (getParameters().getSpiceCopyPasteEnabled() != null) { getVm().setSpiceCopyPasteEnabled(getParameters().getSpiceCopyPasteEnabled()); } if (getParameters().getBootSequence() != null) { getVm().setBootSequence(getParameters().getBootSequence()); } getVm().setVolatileRun(getParameters().isVolatileRun()); getVm().setInitrdUrl(getParameters().getInitrdUrl()); getVm().setKernelUrl(getParameters().getKernelUrl()); getVm().setKernelParams(getParameters().getKernelParams()); getVm().setCustomProperties(getParameters().getCustomProperties()); getVm().setRunOnce(true); }

Target:
protected void init() { if (getVm() == null) { return; } super.init(); String vmClusterCpuName = getCpuFlagsManagerHandler().getCpuId(getVm().getClusterCpuName(), getVm().getCompatibilityVersion()); if (getParameters().getCustomCpuName() != null && !getParameters().getCustomCpuName().equals( getVm().getCustomCpuName() != null ? getVm().getCustomCpuName() : vmClusterCpuName)) { getVm().setUseHostCpuFlags(false); getVm().setCustomCpuName(getParameters().getCustomCpuName()); } if (getParameters().getCustomEmulatedMachine() != null) { getVm().setEmulatedMachine(getParameters().getCustomEmulatedMachine()); } if (getParameters().getBootMenuEnabled() != null) { getVm().setBootMenuEnabled(getParameters().getBootMenuEnabled()); } if (getParameters().getSpiceFileTransferEnabled() != null) { getVm().setSpiceFileTransferEnabled(getParameters().getSpiceFileTransferEnabled()); } if (getParameters().getSpiceCopyPasteEnabled() != null) { getVm().setSpiceCopyPasteEnabled(getParameters().getSpiceCopyPasteEnabled()); } if (getParameters().getBootSequence() != null) { getVm().setBootSequence(getParameters().getBootSequence()); } getVm().setVolatileRun(getParameters().isVolatileRun()); getVm().setInitrdUrl(getParameters().getInitrdUrl()); getVm().setKernelUrl(getParameters().getKernelUrl()); getVm().setKernelParams(getParameters().getKernelParams()); getVm().setCustomProperties(getParameters().getCustomProperties()); getVm().setRunOnce(true); }
Source:
protected void executeCommand() { if (!(Guid.isNullOrEmpty(clusterId))) { performActionForServicesOfCluster(); } else if (!(Guid.isNullOrEmpty(serverId))) { performActionForServicesOfServer(); } }

Target:
protected void executeCommand() { if (!(Guid.isNullOrEmpty(serverId))) { performActionForServicesOfServer(); } else if (!(Guid.isNullOrEmpty(clusterId))) { performActionForServicesOfCluster(); } }
Source:
private List<Flow> getFlowsForPayloadsInSession(List<byte[]> payloads) { final List<Flow> flows = new ArrayList<>(); for (byte[] payload : payloads) { final ByteBuf buffer = Unpooled.wrappedBuffer(payload); final Header header; try { header = new Header(slice(buffer, Header.SIZE)); final Packet packet = new Packet(header, buffer); packet.getRecords().forEach(rec -> { byte[] message = FlowMessageBuilderFactory.buildAndSerialize(Protocol.NETFLOW5, rec); try { FlowMessage flowMessage = FlowMessageProto.parseFrom(message); flows.addAll(nf5Converter.convert(flowMessage)); } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } }); } catch (InvalidPacketException e) { throw new RuntimeException(e); } } return flows; }

Target:
private List<Flow> getFlowsForPayloadsInSession(List<byte[]> payloads) { final List<Flow> flows = new ArrayList<>(); for (byte[] payload : payloads) { final ByteBuf buffer = Unpooled.wrappedBuffer(payload); final Header header; try { header = new Header(slice(buffer, Header.SIZE)); final Packet packet = new Packet(header, buffer); packet.getRecords().forEach(rec -> { byte[] message = buildAndSerialize(Protocol.NETFLOW5, rec); try { FlowMessage flowMessage = FlowMessage.parseFrom(message); flows.addAll(nf5Converter.convert(flowMessage)); } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } }); } catch (InvalidPacketException e) { throw new RuntimeException(e); } } return flows; }
Source:
public ServerHttpRequest apply(ServerHttpRequest request) { if (hasForwardedHeaders(request)) { ServerHttpRequest.Builder builder = request.mutate(); if (!this.removeOnly) { URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri(); builder.uri(uri); String prefix = getForwardedPrefix(request); if (prefix != null) { builder.path(prefix + uri.getRawPath()); builder.contextPath(prefix); } Optional<InetSocketAddress> remoteAddressO = Optional.ofNullable(request.getRemoteAddress()); String originalRemoteHost = remoteAddressO.map(InetSocketAddress::getHostName).orElse(null); UriComponents remoteUriComponents = UriComponentsBuilder.newInstance() .host(originalRemoteHost) .port(remoteAddressO.map(InetSocketAddress::getPort).orElse(-1)) .adaptFromForwardedForHeader(request.getHeaders()) .build(); String remoteHost = remoteUriComponents.getHost(); int remotePort = (remoteUriComponents.getPort() != -1 ? remoteUriComponents.getPort() : 0); if (remoteHost != null && !remoteHost.equals(originalRemoteHost)) { builder.remoteAddress(InetSocketAddress.createUnresolved(remoteHost, remotePort)); } else { remoteAddressO.ifPresent(builder::remoteAddress); } } removeForwardedHeaders(builder); request = builder.build(); } return request; }

Target:
public ServerHttpRequest apply(ServerHttpRequest request) { if (hasForwardedHeaders(request)) { ServerHttpRequest.Builder builder = request.mutate(); if (!this.removeOnly) { URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri(); builder.uri(uri); String prefix = getForwardedPrefix(request); if (prefix != null) { builder.path(prefix + uri.getRawPath()); builder.contextPath(prefix); } InetSocketAddress remoteAddress = request.getRemoteAddress(); HttpHeaders headers = request.getHeaders(); boolean hasForwardedFor = StringUtils.hasText(headers.getFirst(X_FORWARDED_FOR_HEADER)) || (StringUtils.hasText(headers.getFirst(FORWARDED_HEADER)) && FORWARDED_FOR_PATTERN.matcher(headers.getFirst(FORWARDED_HEADER)).matches()); if (hasForwardedFor) { String originalRemoteHost = ((remoteAddress != null) ? remoteAddress.getHostName() : null); int originalRemotePort = ((remoteAddress != null) ? remoteAddress.getPort() : -1); UriComponents remoteUriComponents = UriComponentsBuilder.newInstance() .host(originalRemoteHost) .port(originalRemotePort) .adaptFromForwardedForHeader(headers) .build(); String remoteHost = remoteUriComponents.getHost(); int remotePort = (remoteUriComponents.getPort() != -1 ? remoteUriComponents.getPort() : 0); if (remoteHost != null) { builder.remoteAddress(InetSocketAddress.createUnresolved(remoteHost, remotePort)); } } else { builder.remoteAddress(remoteAddress); } } removeForwardedHeaders(builder); request = builder.build(); } return request; }
Source:
public CruiseConfig loadForEditing() { return currentConfigForEdit; }

Target:
public CruiseConfig loadForEditing() { loadConfigIfNull(); return currentConfigForEdit; }
Source:
private void importLdif(InMemoryDirectoryServer directoryServer) { checkFilePath(this.ldif); try { Resource[] resources = this.context.getResources(this.ldif); if (resources.length > 0 && resources[0].exists() && resources[0].isFile() && resources[0].isReadable()) { try (InputStream inputStream = resources[0].getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } }

Target:
private void importLdif(InMemoryDirectoryServer directoryServer) { if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } }