auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void hsync() throws IOException { if (rateLimiter.isPresent() && !rateLimiter.get().tryAcquire()) { logger.atFine().log( "hsync(): Rate limited. Minimum interval between consecutive calls is %d milliseconds." + " Doing nothing this time.", syncableOutputStreamOptions.getMinSyncTimeIntervalMs()); return; } long startTime = System.nanoTime(); logger.atFine().log( "hsync(): Committing tail file %s to final destination %s", curGcsPath, finalGcsPath); throwIfNotOpen(); commitCurrentFile(); ++curComponentIndex; curGcsPath = getNextTemporaryPath(); logger.atFine().log( "hsync(): Opening next temporary tail file %s as component number %s", curGcsPath, curComponentIndex); curDelegate = new GoogleHadoopOutputStream(ghfs, curGcsPath, statistics, TEMPFILE_CREATE_OPTIONS); long finishTime = System.nanoTime(); logger.atFine().log("Took %d ns to hsync()", finishTime - startTime); }

Target:
public void hsync() throws IOException { long startTimeNs = System.nanoTime(); if (syncRateLimiter != null) { logger.atFine().log( "hsync(): Rate limited (%s) with blocking permit acquisition for %s", syncRateLimiter, finalGcsPath); syncRateLimiter.acquire(); } hsyncInternal(startTimeNs); }
Source:
protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (retryCount < modifications.size()) { byte[] key = modifications.get(retryCount).getKey(); channelFactory.fetchChannelAndInvoke(key, failedServers, cacheName, this); } else { super.fetchChannelAndInvoke(retryCount, failedServers); } }

Target:
protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) { if (modifications.isEmpty()) { super.fetchChannelAndInvoke(retryCount, failedServers); } else { channelFactory.fetchChannelAndInvoke(modifications.get(0).getKey(), failedServers, cacheName, this); } }
Source:
public static List<String> getFeatureList(Schema inputSchema, @Nullable String featuresToInclude, @Nullable String featuresToExclude, String predictionField) { if (!Strings.isNullOrEmpty(featuresToExclude) && !Strings.isNullOrEmpty(featuresToInclude)) { throw new IllegalArgumentException("Cannot specify values for both featuresToInclude and featuresToExclude. " + "Please specify fields for one"); } List<String> fields = new ArrayList<>(); List<Schema.Field> inputSchemaFields = inputSchema.getFields(); if (!Strings.isNullOrEmpty(featuresToInclude)) { List<String> features = Lists.newArrayList(Splitter.on(',').trimResults().split(featuresToInclude)); for (String field : features) { Schema.Field inputField = inputSchema.getField(field); if (!field.equals(predictionField) && inputField != null) { fields.add(field); } } } else { Set<String> excludeFeatures = new HashSet<>(); if (!Strings.isNullOrEmpty(featuresToExclude)) { excludeFeatures.addAll(Lists.newArrayList(Splitter.on(',').trimResults().split(featuresToExclude))); } for (Schema.Field field : inputSchemaFields) { String fieldName = field.getName(); if (!fieldName.equals(predictionField) && (excludeFeatures.isEmpty() || !excludeFeatures.contains(fieldName))) { fields.add(fieldName); } } } return fields; }

Target:
static Map<String, Integer> getFeatureList(Schema inputSchema, @Nullable String featuresToInclude, @Nullable String featuresToExclude, String predictionField) { if (!Strings.isNullOrEmpty(featuresToExclude) && !Strings.isNullOrEmpty(featuresToInclude)) { throw new IllegalArgumentException("Cannot specify values for both featuresToInclude and featuresToExclude. " + "Please specify fields for one."); } Map<String, Integer> fields = new HashMap<>(); if (!Strings.isNullOrEmpty(featuresToInclude)) { Iterable<String> tokens = Splitter.on(',').trimResults().split(featuresToInclude); String[] features = Iterables.toArray(tokens, String.class); for (int i = 0; i < features.length; i++) { String field = features[i]; Schema.Field inputField = inputSchema.getField(field); if (!field.equals(predictionField) && inputField != null) { fields.put(field, i); } } return fields; } Set<String> excludeFeatures = new HashSet<>(); if (!Strings.isNullOrEmpty(featuresToExclude)) { excludeFeatures.addAll(Lists.newArrayList(Splitter.on(',').trimResults().split(featuresToExclude))); } Object[] inputSchemaFields = inputSchema.getFields().toArray(); for (int i = 0; i < inputSchemaFields.length; i++) { String field = ((Schema.Field) inputSchemaFields[i]).getName(); if (!field.equals(predictionField) && !excludeFeatures.contains(field)) { fields.put(field, i); } } return fields; }
Source:
public void testKeyValueBackupAndRestore() throws Exception { if(!mIsBackupSupported){ return; } assertNull(mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), true)); mDevice.executeShellCommand(CLEAR_DATA_IN_PACKAGE_UNDER_TEST_COMMAND); mDevice.executeAdbCommand("logcat", "-c"); mDevice.executeShellCommand(START_ACTIVITY_UNDER_TEST_COMMAND); saveDataValuesReportedByApp(); assertNotAllValuesAreDefault(); String backupnowOutput = mDevice.executeShellCommand( "bmgr run " + PACKAGE_UNDER_TEST); assertBackupIsSuccessful(backupnowOutput); mDevice.uninstallPackage(PACKAGE_UNDER_TEST); assertNull(mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), true)); mDevice.executeAdbCommand("logcat", "-c"); mDevice.executeShellCommand(START_ACTIVITY_UNDER_TEST_COMMAND); assertValuesAreRestored(); }

Target:
public void testKeyValueBackupAndRestore() throws Exception { if(!mIsBackupSupported){ return; } assertNull(mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), true)); mDevice.executeShellCommand(CLEAR_DATA_IN_PACKAGE_UNDER_TEST_COMMAND); mDevice.executeAdbCommand("logcat", "-c"); mDevice.executeShellCommand(START_ACTIVITY_UNDER_TEST_COMMAND); saveDataValuesReportedByApp(); assertNotAllValuesAreDefault(); String backupnowOutput = mDevice.executeShellCommand("bmgr run "); assertBackupIsSuccessful(backupnowOutput); mDevice.uninstallPackage(PACKAGE_UNDER_TEST); assertNull(mDevice.installPackage(mBuild.getTestApp(TEST_APP_APK), true)); mDevice.executeAdbCommand("logcat", "-c"); mDevice.executeShellCommand(START_ACTIVITY_UNDER_TEST_COMMAND); assertValuesAreRestored(); }
Source:
public OauthAuthenticationResult authenticate(HttpRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest cannot be null."); Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = (HttpServletRequest) httpRequest; } else if (HttpRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = new OauthHttpServletRequest((HttpRequest) httpRequest); } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpRequest.class.getName(), HttpServletRequest.class.getName())); } OauthAuthenticationRequestFactory factory = new OauthAuthenticationRequestFactory(); AuthenticationRequest request = factory.createFrom(httpServletRequest); AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }

Target:
public OauthAuthenticationResult authenticate(HttpRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest cannot be null."); Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = (HttpServletRequest) httpRequest; } else if (HttpRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = new OauthHttpServletRequest(httpRequest); } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpRequest.class.getName(), HttpServletRequest.class.getName())); } OauthAuthenticationRequestFactory factory = new OauthAuthenticationRequestFactory(); AuthenticationRequest request = factory.createFrom(httpServletRequest); AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }
Source:
protected void initialize(String value) { assert value != null && value.trim().length() > 0; JComboBox element = weakRef.get(); if (element != null) { element.setSelectedIndex(Integer.parseInt(value)); } }

Target:
protected void initialize(String value) { assert value != null && value.trim().length() > 0; JComboBox element = weakRef.get(); if (element != null) { int index = Integer.parseInt(value); if (index >= 0 && index < element.getItemCount()) { this.selectedIndex = index; element.setSelectedIndex(this.selectedIndex); } } }
Source:
public void destroy() { if (channel.isConnected()) { channel.disconnect(); } }

Target:
public void destroy() { if (channel.isConnected()) channel.disconnect(); }
Source:
public boolean equals(Object obj) { if (obj instanceof MethodKey) { MethodKey toCompare = (MethodKey) obj; return toCompare.name.equals(name) && toCompare.parameterTypes.equals(parameterTypes); } return false; }

Target:
public final boolean equals(Object obj) { if (obj instanceof MethodKey) { MethodKey toCompare = (MethodKey) obj; return toCompare.name.equals(name) && toCompare.parameterTypes.equals(parameterTypes); } return false; }
Source:
UserPostListingURL(Type type, String user, PostSort order, Integer limit, String before, String after) { this.type = type; this.user = user; this.order = order; this.limit = limit; this.before = before; this.after = after; }

Target:
UserPostListingURL(Type type, String user, PostSort order, Integer limit, String before, String after) { this.type = type; this.user = user; this.order = order == PostSort.RISING ? PostSort.NEW : order; this.limit = limit; this.before = before; this.after = after; }
Source:
private TokenizedPattern expandMacros() { TokenizedPattern currentPattern = filterPattern; for(Map.Entry<String, Function<Repository, String>> macro : macros.entrySet()) { String macroString = macro.getKey(); String patternString = currentPattern.getPattern(); if (patternString.contains(macroString)) { String replacingString = macro.getValue().apply(repository); String newString = patternString.replace(macroString, replacingString); currentPattern = new TokenizedPattern(newString); } } return currentPattern; }

Target:
private TokenizedPattern expandMacros() { TokenizedPattern currentPattern = filterPattern; for(Map.Entry<String, Function<Repository, String>> macro : macros.entrySet()) { String macroString = macro.getKey(); if (currentPattern.containsPattern(macroString)) { String replacingString = macro.getValue().apply(repository); String newString = currentPattern.getPattern() .replace(macroString, replacingString); currentPattern = createPattern(newString); } } return currentPattern; }
Source:
public static void configureORCFileSet(String configuredSchema, FileSetProperties.Builder properties) throws IOException, UnsupportedTypeException { String lowerCaseSchema = configuredSchema.toLowerCase(); String hiveSchema = parseHiveSchema(lowerCaseSchema, configuredSchema); hiveSchema = hiveSchema.substring(1, hiveSchema.length() - 1); co.cask.cdap.api.data.schema.Schema schemaObj = co.cask.cdap.api.data.schema.Schema.parseJson(configuredSchema); StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, schemaObj); String orcSchema = builder.toString(); properties.setInputFormat(OrcInputFormat.class) .setOutputFormat(OrcOutputFormat.class) .setExploreInputFormat("org.apache.hadoop.hive.ql.io.orc.OrcInputFormat") .setExploreOutputFormat("org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat") .setSerDe("org.apache.hadoop.hive.ql.io.orc.OrcSerde") .setExploreSchema(hiveSchema) .setEnableExploreOnCreate(true) .setInputProperty("orc.mapred.output.schema", orcSchema) .setOutputProperty("orc.mapred.output.schema", orcSchema) .build(); }

Target:
public static void configureORCFileSet(String configuredSchema, FileSetProperties.Builder properties) { String lowerCaseSchema = configuredSchema.toLowerCase(); String hiveSchema = parseHiveSchema(lowerCaseSchema, configuredSchema); hiveSchema = hiveSchema.substring(1, hiveSchema.length() - 1); String orcSchema = parseOrcSchema(configuredSchema); properties.setInputFormat(OrcInputFormat.class) .setOutputFormat(OrcOutputFormat.class) .setExploreInputFormat("org.apache.hadoop.hive.ql.io.orc.OrcInputFormat") .setExploreOutputFormat("org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat") .setSerDe("org.apache.hadoop.hive.ql.io.orc.OrcSerde") .setExploreSchema(hiveSchema) .setEnableExploreOnCreate(true) .setInputProperty("orc.mapred.output.schema", orcSchema) .setOutputProperty("orc.mapred.output.schema", orcSchema) .build(); }
Source:
public void checkAnotBEarlyStop() { int lgK = 10; int k = 1<<lgK; int u = 4*k; long v = 0; int trials = 10; UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build(); AnotB aNotB = SetOperation.builder().buildANotB(); for (int t = 0; t < trials; t++) { for (int i=0; i<u; i++) { usk1.update(i + v); usk2.update(i + v + (u/2)); } v += u + (u/2); CompactSketch csk1 = usk1.compact(true, null); CompactSketch csk2 = usk2.compact(true, null); Sketch rsk = PairwiseSetOperations.aNotB(csk1, csk2); double result1 = rsk.getEstimate(); aNotB.update(csk1, csk2); CompactSketch csk3 = aNotB.getResult(true, null); double result2 = csk3.getEstimate(); assertEquals(result1, result2, 0.0); usk1.reset(); usk2.reset(); } }

Target:
public void checkAnotBEarlyStop() { int lgK = 10; int k = 1<<lgK; int u = 4*k; long v = 0; int trials = 10; UpdateSketch usk1 = UpdateSketch.builder().setNominalEntries(k).build(); UpdateSketch usk2 = UpdateSketch.builder().setNominalEntries(k).build(); AnotB aNotB = SetOperation.builder().buildANotB(); for (int t = 0; t < trials; t++) { for (int i=0; i<u; i++) { usk1.update(i + v); usk2.update(i + v + (u/2)); } v += u + (u/2); CompactSketch csk1 = usk1.compact(true, null); CompactSketch csk2 = usk2.compact(true, null); Sketch rsk = PairwiseSetOperations.aNotB(csk1, csk2); double result1 = rsk.getEstimate(); CompactSketch csk3 = aNotB.aNotB(csk1, csk2); double result2 = csk3.getEstimate(); assertEquals(result1, result2, 0.0); usk1.reset(); usk2.reset(); } }
Source:
public void checkField(Field field) { if(field.getArguments()==null||field.getArguments().size()<=1){ return; } Set<String> arguments=new HashSet<>(field.getArguments().size()); for (Argument argument : field.getArguments()) { if(arguments.contains(argument.getName())){ addError(ValidationErrorType.DuplicateArgumentNames, field.getSourceLocation(), duplicateArgumentNameMessage(argument.getName())); }else{ arguments.add(argument.getName()); } } }

Target:
public void checkField(Field field) { if (field.getArguments() == null || field.getArguments().size() <= 1) { return; } Set<String> arguments = new HashSet<>(); for (Argument argument : field.getArguments()) { if (arguments.contains(argument.getName())) { addError(ValidationErrorType.DuplicateArgumentNames, field.getSourceLocation(), duplicateArgumentNameMessage(argument.getName())); } else { arguments.add(argument.getName()); } } }
Source:
private MyModel[] createModel() { MyModel[] elements = new MyModel[11]; for (int i = 0; i < elements.length - 1; i++) { elements[i] = new MyModel(i); } elements[elements.length - 1] = new MyModel(42); return elements; }

Target:
private List<MyModel> createModel() { List<MyModel> elements = new ArrayList<MyModel>(); for (int i = 0; i < 10; i++) { elements.add(new MyModel(i)); } return elements; }
Source:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(exercises.size(), 153); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }

Target:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(153, exercises.size()); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }
Source:
public void clickAdvancedButton() { advancedButton.click(); }

Target:
public void clickAdvancedButton() { advancedButton.click(); PageObjectLogging.log("clickAdvancedButton", "Advance button was clicked", true, driver); }
Source:
private String[] rootArgumentsOnly() throws BadArgumentException { List<String> rootArguments = new ArrayList<String>(); for (int i = 0; i < this.args.length; i++) { final String token = this.args[i]; if (matchesOption(COMMAND, token) || matchesOption(VIEW_TYPE, token) || matchesOption(ACCESS_KEY, token) || matchesOption(SECRET_KEY, token) || matchesOption(ENDPOINT, token) || matchesOption(PROXY, token)) { rootArguments.add(token); if (i < this.args.length) { rootArguments.add(this.args[++i]); } else { throw new BadArgumentException("No argument supplied for option: " + token); } } if (matchesOption(COMMAND_HELP, token)) { rootArguments.add(token); if ((i < this.args.length) && (!this.args[i + 1].startsWith("-"))) { rootArguments.add(this.args[++i]); } } if ((matchesOption(VERBOSE, token)) || (matchesOption(PRINT_HELP, token)) || (matchesOption(TRACE, token)) || (matchesOption(DEBUG, token)) || (matchesOption(VERBOSE, token)) || (matchesOption(LOG_TRACE, token)) || (matchesOption(LOG_DEBUG, token)) || (matchesOption(LOG_VERBOSE, token))) { rootArguments.add(token); } } String[] ret = new String[rootArguments.size()]; ret = rootArguments.toArray(ret); return ret; }

Target:
private String[] rootArgumentsOnly() throws BadArgumentException { final List<String> rootArguments = new ArrayList<String>(); for (int i = 0; i < this.args.length; i++) { final String token = this.args[i]; if (matchesOption(COMMAND, token) || matchesOption(VIEW_TYPE, token) || matchesOption(ACCESS_KEY, token) || matchesOption(SECRET_KEY, token) || matchesOption(ENDPOINT, token) || matchesOption(PROXY, token) || matchesOption(RETRIES, token)) { rootArguments.add(token); if (i < this.args.length) { rootArguments.add(this.args[++i]); } else { throw new BadArgumentException("No argument supplied for option: " + token); } } if (matchesOption(COMMAND_HELP, token)) { rootArguments.add(token); if ((i < this.args.length) && (!this.args[i + 1].startsWith("-"))) { rootArguments.add(this.args[++i]); } } if ((matchesOption(VERBOSE, token)) || (matchesOption(PRINT_HELP, token)) || (matchesOption(TRACE, token)) || (matchesOption(DEBUG, token)) || (matchesOption(VERBOSE, token)) || (matchesOption(LOG_TRACE, token)) || (matchesOption(LOG_DEBUG, token)) || (matchesOption(LOG_VERBOSE, token))) { rootArguments.add(token); } } return rootArguments.toArray(new String[rootArguments.size()]); }
Source:
private <T> T query(IQuery<DB, T> query, boolean asTransaction) { DB connection = dbManager.getConnection(); try { connection.setAutoCommit(!asTransaction); long startTime = System.currentTimeMillis(); T value = query.query(connection); if (asTransaction) { connection.commit(); } long executionTime = System.currentTimeMillis() - startTime; if (metricsTrackingEnabled) { queryMetrics.update(executionTime, Thread.currentThread().getStackTrace()[3]); } dbManager.returnConnection(connection); return value; } catch (Exception e) { LOG.error("SQL execution failure", e); if (asTransaction) { try { connection.rollback(); } catch (Exception e2) { } } dbManager.returnConnection(connection); throw new SqlExecutionFailureException(e); } catch (Throwable t) { if (asTransaction) { connection.rollback(); } throw t; } }

Target:
private <T> T query(IQuery<DB, T> query, boolean asTransaction) { DB connection = dbManager.getConnection(); boolean connectionSafeToReturn = true; try { connection.setAutoCommit(!asTransaction); long startTime = System.currentTimeMillis(); T value = query.query(connection); if (asTransaction) { connection.commit(); } long executionTime = System.currentTimeMillis() - startTime; if (metricsTrackingEnabled) { queryMetrics.update(executionTime, Thread.currentThread().getStackTrace()[3]); } return value; } catch (Exception e) { LOG.error("SQL execution failure", e); if (asTransaction) { connectionSafeToReturn = tryToSafelyRollback(connection); } throw new SqlExecutionFailureException(e); } catch (Throwable t) { if (asTransaction) { connectionSafeToReturn = tryToSafelyRollback(connection); } throw t; } finally { if (connectionSafeToReturn) { dbManager.returnConnection(connection); } else { dbManager.invalidateConnection(connection); } } }
Source:
public void testPerformance() throws Exception { init(false, temporaryFolder.getRoot()); File smallFile = temporaryFolder.newFile("smallFile.xml"); File bigFile = temporaryFolder.newFile("bigFile.xml"); String simpleTag = "<tag1 attr=\"val1\">text</tag1>\n"; String xml = "<?xml version=\"1.0\"?><root>\n"; StringBuilder str = new StringBuilder(xml); for (int i = 0; i < 20000; i++) { str.append(simpleTag); } str.append("</root>"); FileUtils.write(smallFile, str.toString()); fs.add(createInputFile(smallFile.getAbsolutePath())); long t1 = System.currentTimeMillis(); sensor.analyse(context); long diffSmall = System.currentTimeMillis() - t1; str = new StringBuilder(xml); for (int i = 0; i < 40000; i++) { str.append(simpleTag); } str.append("</root>"); FileUtils.write(bigFile, str.toString()); init(false, temporaryFolder.getRoot()); fs.add(createInputFile(bigFile.getAbsolutePath())); t1 = System.currentTimeMillis(); sensor.analyse(context); long diffBig = System.currentTimeMillis() - t1; assert (diffBig < (2.5 * diffSmall)); }

Target:
public void testPerformance() throws Exception { initFileSystemWithFile(createXmlFile(20000, "smallFile.xml")); long timeSmallFile = measureTimeToAnalyzeFile(); initFileSystemWithFile(createXmlFile(40000, "bigFile.xml")); long timeBigFile = measureTimeToAnalyzeFile(); assertThat(timeBigFile < (2.5 * timeSmallFile)).isTrue(); }
Source:
public CompletableFuture<LanguageServer> getInitializedServer() { if (initializeFuture != null && !this.initializeFuture.isDone()) { return initializeFuture.thenApply(r -> this.languageServer); } return CompletableFuture.completedFuture(this.languageServer); }

Target:
public CompletableFuture<LanguageServer> getInitializedServer() { try { start(); } catch (IOException ex) { LanguageServerPlugin.logError(ex); } if (initializeFuture != null && !this.initializeFuture.isDone()) { if (Display.getCurrent() != null) { Job waitForInitialization = new Job(Messages.initializeLanguageServer_job) { @Override protected IStatus run(IProgressMonitor monitor) { initializeFuture.join(); return Status.OK_STATUS; } }; waitForInitialization.setUser(true); waitForInitialization.setSystem(false); PlatformUI.getWorkbench().getProgressService().showInDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), waitForInitialization); } return initializeFuture.thenApply(r -> this.languageServer); } return CompletableFuture.completedFuture(this.languageServer); }
Source:
public boolean isExistingRole(String roleName) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { dbConnection = getDBConnection(); prepStmt = dbConnection.prepareStatement(HybridJDBCConstants.GET_ROLE_ID); prepStmt.setString(1, roleName); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { int value = rs.getInt(1); if (value > -1) { isExisting = true; } } if(log.isDebugEnabled()) { log.debug("Is roleName: " + roleName + " Exist: " + isExisting + " TenantId: " + tenantId); } return isExisting; } catch (SQLException e) { throw new UserStoreException("Error occurred while getting role id from role name :"+roleName, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }

Target:
public boolean isExistingRole(String roleName) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { dbConnection = getDBConnection(); prepStmt = dbConnection.prepareStatement(HybridJDBCConstants.GET_ROLE_ID); prepStmt.setString(1, roleName); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { int value = rs.getInt(1); if (value > -1) { isExisting = true; } } if(log.isDebugEnabled()) { log.debug("Is roleName: " + roleName + " Exist: " + isExisting + " TenantId: " + tenantId); } return isExisting; } catch (SQLException e) { String errorMessage = "Error occurred while getting role id from role name : " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } }
Source:
private static Properties loadProperties(Class<?> clazz, String resource) { return loadProperties(clazz.getResourceAsStream(resource)); }

Target:
private static Properties loadProperties(Class<?> clazz, String resource) { try ( InputStream is = clazz.getResourceAsStream(resource); ) { return loadProperties(is); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
public CommonPrefixes toCommonPrefixes() throws RuntimeException{ if(isContents()) { throw new RuntimeException("Could not create CommonPrefixes"); } final CommonPrefixes commonPrefixes = new CommonPrefixes(); commonPrefixes.setPrefix(prefix); return commonPrefixes; }

Target:
public CommonPrefixes toCommonPrefixes() throws RuntimeException{ if (isContents()) { throw new UnableToConvertToCommonPrefixesException("Could not create a CommonPrefix"); } final CommonPrefixes commonPrefixes = new CommonPrefixes(); commonPrefixes.setPrefix(prefix); return commonPrefixes; }
Source:
void saveToPreferences(Preferences prefs, ISecurePreferences securePrefs) throws StorageException { prefs.put(PROPERTY_ID, id); if(userVisibleName == null) { prefs.put(PROPERTY_NAME, userVisibleName); } prefs.putBoolean(PROPERTY_REMOVABLE, removable); if( defaultUsername != null ) prefs.put(PROPERTY_DEFAULT_USER, defaultUsername); Set<String> users = credentials.keySet(); String[] userList = (String[]) users.toArray(new String[users.size()]); prefs.put(PROPERTY_USER_LIST, String.join("\n", userList)); for( int i = 0; i < userList.length; i++ ) { String user = userList[i]; ISecurePreferences userNode = securePrefs.node(user); userNode.put(PROPERTY_PASS, getCredentials(user), true); } String[] promptedUsers = (String[]) promptedCredentials.toArray(new String[promptedCredentials.size()]); prefs.put(PROPERTY_PROMPTED_USER_LIST, String.join("\n", promptedUsers)); }

Target:
void saveToPreferences(Preferences prefs, ISecurePreferences securePrefs) throws StorageException { prefs.put(PROPERTY_ID, id); if(userVisibleName != null) { prefs.put(PROPERTY_NAME, userVisibleName); } prefs.putBoolean(PROPERTY_REMOVABLE, removable); if( defaultUsername != null ) prefs.put(PROPERTY_DEFAULT_USER, defaultUsername); Set<String> users = credentials.keySet(); String[] userList = (String[]) users.toArray(new String[users.size()]); prefs.put(PROPERTY_USER_LIST, String.join("\n", userList)); for( int i = 0; i < userList.length; i++ ) { String user = userList[i]; ISecurePreferences userNode = securePrefs.node(user); userNode.put(PROPERTY_PASS, getCredentials(user), true); } String[] promptedUsers = (String[]) promptedCredentials.toArray(new String[promptedCredentials.size()]); prefs.put(PROPERTY_PROMPTED_USER_LIST, String.join("\n", promptedUsers)); }
Source:
public Response<Void> createWithResponse(Map<String, String> metadata, PublicAccessType accessType, Duration timeout, Context context) { try { return blobContainerClient.createWithResponse(metadata, Transforms.toBlobPublicAccessType(accessType), timeout, context); } catch (BlobStorageException ex) { throw logger.logExceptionAsError(DataLakeImplUtils.transformBlobStorageException(ex)); } }

Target:
public Response<Void> createWithResponse(Map<String, String> metadata, PublicAccessType accessType, Duration timeout, Context context) { return DataLakeImplUtils.returnOrConvertException(() -> blobContainerClient.createWithResponse(metadata, Transforms.toBlobPublicAccessType(accessType), timeout, context), logger); }
Source:
protected List<Trace> getFragmentsForTraceId(String tenantId, String traceId) { List<Trace> ret = new ArrayList<Trace>(); String index = client.getIndex(tenantId); try { RefreshRequestBuilder refreshRequestBuilder = client.getClient().admin().indices().prepareRefresh(index); client.getClient().admin().indices().refresh(refreshRequestBuilder.request()).actionGet(); BoolQueryBuilder query = QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("traceId", traceId)); SearchRequestBuilder request = client.getClient().prepareSearch(index) .setTypes(TRACE_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query) .addSort(ElasticsearchUtil.TIMESTAMP_FIELD, SortOrder.ASC); SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); } for (SearchHit searchHitFields : response.getHits()) { try { ret.add(mapper.readValue(searchHitFields.getSourceAsString(), Trace.class)); } catch (IOException e) { msgLog.errorFailedToParse(e); } } if (msgLog.isTraceEnabled()) { msgLog.tracef("Query fragments with traceId[%s] is: %s", traceId, ret); } } catch (org.elasticsearch.indices.IndexMissingException ime) { if (msgLog.isTraceEnabled()) { msgLog.tracef("No index found, so unable to retrieve traces"); } } catch (org.elasticsearch.action.search.SearchPhaseExecutionException spee) { if (msgLog.isTraceEnabled()) { msgLog.tracef("Failed to get fragments", spee); } } return ret; }

Target:
protected List<Trace> getFragmentsForTraceId(String tenantId, String traceId) { List<Trace> ret = Collections.emptyList(); String index = client.getIndex(tenantId); try { RefreshRequestBuilder refreshRequestBuilder = client.getClient().admin().indices().prepareRefresh(index); client.getClient().admin().indices().refresh(refreshRequestBuilder.request()).actionGet(); BoolQueryBuilder query = QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("traceId", traceId)); SearchRequestBuilder request = client.getClient().prepareSearch(index) .setTypes(TRACE_TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(query); SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); } ret = new ArrayList<Trace>((int)response.getHits().getTotalHits()); for (SearchHit searchHitFields : response.getHits()) { try { ret.add(mapper.readValue(searchHitFields.getSourceAsString(), Trace.class)); } catch (IOException e) { msgLog.errorFailedToParse(e); } } msgLog.tracef("Query fragments with traceId[%s] is: %s", traceId, ret); } catch (org.elasticsearch.indices.IndexMissingException ime) { msgLog.tracef("No index found, so unable to retrieve traces"); } catch (org.elasticsearch.action.search.SearchPhaseExecutionException spee) { msgLog.tracef("Failed to get fragments", spee); } return ret; }
Source:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }

Target:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }
Source:
public ListenableFuture<Boolean> createContainerInLocation(Location location, String container, CreateContainerOptions options) { if (Futures.getUnchecked(containerExists(container))) { return Futures.immediateFuture(Boolean.FALSE); } return super.createContainerInLocation(location, container, options); }

Target:
public ListenableFuture<Boolean> createContainerInLocation(Location location, String container, CreateContainerOptions options) { if ((location == null || location.getId().equals(Region.US_STANDARD)) && Futures.getUnchecked(containerExists(container))) { return Futures.immediateFuture(Boolean.FALSE); } return super.createContainerInLocation(location, container, options); }
Source:
public void testGetErrorDetails() { VerificationError error = ResultErrorBuilder.withCodeAndDescription(VerificationError.asCode("test_code"), "test error desc") .detail(VerificationError.asAttribute("test_attr_1"), "test_detail_1") .detail(VerificationError.HttpAttribute.HTTP_CODE,"test_detail_2") .detail("HTTP_TEXT", "test_detail_3") .build(); Assert.assertEquals("test_detail_1", error.getDetail(VerificationError.asAttribute("test_attr_1"))); Assert.assertEquals("test_detail_1", error.getDetail("test_attr_1")); Assert.assertEquals("test_detail_2", error.getDetail(VerificationError.HttpAttribute.HTTP_CODE)); Assert.assertNull(error.getDetail(VerificationError.asAttribute("HTTP_CODE"))); Assert.assertNull(error.getDetail("HTTP_CODE")); Assert.assertNull(error.getDetail(VerificationError.HttpAttribute.HTTP_TEXT)); Assert.assertEquals("test_detail_3", error.getDetail("HTTP_TEXT")); Assert.assertNull(error.getDetail(VerificationError.asAttribute("test_attr_non_existant"))); }

Target:
public void testGetErrorDetails() { VerificationError error = ResultErrorBuilder.withCodeAndDescription(VerificationError.asCode("test_code"), "test error desc") .detail(VerificationError.asAttribute("test_attr_1"), "test_detail_1") .detail(VerificationError.HttpAttribute.HTTP_CODE,"test_detail_2") .build(); Assert.assertEquals("test_detail_1", error.getDetail(VerificationError.asAttribute("test_attr_1"))); Assert.assertEquals("test_detail_1", error.getDetail("test_attr_1")); Assert.assertEquals("test_detail_2", error.getDetail(VerificationError.HttpAttribute.HTTP_CODE)); Assert.assertNull(error.getDetail(VerificationError.HttpAttribute.HTTP_TEXT)); Assert.assertNull(error.getDetail(VerificationError.asAttribute("test_attr_non_existant"))); }
Source:
public void start() { }

Target:
public void start() { LOG.info("Start called."); }
Source:
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText( String.format("You live in %s, near the %s region.", userData.getCity(), userData.getRegionName())); return SpeechletResponse.newTellResponse(out); } else if (SET_STOP_NUMBER.equals(intent.getName())) { populateAttributes(session); return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else { throw new SpeechletException("Did not recognize intent name"); } }

Target:
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { populateAttributes(session); Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText( String.format("You live in %s, near the %s region.", userData.getCity(), userData.getRegionName())); return SpeechletResponse.newTellResponse(out); } else if (SET_STOP_NUMBER.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else { throw new SpeechletException("Did not recognize intent name"); } }
Source:
private void addStandardMappings(final String indexName) throws ElasticsearchException, IOException { final ContentTypeAPI contentTypeAPI = APILocator.getContentTypeAPI(APILocator.systemUser()); final List<String> allTypes = Try.of(() -> new DotConnect().setSQL("select inode from structure").loadObjectResults()) .getOrElseThrow(e -> new DotRuntimeException(e)) .stream() .map(r -> (String) r.get("inode")) .collect(Collectors.toList()); final Map<String, Map<String, String>> mappingMap = new HashMap<>(); for (final String typeVar : allTypes) { mappingMap.clear(); final ContentType type = Try.of(() -> contentTypeAPI.find(typeVar)).getOrNull(); if (type == null) { continue; } final List<Field> indexedFields = type.fields().stream().filter(f -> f.indexed()) .filter(f -> !f.fieldVariablesMap().containsKey(FieldVariable.ES_CUSTOM_MAPPING_KEY)) .collect(Collectors.toList()); for (Field field : indexedFields) { Optional<Map<String, String>> fieldType = resolveFieldType(field); if (fieldType.isPresent()) { mappingMap.put(type.variable().toLowerCase() + "." + field.variable().toLowerCase(), fieldType.get()); } } if (!mappingMap.isEmpty()) { final JSONObject jsonObject = new JSONObject().put("properties", mappingMap); mappingAPI.putMapping(indexName, jsonObject.toString()); } } }

Target:
private void addStandardMappings(final String indexName) throws ElasticsearchException, IOException { final ContentTypeAPI contentTypeAPI = APILocator.getContentTypeAPI(APILocator.systemUser()); final List<String> allTypes = Try.of(() -> new DotConnect().setSQL("select inode from structure").loadObjectResults()) .getOrElseThrow(e -> new DotRuntimeException(e)) .stream() .map(r -> (String) r.get("inode")) .collect(Collectors.toList()); final Map<String, Map<String, String>> mappingMap = new HashMap<>(); for (final String typeVar : allTypes) { mappingMap.clear(); final ContentType type = Try.of(() -> contentTypeAPI.find(typeVar)).getOrNull(); if (type == null) { continue; } final List<Field> indexedFields = type.fields().stream().filter(f -> f.indexed()) .filter(f -> !f.fieldVariablesMap().containsKey(FieldVariable.ES_CUSTOM_MAPPING_KEY)) .collect(Collectors.toList()); for (Field field : indexedFields) { Optional<Map<String, String>> fieldType = resolveFieldType(field); if (fieldType.isPresent()) { mappingMap.put(field.variable().toLowerCase(), fieldType.get()); } } if (!mappingMap.isEmpty()) { final JSONObject jsonObject = new JSONObject(); final JSONObject properties = new JSONObject(); jsonObject.put(type.variable().toLowerCase(), new JSONObject() .put("properties", mappingMap)); properties.put("properties", jsonObject); mappingAPI.putMapping(indexName, properties.toString()); } } }
Source:
public VersionedCatalog loadDefaultCatalog(final String uriString) throws CatalogApiException { try { final List<URI> xmlURIs; if (uriString.endsWith(XML_EXTENSION)) { xmlURIs = new ArrayList<URI>(); xmlURIs.add(new URI(uriString)); } else { final URL url = getURLFromString(uriString); final String directoryContents = UriAccessor.accessUriAsString(uriString); xmlURIs = findXmlReferences(directoryContents, url); } final DefaultVersionedCatalog result = new DefaultVersionedCatalog(new ArrayList<>()); for (final URI u : xmlURIs) { final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class); result.add(new StandaloneCatalogWithPriceOverride(catalog, priceOverride, InternalCallContextFactory.INTERNAL_TENANT_RECORD_ID, internalCallContextFactory)); } XMLLoader.initializeAndValidate(result); return result; } catch (final ValidationException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (final JAXBException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (IllegalArgumentException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (Exception e) { logger.warn("Failed to load default catalog", e); throw new IllegalStateException(e); } }

Target:
public VersionedCatalog loadDefaultCatalog(final String uriString) throws CatalogApiException { try { final List<URI> xmlURIs; if (uriString.endsWith(XML_EXTENSION)) { xmlURIs = new ArrayList<URI>(); xmlURIs.add(new URI(uriString)); } else { final URL url = getURLFromString(uriString); final String directoryContents = UriAccessor.accessUriAsString(uriString); xmlURIs = findXmlReferences(directoryContents, url); } final DefaultVersionedCatalog result = new DefaultVersionedCatalog(); for (final URI u : xmlURIs) { final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class); result.add(new StandaloneCatalogWithPriceOverride(catalog, priceOverride, InternalCallContextFactory.INTERNAL_TENANT_RECORD_ID, internalCallContextFactory)); } XMLLoader.initializeAndValidate(result); return result; } catch (final ValidationException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (final JAXBException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (IllegalArgumentException e) { logger.warn("Failed to load default catalog", e); throw new CatalogApiException(e, ErrorCode.CAT_INVALID_DEFAULT, uriString); } catch (Exception e) { logger.warn("Failed to load default catalog", e); throw new IllegalStateException(e); } }
Source:
public <T extends StorageLocationSetting> T createStorageLocationSetting(UserInfo userInfo, T storageLocationSetting) throws DatastoreException, NotFoundException { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocationSetting, "The storage location"); if (storageLocationSetting instanceof BaseKeyStorageLocationSetting) { sanitizeBaseKey((BaseKeyStorageLocationSetting) storageLocationSetting); } this.processStorageLocation(userInfo, storageLocationSetting); if (storageLocationSetting instanceof BucketOwnerStorageLocationSetting) { bucketOwnerVerifier.verifyBucketOwnership(userInfo, (BucketOwnerStorageLocationSetting) storageLocationSetting); } if (storageLocationSetting.getUploadType() == null) { storageLocationSetting.setUploadType(UploadType.NONE); } storageLocationSetting.setCreatedBy(userInfo.getId()); storageLocationSetting.setCreatedOn(new Date()); Long storageLocationId = storageLocationDAO.create(storageLocationSetting); return (T) storageLocationDAO.get(storageLocationId); }

Target:
public <T extends StorageLocationSetting> T createStorageLocationSetting(UserInfo userInfo, T storageLocationSetting) throws DatastoreException, NotFoundException { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocationSetting, "The storage location"); this.processStorageLocation(userInfo, storageLocationSetting); if (storageLocationSetting.getUploadType() == null) { storageLocationSetting.setUploadType(UploadType.NONE); } storageLocationSetting.setCreatedBy(userInfo.getId()); storageLocationSetting.setCreatedOn(new Date()); Long storageLocationId = storageLocationDAO.create(storageLocationSetting); return (T) storageLocationDAO.get(storageLocationId); }
Source:
public void testProducers() throws IOException { JsonObject allBeans = getPageAsJSONObject(BEANS_PATH_ALL, url); JsonArray beansData = allBeans.getJsonArray(DATA); List<JsonObject> producers = getAllJsonObjectsByClass(TestProducer.class, beansData); Optional<JsonObject> fieldProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_FIELD.name())) .findAny(); assertNotNull("Cannot find producer field from " + TestProducer.class.getName(), fieldProducer.get()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(String.class.getName(), null, fieldProducer.get().getJsonArray(TYPES), false)); Optional<JsonObject> methodProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_METHOD.name())) .findAny(); assertNotNull("Cannot find producer field from " + TestProducer.class.getName(), methodProducer.get()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(ModelBean.class.getName(), null, methodProducer.get().getJsonArray(TYPES), false)); }

Target:
public void testProducers() throws IOException { JsonObject allBeans = getPageAsJSONObject(BEANS_PATH_ALL, url); JsonArray beansData = allBeans.getJsonArray(DATA); List<JsonObject> producers = getAllJsonObjectsByClass(TestProducer.class, beansData); Optional<JsonObject> fieldProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_FIELD.name())) .findAny(); assertTrue("Cannot find producer field from " + TestProducer.class.getName(), fieldProducer.isPresent()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(String.class.getName(), null, fieldProducer.get().getJsonArray(TYPES), false)); Optional<JsonObject> methodProducer = producers.stream().filter((JsonObject o) -> o.getString(KIND).equals(BeanType.PRODUCER_METHOD.name())) .findAny(); assertTrue("Cannot find producer method from " + TestProducer.class.getName(), methodProducer.isPresent()); assertEquals("@" + Dependent.class.getSimpleName(), fieldProducer.get().getString(SCOPE)); assertTrue(checkStringInArrayRecursively(ModelBean.class.getName(), null, methodProducer.get().getJsonArray(TYPES), false)); }