auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public @NonNull Map<@NonNull String, @NonNull String> getWorkerInformation(long t) { try { int tid = fHostTid.getTid(); if (tid == -1) { return Collections.EMPTY_MAP; } @Nullable KernelAnalysisModule kam = TmfTraceManager.getInstance().getActiveTraceSet().stream() .filter(trace -> trace.getHostId().equals(getHostId())) .map(trace -> TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID)) .filter(mod -> mod != null) .findFirst().get(); ITmfStateSystem ss = kam.getStateSystem(); if (ss == null) { return Collections.EMPTY_MAP; } int quark; Map<String, String> info = new HashMap<>(); quark = ss.getQuarkAbsolute(Attributes.THREADS, Integer.toString(tid), Attributes.PRIO); ITmfStateInterval interval = ss.querySingleState(t, quark); ITmfStateValue stateValue = interval.getStateValue(); if (stateValue.getType().equals(ITmfStateValue.Type.INTEGER)) { info.put(NonNullUtils.nullToEmptyString(Messages.LttngWorker_threadPriority), Integer.toString(stateValue.unboxInt())); } return info; } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(e.getMessage(), e); } return Collections.EMPTY_MAP; }

Target:
public @NonNull Map<@NonNull String, @NonNull String> getWorkerInformation(long t) { try { int tid = fHostTid.getTid(); if (tid == -1) { return Collections.EMPTY_MAP; } Optional<KernelAnalysisModule> kam = TmfTraceManager.getInstance().getActiveTraceSet().stream() .filter(trace -> trace.getHostId().equals(getHostId())) .map(trace -> TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID)) .filter(mod -> mod != null) .findFirst(); if (!kam.isPresent()) { return Collections.EMPTY_MAP; } ITmfStateSystem ss = kam.get().getStateSystem(); if (ss == null) { return Collections.EMPTY_MAP; } int quark; Map<String, String> info = new HashMap<>(); quark = ss.getQuarkAbsolute(Attributes.THREADS, Integer.toString(tid), Attributes.PRIO); ITmfStateInterval interval = ss.querySingleState(t, quark); ITmfStateValue stateValue = interval.getStateValue(); if (stateValue.getType().equals(ITmfStateValue.Type.INTEGER)) { info.put(NonNullUtils.nullToEmptyString(Messages.LttngWorker_threadPriority), Integer.toString(stateValue.unboxInt())); } return info; } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(e.getMessage(), e); } return Collections.EMPTY_MAP; }
Source:
public void testAsyncTaskWithSinglePartition() throws Exception { List<Integer> inputList = Arrays.asList(1, 2, 3, 4, 5); List<Integer> outputList = Arrays.asList(10, 20, 30, 40, 50); InMemorySystemDescriptor isd = new InMemorySystemDescriptor("async-test"); InMemoryInputDescriptor<Integer> imid = isd .getInputDescriptor("ints", new NoOpSerde<Integer>()) .withData(inputList); InMemoryOutputDescriptor imod = isd .getOutputDescriptor("ints-out", new NoOpSerde<>()) .withPartitionCount(1); TestRunner .of(MyAsyncStreamTask.class) .addInputStream(imid) .addOutputStream(imod) .run(Duration.ofSeconds(2)); Assert.assertThat(TestRunner.consumeStream(imod, Duration.ofMillis(1000)).get(0), IsIterableContainingInOrder.contains(outputList.toArray())); }

Target:
public void testAsyncTaskWithSinglePartition() throws Exception { List<Integer> inputList = Arrays.asList(1, 2, 3, 4, 5); List<Integer> outputList = Arrays.asList(10, 20, 30, 40, 50); InMemorySystemDescriptor isd = new InMemorySystemDescriptor("async-test"); InMemoryInputDescriptor<Integer> imid = isd .getInputDescriptor("ints", new NoOpSerde<Integer>()); InMemoryOutputDescriptor imod = isd .getOutputDescriptor("ints-out", new NoOpSerde<>()); TestRunner .of(MyAsyncStreamTask.class) .addInputStream(imid, inputList) .addOutputStream(imod, 1) .run(Duration.ofSeconds(2)); Assert.assertThat(TestRunner.consumeStream(imod, Duration.ofMillis(1000)).get(0), IsIterableContainingInOrder.contains(outputList.toArray())); }
Source:
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); if (document == null) return -1; try { int widgetOffset= styledText.getOffsetAtPoint(new Point(x, y)); Point p= styledText.getLocationAtOffset(widgetOffset); if (p.x > x) { widgetOffset--; } if (textViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer; return extension.widgetOffset2ModelOffset(widgetOffset); } IRegion visibleRegion= textViewer.getVisibleRegion(); return widgetOffset + visibleRegion.getOffset(); } catch (IllegalArgumentException e) { return -1; } }

Target:
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); int widgetOffset = styledText.getOffsetAtPoint(new Point(x, y)); if (document == null || widgetOffset == -1) { return -1; } try { Point p= styledText.getLocationAtOffset(widgetOffset); if (p.x > x) { widgetOffset--; } if (textViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer; return extension.widgetOffset2ModelOffset(widgetOffset); } IRegion visibleRegion= textViewer.getVisibleRegion(); return widgetOffset + visibleRegion.getOffset(); } catch (IllegalArgumentException e) { return -1; } }
Source:
public File move(File src, File dest) throws IOException { assertSessionCreated(); try { session.moveFile(src, dest); } catch (Exception e) { throw new ResourceTransactionException("Error while copying file from " + src + " to " + dest, e); } }

Target:
public File move(File src, File dest) throws IOException { assertSessionCreated(); try { session.moveFile(src, dest); return dest; } catch (Exception e) { throw new ResourceTransactionException("Error while moving file from " + src + " to " + dest, e); } }
Source:
public boolean runTest() { Display display = mContext.getWindowManager().getDefaultDisplay(); boolean passing = checkEqualsAndLog(R.string.tv_hdr_display_is_hdr, false, display.isHdr()); passing &= hasNoHdrCapabilities(display, this); return passing; }

Target:
public void runTest() { Display display = mContext.getWindowManager().getDefaultDisplay(); getAsserter() .withFailureMessage("Display.isHdr()") .that(display.isHdr()) .isTrue(); getAsserter() .withFailureMessage("Display.getHdrCapabilities()") .that(display.getHdrCapabilities().getSupportedHdrTypes()) .isEmpty(); }
Source:
public void testGetCustomPeriod() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setBody(stringFromResource("/monitoringcenters/get.json")) ); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.CustomPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertNotNull(result); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=" + URLEncoder.encode(FormatDateToISO8601(start)) + "&end_date=" + URLEncoder.encode(FormatDateToISO8601(end))); }

Target:
public void testGetCustomPeriod() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setBody(stringFromResource("/monitoringcenters/get.json")) ); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.customPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertNotNull(result); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=2012-11-11T00%3A00%3A00Z&end_date=2013-11-11T00%3A00%3A00Z"); }
Source:
public Supplier<Flux<Message<String>>> sendMessageToTopicOne() { return () -> Flux.fromStream( Stream.generate( new Supplier<Message<String>>() { @Override public Message<String> get() { try { Thread.sleep(10000); } finally { Random rand = new Random(); Message<String> message = MessageBuilder.withPayload("message-" + rand.nextInt(1000)).build(); LOGGER.info( "Sending a message via the output binder to topic-one! Payload: " + message.getPayload()); return message; } } })) .subscribeOn(Schedulers.elastic()) .share(); }

Target:
public Supplier<Flux<Message<String>>> sendMessageToTopicOne() { return () -> Flux.fromStream( Stream.generate( new Supplier<Message<String>>() { @Override public Message<String> get() { try { Thread.sleep(10000); } finally { Message<String> message = MessageBuilder.withPayload("message-" + rand.nextInt(1000)).build(); LOGGER.info( "Sending a message via the output binder to topic-one! Payload: " + message.getPayload()); return message; } } })) .subscribeOn(Schedulers.elastic()) .share(); }
Source:
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz, final String measurementName) throws InfluxDBMapperException { Objects.requireNonNull(queryResult, "queryResult"); Objects.requireNonNull(clazz, "clazz"); throwExceptionIfResultWithError(queryResult); cacheMeasurementClass(clazz); List<T> result = new LinkedList<T>(); if (measurementName == null || measurementName.isEmpty()) { throw new IllegalArgumentException("measurementName must not be null or empty"); } queryResult.getResults().stream() .filter(internalResult -> Objects.nonNull(internalResult) && Objects.nonNull(internalResult.getSeries())) .forEach(internalResult -> { internalResult.getSeries().stream() .filter(series -> series.getName().equals(measurementName)) .forEachOrdered(series -> { parseSeriesAs(series, clazz, result); }); }); return result; }

Target:
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz, final String measurementName) throws InfluxDBMapperException { Objects.requireNonNull(measurementName, "measurementName"); Objects.requireNonNull(queryResult, "queryResult"); Objects.requireNonNull(clazz, "clazz"); throwExceptionIfResultWithError(queryResult); cacheMeasurementClass(clazz); List<T> result = new LinkedList<T>(); queryResult.getResults().stream() .filter(internalResult -> Objects.nonNull(internalResult) && Objects.nonNull(internalResult.getSeries())) .forEach(internalResult -> { internalResult.getSeries().stream() .filter(series -> series.getName().equals(measurementName)) .forEachOrdered(series -> { parseSeriesAs(series, clazz, result); }); }); return result; }
Source:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String lengthHeader = req.getHeader("Content-Length"); if(lengthHeader != null && !isSizeWithinBoundaries(lengthHeader)) { throw new MaxUploadSizeExceededException(multipartConfigElement.getMaxFileSize()); } chain.doFilter(request, response); }

Target:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String lengthHeader = req.getHeader(CONTENT_LENGTH); if(StringUtils.isNotEmpty(lengthHeader)) { checkIfSizeInBoundaries(lengthHeader); } chain.doFilter(request, response); }
Source:
public boolean supportsSecureHardware() { try (SelfDestroyKey sdk = new SelfDestroyKey(TEST_KEY_ALIAS)) { return validateKeySecurityLevel(SECURE_HARDWARE, sdk.key); } catch (Throwable ignored) { return false; } }

Target:
public boolean supportsSecureHardware() { if (null != isSupportsSecureHardware) return isSupportsSecureHardware.get(); synchronized (_sync) { if (null != isSupportsSecureHardware) return isSupportsSecureHardware.get(); isSupportsSecureHardware = new AtomicBoolean(false); SelfDestroyKey sdk = null; try { sdk = new SelfDestroyKey(TEST_KEY_ALIAS); final boolean newValue = validateKeySecurityLevel(SECURE_HARDWARE, sdk.key); isSupportsSecureHardware.set(newValue); } catch (Throwable ignored) { } finally { if (null != sdk) sdk.close(); } } return isSupportsSecureHardware.get(); }
Source:
protected List<RefNode> getRefNodes(RevCommit commit, Repository repo, String refPrefix) { List<Ref> availableBranches = new ArrayList<Ref>(); List<RefNode> nodes = new ArrayList<RefNode>(); try { Map<String, Ref> localBranches = repo.getRefDatabase().getRefs( refPrefix); for (Ref branch : localBranches.values()) { if (branch.getLeaf().getObjectId().equals(commit.getId())) { availableBranches.add(branch); } } RepositoryNode repoNode = new RepositoryNode(null, repo); for (Ref ref : availableBranches) { nodes.add(new RefNode(repoNode, repo, ref)); } } catch (IOException e) { } return nodes; }

Target:
protected List<RefNode> getRefNodes(RevCommit commit, Repository repo, String refPrefix) { List<Ref> availableBranches = new ArrayList<Ref>(); List<RefNode> nodes = new ArrayList<RefNode>(); try { Map<String, Ref> branches = repo.getRefDatabase().getRefs( refPrefix); for (Ref branch : branches.values()) { if (branch.getLeaf().getObjectId().equals(commit.getId())) availableBranches.add(branch); } RepositoryNode repoNode = new RepositoryNode(null, repo); for (Ref ref : availableBranches) nodes.add(new RefNode(repoNode, repo, ref)); } catch (IOException e) { } return nodes; }
Source:
public BaseAveragerFactory(String name, int numBuckets, String fieldName, Integer cycleSize) { this.name = name; this.numBuckets = numBuckets; this.fieldName = fieldName; this.cycleSize = (cycleSize != null) ? cycleSize : DEFAULT_PERIOD; Preconditions.checkNotNull(name, "Must have a valid, non-null averager name"); Preconditions.checkNotNull(fieldName, "Must have a valid, non-null field name"); Preconditions.checkArgument(this.cycleSize > 0, "Cycle size must be greater than zero"); Preconditions.checkArgument(numBuckets > 0, "Bucket size must be greater than zero"); Preconditions.checkArgument(this.cycleSize < numBuckets, "Cycle size must be less than the bucket size"); Preconditions.checkArgument(numBuckets % this.cycleSize == 0, "cycleSize must devide numBuckets without a remainder"); }

Target:
public BaseAveragerFactory(String name, int numBuckets, String fieldName, Integer cycleSize) { this.name = name; this.numBuckets = numBuckets; this.fieldName = fieldName; this.cycleSize = (cycleSize != null) ? cycleSize : DEFAULT_PERIOD; Preconditions.checkNotNull(name, "Must have a valid, non-null averager name"); Preconditions.checkNotNull(fieldName, "Must have a valid, non-null field name"); Preconditions.checkArgument(this.cycleSize > 0, "Cycle size must be greater than zero"); Preconditions.checkArgument(numBuckets > 0, "Bucket size must be greater than zero"); Preconditions.checkArgument(!(this.cycleSize > numBuckets), "Cycle size must be less than the bucket size"); Preconditions.checkArgument(numBuckets % this.cycleSize == 0, "cycleSize must devide numBuckets without a remainder"); }
Source:
public void testAllVisible() throws Exception { when(cqlClient.executeQuery(any())) .thenReturn(Futures.immediateFuture(Optional.of(Value.create(PtBytes.toBytes("dummy"), 11)))) .thenReturn(Futures.immediateFuture(Optional.of(Value.create(PtBytes.toBytes("dummy"), 13)))); Map<Cell, Long> request = ImmutableMap.of(VISIBLE_CELL_1, TIMESTAMP, VISIBLE_CELL_2, TIMESTAMP); AsyncCellLoader asyncCellLoader = AsyncCellLoader.create(cqlClient, testExecutor, DEFAULT_KEYSPACE); Map<Cell, Value> result = asyncCellLoader.loadAllWithTimestamp(DEFAULT_TABLE, request).get(); assertThat(result.isEmpty()).isFalse(); assertThat(result.containsKey(VISIBLE_CELL_1)).isTrue(); assertThat(result.containsKey(VISIBLE_CELL_2)).isTrue(); }

Target:
public void testAllVisible() throws Exception { setUpVisibleCells(VISIBLE_CELL_1, VISIBLE_CELL_2); Map<Cell, Long> request = ImmutableMap.of( VISIBLE_CELL_1, TIMESTAMP, VISIBLE_CELL_2, TIMESTAMP); Map<Cell, Value> result = asyncCellLoader.loadAllWithTimestamp(TABLE, request).get(); assertThat(result) .containsOnlyKeys(VISIBLE_CELL_1, VISIBLE_CELL_2); }
Source:
private static String getFileNamePrefix(String path, int objectId) { StringBuilder name; int f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY; if (f > 0) { name = new StringBuilder(SysProperties.FILE_SEPARATOR + objectId); } else { name = new StringBuilder(); } objectId /= SysProperties.LOB_FILES_PER_DIRECTORY; while (objectId > 0) { f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY; name.insert(0, SysProperties.FILE_SEPARATOR + f + Constants.SUFFIX_LOBS_DIRECTORY); objectId /= SysProperties.LOB_FILES_PER_DIRECTORY; } name = new StringBuilder(FileUtils.toRealPath(path + Constants.SUFFIX_LOBS_DIRECTORY + name)); return name.toString(); }

Target:
private static String getFileNamePrefix(String path, int objectId) { String name; int f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY; if (f > 0) { name = SysProperties.FILE_SEPARATOR + objectId; } else { name = ""; } objectId /= SysProperties.LOB_FILES_PER_DIRECTORY; while (objectId > 0) { f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY; name = SysProperties.FILE_SEPARATOR + f + Constants.SUFFIX_LOBS_DIRECTORY + name; objectId /= SysProperties.LOB_FILES_PER_DIRECTORY; } name = FileUtils.toRealPath(path + Constants.SUFFIX_LOBS_DIRECTORY + name); return name; }
Source:
private void checkIfPageIsSaved() { if (getActivity() != null && getTitle() != null) { pageSaved = SavedPage.PERSISTENCE_HELPER.savedPageExists(app, getTitle()); } }

Target:
private void checkIfPageIsSaved() { if (getActivity() != null && getTitle() != null) { new SavedPageCheckTask(getTitle(), app) { @Override public void onFinish(Boolean exists) { setPageSaved(exists); setSavedPageCheckComplete(true); } }.execute(); } }
Source:
public Date getProjectStartDate() { List<ISprintPlanDesc> sprintList = this.loadListPlans(); return DateUtil.dayFilter(sprintList.get(0).getStartDate()); }

Target:
public Date getProjectStartDate() { List<ISprintPlanDesc> sprintList = loadListPlans(); return DateUtil.dayFilter(sprintList.get(0).getStartDate()); }
Source:
protected boolean canDoAction() { boolean canDo = false; if (!Guid.isNullOrEmpty(getParameters().getUserId())) { DbUser dbUser = getDbFacade().getDbUserDao().get(getParameters().getUserId()); if (dbUser == null) { addCanDoActionMessage(EngineMessage.USER_MUST_EXIST_IN_DB); return false; } UserProfile userProfile = getDbFacade().getUserProfileDao().getByUserId(getParameters().getUserId()); if (userProfile == null || StringUtils.isEmpty(userProfile.getSshPublicKey())) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_PROFILE_NOT_EXIST); return false; } canDo = true; } else if (StringUtils.isNotEmpty(getParameters().getAuthzName()) && StringUtils.isNotEmpty(getParameters().getUserName())) { DbUser dbUser = getDbFacade().getDbUserDao().getByUsernameAndDomain(getParameters().getUserName(), getParameters().getAuthzName()); if (dbUser == null) { addCanDoActionMessage(EngineMessage.USER_MUST_EXIST_IN_DB); return false; } } else if (StringUtils.isNotEmpty(getParameters().getAuthzName()) && StringUtils.isNotEmpty(getParameters().getExternalId()) && StringUtils.isNotEmpty(getParameters().getNamespace())) { DbUser dbUser = getDbFacade().getDbUserDao().getByExternalId(getParameters().getAuthzName(), getParameters().getExternalId()); if (dbUser == null) { addCanDoActionMessage(EngineMessage.USER_MUST_EXIST_IN_DB); return false; } AuthenticationProfile profile = getProfileByAuthzName(getParameters().getAuthzName()); if (profile == null) { log.error("Can't login because authentication profile '{}' doesn't exist.", getParameters().getAuthzName()); addCanDoActionMessage(EngineMessage.USER_FAILED_TO_AUTHENTICATE); return false; } canDo = true; } return canDo; }

Target:
protected boolean canDoAction() { if (getDbUser() == null) { return failCanDoAction(EngineMessage.USER_MUST_EXIST_IN_DB); } return true; }
Source:
public HiveNotReadableException(SchemaTableName tableName, Optional<String> partition, String message) { super(HIVE_PARTITION_NOT_READABLE, format("Table '%s'%s is not readable: %s", tableName, partition.map(name -> " partition '" + name + "'").orElse(""), message)); this.tableName = requireNonNull(tableName, "tableName is null"); this.partition = requireNonNull(partition, "partition is null"); }

Target:
public HiveNotReadableException(SchemaTableName tableName, Optional<String> partition, String message) { super(partition.isPresent() ? HIVE_PARTITION_NOT_READABLE : HIVE_TABLE_READ_ONLY, composeMessage(tableName, partition, message)); this.tableName = requireNonNull(tableName, "tableName is null"); this.partition = requireNonNull(partition, "partition is null"); }
Source:
public void visitNode(Tree tree) { if (hasSemantic()) { if (tree.is(Tree.Kind.REMAINDER)) { BinaryExpressionTree remainderTree = (BinaryExpressionTree) tree; if (isIntegralOne(remainderTree.rightOperand()) && isIntOrLong(remainderTree)) { reportIssue(remainderTree.operatorToken(), "Remove this computation of % 1, which always evaluates to zero."); } } else { MethodInvocationTree mit = (MethodInvocationTree) tree; if (isConstantWithLiteral(mit) || isTruncation(mit) || isConstantWithZero(mit) || isConstantWithZeroOrOne(mit)) { reportIssue(mit.methodSelect(), String.format("Remove this silly call to \"Math.%s\"", mit.symbol().name())); } } } }

Target:
public void visitNode(Tree tree) { if (hasSemantic()) { if (tree.is(Tree.Kind.REMAINDER)) { BinaryExpressionTree remainderTree = (BinaryExpressionTree) tree; if (isIntegralOne(remainderTree.rightOperand()) && isIntOrLong(remainderTree.leftOperand())) { reportIssue(remainderTree.operatorToken(), "Remove this computation of % 1, which always evaluates to zero."); } } else { MethodInvocationTree mit = (MethodInvocationTree) tree; if (isConstantWithLiteral(mit) || isTruncation(mit) || isConstantWithZero(mit) || isConstantWithZeroOrOne(mit)) { reportIssue(mit.methodSelect(), String.format("Remove this silly call to \"Math.%s\"", mit.symbol().name())); } } } }
Source:
private boolean isReadFromNormal(final GATKRead rec) { return normalSampleName != null && ReadUtils.getSampleName(rec, header) == normalSampleName; }

Target:
private boolean isReadFromNormal(final GATKRead rec) { return normalSampleName != null && ReadUtils.getSampleName(rec, header).equals(normalSampleName); }
Source:
private void closeJob(JobTable.Job job, Exception cause) { job.asConnection().ifPresent( jobManagerConnection -> disconnectJobManagerConnection(jobManagerConnection, cause)); job.close(); blobCacheService.getPermanentBlobService().releaseJob(job.getJobId()); }

Target:
private void closeJob(JobTable.Job job, Exception cause) { job.asConnection().ifPresent( jobManagerConnection -> disconnectJobManagerConnection(jobManagerConnection, cause)); job.close(); }
Source:
public Field(String field) { if (field.startsWith(Group.SCHEMA)) { fieldName = field.substring(Group.SCHEMA.length() + 1).toLowerCase(Locale.ENGLISH); } else { fieldName = field.toLowerCase(Locale.ENGLISH); } queryField = GroupQueryField.fromString(fieldName); if (queryField == null) { throw new IllegalArgumentException(String.format("Unable to parse %s, extensions not supported for groups", field)); } }

Target:
public Field(String field) { if (field.toLowerCase().startsWith(Group.SCHEMA.toLowerCase())) { if (field.charAt(Group.SCHEMA.length()) == '.') { throw new IllegalArgumentException(String.format("Period (.) is not a valid field separator: %s", field)); } name = field.substring(Group.SCHEMA.length() + 1).toLowerCase(Locale.ENGLISH); } else { name = field.toLowerCase(Locale.ENGLISH); } queryField = GroupQueryField.fromString(name); if (queryField == null) { throw new IllegalArgumentException(String.format("Unable to parse %s, extensions not supported for groups", field)); } }
Source:
public final This withoutActionsFrom(final This permission) { return withActionBits(permission.getActionBits()); }

Target:
public final This withoutActionsFrom(final This permission) { return withoutActionBits(permission.getActionBits()); }
Source:
public String toString() { return FPFile.class.getSimpleName() + ", filename " + filename + ", type " + type; }

Target:
public String toString() { return FPFile.class.getSimpleName() + ", filename: " + filename + ", type: " + type; }
Source:
public Response<TreeSet<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || (Strings.isNullOrEmpty(input.add) && Strings .isNullOrEmpty(input.remove))) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); if (!control.canEditHashtags()) { throw new AuthException("Editing hashtags not permitted"); } ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> existingHashtags = notes.getHashtags(); Set<String> updatedHashtags = new HashSet<>(); Set<String> toAdd = new HashSet<>(extractTags(input.add)); Set<String> toRemove = new HashSet<>(extractTags(input.remove)); if (existingHashtags != null && !existingHashtags.isEmpty()) { updatedHashtags.addAll(existingHashtags); toAdd.removeAll(existingHashtags); toRemove.retainAll(existingHashtags); } if (toAdd.size() > 0 || toRemove.size() > 0) { updatedHashtags.addAll(toAdd); updatedHashtags.removeAll(toRemove); update.setHashtags(updatedHashtags); update.commit(); indexer.index(dbProvider.get(), update.getChange()); } return Response.ok(new TreeSet<String>(updatedHashtags)); }

Target:
public Response<TreeSet<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || (input.add == null && input.remove == null)) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); if (!control.canEditHashtags()) { throw new AuthException("Editing hashtags not permitted"); } ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> existingHashtags = notes.getHashtags(); Set<String> updatedHashtags = new HashSet<>(); Set<String> toAdd = new HashSet<>(extractTags(input.add)); Set<String> toRemove = new HashSet<>(extractTags(input.remove)); if (existingHashtags != null && !existingHashtags.isEmpty()) { updatedHashtags.addAll(existingHashtags); toAdd.removeAll(existingHashtags); toRemove.retainAll(existingHashtags); } if (toAdd.size() > 0 || toRemove.size() > 0) { updatedHashtags.addAll(toAdd); updatedHashtags.removeAll(toRemove); update.setHashtags(updatedHashtags); update.commit(); indexer.index(dbProvider.get(), update.getChange()); } return Response.ok(new TreeSet<String>(updatedHashtags)); }
Source:
public void review(final CertifiedProductSearchDetails listing) { for (CertificationResult cert : listing.getCertificationResults()) { if (cert.isSuccess()) { if (cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { Iterator<CertificationResultTestTool> testToolIter = cert.getTestToolsUsed().iterator(); while (testToolIter.hasNext()) { CertificationResultTestTool testTool = testToolIter.next(); if (StringUtils.isEmpty(testTool.getTestToolName())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolName", cert.getNumber())); } else { if (StringUtils.isEmpty(testTool.getTestToolVersion())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } TestToolDTO tt = testToolDao.getByName(testTool.getTestToolName()); if (tt != null && tt.isRetired()) { listing.getWarningMessages() .add(msgUtil.getMessage("listing.criteria.retiredTestToolNotAllowed", testTool.getTestToolName(), cert.getNumber())); } else if (tt == null) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.testToolNotFoundAndRemoved", cert.getNumber(), testTool.getTestToolName())); testToolIter.remove(); } } } } } } }

Target:
public void review(final CertifiedProductSearchDetails listing) { for (CertificationResult cert : listing.getCertificationResults()) { if (cert.isSuccess()) { if (cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { Iterator<CertificationResultTestTool> testToolIter = cert.getTestToolsUsed().iterator(); while (testToolIter.hasNext()) { CertificationResultTestTool testTool = testToolIter.next(); if (StringUtils.isEmpty(testTool.getTestToolName())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolName", cert.getNumber())); } else { if (StringUtils.isEmpty(testTool.getTestToolVersion())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getTestToolName(), cert.getNumber())); } TestToolDTO tt = testToolDao.getByName(testTool.getTestToolName()); if (tt != null && tt.isRetired()) { listing.getWarningMessages() .add(msgUtil.getMessage("listing.criteria.retiredTestToolNotAllowed", testTool.getTestToolName(), cert.getNumber())); } else if (tt == null) { listing.getErrorMessages().add(msgUtil.getMessage("listing.criteria.testToolNotFound", cert.getNumber(), testTool.getTestToolName())); } } } } } } }
Source:
private boolean sendAutomaticSavepoint(Query query, EnumSet<QueryFlag> flags) throws IOException { if ((!flags.contains(QueryFlag.SUPPRESS_BEGIN) || getTransactionState() == TransactionState.OPEN) && query != restoreToAutoSave && getAutoSave() != AutoSave.NEVER && (getAutoSave() == AutoSave.ALWAYS || !(query instanceof SimpleQuery) || ((SimpleQuery) query).getFields() != null)) { EnumSet<QueryFlag> flags2 = EnumSet.copyOf(flags); flags2.add(QueryFlag.NO_RESULTS); flags2.add(QueryFlag.NO_METADATA); flags2.add(QueryFlag.EXECUTE_AS_SIMPLE); sendOneQuery(autoSaveQuery, SimpleQuery.NO_PARAMETERS, 1, 0, flags2); return true; } return false; }

Target:
private boolean sendAutomaticSavepoint(Query query, EnumSet<QueryFlag> flags) throws IOException { if ((!flags.contains(QueryFlag.SUPPRESS_BEGIN) || getTransactionState() == TransactionState.OPEN) && query != restoreToAutoSave && getAutoSave() != AutoSave.NEVER && (getAutoSave() == AutoSave.ALWAYS || !(query instanceof SimpleQuery) || ((SimpleQuery) query).getFields() != null)) { EnumSet<QueryFlag> flags2 = EnumSet.of(QueryFlag.NO_RESULTS, QueryFlag.NO_METADATA); updateQueryMode(flags2); if (flags.contains(QueryFlag.EXECUTE_AS_SIMPLE)) { flags2.add(QueryFlag.EXECUTE_AS_SIMPLE); } sendOneQuery(autoSaveQuery, SimpleQuery.NO_PARAMETERS, 1, 0, flags2); return true; } return false; }
Source:
private String getFieldName(AssignmentExpressionTree tree) { ExpressionTree variable = tree.variable(); if (variable.is(Kind.MEMBER_SELECT)) { variable = ((MemberSelectExpressionTree) variable).expression(); } return ((IdentifierTree) variable).name(); }

Target:
private String getFieldName(AssignmentExpressionTree tree) { ExpressionTree variable = tree.variable(); if (variable.is(Kind.MEMBER_SELECT)) { variable = ((MemberSelectExpressionTree) variable).identifier(); } return ((IdentifierTree) variable).name(); }
Source:
protected boolean canDoAction() { if (isImagesAlreadyOnTarget() && !validateImagesOnStorage(vmFromConfiguration, ovfEntityData)) { return false; } return super.canDoAction(); }

Target:
protected boolean canDoAction() { if (isImagesAlreadyOnTarget() && !validateUnregisteredEntity(vmFromConfiguration, ovfEntityData)) { return false; } setImagesWithStoragePoolId(getStorageDomain().getStoragePoolId(), getVm().getImages()); return super.canDoAction(); }
Source:
private Object deserialize(byte[] payload) throws MessageDecoderException { try { ByteBuffer buffer = getByteBuffer(payload); int id = buffer.getInt(); Schema schema = schemaRegistry.getByID(id); if (schema == null) throw new IllegalStateException("Unknown schema id: " + id); logger.debug(schema.toString()); String subject = constructSubject(topic, schema, isNew); logger.debug("Subject = " + subject); if (latestSchema == null) { SchemaMetadata metadata = schemaRegistry.getLatestSchemaMetadata(subject); latestSchema = parser.parse(metadata.getSchema()); latestVersion = metadata.getVersion(); } int version = schemaRegistry.getVersion(subject, schema); if (version > latestVersion) { String errorMsg = String.format( "Producer schema is newer than the schema known to Camus"); throw new MessageDecoderException(errorMsg); } int length = buffer.limit() - 1 - idSize; if (schema.getType().equals(Schema.Type.BYTES)) { byte[] bytes = new byte[length]; buffer.get(bytes, 0, length); return bytes; } int start = buffer.position() + buffer.arrayOffset(); DatumReader<Object> reader = new GenericDatumReader<Object>(schema, latestSchema); Object object = reader.read(null, decoderFactory.binaryDecoder(buffer.array(), start, length, null)); if (schema.getType().equals(Schema.Type.STRING)) { object = ((Utf8) object).toString(); } return object; } catch (IOException ioe) { throw new MessageDecoderException("Error deserializing Avro message", ioe); } catch (RestClientException re) { throw new MessageDecoderException("Error deserializing Avro message", re); } }

Target:
private Object deserialize(byte[] payload) throws MessageDecoderException { try { ByteBuffer buffer = getByteBuffer(payload); int id = buffer.getInt(); Schema schema = schemaRegistry.getByID(id); if (schema == null) throw new IllegalStateException("Unknown schema id: " + id); logger.debug("Schema = " + schema.toString()); String subject = constructSubject(topic, schema, isNew); logger.debug("Subject = " + subject); if (latestSchema == null) { SchemaMetadata metadata = schemaRegistry.getLatestSchemaMetadata(subject); latestSchema = parser.parse(metadata.getSchema()); latestVersion = metadata.getVersion(); } int version = schemaRegistry.getVersion(subject, schema); if (version > latestVersion) { String errorMsg = String.format( "Producer schema is newer than the schema known to Camus"); throw new MessageDecoderException(errorMsg); } int length = buffer.limit() - 1 - idSize; if (schema.getType().equals(Schema.Type.BYTES)) { byte[] bytes = new byte[length]; buffer.get(bytes, 0, length); return bytes; } int start = buffer.position() + buffer.arrayOffset(); DatumReader<Object> reader = new GenericDatumReader<Object>(schema, latestSchema); Object object = reader.read(null, decoderFactory.binaryDecoder(buffer.array(), start, length, null)); if (schema.getType().equals(Schema.Type.STRING)) { object = ((Utf8) object).toString(); } return object; } catch (IOException ioe) { throw new MessageDecoderException("Error deserializing Avro message", ioe); } catch (RestClientException re) { throw new MessageDecoderException("Error deserializing Avro message", re); } }
Source:
private static int dropForTier( final int numToDrop, final NavigableSet<ServerHolder> holdersInTier, final DataSegment segment, final BalancerStrategy balancerStrategy ) { int numDropped = 0; final NavigableSet<ServerHolder> isServingSubset = holdersInTier.stream().filter(s -> s.isServingSegment(segment)).collect(Collectors.toCollection(TreeSet::new)); final Iterator<ServerHolder> iterator = balancerStrategy.pickServersToDrop(segment, isServingSubset); while (numDropped < numToDrop) { if (!iterator.hasNext()) { log.warn("Wtf, holder was null? I have no servers serving [%s]?", segment.getIdentifier()); break; } final ServerHolder holder = iterator.next(); if (holder.isServingSegment(segment)) { holder.getPeon().dropSegment(segment, null); ++numDropped; } } return numDropped; }

Target:
private static int dropForTier( final int numToDrop, final NavigableSet<ServerHolder> holdersInTier, final DataSegment segment, final BalancerStrategy balancerStrategy ) { int numDropped = 0; final NavigableSet<ServerHolder> isServingSubset = holdersInTier.stream().filter(s -> s.isServingSegment(segment)).collect(Collectors.toCollection(TreeSet::new)); final Iterator<ServerHolder> iterator = balancerStrategy.pickServersToDrop(segment, isServingSubset); while (numDropped < numToDrop) { if (!iterator.hasNext()) { log.warn("Wtf, holder was null? I have no servers serving [%s]?", segment.getIdentifier()); break; } final ServerHolder holder = iterator.next(); if (holder.isServingSegment(segment)) { holder.getPeon().dropSegment(segment, null); ++numDropped; } else { log.warn( "Server [%s] is no longer serving segment [%s], skipping drop.", holder.getServer().getName(), segment.getIdentifier() ); } } return numDropped; }
Source:
public List<Step> readSteps() throws IOException, WrongRepositoryStateException { if (repo.getRepositoryState() == RepositoryState.REBASING_INTERACTIVE) return loadSteps(); throw new WrongRepositoryStateException( "Not in rebase interactive state"); }

Target:
public List<Step> readSteps() throws IOException, WrongRepositoryStateException { if (repo.getRepositoryState() == RepositoryState.REBASING_INTERACTIVE) return loadSteps(); throw new WrongRepositoryStateException(MessageFormat.format(JGitText .get().wrongRepositoryState, repo.getRepositoryState().name())); }
Source:
public DiffCommand() { Options o = CommandLineHelper.getCommonOptions(); o.addOption("l", "left", true, "load left ontology from file"); o.addOption("L", "left-iri", true, "load left ontology from IRI"); o.addOption("r", "right", true, "load right ontology from file"); o.addOption("R", "right-iri", true, "load right ontology from IRI"); o.addOption("o", "output", true, "save results to file"); o.addOption( null, "labels", true, "if true, append labels after entity IRIs in the simple format output"); o.addOption("f", "format", true, "format for diff output: simple (default) | html | markdown"); options = o; }

Target:
public DiffCommand() { Options o = CommandLineHelper.getCommonOptions(); o.addOption("l", "left", true, "load left ontology from file"); o.addOption("L", "left-iri", true, "load left ontology from IRI"); o.addOption("r", "right", true, "load right ontology from file"); o.addOption("R", "right-iri", true, "load right ontology from IRI"); o.addOption("o", "output", true, "save results to file"); o.addOption( null, "labels", true, "if true, append labels after entity IRIs in the text format output"); o.addOption( "f", "format", true, "format for diff output: plain (default) | pretty | html | markdown"); options = o; }
Source:
private void assertTimerEventMultiple(InterruptingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isInterrupting, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); if (getMarshallerType() == Marshaller.NEW) { assertNotNull(executionSet.getIsInterrupting()); assertEquals(isInterrupting, executionSet.getIsInterrupting().getValue()); assertNotNull(executionSet.getSlaDueDate()); assertEquals(slaDueDate, executionSet.getSlaDueDate().getValue()); } }

Target:
private void assertTimerEventMultiple(InterruptingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isInterrupting, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); assertStartEventIsInterrupting(executionSet, isInterrupting); assertStartEventSlaDueDate(executionSet, slaDueDate); }
Source:
public void addToTotal(Student student) { if (null == student.getFederalRace()) { totalWhite.add(student); } else { switch (student.getFederalRace()) { case "W": totalWhite.add(student); break; case "B": totalBlack.add(student); break; case "A": totalAsian.add(student); break; case "I": if (student.getFederalEthnicity().equals("YES")) { totalHispanic.add(student); } else { totalIndian.add(student); } break; case "P": totalPacific.add(student); break; case "H": totalHispanic.add(student); break; } } }

Target:
public void addToTotal(Student student) { if (null == student.getFederalRace()) { totalWhite.add(student); } else { switch (student.getFederalRace()) { case WHITE: totalWhite.add(student); break; case BLACK: totalBlack.add(student); break; case ASIAN: totalAsian.add(student); break; case INDIAN: if (student.getFederalEthnicity().equals("YES")) { totalHispanic.add(student); } else { totalIndian.add(student); } break; case PACIFIC: totalPacific.add(student); break; } } }
Source:
private List<InputValueDefinition> createInputValueDefinitions(List<Map<String, Object>> args) { List<InputValueDefinition> result = new ArrayList<>(); for (Map<String, Object> arg : args) { Type argType = createTypeIndirection((Map<String, Object>) arg.get("type")); InputValueDefinition.Builder inputValueDefinition = InputValueDefinition.newInputValueDefinition().name((String) arg.get("name")).type(argType); inputValueDefinition.description(toDescription((String) arg.get("description"))); String valueLiteral = (String) arg.get("defaultValue"); if (valueLiteral != null) { Value defaultValue = AstValueHelper.valueFromAst(valueLiteral); inputValueDefinition.defaultValue(defaultValue); } result.add(inputValueDefinition.build()); } return result; }

Target:
private List<InputValueDefinition> createInputValueDefinitions(List<Map<String, Object>> args) { List<InputValueDefinition> result = new ArrayList<>(); for (Map<String, Object> arg : args) { Type argType = createTypeIndirection((Map<String, Object>) arg.get("type")); InputValueDefinition.Builder inputValueDefinition = InputValueDefinition.newInputValueDefinition().name((String) arg.get("name")).type(argType); inputValueDefinition.description(toDescription(arg)); String valueLiteral = (String) arg.get("defaultValue"); if (valueLiteral != null) { Value defaultValue = AstValueHelper.valueFromAst(valueLiteral); inputValueDefinition.defaultValue(defaultValue); } result.add(inputValueDefinition.build()); } return result; }
Source:
private MaplayerGroup populateFromRequest(JSONObject mapLayerGroupJSON) throws ActionException { MaplayerGroup maplayerGroup = new MaplayerGroup(); try{ JSONObject locales = mapLayerGroupJSON.getJSONObject(KEY_LOCALES); int parentId = mapLayerGroupJSON.optInt(KEY_PARENT_ID, -1); boolean selectable = mapLayerGroupJSON.optBoolean(KEY_SELECTABLE, true); Iterator<?> keys = locales.keys(); while( keys.hasNext() ) { String locale = (String)keys.next(); String name = locales.getString(locale); maplayerGroup.setName(locale, name); } maplayerGroup.setParentId(parentId); maplayerGroup.setSelectable(selectable); } catch(JSONException ex) { log.error("Cannot populate maplayergroup from request", ex); throw new ActionException("Cannot populate maplayergroup from request"); } return maplayerGroup; }

Target:
private MaplayerGroup populateFromRequest(JSONObject mapLayerGroupJSON) throws ActionException { MaplayerGroup maplayerGroup = new MaplayerGroup(); try{ JSONObject locales = mapLayerGroupJSON.getJSONObject(KEY_LOCALES); int parentId = mapLayerGroupJSON.optInt(KEY_PARENT_ID, -1); boolean selectable = mapLayerGroupJSON.optBoolean(KEY_SELECTABLE, true); Iterator<?> keys = locales.keys(); while( keys.hasNext() ) { String locale = (String)keys.next(); String name = locales.getString(locale); maplayerGroup.setName(locale, name); } maplayerGroup.setParentId(parentId); maplayerGroup.setSelectable(selectable); } catch(JSONException ex) { throw new ActionException("Cannot populate maplayer group from request", ex); } return maplayerGroup; }
Source:
public NullValue withNewChildren(NodeChildrenContainer newChildren) { if (!newChildren.isEmpty()) { throw new IllegalArgumentException("Cannot pass non-empty newChildren to Node that doesn't hold children"); } return this; }

Target:
public NullValue withNewChildren(NodeChildrenContainer newChildren) { assertNewChildrenAreEmpty(newChildren); return this; }
Source:
public void delete_quality_gates() { OrganizationDto org = db.organizations().insert(); OrganizationDto otherOrg = db.organizations().insert(); QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(org); QGateWithOrgDto qualityGateInOtherOrg = db.qualityGates().insertQualityGate(otherOrg); logInAsAdministrator(org); sendRequest(org); verifyOrganizationDoesNotExist(org); assertThat(db.select("select uuid as \"uuid\" from quality_gates")) .extracting(row -> (String) row.get("uuid")) .containsOnly(qualityGateInOtherOrg.getUuid()); assertThat(db.select("select organization_uuid as \"organizationUuid\" from org_quality_gates")) .extracting(row -> (String) row.get("organizationUuid")) .containsOnly(otherOrg.getUuid()); }

Target:
public void delete_quality_gates() { OrganizationDto org = db.organizations().insert(); OrganizationDto otherOrg = db.organizations().insert(); QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(org); QGateWithOrgDto qualityGateInOtherOrg = db.qualityGates().insertQualityGate(otherOrg); logInAsAdministrator(org); sendRequest(org); verifyOrganizationDoesNotExist(org); assertThat(db.select("select uuid as \"uuid\" from quality_gates")) .extracting(row -> (String) row.get("uuid")) .containsOnly(qualityGateInOtherOrg.getUuid(), qualityGateFinder.getBuiltInQualityGate(db.getSession()).getUuid()); assertThat(qualityGateFinder.getBuiltInQualityGate(db.getSession())).isNotNull(); assertThat(db.select("select organization_uuid as \"organizationUuid\" from org_quality_gates")) .extracting(row -> (String) row.get("organizationUuid")) .containsOnly(otherOrg.getUuid()); }
Source:
public static DiscoveryStrategy create(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations, boolean jandexStrategyDisabled) { DiscoveryStrategy returnValue = null; final Iterator<Metadata<DiscoveryStrategy>> iterator = ServiceLoader.load(DiscoveryStrategy.class, resourceLoader).iterator(); if (iterator != null && iterator.hasNext()) { final DiscoveryStrategy candidate = iterator.next().getValue(); if (candidate != null) { candidate.setResourceLoader(resourceLoader); candidate.setBootstrap(bootstrap); candidate.setInitialBeanDefiningAnnotations(initialBeanDefiningAnnotations); returnValue = candidate; } } else if (jandexStrategyDisabled) { CommonLogger.LOG.jandexDiscoveryStrategyDisabled(); } else if (Jandex.isJandexAvailable(resourceLoader)) { CommonLogger.LOG.usingJandex(); try { returnValue = Jandex.createJandexDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } catch (Exception e) { throw CommonLogger.LOG.unableToInstantiate(Jandex.JANDEX_DISCOVERY_STRATEGY_CLASS_NAME, Arrays.toString(new Object[] { resourceLoader, bootstrap, initialBeanDefiningAnnotations }), e); } } if (returnValue == null) { returnValue = new ReflectionDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } return returnValue; }

Target:
public static DiscoveryStrategy create(ResourceLoader resourceLoader, Bootstrap bootstrap, Set<Class<? extends Annotation>> initialBeanDefiningAnnotations, boolean jandexStrategyDisabled) { DiscoveryStrategy returnValue = null; final Iterator<Metadata<DiscoveryStrategy>> iterator = ServiceLoader.load(DiscoveryStrategy.class, resourceLoader).iterator(); if (iterator != null && iterator.hasNext()) { final DiscoveryStrategy candidate = iterator.next().getValue(); if (candidate != null) { candidate.setResourceLoader(resourceLoader); candidate.setBootstrap(bootstrap); candidate.setInitialBeanDefiningAnnotations(initialBeanDefiningAnnotations); CommonLogger.LOG.usingServiceLoaderSourcedDiscoveryStrategy(candidate); returnValue = candidate; } } else if (Jandex.isJandexAvailable(resourceLoader)) { if (jandexStrategyDisabled) { CommonLogger.LOG.jandexDiscoveryStrategyDisabled(); } else { CommonLogger.LOG.usingJandex(); try { returnValue = Jandex.createJandexDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } catch (Exception e) { throw CommonLogger.LOG.unableToInstantiate(Jandex.JANDEX_DISCOVERY_STRATEGY_CLASS_NAME, Arrays.toString(new Object[] { resourceLoader, bootstrap, initialBeanDefiningAnnotations }), e); } } } if (returnValue == null) { returnValue = new ReflectionDiscoveryStrategy(resourceLoader, bootstrap, initialBeanDefiningAnnotations); } return returnValue; }