auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String findMatch(Set<String> names, URIish uri) { String bestMatch = null; int bestMatchLength = -1; boolean withUser = false; String uPath = uri.getPath(); boolean hasPath = uPath != null && !uPath.isEmpty(); if (hasPath) { uPath = normalize(uPath); if (uPath == null) { return null; } } for (String s : names) { try { URIish candidate = new URIish(s); if (!compare(uri.getScheme(), candidate.getScheme()) || !compare(uri.getHost(), candidate.getHost())) { continue; } if (defaultedPort(uri.getPort(), uri.getScheme()) != defaultedPort(candidate.getPort(), candidate.getScheme())) { continue; } boolean hasUser = false; if (candidate.getUser() != null) { if (!candidate.getUser().equals(uri.getUser())) { continue; } hasUser = true; } String cPath = candidate.getPath(); int matchLength = -1; if (cPath == null || cPath.isEmpty()) { matchLength = 0; } else { if (!hasPath) { continue; } matchLength = segmentCompare(uPath, cPath); if (matchLength < 0) { continue; } } if (matchLength > bestMatchLength || !withUser && hasUser && matchLength >= 0 && matchLength == bestMatchLength) { bestMatch = s; bestMatchLength = matchLength; withUser = hasUser; } } catch (URISyntaxException e) { LOG.warn(MessageFormat .format(JGitText.get().httpConfigInvalidURL, s)); } } return bestMatch; }

Target:
private String findMatch(Set<String> names, URIish uri) { String bestMatch = null; int bestMatchLength = -1; boolean withUser = false; String uPath = uri.getPath(); boolean hasPath = !StringUtils.isEmptyOrNull(uPath); if (hasPath) { uPath = normalize(uPath); if (uPath == null) { return null; } } for (String s : names) { try { URIish candidate = new URIish(s); if (!compare(uri.getScheme(), candidate.getScheme()) || !compare(uri.getHost(), candidate.getHost())) { continue; } if (defaultedPort(uri.getPort(), uri.getScheme()) != defaultedPort(candidate.getPort(), candidate.getScheme())) { continue; } boolean hasUser = false; if (candidate.getUser() != null) { if (!candidate.getUser().equals(uri.getUser())) { continue; } hasUser = true; } String cPath = candidate.getPath(); int matchLength = -1; if (StringUtils.isEmptyOrNull(cPath)) { matchLength = 0; } else { if (!hasPath) { continue; } matchLength = segmentCompare(uPath, cPath); if (matchLength < 0) { continue; } } if (matchLength > bestMatchLength || !withUser && hasUser && matchLength >= 0 && matchLength == bestMatchLength) { bestMatch = s; bestMatchLength = matchLength; withUser = hasUser; } } catch (URISyntaxException e) { LOG.warn(MessageFormat .format(JGitText.get().httpConfigInvalidURL, s)); } } return bestMatch; }
Source:
boolean trustsDomain(final SecurityDomain domain) { Assert.checkNotNullParam("domain", domain); return this == domain ? true : trustedSecurityDomain.test(domain); }

Target:
boolean trustsDomain(final SecurityDomain domain) { Assert.checkNotNullParam("domain", domain); return this == domain || trustedSecurityDomain.test(domain); }
Source:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); file.createNewFile(); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(content.getBytes("UTF-8")); } finally { if (fos != null) fos.close(); } }

Target:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); FileOutputStream fos = new FileOutputStream(file); try { fos.write(content.getBytes("UTF-8")); } finally { fos.close(); } }
Source:
public ExceptionEvent(String exMessage, boolean isRatioException) { super(); this.description(exMessage); if (isRatioException) { this.tags.add("exception"); } else { this.tags.add("ratio-exception"); } }

Target:
public ExceptionEvent(String exMessage, boolean isRatioException) { super(); this.description(exMessage); if (isRatioException) { this.tags.add("ratio-exception"); } else { this.tags.add("exception"); } }
Source:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); verify(testToolsPresenterSpy, never()).showInstanceListContainerSeparator(eq(true)); }

Target:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); }
Source:
public OneSlotPerExecutionSlotAllocatorFactory( final SlotProvider slotProvider, final boolean slotWillBeOccupiedIndefinitely, final Time allocationTimeout) { this.slotProvider = checkNotNull(slotProvider); this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.allocationTimeout = checkNotNull(allocationTimeout); }

Target:
OneSlotPerExecutionSlotAllocatorFactory( final SlotProvider slotProvider, final boolean slotWillBeOccupiedIndefinitely, final Time allocationTimeout) { this.slotProvider = checkNotNull(slotProvider); this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.allocationTimeout = checkNotNull(allocationTimeout); }
Source:
public void createNewPayment_withCardPayment_invokesCreatePaymentService() { final Account account = new Account("foo", TokenPaymentType.CARD); final CreatePaymentRequest createPaymentRequest = CreatePaymentRequest.builder() .amount(100) .returnUrl("<LINK_0>") .reference("my_ref") .description("New Passport") .build(); PaymentWithAllLinks injectedResponse = aSuccessfullyCreatedPayment(); when(createPaymentService.create(eq(account), ArgumentMatchers.any())).thenReturn(injectedResponse); final Response newPayment = paymentsResource.createNewPayment(account, createPaymentRequest); assertThat(newPayment.getStatus(), is(201)); assertThat(newPayment.getLocation(), is(URI.create(paymentUri))); assertThat(newPayment.getEntity(), sameInstance(injectedResponse)); }

Target:
public void createNewPayment_withCardPayment_invokesCreatePaymentService() { final Account account = new Account("foo", TokenPaymentType.CARD); final CreatePaymentRequest createPaymentRequest = CreatePaymentRequest.builder() .amount(100) .returnUrl("<LINK_0>") .reference("my_ref") .description("New Passport") .build(); final ValidCreatePaymentRequest validCreatePaymentRequest = new ValidCreatePaymentRequest(createPaymentRequest); PaymentWithAllLinks injectedResponse = aSuccessfullyCreatedPayment(); when(createPaymentService.create(account, validCreatePaymentRequest)).thenReturn(injectedResponse); final Response newPayment = paymentsResource.createNewPayment(account, createPaymentRequest); assertThat(newPayment.getStatus(), is(201)); assertThat(newPayment.getLocation(), is(URI.create(paymentUri))); assertThat(newPayment.getEntity(), sameInstance(injectedResponse)); }
Source:
public Collection<IteratorSetting> getIterators() { return iterators.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toSet()); }

Target:
public Collection<IteratorSetting> getIterators() { return iterators.values(); }
Source:
public static Timestamp addMonths(final Timestamp refDate, final int nrOfMonthsToAdd) { Calendar calendar = Calendar.getInstance(); calendar.setTime(refDate); calendar.add(Calendar.MONTH, nrOfMonthsToAdd); return new Timestamp(calendar.getTime().getTime()); }

Target:
public static Timestamp addMonths(final Timestamp refDate, final int nrOfMonthsToAdd) { Calendar calendar = Calendar.getInstance(); calendar.setTime(refDate); calendar.add(Calendar.MONTH, nrOfMonthsToAdd); Timestamp resultDate = new Timestamp(calendar.getTimeInMillis()); resultDate.setNanos(refDate.getNanos()); return resultDate; }
Source:
public void endVisit(@Nonnull JDefinedClassOrInterface type) { String binaryName = remapper.mapValue(formatter.getName(type)); String packageName = NamingTools.getPackageNameFromBinaryName(binaryName); JPackage newPackage = lookup.getOrCreatePackage(packageName); lookup.removeType(type); request.append(new ChangeEnclosingPackage(type, newPackage)); }

Target:
public void endVisit(@Nonnull JDefinedClassOrInterface type) { String binaryName = remapper.mapValue(formatter.getName(type)); String simpleName = NamingTools.getSimpleClassNameFromBinaryName(binaryName); type.setName(simpleName); String packageName = NamingTools.getPackageNameFromBinaryName(binaryName); JPackage newPackage = lookup.getOrCreatePackage(packageName); lookup.removeType(type); request.append(new ChangeEnclosingPackage(type, newPackage)); }
Source:
private Void deleteScheduledTask(String taskId, SingularityUser user) { SingularityTaskRequest taskRequest = getPendingTask(user, taskId); SingularityRequest request = taskRequest.getRequest(); authorizationHelper.checkForAuthorization(request, user, SingularityAuthorizationScope.WRITE); checkBadRequest(request.getRequestType() == RequestType.ON_DEMAND, "Only ON_DEMAND tasks may be deleted."); taskManager.markPendingTaskForDeletion(taskRequest.getPendingTask().getPendingTaskId()); return null; }

Target:
public Optional<SingularityPendingTask> deleteScheduledTask(String taskId, SingularityUser user) { Optional<SingularityPendingTask> maybePendingTask = taskManager.getPendingTask(getPendingTaskIdFromStr(taskId)); if (maybePendingTask.isPresent()) { SingularityPendingTaskId pendingTaskId = maybePendingTask.get().getPendingTaskId(); Optional<SingularityRequestWithState> maybeRequest = requestManager.getRequest(pendingTaskId.getRequestId()); checkNotFound(maybeRequest.isPresent(), "Couldn't find: " + taskId); SingularityRequest request = maybeRequest.get().getRequest(); authorizationHelper.checkForAuthorizationByRequestId(request.getId(), user, SingularityAuthorizationScope.WRITE); checkBadRequest(request.getRequestType() == RequestType.ON_DEMAND, "Only ON_DEMAND tasks may be deleted."); taskManager.markPendingTaskForDeletion(pendingTaskId); } return maybePendingTask; }
Source:
protected WorkDefinitionMatch getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(IAtsTeamDefinition teamDefinition) throws OseeCoreException { Conditions.notNull(teamDefinition); Collection<Object> attrs = workItemService.getAttributeValues(teamDefinition, AtsAttributeTypes.RelatedPeerWorkflowDefinition); if (attrs.isEmpty()) { IAtsTeamDefinition parentTeamDef = teamDefinition.getParentTeamDef(); if (parentTeamDef != null) { return getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(parentTeamDef); } } else { WorkDefinitionMatch match = getWorkDefinition((String) attrs.iterator().next()); match.addTrace("PeerToPeer from Team Definition"); return match; } return new WorkDefinitionMatch(); }

Target:
protected WorkDefinitionMatch getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(IAtsTeamDefinition teamDefinition) throws OseeCoreException { Conditions.notNull(teamDefinition, getClass().getSimpleName()); WorkDefinitionMatch match = new WorkDefinitionMatch(); Collection<Object> attrs = workItemService.getAttributeValues(teamDefinition, AtsAttributeTypes.RelatedPeerWorkflowDefinition); if (attrs.isEmpty()) { IAtsTeamDefinition parentTeamDef = teamDefinition.getParentTeamDef(); if (parentTeamDef != null) { match = getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(parentTeamDef); } } else { match = getWorkDefinition((String) attrs.iterator().next()); match.addTrace("PeerToPeer from Team Definition"); } return match; }
Source:
public static <A> Hash<A> anyHash() { return new Hash<A>(a -> a.hashCode()); }

Target:
public static <A> Hash<A> anyHash() { return hash(a -> a.hashCode()); }
Source:
private List<Object> listInternal() { List<Object> results; try (CloseableIterator<ObjectFilter.FilterResult> iterator = getIterator()) { if (!iterator.hasNext()) { results = Collections.emptyList(); } else { Comparator<Comparable[]> comparator = getComparator(); if (comparator == null) { if (iterator.hasNext()) { results = new ArrayList<>(INITIAL_CAPACITY); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; if (resultSize > startOffset && (maxResults == -1 || results.size() < maxResults)) { results.add(projection != null ? entry.getProjection() : entry.getInstance()); } } } else { results = Collections.emptyList(); } } else { PriorityQueue<ObjectFilter.FilterResult> filterResults = new PriorityQueue<>(INITIAL_CAPACITY, new ReverseFilterResultComparator(comparator)); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; filterResults.add(entry); if (maxResults != -1 && filterResults.size() > startOffset + maxResults) { filterResults.remove(); } } if (filterResults.size() > startOffset) { Object[] res = new Object[filterResults.size() - startOffset]; int i = filterResults.size(); while (i-- > startOffset) { ObjectFilter.FilterResult r = filterResults.remove(); res[i - startOffset] = projection != null ? r.getProjection() : r.getInstance(); } results = Arrays.asList(res); } else { results = Collections.emptyList(); } } } } return results; }

Target:
private List<Object> listInternal() { List<Object> results; try (CloseableIterator<ObjectFilter.FilterResult> iterator = getIterator()) { if (!iterator.hasNext()) { results = Collections.emptyList(); } else { Comparator<Comparable[]> comparator = getComparator(); if (comparator == null) { results = new ArrayList<>(INITIAL_CAPACITY); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; if (resultSize > startOffset && (maxResults == -1 || results.size() < maxResults)) { results.add(projection != null ? entry.getProjection() : entry.getInstance()); } } } else { PriorityQueue<ObjectFilter.FilterResult> filterResults = new PriorityQueue<>(INITIAL_CAPACITY, new ReverseFilterResultComparator(comparator)); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; filterResults.add(entry); if (maxResults != -1 && filterResults.size() > startOffset + maxResults) { filterResults.remove(); } } if (filterResults.size() > startOffset) { Object[] res = new Object[filterResults.size() - startOffset]; int i = filterResults.size(); while (i-- > startOffset) { ObjectFilter.FilterResult r = filterResults.remove(); res[i - startOffset] = projection != null ? r.getProjection() : r.getInstance(); } results = Arrays.asList(res); } else { results = Collections.emptyList(); } } } } return results; }
Source:
public AggregateRoot(Command command) { ApplyMore antThen = apply(new Event_1(command.getId(), 0)); for (int i = 0; i < command.value; i++) { antThen = antThen.andThenApply(() -> new Event_1(id, value + 1)); } }

Target:
public AggregateRoot(Command command) { ApplyMore andThen = apply(new Event_1(command.getId(), 0)); for (int i = 0; i < command.value; i++) { andThen = andThen.andThenApply(() -> new Event_1(id, value + 1)); } }
Source:
public static String randomCreditCardNumber(final String prefix) { Check.matchesPattern("prefix", prefix, CARD_PREFIX_PATTERN); final int length = randomIntInRange(13, 19); final int randomNumberLength = length - (prefix.length() + 1); final StringBuffer buffer = new StringBuffer(prefix); for (int i = 0; i < randomNumberLength; i++) { final int digit = Randoms.randomInt(10); buffer.append(digit); } final int checkDigit = getCheckDigit(buffer.toString()); buffer.append(checkDigit); return buffer.toString(); }

Target:
public static String randomCreditCardNumber(final String prefix) { if (!CARD_PREFIX_PATTERN.matcher(prefix).matches()) { throw new IllegalArgumentException(String.format("Invalid card prefix: %s", prefix)); } final int length = randomIntInRange(13, 19); final int randomNumberLength = length - (prefix.length() + 1); final StringBuffer buffer = new StringBuffer(prefix); for (int i = 0; i < randomNumberLength; i++) { final int digit = Randoms.randomInt(10); buffer.append(digit); } final int checkDigit = getCreditCardCheckDigit(buffer.toString()); buffer.append(checkDigit); return buffer.toString(); }
Source:
public void testConcurrentWarningReadAndClear() throws SQLException, InterruptedException, ExecutionException, TimeoutException { final int iterations = 1000; final ExecutorService executor = Executors.newSingleThreadExecutor(); final PgStatement statement = (PgStatement) con.createStatement(); final Future warningReaderThread = executor.submit(new Callable<Object>() { @Override public Object call() throws SQLException, InterruptedException { SQLWarning lastProcessed = null; int warnings = 0; while (warnings < iterations) { final SQLWarning warn = lastProcessed != null && lastProcessed.getNextWarning() != null ? lastProcessed.getNextWarning() : statement.getWarnings(); if (warn != null) { warnings++; lastProcessed = warn; if (warn == statement.getWarnings()) { statement.clearWarnings(); } } else { Thread.sleep(10); } } assertEquals(lastProcessed.getMessage(), "Warning " + (iterations - 1)); return null; } }); for (int i = 0; i < iterations; i++) { statement.addWarning(new SQLWarning("Warning " + i)); if (i % 33 == 0 ) { Thread.sleep(1); } } warningReaderThread.get(2, TimeUnit.SECONDS); }

Target:
public void testConcurrentWarningReadAndClear() throws SQLException, InterruptedException, ExecutionException, TimeoutException { final int iterations = 1000; con.createStatement() .execute("CREATE OR REPLACE FUNCTION notify_loop() RETURNS VOID AS " + "$BODY$ " + "BEGIN " + "FOR i IN 1.. " + iterations + " LOOP " + " RAISE NOTICE 'Warning %', i; " + "END LOOP; " + "END " + "$BODY$ " + "LANGUAGE plpgsql;"); con.createStatement().execute("SET SESSION client_min_messages = 'NOTICE'"); final PreparedStatement statement = con.prepareStatement("SELECT notify_loop()"); final Callable<Void> warningReader = new Callable<Void>() { @Override public Void call() throws SQLException, InterruptedException { SQLWarning lastProcessed = null; int warnings = 0; while (warnings < iterations) { SQLWarning warn = statement.getWarnings(); if (lastProcessed != null && lastProcessed.getNextWarning() != null) { warn = lastProcessed.getNextWarning(); } if (warn != null) { warnings++; assertEquals("Received warning out of expected order", "Warning " + warnings, warn.getMessage()); lastProcessed = warn; if (warn == statement.getWarnings()) { statement.clearWarnings(); } } else { Thread.sleep(10); } } assertEquals("Didn't receive expected last warning", "Warning " + iterations, lastProcessed.getMessage()); return null; } }; final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future warningReaderThread = executor.submit(warningReader); statement.execute(); warningReaderThread.get(2, TimeUnit.SECONDS); } finally { executor.shutdownNow(); } }
Source:
public static void setup() { runRollersButton.send(runRollers); toggleRollersButton.send(new BooleanOutput() { public void set(boolean value) { if (value) { direction.set(!direction.get()); } } }); Igneous.globalPeriodic.send(new EventOutput() { public void event() { if (speed.get() != 0.0f) { float newSpeed = direction.get() ? 1.0f : -1.0f; allRollers.set(newSpeed); } else { allRollers.set(0.0f); } } }); }

Target:
public static void setup() { running.toggleWhen(runRollersButton); direction.toggleWhen(toggleRollersButton); motorSpeed.send(allRollers); }
Source:
private void sendInvalidJSonPayload(int size) throws JsonProcessingException { thrown.expectCause(isA(BeatsParser.InvalidPayloadSize.class)); Map mapData = Collections.singletonMap("message", "hola"); ByteBuf payload = Unpooled.buffer(); payload.writeByte(Protocol.VERSION_2); payload.writeByte('W'); payload.writeInt(1); payload.writeByte(Protocol.VERSION_2); payload.writeByte('J'); payload.writeInt(1); payload.writeInt(size); byte[] json = BeatsParser.MAPPER.writeValueAsBytes(mapData); payload.writeBytes(json); sendPayloadToParser(payload); }

Target:
private void sendInvalidJSonPayload(int size) throws JsonProcessingException { thrown.expectCause(isA(BeatsParser.InvalidFrameProtocolException.class)); thrown.expectMessage("Invalid json length, received: " + size); Map mapData = Collections.singletonMap("message", "hola"); ByteBuf payload = Unpooled.buffer(); payload.writeByte(Protocol.VERSION_2); payload.writeByte('W'); payload.writeInt(1); payload.writeByte(Protocol.VERSION_2); payload.writeByte('J'); payload.writeInt(1); payload.writeInt(size); byte[] json = BeatsParser.MAPPER.writeValueAsBytes(mapData); payload.writeBytes(json); sendPayloadToParser(payload); }
Source:
public void update(long value, long timestamp) { rescaleIfNeeded(); lockForRegularUsage(); try { final double itemWeight = weight(timestamp - startTime); final WeightedSample sample = new WeightedSample(value, itemWeight); final double priority = itemWeight / ThreadLocalRandomFactory.current().nextDouble(); final long newCount = count.incrementAndGet(); if (newCount <= size) { values.put(priority, sample); } else { Double first = values.firstKey(); if (first < priority && values.putIfAbsent(priority, sample) == null) { while (values.remove(first) == null) { first = values.firstKey(); } } } } finally { unlockForRegularUsage(); } }

Target:
public void update(long value, long timestamp) { rescaleIfNeeded(); lockForRegularUsage(); try { final double itemWeight = weight(timestamp - startTime); final WeightedSample sample = new WeightedSample(value, itemWeight); final double priority = itemWeight / ThreadLocalRandomProxy.current().nextDouble(); final long newCount = count.incrementAndGet(); if (newCount <= size) { values.put(priority, sample); } else { Double first = values.firstKey(); if (first < priority && values.putIfAbsent(priority, sample) == null) { while (values.remove(first) == null) { first = values.firstKey(); } } } } finally { unlockForRegularUsage(); } }
Source:
public void setup() { client = helper.createClientForBasicAuth(); factory = new ResourceFactory(client); OpenshiftProjectRequest projectRequest = factory.create(VERSION, ResourceKind.PROJECT_REQUEST); projectRequest.setName(helper.generateNamespace()); project = (IProject) client.create(projectRequest); buildConfigs.add(createBuildConfigWithLabels(project, "build1", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "no"); put("baz", "no"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build2", new HashMap<String, String>() {{ put("foo", "no"); put("bar", "yes"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build3", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "yes"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build4", new HashMap<>())); }

Target:
public static void setup() { client = helper.createClientForBasicAuth(); factory = new ResourceFactory(client); OpenshiftProjectRequest projectRequest = factory.create(VERSION, ResourceKind.PROJECT_REQUEST); projectRequest.setName(helper.generateNamespace()); project = (IProject) client.create(projectRequest); createBuildConfigWithLabels(project, "build1", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "no"); put("baz", "no"); }}); createBuildConfigWithLabels(project, "build2", new HashMap<String, String>() {{ put("foo", "no"); put("bar", "yes"); }}); createBuildConfigWithLabels(project, "build3", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "yes"); }}); createBuildConfigWithLabels(project, "build4", new HashMap<>()); }
Source:
public Document parse(Reader input) throws IOException { DocumentBlockParser documentBlockParser = new DocumentBlockParser(); activateBlockParser(documentBlockParser); BufferedReader bufferedReader; if (input instanceof BufferedReader) { bufferedReader = (BufferedReader) input; } else { bufferedReader = new BufferedReader(input); } String line; while ((line = bufferedReader.readLine()) != null) { incorporateLine(line); } finalizeBlocks(activeBlockParsers); this.processInlines(); return documentBlockParser.getBlock(); }

Target:
public Document parse(Reader input) throws IOException { BufferedReader bufferedReader; if (input instanceof BufferedReader) { bufferedReader = (BufferedReader) input; } else { bufferedReader = new BufferedReader(input); } String line; while ((line = bufferedReader.readLine()) != null) { incorporateLine(line); } return finalizeAndProcess(); }
Source:
ProcessWorkProcessor(WorkProcessor.Process<T> process) { this.process = requireNonNull(process, "process is null"); }

Target:
private ProcessWorkProcessor(WorkProcessor.Process<T> process) { this.process = requireNonNull(process, "process is null"); }
Source:
private static Map<Guid, VdcObjectType> getSubjectEntities(List<PermissionSubject> permSubjectList) { return permSubjectList.stream() .filter(subject -> subject != null) .filter(subject -> subject.getObjectType() != null) .collect(toMap( subject -> subject.getObjectId(), subject -> subject.getObjectType() )); }

Target:
private static Map<Guid, VdcObjectType> getSubjectEntities(List<PermissionSubject> permSubjectList) { return permSubjectList.stream() .filter(subject -> subject != null) .filter(subject -> subject.getObjectType() != null) .collect(Collectors.toMap(PermissionSubject::getObjectId, PermissionSubject::getObjectType)); }
Source:
protected Cluster updateTopology() { Cluster cluster = destinationCluster.clone(); switch (operationType) { case NODE: { logger.info("Detaching node: from stripe: {}", source, destination); Stripe stripe = cluster.getStripe(source).get(); if (stripe.getNodeCount() == 1) { throw new IllegalStateException("Unable to detach since destination stripe contains only 1 node"); } cluster.detachNode(source); break; } case STRIPE: { Stripe stripe = cluster.getStripe(source).get(); logger.info("Detaching stripe containing nodes: from cluster: {}", toString(stripe.getNodeAddresses()), destination); cluster.detachStripe(stripe); break; } default: { throw new UnsupportedOperationException(operationType.name()); } } return cluster; }

Target:
protected Cluster updateTopology() { Cluster cluster = destinationCluster.clone(); switch (operationType) { case NODE: { logger.info("Detaching node: from stripe: {}", source, destination); cluster.detachNode(source); break; } case STRIPE: { Stripe stripe = cluster.getStripe(source).get(); logger.info("Detaching stripe containing nodes: from cluster: {}", toString(stripe.getNodeAddresses()), destination); cluster.detachStripe(stripe); break; } default: { throw new UnsupportedOperationException(operationType.name()); } } return cluster; }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { Assumption.assertNotNull(regkey); String nextUrl; if (regkey.contains("${amp}" + Const.ParamsNames.NEXT_URL)) { String[] split = regkey.split("\\$\\{amp\\}" + Const.ParamsNames.NEXT_URL + "="); regkey = split[0]; nextUrl = split[1]; } else { nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); } Assumption.assertNotNull(nextUrl); nextUrl = Sanitizer.desanitizeFromNextUrl(nextUrl); ensureStudentExists(); try { logic.joinCourseForStudent(regkey, account.googleId); } catch (JoinCourseException e) { if (e.errorCode == Const.StatusCodes.INVALID_KEY) { setStatusForException(e, String.format(e.getMessage(), requestUrl)); } else { setStatusForException(e, e.getMessage()); } nextUrl = Const.ActionURIs.STUDENT_HOME_PAGE; excludeStudentDetailsFromResponseParams(); return createRedirectResult(nextUrl); } final String studentInfo = "Action Student Joins Course" + "<br/>Google ID: " + account.googleId + "<br/>Key : " + regkey; RedirectResult response = createRedirectResult(nextUrl); response.addResponseParam(Const.ParamsNames.CHECK_PERSISTENCE_COURSE, getStudent().course); excludeStudentDetailsFromResponseParams(); if(statusToAdmin != null && !statusToAdmin.trim().isEmpty()) { statusToAdmin += "<br/><br/>" + studentInfo; } else { statusToAdmin = studentInfo; } addStatusMessageToUser(); return response; }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { Assumption.assertNotNull(regkey); String nextUrl; if (regkey.contains("${amp}" + Const.ParamsNames.NEXT_URL + "=")) { String[] split = regkey.split("\\$\\{amp\\}" + Const.ParamsNames.NEXT_URL + "="); regkey = split[0]; nextUrl = split[1]; } else { nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); } Assumption.assertNotNull(nextUrl); nextUrl = Sanitizer.desanitizeFromNextUrl(nextUrl); ensureStudentExists(); try { logic.joinCourseForStudent(regkey, account.googleId); } catch (JoinCourseException e) { if (e.errorCode == Const.StatusCodes.INVALID_KEY) { setStatusForException(e, String.format(e.getMessage(), requestUrl)); } else { setStatusForException(e, e.getMessage()); } nextUrl = Const.ActionURIs.STUDENT_HOME_PAGE; excludeStudentDetailsFromResponseParams(); return createRedirectResult(nextUrl); } final String studentInfo = "Action Student Joins Course" + "<br/>Google ID: " + account.googleId + "<br/>Key : " + regkey; RedirectResult response = createRedirectResult(nextUrl); response.addResponseParam(Const.ParamsNames.CHECK_PERSISTENCE_COURSE, getStudent().course); excludeStudentDetailsFromResponseParams(); if(statusToAdmin != null && !statusToAdmin.trim().isEmpty()) { statusToAdmin += "<br/><br/>" + studentInfo; } else { statusToAdmin = studentInfo; } addStatusMessageToUser(); return response; }
Source:
public GradleProjectConvertWizard(IDialogSettings dialogSettings, PublishedGradleVersions publishedGradleVersions) { Preconditions.checkNotNull(dialogSettings); Preconditions.checkNotNull(publishedGradleVersions); setDialogSettings(dialogSettings); this.setController(new ProjectImportWizardController(this)); ProjectImportConfiguration configuration = this.getController().getConfiguration(); this.gradleOptionsPage = new GradleOptionsWizardPage(configuration, publishedGradleVersions); this.gradleOptionsPage.setTitle("Convert to Gralde"); this.gradleOptionsPage.setMessage("Settings for the conversion to Gralde"); }

Target:
public GradleProjectConvertWizard(IDialogSettings dialogSettings, PublishedGradleVersions publishedGradleVersions) { Preconditions.checkNotNull(dialogSettings); Preconditions.checkNotNull(publishedGradleVersions); setDialogSettings(dialogSettings); setController(new ProjectImportWizardController(this)); ProjectImportConfiguration configuration = getController().getConfiguration(); this.gradleOptionsPage = new GradleOptionsWizardPage(configuration, publishedGradleVersions); this.gradleOptionsPage.setTitle("Convert to Gradle"); this.gradleOptionsPage.setMessage("Settings for the conversion to Gradle"); }
Source:
private TreeNode getTree(Node parent, TreeNode treeparent) { for (Relationship r : IteratorUtil.loop(parent.getRelationships(Direction.OUTGOING, RelTypes.ANCESTOR_OF).iterator())) { TreeNode child = new TreeNode(treeparent); child.setDistance((int) parent.getProperty(PropertyTypes.DIST_TO_ROOT.name()) + 1); if (r.getEndNode().hasLabel(NodeLabels.SOURCE)) { child.setName((String) r.getEndNode().getProperty(PropertyTypes.SOURCE.name())); } else { getTree(r.getEndNode(), child); } } return treeparent; }

Target:
private TreeNode getTree(Node parent, TreeNode treeparent) { for (Relationship r : parent.getRelationships(Direction.OUTGOING, RelTypes.ANCESTOR_OF)) { TreeNode child = new TreeNode(treeparent); child.setDistance((int) parent.getProperty(PropertyTypes.DIST_TO_ROOT.name()) + 1); if (r.getEndNode().hasLabel(NodeLabels.SOURCE)) { child.setName((String) r.getEndNode().getProperty(PropertyTypes.SOURCE.name())); } else { getTree(r.getEndNode(), child); } } return treeparent; }
Source:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object object = nonEntityDictionary.getValue(nonEntity, fieldName, context.requestScope); if (object == null) { return null; } if (nonEntityDictionary.hasBinding(new ClassType(object.getClass()))) { return new NonEntityContainer(object); } if (object instanceof Map) { return ((Map<Object, Object>) object).entrySet().stream() .map(MapEntryContainer::new) .collect(Collectors.toList()); } if (object instanceof Collection) { Type<?> innerType = nonEntityDictionary.getParameterizedType(nonEntity.getClass(), fieldName); if (nonEntityDictionary.hasBinding(innerType)) { return ((Collection) object).stream() .map(NonEntityContainer::new) .collect(Collectors.toList()); } } return object; }

Target:
public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { NonEntityDictionary nonEntityDictionary = fetcher.getNonEntityDictionary(); String fieldName = context.field.getName(); Object object = nonEntityDictionary.getValue(nonEntity, fieldName, context.requestScope); if (object == null) { return null; } if (nonEntityDictionary.hasBinding(EntityDictionary.getType(object))) { return new NonEntityContainer(object); } if (object instanceof Map) { return ((Map<Object, Object>) object).entrySet().stream() .map(MapEntryContainer::new) .collect(Collectors.toList()); } if (object instanceof Collection) { Type<?> innerType = nonEntityDictionary.getParameterizedType(nonEntity.getClass(), fieldName); if (nonEntityDictionary.hasBinding(innerType)) { return ((Collection) object).stream() .map(NonEntityContainer::new) .collect(Collectors.toList()); } } return object; }
Source:
private void validatePayloadHasFields(JsonNode payload, List<String> expectedFields, List<String> atLeastOneOfTheseFieldsMustExist) throws ValidationException { if (payload == null) { throw new ValidationException("Body cannot be empty"); } List<String> missingFields = expectedFields .stream() .filter(expectedKey -> !payload.has(expectedKey)) .collect(Collectors.toList()); if (!missingFields.isEmpty()) { throw new ValidationException(format("Missing fields: [%s]", String.join(", ", missingFields))); } if (!atLeastOneOfTheseFieldsMustExist.isEmpty() && atLeastOneOfTheseFieldsMustExist .stream() .noneMatch(payload::has)) { throw new ValidationException(format("At least one of these fields must be present: [%s]", String.join(", ", atLeastOneOfTheseFieldsMustExist))); } }

Target:
private void validatePayloadHasFields(JsonNode payload, List<String> expectedFields, List<String> atLeastOneOfTheseFieldsMustExist) throws ValidationException { if (payload == null) { throw new ValidationException("Body cannot be empty"); } List<String> missingFields = expectedFields .stream() .filter(expectedKey -> !payload.has(expectedKey)) .collect(Collectors.toList()); if (!missingFields.isEmpty()) { throw new ValidationException("Missing fields: " + missingFields); } if (!atLeastOneOfTheseFieldsMustExist.isEmpty() && atLeastOneOfTheseFieldsMustExist .stream() .noneMatch(payload::has)) { throw new ValidationException("At least one of these fields must be present: " + atLeastOneOfTheseFieldsMustExist); } }
Source:
public PasswordGrantRequest createAccessTokenAuthenticationRequest(HttpServletRequest request) throws OauthException { try { String username = Strings.clean(request.getParameter(USERNAME_PARAM_NAME)); Assert.hasText(username, "username must not be null or empty."); String password = Strings.clean(request.getParameter(PASSWORD_PARAM_NAME)); Assert.hasText(password, "password must not be null or empty."); String accountStoreId = Strings.clean(request.getParameter(ACCOUNT_STORE_PARAM_NAME)); AccountStore accountStore = null; if (accountStore != null){ return Oauth2Requests.PASSWORD_GRANT_REQUEST.builder() .setPassword(password) .setLogin(username) .setAccountStore(accountStore) .build(); } else { return Oauth2Requests.PASSWORD_GRANT_REQUEST.builder() .setPassword(password) .setLogin(username) .build(); } } catch (Exception e){ throw new OauthException(OauthErrorCode.INVALID_REQUEST); } }

Target:
public PasswordGrantRequest createAccessTokenAuthenticationRequest(HttpServletRequest request) throws OauthException { try { String username = Strings.clean(request.getParameter(USERNAME_PARAM_NAME)); Assert.hasText(username, "username must not be null or empty."); String password = Strings.clean(request.getParameter(PASSWORD_PARAM_NAME)); Assert.hasText(password, "password must not be null or empty."); AccountStore accountStore = accountStoreResolver.getAccountStore(request, null); PasswordGrantRequestBuilder requestBuilder = Oauth2Requests.PASSWORD_GRANT_REQUEST.builder() .setPassword(password) .setLogin(username); if (accountStore != null){ requestBuilder.setAccountStore(accountStore); } return requestBuilder.build(); } catch (Exception e){ throw new OauthException(OauthErrorCode.INVALID_REQUEST); } }
Source:
public void init() { if (!versionTableExist()) { try (Connection connection = dataSource.getConnection()) { createVersionTable(connection); createVersionTableRow(connection); } catch (SQLException e) { throw new RuntimeException(e); } } }

Target:
public void init() { if (!versionTableExist()) { try (Connection connection = dataSource.getConnection()) { createVersionTable(connection); createVersionTableRow(connection); } catch (SQLException e) { throw new UncheckedSqlException(e); } } }
Source:
public void dispose() { super.dispose(); if (fStatsViewers != null) { fStatsViewers.dispose(); } TmfStatisticsTreeRootFactory.removeAll(); }

Target:
public void dispose() { super.dispose(); fStatsViewers.dispose(); TmfStatisticsTreeRootFactory.removeAll(); }
Source:
public void writeTaskPartitionAssignments(Map<SystemStreamPartition, List<String>> sspToTaskNameMapping) { for (SystemStreamPartition partition: sspToTaskNameMapping.keySet()) { List<String> taskNames = sspToTaskNameMapping.get(partition); LOG.info("Storing ssp: and task: into metadata store", partition, taskNames); String serializedSSPAsJson = serializeSSPToJson(partition); if (taskNames == null || taskNames.isEmpty()) { LOG.info("Deleting the key: from the metadata store.", partition); metadataStore.delete(serializedSSPAsJson); } else { try { String taskNamesAsString = taskNamesMapper.writeValueAsString(taskNames); byte[] taskNamesAsBytes = valueSerde.toBytes(taskNamesAsString); LOG.info("Storing the partition: and taskNames: into the metadata store.", serializedSSPAsJson, taskNames); metadataStore.put(serializedSSPAsJson, taskNamesAsBytes); } catch (Exception e) { throw new SamzaException("Exception occurred when writing task to partition assignment.", e); } } } metadataStore.flush(); }

Target:
public void writeTaskPartitionAssignments(Map<SystemStreamPartition, List<String>> sspToTaskNameMapping) { for (SystemStreamPartition partition: sspToTaskNameMapping.keySet()) { List<String> taskNames = sspToTaskNameMapping.get(partition); String serializedSSPAsJson = serializeSSPToJson(partition); if (taskNames == null || taskNames.isEmpty()) { LOG.info("Deleting the key: from the metadata store.", partition); metadataStore.delete(serializedSSPAsJson); } else { try { String taskNamesAsString = taskNamesMapper.writeValueAsString(taskNames); byte[] taskNamesAsBytes = valueSerde.toBytes(taskNamesAsString); LOG.info("Storing the partition: and taskNames: into the metadata store.", serializedSSPAsJson, taskNames); metadataStore.put(serializedSSPAsJson, taskNamesAsBytes); } catch (Exception e) { throw new SamzaException("Exception occurred when writing task to partition assignment.", e); } } } metadataStore.flush(); }
Source:
public static OVirtNodeInfo[] get() { final String delimiter = ":"; final String path[] = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String regex[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); Pattern exp = Pattern.compile("\\((.*?)\\)", Pattern.DOTALL); String prefix = null; List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); log.debugFormat("NodeInfo: regex length {0} minimum length {1} path length {2}", regex.length, minimumVersion.length, path.length); if (regex.length != minimumVersion.length || regex.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } for (int i=0; i < regex.length; i++) { log.debugFormat("NodeInfo: regex {0} path {1}, minimumVersion {2}", regex[i], path[i], minimumVersion[i]); Matcher matcher = exp.matcher(regex[i]); matcher.find(); prefix = matcher.group(1); log.infoFormat("matcher group: [{0}] prefix found: [{1}]", regex[i], prefix); info.add(new OVirtNodeInfo(prefix, path[i], minimumVersion[i], regex[i])); } return info.toArray(new OVirtNodeInfo[info.size()]); }

Target:
public static OVirtNodeInfo[] get() { final String delimiter = ":"; final String path[] = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String regex[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); log.debugFormat("NodeInfo: regex length {0} minimum length {1} path length {2}", regex.length, minimumVersion.length, path.length); if (regex.length != minimumVersion.length || regex.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } for (int i=0; i < regex.length; i++) { log.debugFormat("NodeInfo: regex {0} path {1}, minimumVersion {2}", regex[i], path[i], minimumVersion[i]); info.add(new OVirtNodeInfo(Pattern.compile(regex[i]), path[i], minimumVersion[i])); } return info.toArray(new OVirtNodeInfo[info.size()]); }
Source:
public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateEscalationEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_OUTGOING_EDGE_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public BaseResponseDto<RegisterResponseDataDto> registerUserFromHuizu(RegisterHuizuRequestDto registerHuizuRequestDto) { RegisterUserDto dto = registerHuizuRequestDto.convertToRegisterUserDto(); BaseResponseDto<RegisterResponseDataDto> baseResponseDto = new BaseResponseDto<>(ReturnMessage.SUCCESS.getCode(), ReturnMessage.SUCCESS.getMsg()); RegisterResponseDataDto registerDataDto = new RegisterResponseDataDto(); baseResponseDto.setData(registerDataDto); registerDataDto.setPhoneNum(dto.getMobile()); boolean mobileIsExist = userService.mobileIsExist(dto.getMobile()); if (mobileIsExist) { registerDataDto.setToken(myAuthenticationUtil.createAuthentication(dto.getLoginName(), dto.getSource())); return baseResponseDto; } userService.registerUserFromHuizu(dto); registerDataDto.setToken(myAuthenticationUtil.createAuthentication(dto.getLoginName(), dto.getSource())); return baseResponseDto; }

Target:
public BaseResponseDto<RegisterResponseDataDto> registerUserFromHuizu(RegisterHuizuRequestDto registerHuizuRequestDto) { RegisterUserDto dto = registerHuizuRequestDto.convertToRegisterUserDto(); BaseResponseDto<RegisterResponseDataDto> baseResponseDto = new BaseResponseDto<>(ReturnMessage.SUCCESS.getCode(), ReturnMessage.SUCCESS.getMsg()); RegisterResponseDataDto registerDataDto = new RegisterResponseDataDto(); baseResponseDto.setData(registerDataDto); registerDataDto.setPhoneNum(dto.getMobile()); UserModel userModel = userService.findByMobile(dto.getMobile()); if (userModel == null) { userService.registerUserFromHuizu(dto); } else { dto.setLoginName(userModel.getLoginName()); } registerDataDto.setToken(myAuthenticationUtil.createAuthentication(dto.getLoginName(), dto.getSource())); return baseResponseDto; }
Source:
private Message createNickMessage(EntityBareJid to, String nickName) { String escapedNickName = StringUtils.escapeForXml(nickName).toString(); Message message = new Message(); message.setFrom(connection().getUser()); message.setTo(to); message.setType(Message.Type.chat); message.setStanzaId(); message.addExtension(new Nick(escapedNickName)); return message; }

Target:
private static Message createNickMessage(EntityBareJid to, String nickName) { Message message = new Message(); message.setTo(to); message.setType(Message.Type.chat); message.setStanzaId(); message.addExtension(new Nick(nickName)); return message; }
Source:
public Response add(OpenStackVolumeProvider provider) { validateParameters(provider, "name"); StoragePool storagePool = provider.isSetDataCenter() ? getStoragePool(provider.getDataCenter()) : new StoragePool(); provider.setDataCenter(DataCenterMapper.map(storagePool, null)); return performCreate( VdcActionType.AddProvider, new ProviderParameters(map(provider)), new QueryIdResolver<Guid>(VdcQueryType.GetProviderById, IdQueryParameters.class) ); }

Target:
public Response add(OpenStackVolumeProvider provider) { validateParameters(provider, "name"); if (provider.isSetDataCenter()) { StoragePool storagePool = getStoragePool(provider.getDataCenter()); provider.setDataCenter(DataCenterMapper.map(storagePool, null)); } return performCreate( VdcActionType.AddProvider, new ProviderParameters(map(provider)), new QueryIdResolver<Guid>(VdcQueryType.GetProviderById, IdQueryParameters.class) ); }
Source:
public List<AggregatorFactory> getRequiredColumns() { return Arrays.asList(new StringLastAggregatorFactory(fieldName, fieldName, maxStringBytes)); }

Target:
public List<AggregatorFactory> getRequiredColumns() { return Collections.singletonList(new StringLastAggregatorFactory(fieldName, fieldName, maxStringBytes)); }
Source:
void packageNameFilterInclude_nonMatchingPackagesAreExcluded() { EngineDiscoveryRequest request = request().filters( PackageNameFilter.includePackageNames("org.junit.jupiter.engine.unknown")).build(); TestDescriptor engineDescriptor = engineDescriptor() .with( classTestDescriptor("matching", MatchingClass.class) ) .build(); applier.applyAllFilters(request, engineDescriptor); Stream<UniqueId> includedDescriptors = engineDescriptor.getDescendants().stream().map(TestDescriptor::getUniqueId); assertThat(includedDescriptors).isEmpty(); }

Target:
void packageNameFilterInclude_nonMatchingPackagesAreExcluded() { EngineDiscoveryRequest request = request().filters( PackageNameFilter.includePackageNames("org.junit.jupiter.engine.unknown")).build(); TestDescriptor engineDescriptor = engineDescriptor() .with( classTestDescriptor("matching", MatchingClass.class) ) .build(); applier.applyAllFilters(request, engineDescriptor); assertThat(engineDescriptor.getDescendants()).isEmpty(); }
Source:
private void testUnlimitedFailedAuthAttempts( int maxFailedAttempts ) { FakeClock clock = getFakeClock(); AuthenticationStrategy authStrategy = new RateLimitedAuthenticationStrategy( clock, maxFailedAttempts ); User user = new User.Builder( "user", Credential.forPassword( "right" ) ).build(); int attempts = ThreadLocalRandom.current().nextInt( 5, 100 ); for ( int i = 0; i < attempts; i++ ) { assertEquals( AuthenticationResult.TOO_MANY_ATTEMPTS, authStrategy.authenticate( user, "wrong" ) ); } }

Target:
private void testUnlimitedFailedAuthAttempts( int maxFailedAttempts ) { FakeClock clock = getFakeClock(); AuthenticationStrategy authStrategy = new RateLimitedAuthenticationStrategy( clock, maxFailedAttempts ); User user = new User.Builder( "user", Credential.forPassword( "right" ) ).build(); int attempts = ThreadLocalRandom.current().nextInt( 5, 100 ); for ( int i = 0; i < attempts; i++ ) { assertEquals( AuthenticationResult.FAILURE, authStrategy.authenticate( user, "wrong" ) ); } }