auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void click(String title, Constants.InvokeSource source) { SuggestedEditStats stats = null; if (source == Constants.InvokeSource.EDIT_FEED_TITLE_DESC) { stats = statsCollection.addDescriptionStats; } else if (source == Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC) { stats = statsCollection.translateDescriptionStats; } stats.clicks++; if (!uniqueTitles.contains(title)) { uniqueTitles.add(title); final int maxItems = 100; if (uniqueTitles.size() > maxItems) { uniqueTitles.remove(0); } stats.suggestionsClicked++; } }

Target:
public void click(String title, Constants.InvokeSource source) { SuggestedEditStats stats; if (source == Constants.InvokeSource.EDIT_FEED_TITLE_DESC) { stats = statsCollection.addDescriptionStats; } else if (source == Constants.InvokeSource.EDIT_FEED_TRANSLATE_TITLE_DESC) { stats = statsCollection.translateDescriptionStats; } else { return; } stats.clicks++; if (!uniqueTitles.contains(title)) { uniqueTitles.add(title); final int maxItems = 100; if (uniqueTitles.size() > maxItems) { uniqueTitles.remove(0); } stats.suggestionsClicked++; } }
Source:
public void testPopulate() throws Exception { setupParentExpectations(); setUriInfo(setUpBasicUriExpectations()); setUpGetEntityExpectationsAllContent(1,false); resource.setParent(bricksResourceMock); control.replay(); verifyModel(resource.get(), 0); }

Target:
public void testPopulate() throws Exception { setupParentExpectations(); setUriInfo(setUpBasicUriExpectations()); setUpGetEntityExpectationsAllContent(1,false); resource.setParent(bricksResourceMock); control.replay(); verifyModelWithDetails(resource.get(), 0); }
Source:
private void logMeasureByResource(Resource resource, Measure measure) { if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }

Target:
private static void logMeasureByResource(Resource resource, Measure measure) { if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }
Source:
public synchronized boolean trySetBytes(long bytes) { checkState(!closed, "SimpleLocalMemoryContext is already closed"); long delta = bytes - usedBytes; if (parentMemoryContext.tryUpdateBytes(delta)) { usedBytes += delta; return true; } return false; }

Target:
public synchronized boolean trySetBytes(long bytes) { checkState(!closed, "SimpleLocalMemoryContext is already closed"); checkArgument(bytes >= 0, "bytes cannot be negative"); long delta = bytes - usedBytes; if (parentMemoryContext.tryUpdateBytes(delta)) { usedBytes = bytes; return true; } return false; }
Source:
void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AmqpException(false, "some error occurred.", null))); StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID)) .verifyErrorMatches(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusAmqpException); final ServiceBusErrorSource actual = ((ServiceBusAmqpException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); return true; }); }

Target:
void errorSourceOnSessionLock() { when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.error(new AmqpException(false, "some error occurred.", null))); StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID)) .verifyErrorSatisfies(throwable -> { Assertions.assertTrue(throwable instanceof ServiceBusAmqpException); final ServiceBusErrorSource actual = ((ServiceBusAmqpException) throwable).getErrorSource(); Assertions.assertEquals(ServiceBusErrorSource.RENEW_LOCK, actual); }); }
Source:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); if (branchKey.isEmpty()) { branchKey = null; } try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = checkFoundWithOptional(dbClient.componentDao().selectByKey(dbSession, projectKey), "Project key '%s' not found", projectKey); checkPermission(project); BranchDto branch = checkFoundWithOptional( dbClient.branchDao().selectByKey(dbSession, project.uuid(), BranchKeyType.BRANCH, branchKey), "Branch '%s' not found for project '%s'", branchKey, projectKey); if (branch.isMain()) { throw new IllegalArgumentException("Only non-main branches can be deleted"); } componentCleanerService.delete(dbSession, project); response.noContent(); } }

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String projectKey = request.mandatoryParam(PARAM_PROJECT); String branchKey = request.mandatoryParam(PARAM_BRANCH); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getRootComponentByUuidOrKey(dbSession, null, projectKey); checkPermission(project); BranchDto branch = checkFoundWithOptional( dbClient.branchDao().selectByKey(dbSession, project.uuid(), BranchKeyType.BRANCH, branchKey), "Branch '%s' not found for project '%s'", branchKey, projectKey); if (branch.isMain()) { throw new IllegalArgumentException("Only non-main branches can be deleted"); } ComponentDto branchComponent = componentFinder.getByKeyAndBranch(dbSession, projectKey, branchKey); componentCleanerService.deleteBranch(dbSession, branchComponent); response.noContent(); } }
Source:
public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); Host host = null; if (hostId != null) { host = hostAPI.find(hostId, user, false); } return host; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }

Target:
public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); return (null != hostId) ? hostAPI.find(hostId, user, false) : null; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }
Source:
public ArticleMetadata get(Site site, RequestedDoiVersion id, ArticlePointer articlePointer) throws IOException { try { Map<String, Object> ingestionMetadata = (Map<String, Object>) articleApi.requestObject( articlePointer.asApiAddress().build(), Map.class); Map<String, ?> itemTable = articleService.getItemTable(articlePointer); ApiAddress relationshipsApiAddress = ApiAddress.builder("articles") .embedDoi(articlePointer.getDoi()).addToken("relationships").build(); Map<String, List<Map<String, ?>>> relationships = articleApi.requestObject(relationshipsApiAddress, Map.class); return new ArticleMetadata(this, site, id, articlePointer, ingestionMetadata, itemTable, relationships); } catch (EntityNotFoundException e) { throw new NotFoundException(e); } }

Target:
public ArticleMetadata get(Site site, RequestedDoiVersion id, ArticlePointer articlePointer) throws IOException { Map<String, Object> ingestionMetadata; try { ingestionMetadata = (Map<String, Object>) articleApi.requestObject( articlePointer.asApiAddress().build(), Map.class); } catch (EntityNotFoundException e) { throw new NotFoundException(e); } Map<String, ?> itemTable = articleService.getItemTable(articlePointer); ApiAddress relationshipsApiAddress = ApiAddress.builder("articles") .embedDoi(articlePointer.getDoi()).addToken("relationships").build(); Map<String, List<Map<String, ?>>> relationships = articleApi.requestObject(relationshipsApiAddress, Map.class); return new ArticleMetadata(this, site, id, articlePointer, ingestionMetadata, itemTable, relationships); }
Source:
public void shouldUpdateSalaryWhenAppraisalIsDue() throws Exception { Appraisal appraisal = new Appraisal(); appraisal.setJob(new Job()); appraisal.getJob().setAppointmentType(AppointmentType.CLASSIFIED_IT); DateTime endDate = new DateTime().plusDays(61).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().add(new Salary()); Session session = HibernateUtil.getCurrentSession(); Transaction tx = session.beginTransaction(); BackendMgr mgr = getMgrInstance(); session = HibernateUtil.getCurrentSession(); tx = session.beginTransaction(); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due in one day"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due today"; endDate = new DateTime().plusDays(59).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since appraisal is due in past"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().clear(); Salary salary = new Salary(); salary.setIncrease(7d); appraisal.getSalaries().add(salary); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since salary increase is set"; tx.commit(); }

Target:
public void shouldUpdateSalaryWhenAppraisalIsDue() throws Exception { Appraisal appraisal = new Appraisal(); appraisal.setJob(new Job()); appraisal.getJob().setAppointmentType(AppointmentType.CLASSIFIED_IT); DateTime endDate = new DateTime().plusDays(61).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().add(new Salary()); BackendMgr mgr = getMgrInstance(); Session session = HibernateUtil.getCurrentSession(); Transaction tx = session.beginTransaction(); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due in one day"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due today"; endDate = new DateTime().plusDays(59).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since appraisal is due in past"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().clear(); Salary salary = new Salary(); salary.setIncrease(7d); appraisal.getSalaries().add(salary); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since salary increase is set"; tx.commit(); }
Source:
public void testSetSocketBufferSize() throws Exception { Socket s = new Socket(); int initSendBufferSize = s.getSendBufferSize(); int initReceiveBufferSize = s.getReceiveBufferSize(); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(initSendBufferSize, s.getSendBufferSize()); Assert.assertEquals(initReceiveBufferSize, s.getReceiveBufferSize()); int networkBufferSize = 1024 * 1024; SocketUtil.setNetworkBufferSize(networkBufferSize); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(networkBufferSize, s.getSendBufferSize()); Assert.assertEquals(networkBufferSize, s.getReceiveBufferSize()); }

Target:
public void testSetSocketBufferSize() throws Exception { Socket s = new Socket(); int initSendBufferSize = s.getSendBufferSize(); int initReceiveBufferSize = s.getReceiveBufferSize(); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(initSendBufferSize, s.getSendBufferSize()); Assert.assertEquals(initReceiveBufferSize, s.getReceiveBufferSize()); int networkBufferSize = 32 * 1024; SocketUtil.setNetworkBufferSize(networkBufferSize); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(networkBufferSize, s.getSendBufferSize()); Assert.assertEquals(networkBufferSize, s.getReceiveBufferSize()); }
Source:
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, servletRequest, servletResponse, true); event.setDispatchContext(getServletContext()); state.startAsync(event); return _async; }

Target:
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, servletRequest, servletResponse, getHttpURI()); event.setDispatchContext(getServletContext()); state.startAsync(event); return _async; }
Source:
public void onDataTypeEditModeToggle(final @Observes DataTypeEditModeToggleEvent event) { if (event.isEditModeEnabled()) { if (getCurrentEditingItem() != null && getItems().contains(getCurrentEditingItem())) { getCurrentEditingItem().disableEditMode(); } setCurrentEditingItem(event.getItem()); } else if (event.getItem() == getCurrentEditingItem()) { setCurrentEditingItem(null); } }

Target:
public void onDataTypeEditModeToggle(final @Observes DataTypeEditModeToggleEvent event) { if (event.isEditModeEnabled()) { if (getCurrentEditingItem() != null && getItems().contains(getCurrentEditingItem())) { getCurrentEditingItem().disableEditMode(); } setCurrentEditingItem(event.getItem()); } else if (Objects.equals(event.getItem(), getCurrentEditingItem())) { setCurrentEditingItem(null); } }
Source:
public void addCatchUpPointMetricForPartition(PartitionId partitionId) { if (!cloudReplicaCatchUpPoint.containsKey(partitionId)) { cloudReplicaCatchUpPoint.put(partitionId, 0L); Gauge<Long> catchUpPoint = () -> cloudReplicaCatchUpPoint.get(partitionId); registry.register(MetricRegistry.name(ReplicaThread.class, "Partition-" + partitionId.toPathString() + "-catchupPointFromCloud"), catchUpPoint); } }

Target:
public void addCatchUpPointMetricForPartition(PartitionId partitionId) { if (!cloudReplicaCatchUpPoint.containsKey(partitionId)) { cloudReplicaCatchUpPoint.put(partitionId, 0L); Gauge<Long> catchUpPoint = () -> cloudReplicaCatchUpPoint.get(partitionId); registry.register(MetricRegistry.name(ReplicaThread.class, String.format(CATCH_POINT_FROM_CLOUD_METRIC_NAME_TEMPLATE, partitionId.toPathString())), catchUpPoint); } }
Source:
public IRunnableWithProgress getRunnable() { return new WorkspaceModifyDelegatingOperation(imonitor -> { final Exception except[] = new Exception[1]; getShell().getDisplay().syncExec(() -> { IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(monitor -> { final IProgressMonitor fMonitor; if (monitor == null) { fMonitor = new NullProgressMonitor(); } else { fMonitor = monitor; } SubMonitor subMonitor = SubMonitor.convert(fMonitor, 3); subMonitor.subTask(CUIPlugin.getResourceString(OP_DESC)); doRunPrologue(subMonitor.split(1)); subMonitor.setWorkRemaining(2); try { doRun(subMonitor.split(1)); subMonitor.setWorkRemaining(1); } catch (CoreException e) { except[0] = e; } doRunEpilogue(subMonitor.split(1)); subMonitor.setWorkRemaining(0); }); try { getContainer().run(false, true, op); } catch (InvocationTargetException e1) { except[0] = e1; } catch (InterruptedException e2) { except[0] = e2; } }); if (except[0] != null) { if (except[0] instanceof InvocationTargetException) { throw (InvocationTargetException) except[0]; } if (except[0] instanceof InterruptedException) { throw (InterruptedException) except[0]; } throw new InvocationTargetException(except[0]); } }); }

Target:
public IRunnableWithProgress getRunnable() { return new WorkspaceModifyDelegatingOperation(imonitor -> { final Exception except[] = new Exception[1]; getShell().getDisplay().syncExec(() -> { IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(monitor -> { SubMonitor subMonitor = SubMonitor.convert(monitor, 3); subMonitor.subTask(CUIPlugin.getResourceString(OP_DESC)); doRunPrologue(subMonitor.split(1)); try { doRun(subMonitor.split(1)); } catch (CoreException e) { except[0] = e; } doRunEpilogue(subMonitor.split(1)); }); try { getContainer().run(false, true, op); } catch (InvocationTargetException e1) { except[0] = e1; } catch (InterruptedException e2) { except[0] = e2; } }); if (except[0] != null) { if (except[0] instanceof InvocationTargetException) { throw (InvocationTargetException) except[0]; } if (except[0] instanceof InterruptedException) { throw (InterruptedException) except[0]; } throw new InvocationTargetException(except[0]); } }); }
Source:
public boolean equals(Object obj) { if (obj instanceof Application) { Application other = (Application) obj; return Objects.equal(this.getId(), other.getId()) && Objects.equal(this.getSlug(), other.getSlug()) && Objects.equal(this.getTitle(), other.getTitle()) && Objects.equal(this.getDescription(), other.getDescription()) && Objects.equal(this.getCreated(), other.getCreated()) && Objects.equal(this.getCredentials(), other.getCredentials()) && Objects.equal(this.getSources(), other.getSources()); } return false; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Application) { Application other = (Application) obj; return this.getId().equals(other.getId()) && this.getSlug().equals(other.getSlug()) && Objects.equal(this.getTitle(), other.getTitle()) && Objects.equal(this.getDescription(), other.getDescription()) && this.getCreated().equals(other.getCreated()) && this.getCredentials().equals(other.getCredentials()) && this.getSources().equals(other.getSources()); } return false; }
Source:
public static TmfProtocol getProtocol(Protocol protocol) { for (TmfProtocol prot : TmfProtocol.values()) { if (prot.getName().equals(protocol.getName())) { return prot; } } return UNKNOWN; }

Target:
public static TmfProtocol getProtocol(Protocol protocol) { switch (protocol) { case ETHERNET_II: return TmfProtocol.ETHERNET_II; case IPV4: return TmfProtocol.IPV4; case PCAP: return TmfProtocol.PCAP; case TCP: return TmfProtocol.TCP; case UDP: return TmfProtocol.UDP; case UNKNOWN: default: return TmfProtocol.UNKNOWN; } }
Source:
public ParameterizedCurveVectorFunction(final double[] samplePoints, final ParameterizedCurve curve) { ArgumentChecker.notEmpty(samplePoints, "samplePoints"); ArgumentChecker.notNull(curve, "curve"); _samplePoints = samplePoints; _curve = curve; }

Target:
public ParameterizedCurveVectorFunction(final double[] samplePoints, final ParameterizedCurve curve) { ArgumentChecker.notEmpty(samplePoints, "samplePoints"); ArgumentChecker.notNull(curve, "curve"); _samplePoints = Arrays.copyOf(samplePoints, samplePoints.length); _curve = curve; }
Source:
public ByContentSpec unspecified(String mimeType) { unspecifiedHandler = ctx -> { ctx.getResponse().contentType(mimeType); blocks.get(mimeType).execute(); }; return this; }

Target:
public ByContentSpec unspecified(String mimeType) { unspecifiedHandler = handleWithMimeTypeBlock(mimeType); return this; }
Source:
protected Predicate<DetailedS3Object> getOwnerPredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String owner = metaLookup(OWNER); if (Guard.isStringNullOrEmpty(owner)) { return Predicates.notNull(); } return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getOwner().equals(owner); } }; }

Target:
private Predicate<DetailedS3Object> getOwnerPredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String owner = paramLookup(OWNER); if (Guard.isStringNullOrEmpty(owner)) { return Predicates.notNull(); } return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getOwner().equals(owner); } }; }
Source:
public void setContent(CharSequence text) { content.fromHtml(text.toString()); updateFailedMediaList(); overlayFailedMedia(); convertUploadingUponStartToFailed(); }

Target:
public void setContent(CharSequence text) { content.fromHtml(text.toString()); updateFailedMediaList(); overlayFailedMedia(); markAllUploadingMediaAsFailed(); }
Source:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { String fieldName = Optional.ofNullable(field.getAnnotation(Named.class)) .map(a -> a.value()).orElse(field.getName()); Object value = getInjectableValue(field.getAnnotation(decorator), fieldName, clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }

Target:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { String fieldName = Optional.ofNullable(field.getAnnotation(Named.class)) .map(a -> a.value()).orElseGet(() -> field.getName()); Object value = getInjectableValue(field.getAnnotation(decorator), fieldName, clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }
Source:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); result.put("ERL_EPMD_PORT", "" + getEntity().getEpmdListenerPort()); return result; }

Target:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); result.put("ERL_EPMD_PORT", "" + Integer.toString(getEntity().getEpmdListenerPort())); return result; }
Source:
public Aggregator factorize(final ColumnSelectorFactory metricFactory) { if (metricColumns == null) { final BaseObjectColumnValueSelector<ArrayOfDoublesSketch> selector = metricFactory .makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } return new ArrayOfDoublesSketchMergeAggregator(selector, nominalEntries, numberOfValues); } final DimensionSelector keySelector = metricFactory .makeDimensionSelector(new DefaultDimensionSpec(fieldName, fieldName)); if (keySelector instanceof NullDimensionSelector) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } final List<BaseDoubleColumnValueSelector> valueSelectors = new ArrayList<>(); for (final String column: metricColumns) { final BaseDoubleColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(column); valueSelectors.add(valueSelector); } return new ArrayOfDoublesSketchBuildAggregator(keySelector, valueSelectors, nominalEntries); }

Target:
public Aggregator factorize(final ColumnSelectorFactory metricFactory) { if (metricColumns == null) { final BaseObjectColumnValueSelector<ArrayOfDoublesSketch> selector = metricFactory .makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } return new ArrayOfDoublesSketchMergeAggregator(selector, nominalEntries, numberOfValues); } final DimensionSelector keySelector = metricFactory .makeDimensionSelector(new DefaultDimensionSpec(fieldName, fieldName)); if (DimensionSelectorUtils.isNilSelector(keySelector)) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } final List<BaseDoubleColumnValueSelector> valueSelectors = new ArrayList<>(); for (final String column : metricColumns) { final BaseDoubleColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(column); valueSelectors.add(valueSelector); } return new ArrayOfDoublesSketchBuildAggregator(keySelector, valueSelectors, nominalEntries); }
Source:
protected int resolveInitializationVectorLength(PrivateKeyEncryptionContext encContext) throws GeneralSecurityException { int keyLength = resolveKeyLength(encContext); String cipherMode = encContext.getCipherMode(); String xformMode = "/" + cipherMode.toUpperCase() + "/"; List<CipherInformation> matches = BuiltinCiphers.VALUES.stream() .filter(c -> CIPHER_NAME.equalsIgnoreCase(c.getAlgorithm()) && (keyLength == c.getKeySize()) && c.getTransformation().contains(xformMode)) .collect(Collectors.toList()); int numMatches = GenericUtils.size(matches); if (numMatches <= 0) { throw new NoSuchAlgorithmException("No match found for " + encContext); } if (numMatches > 1) { throw new InvalidKeySpecException("Multiple matches (" + numMatches + ") for " + encContext); } CipherInformation ci = matches.get(0); return ci.getIVSize(); }

Target:
protected int resolveInitializationVectorLength(PrivateKeyEncryptionContext encContext) throws GeneralSecurityException { int keyLength = resolveKeyLength(encContext); CipherInformation ci = resolveCipherInformation(keyLength, encContext.getCipherMode()); if (ci == null) { throw new NoSuchAlgorithmException("No match found for " + encContext); } return ci.getIVSize(); }
Source:
public Version(String versionInString) { String[] list; if (versionInString.contains("-")) { list = versionInString.split("-", 3); } else { list = versionInString.split(".", 3); } if (list.length > 0) { major = Integer.parseInt(list[0]); } if (list.length > 1) { minor = Integer.parseInt(list[1]); } if (list.length > 2) { patch = list[2]; } }

Target:
public Version(String versionInString) { originalRepresentation = versionInString; if (versionInString.contains("rc")) { versionInString = versionInString.replace("rc", ""); isRcVersion = true; } else { isRcVersion = false; } String[] list; if (versionInString.contains("-")) { list = versionInString.split("-", 3); } else { list = versionInString.split("\\.", 3); } if (list.length > 0) { major = list[0]; } if (list.length > 1) { minor = list[1]; } if (list.length > 2) { patch = list[2]; } }
Source:
static void checkImageCaptureEnabled(EffectMode effectMode, Collection<UseCase> activeUseCases) { boolean isImageCaptureExtenderEnabled = false; boolean isMismatched = false; if (activeUseCases == null) { return; } for (UseCase useCase : activeUseCases) { EffectMode imageCaptureExtenderMode = useCase.getUseCaseConfig().retrieveOption( ImageCaptureExtender.OPTION_IMAGE_CAPTURE_EXTENDER_MODE, null); if (effectMode == imageCaptureExtenderMode) { isImageCaptureExtenderEnabled = true; } else if (imageCaptureExtenderMode != null) { isMismatched = true; } } if (isMismatched) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.MISMATCHED_EXTENSIONS_ENABLED); } else if (!isImageCaptureExtenderEnabled) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.IMAGE_CAPTURE_EXTENSION_REQUIRED); } }

Target:
static void checkImageCaptureEnabled(EffectMode effectMode, Collection<UseCase> activeUseCases) { boolean isImageCaptureExtenderEnabled = false; boolean isMismatched = false; if (activeUseCases == null || activeUseCases.isEmpty()) { return; } for (UseCase useCase : activeUseCases) { EffectMode imageCaptureExtenderMode = useCase.getUseCaseConfig().retrieveOption( ImageCaptureExtender.OPTION_IMAGE_CAPTURE_EXTENDER_MODE, null); if (effectMode == imageCaptureExtenderMode) { isImageCaptureExtenderEnabled = true; } else if (imageCaptureExtenderMode != null) { isMismatched = true; } } if (isMismatched) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.MISMATCHED_EXTENSIONS_ENABLED); } else if (!isImageCaptureExtenderEnabled) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.IMAGE_CAPTURE_EXTENSION_REQUIRED); } }
Source:
public void setPortNumber(int portNumber) { this.portNumbers = new int[] { portNumber }; }

Target:
public void setPortNumber(int portNumber) { setPortNumbers(new int[] { portNumber }); }
Source:
public synchronized void write(final PagedMessage message) throws Exception { if (!file.isOpen()) { throw new IllegalStateException("can't write to closed file " + file); } final int messageEncodedSize = message.getEncodeSize(); final int bufferSize = messageEncodedSize + Page.SIZE_RECORD; final ByteBuffer buffer = fileFactory.newBuffer(bufferSize); ChannelBufferWrapper activeMQBuffer = wrapBuffer(bufferSize, buffer); activeMQBuffer.clear(); activeMQBuffer.writeByte(Page.START_BYTE); activeMQBuffer.writeInt(messageEncodedSize); message.encode(activeMQBuffer); activeMQBuffer.writeByte(Page.END_BYTE); assert (activeMQBuffer.readableBytes() == bufferSize) : "messageEncodedSize is different from expected"; assert (buffer.remaining() == bufferSize) : "buffer position or limit are changed"; file.writeDirect(buffer, false); if (pageCache != null) { pageCache.addLiveMessage(message); } numberOfMessages.lazySet(numberOfMessages.get() + 1); size.lazySet(size.get() + bufferSize); storageManager.pageWrite(message, pageId); }

Target:
public synchronized void write(final PagedMessage message) throws Exception { if (!file.isOpen()) { throw ActiveMQMessageBundle.BUNDLE.cannotWriteToClosedFile(file); } final int messageEncodedSize = message.getEncodeSize(); final int bufferSize = messageEncodedSize + Page.SIZE_RECORD; final ByteBuffer buffer = fileFactory.newBuffer(bufferSize); ChannelBufferWrapper activeMQBuffer = wrapBuffer(bufferSize, buffer); activeMQBuffer.clear(); activeMQBuffer.writeByte(Page.START_BYTE); activeMQBuffer.writeInt(messageEncodedSize); message.encode(activeMQBuffer); activeMQBuffer.writeByte(Page.END_BYTE); assert (activeMQBuffer.readableBytes() == bufferSize) : "messageEncodedSize is different from expected"; assert (buffer.remaining() == bufferSize) : "buffer position or limit are changed"; file.writeDirect(buffer, false); if (pageCache != null) { pageCache.addLiveMessage(message); } numberOfMessages.lazySet(numberOfMessages.get() + 1); size.lazySet(size.get() + bufferSize); storageManager.pageWrite(message, pageId); }
Source:
private ResponseEntity<?> createSubscription(final SubscriptionBase subscriptionBase, final NativeWebRequest request) throws InternalNakadiException, DuplicatedSubscriptionException { final List<String> noneExistingEventTypes = checkExistingEventTypes(subscriptionBase); if (!noneExistingEventTypes.isEmpty()) { final String errorMessage = createErrorMessage(noneExistingEventTypes); LOG.debug(errorMessage); return create(UNPROCESSABLE_ENTITY, errorMessage, request); } final Subscription subscription = subscriptionRepository.createSubscription(subscriptionBase); return new ResponseEntity<>(subscription, HttpStatus.CREATED); }

Target:
private ResponseEntity<?> createSubscription(final SubscriptionBase subscriptionBase, final NativeWebRequest request) throws InternalNakadiException, DuplicatedSubscriptionException { final List<String> noneExistingEventTypes = checkExistingEventTypes(subscriptionBase); if (!noneExistingEventTypes.isEmpty()) { final String errorMessage = createErrorMessage(noneExistingEventTypes); LOG.debug(errorMessage); return create(UNPROCESSABLE_ENTITY, errorMessage, request); } final Subscription subscription = subscriptionRepository.createSubscription(subscriptionBase); return status(HttpStatus.CREATED).body(subscription); }
Source:
private void setCurrentProxySettings() { String currentProxyType = BriefcasePreferences.getBriefCaseProxyType(); if (currentProxyType.equals(ProxyConnection.ProxyType.NO_PROXY.toString())){ schemaComboBox.setSelectedIndex(0); } else if (currentProxyType.equals(ProxyConnection.ProxyType.HTTP.toString())) { schemaComboBox.setSelectedIndex(1); } else { schemaComboBox.setSelectedIndex(2); } txtHost.setText(BriefcasePreferences.getBriefCaseProxyHost()); txtHost.setEnabled(false); txtPort.setText(BriefcasePreferences.getBriefCaseProxyPort()); txtPort.setEnabled(false); }

Target:
private void setCurrentProxySettings() { ProxyConnection currentProxy = BriefcasePreferences.getBriefCaseProxyConnection(); if (currentProxy == null){ schemaComboBox.setSelectedIndex(0); return; } if (currentProxy.getProxyType().equals(ProxyConnection.ProxyType.HTTP.toString())) { schemaComboBox.setSelectedIndex(1); } else { schemaComboBox.setSelectedIndex(2); } txtHost.setText(currentProxy.getHost()); txtHost.setEnabled(false); txtPort.setText(currentProxy.getPort().toString()); txtPort.setEnabled(false); }
Source:
private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { TimerContext context = _registerTimer.time(); checkNotNull(endPoint); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized (this) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if (existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld()) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<S>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; toDelete = existingServiceHandle; toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } context.stop(); return toReturn; }

Target:
private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { checkNotNull(endPoint); TimerContext context = _registerTimer.time(); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized (this) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if (existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld()) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<S>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; toDelete = existingServiceHandle; toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } context.stop(); return toReturn; }
Source:
public void onMessage(Message message) { BasicMessageWithExtraData<T> msgWithExtraData = parseMessage(message); if (msgWithExtraData == null) { return; } U responseBasicMessage = onBasicMessage(msgWithExtraData); ConsumerConnectionContext consumerConnectionContext = null; try { Destination replyTo = message.getJMSReplyTo(); if (replyTo != null) { getLog().debugf("RPC client asked to get response sent to [%s]", replyTo); MessageProcessor sender = getMessageSender(); if (sender == null) { msglog.errorNoMessageSenderInListener(); return; } consumerConnectionContext = getConsumerConnectionContext(); if (consumerConnectionContext == null) { msglog.errorNoConnectionContextInListener(); return; } ProducerConnectionContext producerContext = new ProducerConnectionContext(); producerContext.copy(consumerConnectionContext); producerContext.setDestination(replyTo); Session session = producerContext.getSession(); if (session == null) { msglog.errorNoSessionInListener(); } else { MessageProducer sessionProducer = session.createProducer(replyTo); producerContext.setMessageProducer(sessionProducer); sender.send(producerContext, responseBasicMessage); sessionProducer.close(); } } else { getLog().debug("Sender did not tell us where to reply - will not send any response back"); } } catch (Exception e) { msglog.errorFailedToSendResponse(e); return; } }

Target:
public void onMessage(Message message) { BasicMessageWithExtraData<T> msgWithExtraData = parseMessage(message); if (msgWithExtraData == null) { return; } U responseBasicMessage = onBasicMessage(msgWithExtraData); ConsumerConnectionContext consumerConnectionContext = null; MessageProducer sessionProducer = null; try { Destination replyTo = message.getJMSReplyTo(); if (replyTo != null) { getLog().debugf("RPC client asked to get response sent to [%s]", replyTo); MessageProcessor sender = getMessageSender(); if (sender == null) { msglog.errorNoMessageSenderInListener(); return; } consumerConnectionContext = getConsumerConnectionContext(); if (consumerConnectionContext == null) { msglog.errorNoConnectionContextInListener(); return; } ProducerConnectionContext producerContext = new ProducerConnectionContext(); producerContext.copy(consumerConnectionContext); producerContext.setDestination(replyTo); Session session = producerContext.getSession(); if (session == null) { msglog.errorNoSessionInListener(); } else { sessionProducer = session.createProducer(replyTo); producerContext.setMessageProducer(sessionProducer); sender.send(producerContext, responseBasicMessage); } } else { getLog().debug("Sender did not tell us where to reply - will not send any response back"); } } catch (Exception e) { msglog.errorFailedToSendResponse(e); return; } finally { try { if (sessionProducer != null) { sessionProducer.close(); } } catch (JMSException e) { msglog.errorFailedToCloseResourcesToRPCClient(e); } } }
Source:
public synchronized void setTableDescriptionSupplier(Supplier<Map<SchemaTableName, ElasticsearchTableDescription>> tableDescriptionSupplier) { this.tableDescriptionSupplier = Optional.of(requireNonNull(tableDescriptionSupplier, "tableDescriptionSupplier is null")); }

Target:
public synchronized void setTableDescriptionSupplier(Supplier<Map<SchemaTableName, ElasticsearchTableDescription>> tableDescriptionSupplier) { requireNonNull(tableDescriptionSupplier, "tableDescriptionSupplier is null"); this.tableDescriptionSupplier = Optional.of(tableDescriptionSupplier); }
Source:
private void calculateCompactSize() { int uniqueIds = 0; boolean[] seen = new boolean[dictionary.getPositionCount()]; boolean[] used = new boolean[dictionary.getPositionCount()]; for (int i = 0; i < positionCount; i++) { int position = getId(i); if (!seen[position]) { if (!dictionary.isNull(position)) { used[position] = true; } uniqueIds++; seen[position] = true; } } this.sizeInBytes = dictionary.getPositionsSizeInBytes(used) + (Integer.BYTES * (long) positionCount); this.uniqueIds = uniqueIds; }

Target:
private void calculateCompactSize() { int uniqueIds = 0; boolean[] used = new boolean[dictionary.getPositionCount()]; for (int i = 0; i < positionCount; i++) { int position = getId(i); if (!used[position]) { uniqueIds++; used[position] = true; } } this.sizeInBytes = dictionary.getPositionsSizeInBytes(used) + (Integer.BYTES * (long) positionCount); this.uniqueIds = uniqueIds; }
Source:
void readsLineFromDefaultMaxCharsFileWithDefaultConfig(@TempDir Path tempDir) throws Exception { Path csvFile = writeClasspathResourceToFile("/default-max-chars.csv", tempDir.resolve("default-max-chars.csv")); CsvFileSource annotation = csvFileSource() .encoding("ISO-8859-1") .resources("/default-max-chars.csv") .files(csvFile.toAbsolutePath().toString()) .build(); Stream<Object[]> arguments = provideArguments(new CsvFileArgumentsProvider(), annotation); assertThat(arguments).hasSize(2 * 1); }

Target:
void readsLineFromDefaultMaxCharsFileWithDefaultConfig(@TempDir Path tempDir) throws Exception { Path csvFile = writeClasspathResourceToFile("/default-max-chars.csv", tempDir.resolve("default-max-chars.csv")); CsvFileSource annotation = csvFileSource() .encoding("ISO-8859-1") .resources("/default-max-chars.csv") .files(csvFile.toAbsolutePath().toString()) .build(); Stream<Object[]> arguments = provideArguments(new CsvFileArgumentsProvider(), annotation); assertThat(arguments).hasSize(2); }
Source:
private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final Collection<? extends ObjectId> unshallowObjects, int depth) throws MissingObjectException, IOException, IncorrectObjectTypeException { final ObjectWalk walker; walker = new DepthWalk.ObjectWalk(reader, depth); walker.setRetainBody(false); walker.sort(RevSort.COMMIT_TIME_DESC); if (thin) walker.sort(RevSort.BOUNDARY, true); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } if (uninterestingObjects != null) { for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } } if (unshallowObjects != null) { for (ObjectId id : unshallowObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } ((DepthWalk.ObjectWalk)walker).markUnshallow(o); } } return walker; }

Target:
private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final Collection<? extends ObjectId> unshallowObjects, int depth) throws MissingObjectException, IOException, IncorrectObjectTypeException { final DepthWalk.ObjectWalk walker = new DepthWalk.ObjectWalk(reader, depth); walker.setRetainBody(false); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } if (uninterestingObjects != null) { for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } } if (unshallowObjects != null) { for (ObjectId id : unshallowObjects) { final RevObject o = walker.parseAny(id); walker.markUnshallow(o); } } return walker; }
Source:
protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__SYNC); addValidationMessage(EngineMessage.VAR__TYPE__GLUSTER_SERVICE); }

Target:
protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__SYNC); addValidationMessage(EngineMessage.VAR__TYPE__GLUSTER_VOLUME); }
Source:
public GroupedPropertyList getPropertyList() { if (propertyList == null) { try{ boolean parallel = true; long t1 = System.currentTimeMillis(); propertyList = new GroupedPropertyList(individual, vreq, editing,parallel); log.debug(" getPropertyList parallel: "+parallel+" time :"+(System.currentTimeMillis()-t1)+" ms"); }catch(Exception e) { e.printStackTrace(); } } return propertyList; }

Target:
public GroupedPropertyList getPropertyList() throws Exception { propertyList = new GroupedPropertyList(individual, vreq, editing); return propertyList; }
Source:
public boolean rolesHavePermission(final Session userSession, final String absPath, final String[] actions, final Set<String> roles) { final String agent = userSession.getUserID(); final List<URI> actionURIs = actionsAsURIs(actions); final Optional<URI> effectiveACL = getEffectiveAcl(new FedoraResourceImpl(userSession.getNode(absPath))); final AuthorizationHandler authHandler = new AuthorizationHandlerImpl(); final Optional<boolean> userPermission = effectiveACL .map(x -> authHandler.getAuthorizations(x, absPath, agent)) .map(x -> isPermitted(actionURIs, x)); final Optional<boolean> groupPermission = effectiveACL .map(x -> authHandler.getAuthorizations(x, absPath, roles)) .map(x -> isPermitted(actionURIs, x)); final boolean permit = userPermission .orElse(groupPermission.orElse(false)); LOGGER.debug("Request for actions: {}, on path: {}, with roles: {}. Permission={}", actions, absPath, roles, permit); return permit; }

Target:
public boolean rolesHavePermission(final Session userSession, final String absPath, final String[] actions, final Set<String> roles) { final Principal userPrincipal = (Principal) userSession.getAttribute(FEDORA_USER_PRINCIPAL); final String agent = userPrincipal.getName(); try { final Map<String, List<String>> resourceAccessRoles = accessRolesProvider.getRoles(userSession.getNode(absPath), true); final Set<String> effectiveRoles = new HashSet<>(); if (resourceAccessRoles.containsKey(agent)) { LOGGER.debug("Applying WebAC rules for user with modes {}", agent, resourceAccessRoles.get(agent)); effectiveRoles.addAll(resourceAccessRoles.get(agent)); } else { for (final String r : roles) { if (resourceAccessRoles.containsKey(r)) { effectiveRoles.addAll(resourceAccessRoles.get(r)); LOGGER.debug("Applying WebAC rules for group with modes {}", r, resourceAccessRoles.get(r)); } } } final boolean permit = effectiveRoles.containsAll(actionsAsURIs(actions)); LOGGER.debug("Request for actions: {}, on path: {}, with roles: {}. Permission={}", actions, absPath, roles, permit); return permit; } catch (final Exception ex) { return false; } }
Source:
private void checkHeaders(final HttpServletRequest request) throws SanitizationException { final Enumeration<String> headerNames = request.getHeaderNames(); LOG.debug("About to check header malious code"); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = request.getHeader(name); try { boolean isValid = ESAPI.validator().isValidInput("HTTP header value: " + value, value, "HTTPHeaderValue", 200, true); if (!isValid) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Detect malious code -->orignal name/values: "); strBuilder.append(name); strBuilder.append("/"); strBuilder.append(value); LOG.error(strBuilder.toString()); throw new SanitizationException(strBuilder.toString()); } } catch (IntrusionException ex) { throw new SanitizationException(ex); } } LOG.debug("End of checking header malious code"); }

Target:
private static void checkHeaders(final HttpServletRequest request) throws SanitizationException { final Enumeration<String> headerNames = request.getHeaderNames(); LOG.debug("About to check header malicious code"); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = request.getHeader(name); try { boolean isValid = ESAPI.validator().isValidInput("HTTP header value: " + value, value, "HTTPHeaderValue", 200, true); if (!isValid) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Detect malicious code -->orignal name/values: "); strBuilder.append(name); strBuilder.append("/"); strBuilder.append(value); LOG.error(strBuilder.toString()); throw new SanitizationException(strBuilder.toString()); } } catch (IntrusionException ex) { throw new SanitizationException(ex); } } LOG.debug("End of checking header malicious code"); }
Source:
protected IShowInTargetList getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }

Target:
private IShowInTargetList getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }