auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void validatePropertySectionPropertyTokens(String fileName, String sectionName, AbstractCheck check, List<Node> columns) { assertEquals("tokens to check", columns.get(1).getTextContent(), fileName + " section '" + sectionName + "' should have the basic token description"); String acceptableTokenText = columns.get(2).getTextContent().trim(); final int removePrefixIdx = "subset of tokens".length(); acceptableTokenText = acceptableTokenText.substring(removePrefixIdx); assertFalse(isInvalidTokenPunctuation(acceptableTokenText), ", & . should be placed at beginning of the next corresponding lines " + "in " + fileName + " acceptable token section: " + sectionName); assertEquals(CheckUtil.getTokenText(check.getAcceptableTokens(), check.getRequiredTokens()).replaceAll("\\s+", ""), acceptableTokenText.replaceAll("\\s+", ""), fileName + " section '" + sectionName + "' should have all the acceptable tokens"); final String defaultTokenText = columns.get(3).getTextContent().trim(); assertFalse(isInvalidTokenPunctuation(defaultTokenText), ", & . should be placed at beginning of the next corresponding lines " + "in " + fileName + " default token section: " + sectionName); assertEquals(CheckUtil.getTokenText(check.getDefaultTokens(), check.getRequiredTokens()).replaceAll("\\s+", ""), defaultTokenText.replaceAll("\\s+", ""), fileName + " section '" + sectionName + "' should have all the default tokens"); }

Target:
private static void validatePropertySectionPropertyTokens(String fileName, String sectionName, AbstractCheck check, List<Node> columns) { assertEquals("tokens to check", columns.get(1).getTextContent(), fileName + " section '" + sectionName + "' should have the basic token description"); final String acceptableTokenText = columns.get(2).getTextContent().trim(); assertEquals("subset of tokens " + CheckUtil.getTokenText(check.getAcceptableTokens(), check.getRequiredTokens()), acceptableTokenText .replaceAll("\\s+", " ") .replaceAll("\\s,", ",") .replaceAll("\\s\\.", "."), fileName + " section '" + sectionName + "' should have all the acceptable tokens"); assertFalse(isInvalidTokenPunctuation(acceptableTokenText), fileName + "'s acceptable token section: " + sectionName + "should have ',' & '.' at beginning of the next corresponding lines."); final String defaultTokenText = columns.get(3).getTextContent().trim(); assertEquals(CheckUtil.getTokenText(check.getDefaultTokens(), check.getRequiredTokens()), defaultTokenText .replaceAll("\\s+", " ") .replaceAll("\\s,", ",") .replaceAll("\\s\\.", "."), fileName + " section '" + sectionName + "' should have all the default tokens"); assertFalse(isInvalidTokenPunctuation(defaultTokenText), fileName + "'s default token section: " + sectionName + "should have ',' & '.' at beginning of the next corresponding lines."); }
Source:
private List<JSONObject> getOutgoingRelationshipsPerNode(final Integer nodeId) { List<JSONObject> outgoingRelationshipsPerNode = new ArrayList<>(); String outgoingRelationshipsPerNodeJsonString = _requestWrapper.executeRestRequest(new HttpGet(_serviceRoot + "/node/" + nodeId + "/relationships/out")); JSONArray outgoingRelationshipsPerNodeJsonArray; try { outgoingRelationshipsPerNodeJsonArray = new JSONArray(outgoingRelationshipsPerNodeJsonString); for (int i = 0; i < outgoingRelationshipsPerNodeJsonArray.length(); i++) { JSONObject relationship = outgoingRelationshipsPerNodeJsonArray.getJSONObject(i); if (!outgoingRelationshipsPerNode.contains(relationship)) { outgoingRelationshipsPerNode.add(relationship); } } return outgoingRelationshipsPerNode; } catch (JSONException e) { logger.error("Error occured in parsing JSON while detecting outgoing relationships for node: " + nodeId, e); throw new IllegalStateException(e); } }

Target:
private List<JSONObject> getOutgoingRelationshipsPerNode(final Integer nodeId) { final List<JSONObject> outgoingRelationshipsPerNode = new ArrayList<>(); final String outgoingRelationshipsPerNodeJsonString = _requestWrapper.executeRestRequest( new HttpGet(_serviceRoot + "/node/" + nodeId + "/relationships/out")); final JSONArray outgoingRelationshipsPerNodeJsonArray; try { outgoingRelationshipsPerNodeJsonArray = new JSONArray(outgoingRelationshipsPerNodeJsonString); for (int i = 0; i < outgoingRelationshipsPerNodeJsonArray.length(); i++) { final JSONObject relationship = outgoingRelationshipsPerNodeJsonArray.getJSONObject(i); if (!outgoingRelationshipsPerNode.contains(relationship)) { outgoingRelationshipsPerNode.add(relationship); } } return outgoingRelationshipsPerNode; } catch (final JSONException e) { logger.error("Error occurred in parsing JSON while detecting outgoing relationships for node: " + nodeId, e); throw new IllegalStateException(e); } }
Source:
private static void instantiateTemplateRule(String projectKey, String ruleTemplateKey, String instantiationKey, String params) { SonarClient sonarClient = orchestrator.getServer().adminWsClient(); sonarClient.post("/api/rules/create", ImmutableMap.<String, Object>builder() .put("name", instantiationKey) .put("markdown_description", instantiationKey) .put("severity", "INFO") .put("status", "READY") .put("template_key", "javascript:" + ruleTemplateKey) .put("custom_key", instantiationKey) .put("prevent_reactivation", "true") .put("params", "name=\"" + instantiationKey + "\";key=\"" + instantiationKey + "\";markdown_description=\"" + instantiationKey + "\";" + params) .build()); String post = sonarClient.get("api/qualityprofiles/search?projectKey=" + projectKey); String profileKey = null; Map profilesForProject = new Gson().fromJson(post, Map.class); for (Map profileDescription : (List<Map>) profilesForProject.get("profiles")) { if ("rules".equals(profileDescription.get("name"))) { profileKey = (String) profileDescription.get("key"); break; } } if (profileKey != null) { String response = sonarClient.post("api/qualityprofiles/activate_rule", ImmutableMap.of( "profile_key", profileKey, "rule_key", "javascript:" + instantiationKey, "severity", "INFO", "params", "")); LoggerFactory.getLogger(JavaScriptRulingTest.class).warn(response); } else { LoggerFactory.getLogger(JavaScriptRulingTest.class).error("Could not retrieve profile key : Template rule " + ruleTemplateKey + " has not been activated"); } }

Target:
private static void instantiateTemplateRule(String projectKey, String ruleTemplateKey, String instantiationKey, String params) { SonarClient sonarClient = orchestrator.getServer().adminWsClient(); sonarClient.post("/api/rules/create", ImmutableMap.<String, Object>builder() .put("name", instantiationKey) .put("markdown_description", instantiationKey) .put("severity", "INFO") .put("status", "READY") .put("template_key", "javascript:" + ruleTemplateKey) .put("custom_key", instantiationKey) .put("prevent_reactivation", "true") .put("params", "name=\"" + instantiationKey + "\";key=\"" + instantiationKey + "\";markdown_description=\"" + instantiationKey + "\";" + params) .build()); String post = sonarClient.get("api/qualityprofiles/search?projectKey=" + projectKey); String profileKey = null; Map profilesForProject = new Gson().fromJson(post, Map.class); for (Map profileDescription : (List<Map>) profilesForProject.get("profiles")) { if ("rules".equals(profileDescription.get("name"))) { profileKey = (String) profileDescription.get("key"); break; } } if (profileKey != null) { String response = sonarClient.post("api/qualityprofiles/activate_rule", ImmutableMap.of( "profile_key", profileKey, "rule_key", "javascript:" + instantiationKey, "severity", "INFO", "params", "")); LOG.warn(response); } else { LOG.error("Could not retrieve profile key : Template rule " + ruleTemplateKey + " has not been activated"); } }
Source:
public String combineIt() { StringBuffer stringBuffer = new StringBuffer(); for (String string : field) { stringBuffer.append(string); } return stringBuffer.toString(); }

Target:
public String combineIt() { StringBuilder stringBuilder = new StringBuilder(); for (String string : field) { stringBuilder.append(string); } return stringBuilder.toString(); }
Source:
public void init() throws Exception { super.init(); API_BASE_URL = getGatewayServerURLHttp() + "/"; USER_NAME1 = apimContext.getContextTenant().getContextUser().getUserName(); String publisherURLHttp = getPublisherServerURLHttp(); String storeURLHttp = getStoreServerURLHttp(); apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp); apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp); apiPublisherClientUser2 = new APIPublisherRestClient(publisherURLHttp); apiStoreClientUser2 = new APIStoreRestClient(storeURLHttp); apiPublisherClientUser1.login(apimContext.getContextTenant().getContextUser().getUserName(), apimContext.getContextTenant().getContextUser().getPassword()); apiStoreClientUser1.login(apimContext.getContextTenant().getContextUser().getUserName(), apimContext.getContextTenant().getContextUser().getPassword()); USER_NAME2 = apimContext.getContextTenant().getTenantUser(USER_KEY_USER2).getUserName(); String user2PassWord = apimContext.getContextTenant().getTenantUser(USER_KEY_USER2).getPassword(); apiPublisherClientUser2.login(USER_NAME2, user2PassWord); apiStoreClientUser2.login(USER_NAME2, user2PassWord); }

Target:
public void init() throws APIManagerIntegrationTestException { super.init(); GATEWAY_WEB_APP_URL = gatewayUrls.getWebAppURLNhttp(); }
Source:
public void setQueue(List<FeedItem> queue) { ContentValues values = new ContentValues(); long[] ids = new long[queue.size()]; db.beginTransaction(); db.delete(TABLE_NAME_QUEUE, null, null); for (int i = 0; i < queue.size(); i++) { FeedItem item = queue.get(i); ids[i] = item.getId(); values.put(KEY_ID, i); values.put(KEY_FEEDITEM, item.getId()); values.put(KEY_FEED, item.getFeed().getId()); db.insertWithOnConflict(TABLE_NAME_QUEUE, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); db.endTransaction(); }

Target:
public void setQueue(List<FeedItem> queue) { ContentValues values = new ContentValues(); db.beginTransaction(); db.delete(TABLE_NAME_QUEUE, null, null); for (int i = 0; i < queue.size(); i++) { FeedItem item = queue.get(i); values.put(KEY_ID, i); values.put(KEY_FEEDITEM, item.getId()); values.put(KEY_FEED, item.getFeed().getId()); db.insertWithOnConflict(TABLE_NAME_QUEUE, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); db.endTransaction(); }
Source:
protected void copyValues(RegularStatement that) { if (!that.hasValues()) return; Preconditions.checkArgument(parameterMode != ParameterMode.NAMED && that.usesPositionalValues()); int offset = values.isEmpty() ? 0 : (Integer)(values.lastEntry().getKey()) + 1; for (ValueDefinition definition : that.getValueDefinitions()) { int thatIndex = definition.getIndex(); assert thatIndex >= 0; int thisIndex = offset + thatIndex; setInternal(thisIndex, new Value(new ValueDefinition(thisIndex, definition.getType()), that.getBytesUnsafe(thatIndex))); } }

Target:
protected void copyValues(RegularStatement that) { if (!that.hasValues()) return; Preconditions.checkArgument(parameterMode != ParameterMode.NAMED && that.usesPositionalValues()); int offset = values.isEmpty() ? 0 : (Integer)(values.lastEntry().getKey()) + 1; for (ValueDefinition definition : that.getValueDefinitions()) { int thatIndex = definition.getIndex(); assert thatIndex >= 0; int thisIndex = offset + thatIndex; setInternal(thisIndex, new Value(thisIndex, definition.getType(), that.getBytesUnsafe(thatIndex))); } }
Source:
private File getTrustStorePkcs12File() throws IOException { if (trustStorePkcs12File == null) { try { File trustStorePkcs12File = File.createTempFile( TRUST_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir); trustStorePkcs12File.deleteOnExit(); final FileOutputStream trustStoreOutputStream = new FileOutputStream(trustStorePkcs12File); try { byte[] bytes = X509TestHelpers.certToPKCS12TrustStoreBytes(trustStoreCertificate, trustStorePassword); trustStoreOutputStream.write(bytes); trustStoreOutputStream.flush(); } finally { trustStoreOutputStream.close(); } this.trustStorePkcs12File = trustStorePkcs12File; } catch (GeneralSecurityException e) { throw new IOException(e); } } return trustStorePkcs12File; }

Target:
private File getTrustStorePkcs12File() throws IOException { if (trustStorePkcs12File == null) { File trustStorePkcs12File = File.createTempFile( TRUST_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir); trustStorePkcs12File.deleteOnExit(); try (final FileOutputStream trustStoreOutputStream = new FileOutputStream(trustStorePkcs12File)) { byte[] bytes = X509TestHelpers.certToPKCS12TrustStoreBytes(trustStoreCertificate, trustStorePassword); trustStoreOutputStream.write(bytes); trustStoreOutputStream.flush(); } catch (GeneralSecurityException e) { throw new IOException(e); } this.trustStorePkcs12File = trustStorePkcs12File; } return trustStorePkcs12File; }
Source:
public static LockAwareTransactionManager setupTxManager(KeyValueService kvs, TimestampService tsService, SweepStrategyManager ssm, TransactionService txService) { LockClient lockClient = LockClient.of("sweep client"); LockService lockService = LockServiceImpl.create(new LockServerOptions() { @Override public boolean isStandaloneServer() { return false; } }); Supplier<AtlasDbConstraintCheckingMode> constraints = () -> AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING; ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); Cleaner cleaner = new NoOpCleaner(); LockAwareTransactionManager txManager = new SerializableTransactionManager(kvs, tsService, lockClient, lockService, txService, constraints, cdm, ssm, cleaner, false, 16, java.time.Duration.ofMinutes(1)); setupTables(kvs); return txManager; }

Target:
public static LockAwareTransactionManager setupTxManager(KeyValueService kvs, TimestampService tsService, SweepStrategyManager ssm, TransactionService txService) { LockClient lockClient = LockClient.of("sweep client"); LockService lockService = LockServiceImpl.create( LockServerOptions.builder().isStandaloneServer(false).build()); Supplier<AtlasDbConstraintCheckingMode> constraints = () -> AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING; ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); Cleaner cleaner = new NoOpCleaner(); LockAwareTransactionManager txManager = new SerializableTransactionManager(kvs, tsService, lockClient, lockService, txService, constraints, cdm, ssm, cleaner, false, 16); setupTables(kvs); return txManager; }
Source:
public void beforeParamAndAfterParamAreRun() { fLog = ""; final Result result = JUnitCore.runClasses(BeforeParamAndAfterParam.class); assertEquals(0, result.getFailureCount()); assertEquals("beforeClass before(A) first(A) second(A) afterParam " + "before(B) first(B) second(B) afterParam afterClass ", fLog); }

Target:
public void beforeParamAndAfterParamAreRun() { fLog = ""; Result result = JUnitCore.runClasses(BeforeParamAndAfterParam.class); assertEquals(0, result.getFailureCount()); assertEquals("beforeClass before(A) first(A) second(A) afterParam " + "before(B) first(B) second(B) afterParam afterClass ", fLog); }
Source:
public static String get() { return props.getOrDefault(VERSION_RELEASE_KEY, "unset"); }

Target:
public static String get() { return props.get(VERSION_RELEASE_KEY); }
Source:
private static Schema getSchema(String typeName, int sqlType, int precision, int scale, String columnName) throws SQLException { Schema.Type type = Schema.Type.STRING; switch (sqlType) { case Types.NULL: type = Schema.Type.NULL; break; case Types.ROWID: break; case Types.BOOLEAN: case Types.BIT: type = Schema.Type.BOOLEAN; break; case Types.TINYINT: case Types.SMALLINT: type = Schema.Type.INT; break; case Types.INTEGER: type = "int unsigned".equalsIgnoreCase(typeName) ? Schema.Type.LONG : Schema.Type.INT; break; case Types.BIGINT: type = Schema.Type.LONG; break; case Types.REAL: case Types.FLOAT: type = Schema.Type.FLOAT; break; case Types.NUMERIC: case Types.DECIMAL: return Schema.decimalOf(2,scale); case Types.DOUBLE: type = Schema.Type.DOUBLE; break; case Types.DATE: return Schema.of(Schema.LogicalType.DATE); case Types.TIME: return Schema.of(Schema.LogicalType.TIME_MICROS); case Types.TIMESTAMP: return Schema.of(Schema.LogicalType.TIMESTAMP_MICROS); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: type = Schema.Type.BYTES; break; case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.OTHER: case Types.REF: case Types.SQLXML: case Types.STRUCT: throw new SQLException(new UnsupportedTypeException(String.format("Column %s has unsupported SQL type of %s." , columnName, sqlType))); } return Schema.of(type); }

Target:
private static Schema getSchema(String typeName, int sqlType, int precision, int scale, String columnName) throws SQLException { Schema.Type type = Schema.Type.STRING; switch (sqlType) { case Types.NULL: type = Schema.Type.NULL; break; case Types.ROWID: break; case Types.BOOLEAN: case Types.BIT: type = Schema.Type.BOOLEAN; break; case Types.TINYINT: case Types.SMALLINT: type = Schema.Type.INT; break; case Types.INTEGER: type = "int unsigned".equalsIgnoreCase(typeName) ? Schema.Type.LONG : Schema.Type.INT; break; case Types.BIGINT: type = Schema.Type.LONG; break; case Types.REAL: case Types.FLOAT: type = Schema.Type.FLOAT; break; case Types.NUMERIC: type = scale != 0 ? Schema.Type.DOUBLE : precision > 9 ? Schema.Type.LONG : Schema.Type.INT; break; case Types.DECIMAL: return Schema.decimalOf(precision, scale); case Types.DOUBLE: type = Schema.Type.DOUBLE; break; case Types.DATE: return Schema.of(Schema.LogicalType.DATE); case Types.TIME: return Schema.of(Schema.LogicalType.TIME_MICROS); case Types.TIMESTAMP: return Schema.of(Schema.LogicalType.TIMESTAMP_MICROS); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: type = Schema.Type.BYTES; break; case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.OTHER: case Types.REF: case Types.SQLXML: case Types.STRUCT: throw new SQLException(new UnsupportedTypeException(String.format("Column %s has unsupported SQL type of %s." , columnName, sqlType))); } return Schema.of(type); }
Source:
private void parseProperties() { for(String arg : getPrefixArguments()) { Argument argument = new Argument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setValue( getArgAttrValue(arg, "value") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( Argument.Type.valueOfIgnoreCase( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setValueType( Class.forName( getArgAttrValue(arg, "convert"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check convert class in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } arguments.put(argument.getName(), argument); } }

Target:
private void parseProperties() { for(String arg : getPrefixArguments()) { Argument argument = new Argument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setValue( getArgAttrValue(arg, "value") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( Argument.Type.valueOfIgnoreCase( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setValueType( Class.forName( getArgAttrValue(arg, "valuetype"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check valuetype in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } arguments.put(argument.getName(), argument); } }
Source:
public boolean isSideBand() throws RequestNotYetReadException { if (currentRequest == null) throw new RequestNotYetReadException(); Set<String> cc = currentRequest.getClientCapabilities(); return cc.contains(OPTION_SIDE_BAND) || cc.contains(OPTION_SIDE_BAND_64K); }

Target:
public boolean isSideBand() throws RequestNotYetReadException { if (currentRequest == null) { throw new RequestNotYetReadException(); } Set<String> caps = currentRequest.getClientCapabilities(); return caps.contains(OPTION_SIDE_BAND) || caps.contains(OPTION_SIDE_BAND_64K); }
Source:
public Message.Request request() { Message.Request request = callback.request(); if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) return request.copy(retryConsistencyLevel); else return request; }

Target:
public Message.Request request() { if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) return request.copy(retryConsistencyLevel); else return request; }
Source:
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView != null) { PluginController molgenisPlugin = validateHandler(handler); String pluginId = molgenisPlugin.getId(); if (!modelAndView.getModel().containsKey(PluginAttributes.KEY_PLUGIN_ID)) { modelAndView.addObject(PluginAttributes.KEY_PLUGIN_ID, pluginId); } Entity pluginSettings = molgenisPlugin.getPluginSettings(); Boolean pluginSettingsCanWrite; if (pluginSettings != null) { String pluginSettingsEntityName = pluginSettings.getEntityType().getId(); pluginSettingsCanWrite = permissionService.hasPermissionOnEntityType(pluginSettingsEntityName, Permission.WRITE); } else { pluginSettingsCanWrite = null; } modelAndView.addObject(PluginAttributes.KEY_PLUGIN_SETTINGS, pluginSettings); modelAndView.addObject(PluginAttributes.KEY_PLUGIN_SETTINGS_CAN_WRITE, pluginSettingsCanWrite); modelAndView.addObject(PluginAttributes.KEY_MOLGENIS_UI, molgenisUi); modelAndView.addObject(PluginAttributes.KEY_AUTHENTICATED, SecurityUtils.currentUserIsAuthenticated()); modelAndView.addObject(PluginAttributes.KEY_PLUGIN_ID_WITH_QUERY_STRING, getPluginIdWithQueryString(request, pluginId)); modelAndView.addObject(PluginAttributes.KEY_PLUGIN_DESCRIPTION, molgenisPlugin.getDescription(pluginId)); } }

Target:
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView != null) { PluginController molgenisPlugin = validateHandler(handler); String pluginId = molgenisPlugin.getId(); if (!modelAndView.getModel().containsKey(PluginAttributes.KEY_PLUGIN_ID)) { modelAndView.addObject(PluginAttributes.KEY_PLUGIN_ID, pluginId); } Entity pluginSettings = molgenisPlugin.getPluginSettings(); Boolean pluginSettingsCanWrite; if (pluginSettings != null) { String pluginSettingsEntityName = pluginSettings.getEntityType().getId(); pluginSettingsCanWrite = permissionService.hasPermissionOnEntityType(pluginSettingsEntityName, Permission.WRITE); } else { pluginSettingsCanWrite = null; } modelAndView.addObject(PluginAttributes.KEY_PLUGIN_SETTINGS, pluginSettings); modelAndView.addObject(PluginAttributes.KEY_PLUGIN_SETTINGS_CAN_WRITE, pluginSettingsCanWrite); modelAndView.addObject(PluginAttributes.KEY_MOLGENIS_UI, molgenisUi); modelAndView.addObject(PluginAttributes.KEY_AUTHENTICATED, SecurityUtils.currentUserIsAuthenticated()); modelAndView.addObject(PluginAttributes.KEY_PLUGIN_ID_WITH_QUERY_STRING, getPluginIdWithQueryString(request, pluginId)); } }
Source:
public void execute(Runnable task) { if (task == null) { throw new NullPointerException("task"); } boolean inEventLoop = inEventLoop(); if (!inEventLoop) { if (isShutdown()) { reject(); } addTask(task); startThread(); if (isShutdown() && removeTask(task)) { reject(); } } else { addTask(task); } if (!addTaskWakesUp && wakesUpForTask(task)) { wakeup(inEventLoop); } }

Target:
public void execute(Runnable task) { if (task == null) { throw new NullPointerException("task"); } boolean inEventLoop = inEventLoop(); addTask(task); if (!inEventLoop) { startThread(); if (isShutdown()) { boolean reject = false; try { if (removeTask(task)) { reject = true; } } catch (UnsupportedOperationException e) { } if (reject) { reject(); } } } if (!addTaskWakesUp && wakesUpForTask(task)) { wakeup(inEventLoop); } }
Source:
public static TestReport from(Entity entity) { checkNotNull(entity, "'entity' parameter cannot be null"); checkArgument(TEST_REPORT.equals(entity.getKind()), "'entity' parameter wrong kind"); final List<Test> failedTests = new ArrayList<>(); try { final JSONArray jsonArray = new JSONArray(new JSONTokener(((Text) entity.getProperty("failedTests")).getValue())); for (int i = 0; i < jsonArray.length(); i++) { final Test test = Test.valueOf(jsonArray.getJSONObject(i)); failedTests.add(test); } } catch (JSONException e) { throw new RuntimeException(e); } final List<Test> ignoredTests = new ArrayList<>(); try { final JSONArray jsonArray = new JSONArray(new JSONTokener(((Text) entity.getProperty("ignoredTests")).getValue())); for (int i = 0; i < jsonArray.length(); i++) { final Test test = Test.valueOf(jsonArray.getJSONObject(i)); ignoredTests.add(test); } } catch (JSONException e) { throw new RuntimeException(e); } catch (NullPointerException e) { log.info(String.format("Ignored test do not have detailed information : %s [%s]", entity.getProperty("buildTypeId"), entity.getProperty("buildId"))); } return new TestReport( (String) entity.getProperty("buildTypeId"), ((Long) entity.getProperty("buildId")).intValue(), (Date) entity.getProperty("buildDate"), ((Long) entity.getProperty("buildDuration")), ((Long) entity.getProperty("numberOfPassedTests")).intValue(), ((Long) entity.getProperty("numberOfIgnoredTests")).intValue(), ((Long) entity.getProperty("numberOfFailedTests")).intValue(), failedTests, ignoredTests ); }

Target:
public static TestReport from(Entity entity) { checkNotNull(entity, "'entity' parameter cannot be null"); checkArgument(TEST_REPORT.equals(entity.getKind()), "'entity' parameter wrong kind"); final List<Test> failedTests = new ArrayList<>(); try { final JSONArray jsonArray = new JSONArray(new JSONTokener(((Text) entity.getProperty("failedTests")).getValue())); for (int i = 0; i < jsonArray.length(); i++) { final Test test = Test.valueOf(jsonArray.getJSONObject(i)); failedTests.add(test); } } catch (JSONException e) { throw new RuntimeException(e); } final List<Test> ignoredTests = new ArrayList<>(); try { final Text ignoredTestsEntity = (Text) entity.getProperty("ignoredTests"); if (ignoredTestsEntity != null) { final JSONArray jsonArray = new JSONArray(new JSONTokener(ignoredTestsEntity.getValue())); for (int i = 0; i < jsonArray.length(); i++) { final Test test = Test.valueOf(jsonArray.getJSONObject(i)); ignoredTests.add(test); } } else { log.info(String.format("Ignored test do not have detailed information : %s [%s]", entity.getProperty("buildTypeId"), entity.getProperty("buildId"))); } } catch (JSONException e) { throw new RuntimeException(e); } return new TestReport( (String) entity.getProperty("buildTypeId"), ((Long) entity.getProperty("buildId")).intValue(), (Date) entity.getProperty("buildDate"), ((Long) entity.getProperty("buildDuration")), ((Long) entity.getProperty("numberOfPassedTests")).intValue(), ((Long) entity.getProperty("numberOfIgnoredTests")).intValue(), ((Long) entity.getProperty("numberOfFailedTests")).intValue(), failedTests, ignoredTests ); }
Source:
protected boolean isVmTemplateWithSameNameExist() { return DbFacade.getInstance() .getVmTemplateDao() .getByName(getParameters().getVmTemplate().getName(), getParameters().getStoragePoolId(), null, false) != null; }

Target:
protected boolean isVmTemplateWithSameNameExist() { return vmTemplateDao.getByName(getParameters().getVmTemplate().getName(), getParameters().getStoragePoolId(), null, false) != null; }
Source:
private int getSelectedIndex(List<PickerMilestone> milestones) { for (int i = 0; i < milestones.size(); i++) { if (milestones.get(i).isSelected()) { return i; } } return -1; }

Target:
private Optional<Integer> getSelectedIndex(List<PickerMilestone> milestones) { for (int i = 0; i < milestones.size(); i++) { if (milestones.get(i).isSelected()) { return Optional.of(i); } } return Optional.empty(); }
Source:
public void simpleEvidenceSearch() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setEvidence("imatinib"); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response).isNotNull(); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().get(0)).isNotNull() ; }

Target:
public void simpleEvidenceSearch() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setEvidence(TestData.EVIDENCE_NAME); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations()).isNotEmpty() ; }
Source:
public CommentService() { super(new CommentDAO()); }

Target:
private CommentService() { super(new CommentDAO()); }
Source:
private void runAlgo() { double currWeightToGoal, estimationFullWeight; while (true) { visitedNodes++; if (isMaxVisitedNodesExceeded() || finished()) break; int currNode = currEdge.adjNode; EdgeIterator iter = edgeExplorer.setBaseNode(currNode); while (iter.next()) { if (!accept(iter, currEdge.edge)) continue; double tmpWeight = !outEdgeFilter.accept(iter) ? Double.POSITIVE_INFINITY : weighting.calcWeight(iter, false, currEdge.edge) + currEdge.weightOfVisitedPath; if (Double.isInfinite(tmpWeight)) { continue; } int traversalId = traversalMode.createTraversalId(iter, false); AStarEntry ase = fromMap.get(traversalId); if (ase == null || ase.weightOfVisitedPath > tmpWeight) { int neighborNode = iter.getAdjNode(); currWeightToGoal = weightApprox.approximate(neighborNode); estimationFullWeight = tmpWeight + currWeightToGoal; if (ase == null) { ase = new AStarEntry(iter.getEdge(), neighborNode, estimationFullWeight, tmpWeight); fromMap.put(traversalId, ase); } else { fromHeap.remove(ase); ase.edge = iter.getEdge(); ase.weight = estimationFullWeight; ase.weightOfVisitedPath = tmpWeight; } ase.parent = currEdge; fromHeap.add(ase); updateBestPath(iter, ase, traversalId); } } if (fromHeap.isEmpty()) break; currEdge = fromHeap.poll(); if (currEdge == null) throw new AssertionError("Empty edge cannot happen"); } }

Target:
private void runAlgo() { double currWeightToGoal, estimationFullWeight; while (true) { visitedNodes++; if (isMaxVisitedNodesExceeded() || finished()) break; int currNode = currEdge.adjNode; EdgeIterator iter = edgeExplorer.setBaseNode(currNode); while (iter.next()) { if (!accept(iter, currEdge.edge)) continue; double tmpWeight = !outEdgeFilter.accept(iter) ? Double.POSITIVE_INFINITY : (weighting.calcWeight(iter, false, currEdge.edge) + currEdge.weightOfVisitedPath); if (Double.isInfinite(tmpWeight)) { continue; } int traversalId = traversalMode.createTraversalId(iter, false); AStarEntry ase = fromMap.get(traversalId); if (ase == null || ase.weightOfVisitedPath > tmpWeight) { int neighborNode = iter.getAdjNode(); currWeightToGoal = weightApprox.approximate(neighborNode); estimationFullWeight = tmpWeight + currWeightToGoal; if (ase == null) { ase = new AStarEntry(iter.getEdge(), neighborNode, estimationFullWeight, tmpWeight); fromMap.put(traversalId, ase); } else { fromHeap.remove(ase); ase.edge = iter.getEdge(); ase.weight = estimationFullWeight; ase.weightOfVisitedPath = tmpWeight; } ase.parent = currEdge; fromHeap.add(ase); updateBestPath(iter, ase, traversalId); } } if (fromHeap.isEmpty()) break; currEdge = fromHeap.poll(); if (currEdge == null) throw new AssertionError("Empty edge cannot happen"); } }
Source:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); if (usesPatternSubscription() && !existingTopics.equals(topics)) { topics.addAll(existingTopics); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } }

Target:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); if (!existingTopics.equals(topics)) { topics.addAll(existingTopics); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } }
Source:
private void poll() { log.info("polling published segments from coordinator"); final JsonParserIterator<SegmentWithOvershadowedStatus> metadataSegments = getMetadataSegments( coordinatorDruidLeaderClient, jsonMapper, responseHandler, segmentWatcherConfig.getWatchedDataSources() ); final DateTime timestamp = DateTimes.nowUtc(); while (metadataSegments.hasNext()) { final SegmentWithOvershadowedStatus segment = metadataSegments.next(); final DataSegment interned = DataSegmentInterner.intern(segment.getDataSegment()); final SegmentWithOvershadowedStatus segmentWithOvershadowedStatus = new SegmentWithOvershadowedStatus( interned, segment.isOvershadowed() ); publishedSegments.put(segmentWithOvershadowedStatus, timestamp); } publishedSegments.entrySet().removeIf(e -> e.getValue() != timestamp); cachePopulated.set(true); }

Target:
private void poll() { log.info("polling published segments from coordinator"); final JsonParserIterator<SegmentWithOvershadowedStatus> metadataSegments = getMetadataSegments( coordinatorDruidLeaderClient, jsonMapper, responseHandler, segmentWatcherConfig.getWatchedDataSources() ); final ImmutableSortedSet.Builder<SegmentWithOvershadowedStatus> builder = ImmutableSortedSet.naturalOrder(); while (metadataSegments.hasNext()) { final SegmentWithOvershadowedStatus segment = metadataSegments.next(); final DataSegment interned = DataSegmentInterner.intern(segment.getDataSegment()); final SegmentWithOvershadowedStatus segmentWithOvershadowedStatus = new SegmentWithOvershadowedStatus( interned, segment.isOvershadowed() ); builder.add(segmentWithOvershadowedStatus); } publishedSegments = builder.build(); cachePopulated.countDown(); }
Source:
protected void run() throws Exception { final int cnt = 100; final long start = System.currentTimeMillis(); for (int i = 0; i < cnt; i++) DirCache.read(db); final long end = System.currentTimeMillis(); out.println(" "); out.println(CLIText.get().averageLabel); out.println(" " + ((end - start) / cnt) + " "); out.println(CLIText.get().milliSecondsLabel); out.println("/"); out.println(CLIText.get().readLabel); }

Target:
protected void run() throws Exception { final int cnt = 100; final long start = System.currentTimeMillis(); for (int i = 0; i < cnt; i++) DirCache.read(db); final long end = System.currentTimeMillis(); out.print(" "); out.println(MessageFormat.format(CLIText.get().averageMSPerRead, (end - start) / cnt)); }
Source:
public JClass refClass(String fullyQualifiedClassName) { JClass refClass = loadedClasses.get(fullyQualifiedClassName); if (refClass == null) { if (fullyQualifiedClassName.endsWith("[]")) { return refClass(fullyQualifiedClassName.substring(0, fullyQualifiedClassName.length() - 2)).array(); } else { refClass = new TypeNameParser(fullyQualifiedClassName).parseTypeName(); loadedClasses.put(fullyQualifiedClassName, refClass); } } return refClass; }

Target:
public JClass refClass(String fullyQualifiedClassName) { int arrayCounter = 0; while (fullyQualifiedClassName.endsWith("[]")) { arrayCounter++; fullyQualifiedClassName = fullyQualifiedClassName.substring(0, fullyQualifiedClassName.length() - 2); } JClass refClass = loadedClasses.get(fullyQualifiedClassName); if (refClass == null) { refClass = codeModel.directClass(fullyQualifiedClassName); loadedClasses.put(fullyQualifiedClassName, refClass); } for (int i = 0; i < arrayCounter; i++) { refClass = refClass.array(); } return refClass; }
Source:
public void showLinkPreview(PageTitle title, int entrySource) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { DialogFragment linkPreview = app.getLinkPreviewVersion() == 0 ? LinkPreviewDialog.newInstance(title, entrySource) : LinkPreviewDialogB.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } }

Target:
public void showLinkPreview(PageTitle title, int entrySource) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { DialogFragment linkPreview = app.isLinkPreviewExperimental() ? LinkPreviewDialogB.newInstance(title, entrySource) : LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } }
Source:
public RefreshFileJob(File file, boolean derived) throws Exception { super("Refreshing " + file); this.derived = derived; this.files = new ArrayList<File>(); this.files.add(file); }

Target:
public RefreshFileJob(File file, boolean derived) throws Exception { super("Refreshing " + file); this.derived = derived; this.files = Collections.singletonList(file); }
Source:
public static String getMessageFromIntent(Intent intent) { if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) { NdefMessage[] messages; Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { messages = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { messages[i] = (NdefMessage) rawMsgs[i]; } if (messages[0] != null) { String result = ""; byte[] payload = messages[0].getRecords()[0].getPayload(); if (payload.length > 0) { int i = payloadStartContainsText(payload[0]) ? 0 : 1; for (; i < payload.length; i++) { result += (char) payload[i]; } } return result; } } } return null; }

Target:
public static String getMessageFromIntent(Intent intent) { if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { NdefMessage[] messages = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { messages[i] = (NdefMessage) rawMsgs[i]; } if (messages[0] != null) { String result = ""; byte[] payload = messages[0].getRecords()[0].getPayload(); if (payload.length > 0) { int i = payloadStartContainsText(payload[0]) ? 0 : 1; for (; i < payload.length; i++) { result += (char) payload[i]; } } return result; } } } return null; }
Source:
public void save(OutputStream os) { try (PrintStream ps = new PrintStream(os)) { save(ps); } }

Target:
public void save(OutputStream os) throws IOException { try (PrintStream ps = new PrintStream(os, false, UTF_8.name())) { save(ps); ps.flush(); } }
Source:
private ArrayList<CategoryPill.Data> getCategories(String response, CreateCategoryContext ctxt) { Object json = Configuration.defaultConfiguration().jsonProvider().parse(response); int len = JsonPath.read(json, "$._embedded.doc:forum.length()"); ArrayList<CategoryPill.Data> categories = new ArrayList<>(); for (int i = 0; i < len; i++) { String id = JsonPath.read(json, "$._embedded.doc:forum[" + i + "].id"); String name = JsonPath.read(json, "$._embedded.doc:forum[" + i + "].name"); if (!id.equals(ctxt.getSiteId())) { categories.add(new CategoryPill.Data(id, name)); } } return categories; }

Target:
private List<CategoryPill.Data> getCategories(String response, CreateCategoryContext ctxt) { Object json = Configuration.defaultConfiguration().jsonProvider().parse(response); int len = JsonPath.read(json, "$._embedded.doc:forum.length()"); List<CategoryPill.Data> categories = new ArrayList<>(); for (int i = 0; i < len; i++) { String id = JsonPath.read(json, "$._embedded.doc:forum[" + i + "].id"); String name = JsonPath.read(json, "$._embedded.doc:forum[" + i + "].name"); if (!id.equals(ctxt.getSiteId())) { categories.add(new CategoryPill.Data(id, name)); } } return categories; }
Source:
public void getStorageDomainDefaultWipeAfterDelete(AsyncQuery aQuery, StorageType storageType) { aQuery.converterCallback = new IAsyncConverter<Boolean>() { @Override public Boolean Convert(Object returnValue, AsyncQuery asyncQuery) { return (Boolean) returnValue; } }; GetStorageDomainDefaultWipeAfterDeleteParameters params = new GetStorageDomainDefaultWipeAfterDeleteParameters(storageType); Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainWipeAfterDelete, params, aQuery); }

Target:
public void getStorageDomainDefaultWipeAfterDelete(AsyncQuery aQuery, StorageType storageType) { aQuery.converterCallback = new IAsyncConverter<Boolean>() { @Override public Boolean Convert(Object returnValue, AsyncQuery asyncQuery) { return (Boolean) returnValue; } }; GetStorageDomainDefaultWipeAfterDeleteParameters params = new GetStorageDomainDefaultWipeAfterDeleteParameters(storageType); Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainDefaultWipeAfterDelete, params, aQuery); }
Source:
public String getError() { return ""; }

Target:
public String getError() { return "No lastUpdated field provided for the entry."; }
Source:
protected PopupPresenter() { this(null); }

Target:
protected PopupPresenter() { this(""); }
Source:
public InfrastructureResponse listInfrastructure() { final InfrastructureResponse response = new InfrastructureResponse(); response.setZones(dataCenterDao.listAllZones().size()); response.setPods(podDao.listAllPods(null).size()); response.setClusters(clusterDao.listAllClusters(null).size()); response.setHosts(hostDao.listByType(Host.Type.Routing).size()); response.setStoragePools(storagePoolDao.listAll().size()); response.setImageStores(imageStoreDao.listImageStores().size()); response.setSystemvms(vmInstanceDao.listByTypes(VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm).size()); response.setRouters(domainRouterDao.listByRole(VirtualRouter.Role.VIRTUAL_ROUTER).size()); response.setInternalLbs(domainRouterDao.listByRole(VirtualRouter.Role.INTERNAL_LB_VM).size()); response.setAlerts(alertDao.listAll().size()); int cpuSockets = 0; for (final Host host : hostDao.listByType(Host.Type.Routing)) { if (host.getCpuSockets() != null) { cpuSockets += host.getCpuSockets(); } } response.setCpuSockets(cpuSockets); response.setManagementServers(managementServerHostDao.listAll().size()); return response; }

Target:
public InfrastructureResponse listInfrastructure() { final InfrastructureResponse response = new InfrastructureResponse(); response.setZones(dataCenterDao.countAll()); response.setPods(podDao.countAll()); response.setClusters(clusterDao.countAll()); response.setHosts(hostDao.countAllByType(Host.Type.Routing)); response.setStoragePools(storagePoolDao.countAll()); response.setImageStores(imageStoreDao.countAllImageStores()); response.setSystemvms(vmInstanceDao.listByTypes(VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm).size()); response.setRouters(domainRouterDao.countAllByRole(VirtualRouter.Role.VIRTUAL_ROUTER)); response.setInternalLbs(domainRouterDao.countAllByRole(VirtualRouter.Role.INTERNAL_LB_VM)); response.setAlerts(alertDao.countAll()); int cpuSockets = 0; for (final Host host : hostDao.listByType(Host.Type.Routing)) { if (host.getCpuSockets() != null) { cpuSockets += host.getCpuSockets(); } } response.setCpuSockets(cpuSockets); response.setManagementServers(managementServerHostDao.listAll().size()); return response; }
Source:
public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { final SubMonitor subMonitor = SubMonitor.convert(monitor, 1); try { IProject[] projects = getBuildOrder(configuration, mode); if (projects == null) { return true; } buildProjects(projects, subMonitor.split(1)); return false; } finally { if (monitor != null) { monitor.done(); } } }

Target:
public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { try { IProject[] projects = getBuildOrder(configuration, mode); if (projects == null) { return true; } buildProjects(projects, SubMonitor.convert(monitor, 1)); return false; } finally { if (monitor != null) { monitor.done(); } } }
Source:
@Test public void maskingFreeStyleSecrets() throws Exception { String credentialsId_1 = "creds_1"; String username_1 = "s3cr3t"; String password_1 = "p4ss"; StringCredentialsImpl c_1 = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId_1, "sample1", Secret.fromString(password_1)); String credentialsId_2 = "creds_2"; String username_2 = "s3cr3t0"; String password_2 = "p4ss" + "EvenLonger"; StringCredentialsImpl c_2 = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId_2, "sample2", Secret.fromString(password_2)); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c_1); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c_2); SecretBuildWrapper bw_1 = new SecretBuildWrapper(Collections.<MultiBinding<?>>singletonList(new StringBinding("PASS_1", credentialsId_1))); SecretBuildWrapper bw_2 = new SecretBuildWrapper(Collections.<MultiBinding<?>>singletonList(new StringBinding("PASS_2", credentialsId_2))); FreeStyleProject f = r.createFreeStyleProject(); f.setConcurrentBuild(true); f.getBuildersList().add(new Shell("echo $PASS_1")); f.getBuildersList().add(new Shell("echo $PASS_2")); f.getBuildWrappersList().add(bw_1); f.getBuildWrappersList().add(bw_2); r.configRoundtrip((Item)f); FreeStyleBuild b = r.buildAndAssertSuccess(f); r.assertLogNotContains(password_1, b); r.assertLogNotContains(password_2, b); r.assertLogContains("echo ****", b); }

Target:
@Test public void maskingFreeStyleSecrets() throws Exception { String firstCredentialsId = "creds_1"; String firstPassword = "p4ss"; StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword)); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds); SecretBuildWrapper wrapper = new SecretBuildWrapper(Collections.singletonList(new StringBinding("PASS_1", firstCredentialsId))); FreeStyleProject f = r.createFreeStyleProject(); f.setConcurrentBuild(true); f.getBuildersList().add(new Shell("echo $PASS_1")); f.getBuildWrappersList().add(wrapper); r.configRoundtrip((Item)f); FreeStyleBuild b = r.buildAndAssertSuccess(f); r.assertLogNotContains(firstPassword, b); r.assertLogContains("echo ****", b); }
Source:
public String getName(ItemType itemType) { if (FMLLoader.getDist().isClient()) { final Item item = RegistryManager.ACTIVE.getRegistry(Item.class) .getValue(ResourceLocation.tryCreate(itemType.getId())); if (item == null) { return super.getName(itemType); } return I18n.format(item.getTranslationKey()); } return super.getName(itemType); }

Target:
public String getName(ItemType itemType) { if (FMLLoader.getDist().isClient()) { final Item item = RegistryManager.ACTIVE.getRegistry(Item.class) .getValue(ResourceLocation.tryCreate(itemType.getId())); if (item != null) { return I18n.format(item.getTranslationKey()); } } return super.getName(itemType); }