auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() { @Override public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { req.setAttribute("javax.servlet.error.exception",e); try { WebApp.get(j.servletContext).getSomeStapler() .invoke(req,rsp, Jenkins.getInstance(), "/oops"); } catch (ServletException x) { if (!Stapler.isSocketException(x)) { throw x; } } catch (IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } } }); Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); }

Target:
public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() { @Override public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { req.setAttribute("javax.servlet.error.exception",e); try { WebApp.get(j.servletContext).getSomeStapler() .invoke(req,rsp, Jenkins.getInstance(), "/oops"); } catch (ServletException x) { if (!Stapler.isSocketException(x)) { throw x; } } catch (IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } } }); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); DefaultUncaughtExceptionHandler.LOGGER.log(Level.INFO, "Succesfully installed a global UncaughtExceptionHandler."); } catch (SecurityException ex) { DefaultUncaughtExceptionHandler.LOGGER.log(Level.SEVERE, "Failed to set the default UncaughtExceptionHandler. " + "If any threads die due to unhandled coding errors then there will be no logging of this information. " + "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins. " + "It is highly recomended that you consult the documentation that comes with you servlet container on how to allow the " + "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex); } }
Source:
public void execute(Context context) throws SQLException { context.execute(new CreateTableBuilder(getDialect(), TABLE_NAME) .addPkColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("uuid") .setIsNullable(false) .setLimit(40) .build()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName(SNAPSHOT_UUID) .setIsNullable(false) .setLimit(40) .build()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("kee") .setIsNullable(false) .setLimit(512) .build()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("text_value") .setIsNullable(true) .setLimit(4000) .build()) .addColumn(ClobColumnDef.newClobColumnDefBuilder() .setColumnName("clob_value") .setIsNullable(true) .build()) .addColumn(BooleanColumnDef.newBooleanColumnDefBuilder() .setColumnName("is_empty") .setIsNullable(false) .build()) .addColumn(BigIntegerColumnDef.newBigIntegerColumnDefBuilder() .setColumnName("created_at") .setIsNullable(false) .build()) .build() ); context.execute(new CreateIndexBuilder(getDialect()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName(SNAPSHOT_UUID) .setIsNullable(false) .setLimit(40) .build()) .setUnique(false) .setTable(TABLE_NAME) .setName(SNAPSHOT_UUID) .build() ); }

Target:
public void execute(Context context) throws SQLException { context.execute(new CreateTableBuilder(getDialect(), TABLE_NAME) .addPkColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("uuid") .setIsNullable(false) .setLimit(VarcharColumnDef.UUID_SIZE) .build()) .addColumn(SNAPSHOT_UUID_COLUMN) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("kee") .setIsNullable(false) .setLimit(512) .build()) .addColumn(VarcharColumnDef.newVarcharColumnDefBuilder() .setColumnName("text_value") .setIsNullable(true) .setLimit(VarcharColumnDef.MAX_SIZE) .build()) .addColumn(ClobColumnDef.newClobColumnDefBuilder() .setColumnName("clob_value") .setIsNullable(true) .build()) .addColumn(BooleanColumnDef.newBooleanColumnDefBuilder() .setColumnName("is_empty") .setIsNullable(false) .build()) .addColumn(BigIntegerColumnDef.newBigIntegerColumnDefBuilder() .setColumnName("created_at") .setIsNullable(false) .build()) .build() ); context.execute(new CreateIndexBuilder(getDialect()) .addColumn(SNAPSHOT_UUID_COLUMN) .setUnique(false) .setTable(TABLE_NAME) .setName("ix_snapshot_uuid") .build() ); }
Source:
public void execute() { if (!isProperlyConfigured()) { logger.warn("Binding not properly configured, exiting"); return; } if (!this.satelModule.isInitialized()) { logger.debug("Module not initialized yet, skipping refresh"); return; } logger.trace("Sending 'get new states' command"); this.satelModule .sendCommand(NewStatesCommand.buildMessage(this.satelModule.getIntegraType() == IntegraType.I256_PLUS)); }

Target:
public void execute() { if (!this.satelModule.isInitialized()) { logger.debug("Module not initialized yet, skipping refresh"); return; } logger.trace("Sending 'get new states' command"); if (this.newStatesCommand == null) { this.newStatesCommand = NewStatesCommand .buildMessage(this.satelModule.getIntegraType() == IntegraType.I256_PLUS); } this.satelModule.sendCommand(this.newStatesCommand); }
Source:
public Map<String, Object> getProducerConfigs(final String clientId) { final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames()); checkIfUnexpectedUserSpecifiedConsumerConfig(clientProvidedProps, NON_CONFIGURABLE_PRODUCER_EOS_CONFIGS); final Map<String, Object> props = new HashMap<>(eosEnabled ? PRODUCER_EOS_OVERRIDES : PRODUCER_DEFAULT_OVERRIDES); if (StreamThread.eosBetaEnabled(this) && !StreamThread.eosUpgradeModeEnabled(this)) { props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, getString(StreamsConfig.APPLICATION_ID_CONFIG) + "-" + UUID.randomUUID()); } props.putAll(getClientCustomProps()); props.putAll(clientProvidedProps); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, originals().get(BOOTSTRAP_SERVERS_CONFIG)); props.put(CommonClientConfigs.CLIENT_ID_CONFIG, clientId); return props; }

Target:
public Map<String, Object> getProducerConfigs(final String clientId) { final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames()); checkIfUnexpectedUserSpecifiedConsumerConfig(clientProvidedProps, NON_CONFIGURABLE_PRODUCER_EOS_CONFIGS); final Map<String, Object> props = new HashMap<>(eosEnabled ? PRODUCER_EOS_OVERRIDES : PRODUCER_DEFAULT_OVERRIDES); props.putAll(getClientCustomProps()); props.putAll(clientProvidedProps); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, originals().get(BOOTSTRAP_SERVERS_CONFIG)); props.put(CommonClientConfigs.CLIENT_ID_CONFIG, clientId); return props; }
Source:
private boolean isInteresting(ThreadInfo thread) { for (StackTraceElement element : thread.getStackTrace()) { String className = element.getClassName(); if (!className.startsWith("java.") && !className.startsWith("sun.") && !NON_INTERESTING_THREAD_FILTER.matchesFilter(element)) { return true; } } return false; }

Target:
private boolean isInteresting(ThreadInfo thread) { for (StackTraceElement element : thread.getStackTrace()) { if (!NON_INTERESTING_THREAD_FILTER.matchesFilter(element)) { return true; } } return false; }
Source:
public String getBioentityInformation(@PathVariable String geneId) { Species species = speciesInferrer.inferSpeciesForGeneQuery(SemanticQuery.create(geneId)); Map<BioentityPropertyName, Set<String>> propertyValues = bioEntityPropertyDao.fetchGenePageProperties(geneId); String geneName = bioEntityPropertyDao.fetchPropertyValuesForGeneId(geneId, SYMBOL).stream() .collect(Collectors.joining("/")); Map<String, Object> model = bioEntityCardModelFactory.modelAttributes( geneId, species, BIOENTITY_PROPERTY_NAMES, geneName, propertyValues); String bioentityProperties = model.get("bioentityProperties").toString(); bioentityProperties = bioentityProperties.substring(0, bioentityProperties.length() - 1); JsonArray values = new JsonArray(); JsonObject jsonObject = new JsonObject(); ImmutableMap.of("text", geneId, "url", "<LINK_0>"+geneId,"relevance","0").forEach( (key, value) -> { jsonObject.addProperty(key,value); } ); values.add(jsonObject); JsonObject o = new JsonObject(); o.addProperty("type", "expression_atlas"); o.addProperty("name", "ExpressionAtlas"); o.add("values", values); String result = bioentityProperties + "," + GSON.toJson(o) + "]"; return result; }

Target:
public String getBioentityInformation(@PathVariable String geneId) { Species species = speciesInferrer.inferSpeciesForGeneQuery(SemanticQuery.create(geneId)); Map<BioentityPropertyName, Set<String>> propertyValues = bioEntityPropertyDao.fetchGenePageProperties(geneId); String geneName = bioEntityPropertyDao.fetchPropertyValuesForGeneId(geneId, SYMBOL).stream() .collect(Collectors.joining("/")); Map<String, Object> model = bioEntityCardModelFactory.modelAttributes( geneId, species, BIOENTITY_PROPERTY_NAMES, geneName, propertyValues); JsonArray jsonArray = GSON.fromJson(model.get("bioentityProperties").toString(), JsonArray.class); JsonArray values = new JsonArray(); JsonObject jsonObject = new JsonObject(); ImmutableMap.of("text", geneId, "url", "<LINK_0>"+geneId,"relevance","0").forEach( (key, value) -> { jsonObject.addProperty(key,value); } ); values.add(jsonObject); JsonObject o = new JsonObject(); o.addProperty("type", "expression_atlas"); o.addProperty("name", "ExpressionAtlas"); o.add("values", values); jsonArray.add(o); return GSON.toJson(jsonArray); }
Source:
public void update(Username currentUser, String md5, ElasticProfile newProfile, LocalizedOperationResult result) { ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(goConfigService, newProfile, elasticAgentExtension, currentUser, result, hashingService, md5); validatePluginProperties(command, newProfile); update(currentUser, newProfile, result, command); }

Target:
public void update(Username currentUser, String md5, ElasticProfile newProfile, LocalizedOperationResult result) { ElasticAgentProfileUpdateCommand command = new ElasticAgentProfileUpdateCommand(goConfigService, newProfile, elasticAgentExtension, currentUser, result, hashingService, md5); update(currentUser, newProfile, result, command); }
Source:
public void testDeleteCount_nonPK() throws Exception { String schemaName = generateUniqueName(); String dataTableName = "TBL_" + generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName = "IND_" + generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute("CREATE TABLE " + dataTableFullName + " (ID INTEGER NOT NULL PRIMARY KEY, VAL1 INTEGER, VAL2 INTEGER) " + this.tableDDLOptions); conn.createStatement().execute(String.format( "CREATE INDEX %s ON %s (VAL1) INCLUDE (VAL2)", indexTableName, dataTableFullName)); PreparedStatement dataPreparedStatement = conn.prepareStatement("UPSERT INTO " + dataTableFullName + " VALUES(?,?,?)"); for (int i = 1; i <= 10; i++) { dataPreparedStatement.setInt(1, i); dataPreparedStatement.setInt(2, i + 1); dataPreparedStatement.setInt(3, i * 2); dataPreparedStatement.execute(); } conn.commit(); PreparedStatement deleteStmt = conn.prepareStatement("DELETE FROM " + dataTableFullName + " WHERE VAL1 > 6"); assertEquals(5, deleteStmt.executeUpdate()); conn.commit(); } }

Target:
public void testDeleteCount_nonPK() throws Exception { String schemaName = generateUniqueName(); String dataTableName = "TBL_" + generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName1 = "IND_" + generateUniqueName(); String indexTableName2 = "IND_" + generateUniqueName(); try (Connection conn = DriverManager.getConnection(getUrl())) { setupForDeleteCount(conn, schemaName, dataTableName, indexTableName1, indexTableName2); PreparedStatement deleteStmt = conn.prepareStatement("DELETE FROM " + dataTableFullName + " WHERE VAL1 > 6"); assertEquals(5, deleteStmt.executeUpdate()); conn.commit(); } }
Source:
public void edit(final VolumeRebalanceStatusModel object) { driver.edit(object); rebalanceHostsTable.asEditor().edit(object.getRebalanceSessions()); object.getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { PropertyChangedEventArgs e = (PropertyChangedEventArgs) args; if (e.PropertyName.equals("IS_STATUS_APPLICABLE")) { status.setText(constants.rebalanceComplete()); status.setVisible(true); } else if (e.PropertyName.equals("STOP_TIME_UPDATED")) { stopTimePanel.setVisible(object.isStopTimeVisible()); status.setVisible(false); } } }); }

Target:
public void edit(final VolumeRebalanceStatusModel object) { driver.edit(object); rebalanceHostsTable.asEditor().edit(object.getRebalanceSessions()); object.getPropertyChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { PropertyChangedEventArgs e = (PropertyChangedEventArgs) args; if (e.PropertyName.equals("STATUS_UPDATED")) { status.setText(constants.rebalanceComplete()); status.setVisible(object.isStatusAvailable()); } else if (e.PropertyName.equals("STOP_TIME_UPDATED")) { stopTimePanel.setVisible(object.isStopTimeVisible()); status.setVisible(object.isStatusAvailable()); } } }); }
Source:
public static List<ObjectModel> loadJsonStream(InputStream input) { try { Reader reader = new InputStreamReader(input); JsonValue json = Json.parse(reader); List<ObjectModel> models = new ObjectModelSerDes().deserialize(json.asArray()); return models; } catch (IOException e) { LOG.error("Cannot load json model from inputstream"); } return null; }

Target:
public static List<ObjectModel> loadJsonStream(InputStream input) { try { Reader reader = new InputStreamReader(input); JsonValue json = Json.parse(reader); return new ObjectModelSerDes().deserialize(json.asArray()); } catch (IOException e) { LOG.error("Cannot load json model from inputstream"); } return null; }
Source:
static protected TextView getTxtvFFFromActivity(MediaplayerActivity activity) { return activity.txtvFF; }

Target:
protected static TextView getTxtvFFFromActivity(MediaplayerActivity activity) { return activity.txtvFF; }
Source:
public static List<GraphQLDirective> enforceAdd(List<GraphQLDirective> targetList, GraphQLDirective newDirective) { assertNotNull(targetList, () -> "directive list can't be null"); assertNotNull(newDirective, () -> "directive can't be null"); Map<String, List<GraphQLDirective>> map = allDirectivesByName(targetList); assertNonRepeatable(newDirective, map); targetList.add(newDirective); return targetList; }

Target:
public static List<GraphQLDirective> enforceAdd(List<GraphQLDirective> targetList, GraphQLDirective newDirective) { assertNotNull(targetList, () -> "directive list can't be null"); assertNotNull(newDirective, () -> "directive can't be null"); if (newDirective.isNonRepeatable()) { Map<String, ImmutableList<GraphQLDirective>> map = allDirectivesByName(targetList); assertNonRepeatable(newDirective, map); } targetList.add(newDirective); return targetList; }
Source:
public void setTestClass(ITestClass tc) { if (tc == null) { throw new IllegalArgumentException("test class cannot be null"); } m_testClass = tc; }

Target:
public void setTestClass(ITestClass tc) { if (tc == null) { throw new IllegalArgumentException("test class cannot be null"); } boolean assignable = m_method.getDeclaringClass().isAssignableFrom(tc.getRealClass()); if (!assignable) { throw new IllegalArgumentException( "mismatch in classes between " + tc.getName() + " and " + m_method.getDeclaringClass().getName()); } m_testClass = tc; }
Source:
public void test_getContainerByFolder_cache() throws DotDataException, DotSecurityException { final User user = APILocator.systemUser(); final Host host = APILocator.getHostAPI().findDefaultHost(user, false); final Folder folder = APILocator.getFolderAPI().findFolderByPath (Constants.CONTAINER_FOLDER_PATH + "/large-column", host, user, false); final Container container1 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); final Container container2 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); Assert.assertTrue(container1 == container2); CacheLocator.getContainerCache().remove(container1); final Container container3 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); Assert.assertTrue(container3 != container2); }

Target:
public void test_getContainerByFolder_cache() throws DotDataException, DotSecurityException, IOException { final String containerPath = Constants.CONTAINER_FOLDER_PATH + "/test-container" + System.currentTimeMillis(); this.createTestFileContainer(containerPath, APILocator.getHostAPI() .findDefaultHost(APILocator.systemUser(), false), "$dotJSON.put(\"title\", \"Test Container\""+ System.currentTimeMillis() +")\n" + "$dotJSON.put(\"description\", \"Test container\")\n" + "$dotJSON.put(\"max_contentlets\", 25)\n"); final User user = APILocator.systemUser(); final Host host = APILocator.getHostAPI().findDefaultHost(user, false); final Folder folder = APILocator.getFolderAPI().findFolderByPath (containerPath, host, user, false); final Container container1 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); final Container container2 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); Assert.assertTrue(container1 == container2); CacheLocator.getContainerCache().remove(container1); final Container container3 = APILocator.getContainerAPI().getContainerByFolder(folder, host, user, false); Assert.assertTrue(container3 != container2); }
Source:
public void createNewWikiLangTC001(String lang) { WikiBasePageObject base = new WikiBasePageObject(); CreateNewWikiPageObjectStep1 cnw1 = base.openSpecialCreateNewWikiPage(wikiCorporateURL); cnw1.selectLanguage(lang); String expectedDomainSufix = "en".equals(lang) ? "" : String.format("%s", lang);; assertEquals(cnw1.getDomainSufix(), "fandom.com/" + expectedDomainSufix); String wikiName = cnw1.getWikiName(); cnw1.typeInWikiName(wikiName); cnw1.verifyNextButtonEnabled(); CreateNewWikiPageObjectStep2 cnw2 = cnw1.submit(); cnw2.selectCategory(CreateWikiMessages.WIKI_CATEGORY_ID); CreateNewWikiPageObjectStep3 cnw3 = cnw2.submit(); cnw3.selectThemeByName(CreateWikiMessages.WIKI_THEME); cnw3.logWikiTaskId(); ArticlePageObject article = cnw3.submit(); article.verifyWikiTitleOnCongratualtionsLightBox(wikiName); article.closeNewWikiCongratulationsLightBox(); article.verifyWikiTitleHeader(wikiName); new WikiFactory().setIsTestWiki(article.getWikiID(), true); article.verifyUserLoggedIn(User.USER_CNW.getUserName()); }

Target:
public void createNewWikiLangTC001(String lang) { WikiBasePageObject base = new WikiBasePageObject(); CreateNewWikiPageObjectStep1 cnw1 = base.openSpecialCreateNewWikiPage(wikiCorporateURL); cnw1.selectLanguage(lang); String expectedDomainSufix; if (lang.equals("en")) { expectedDomainSufix = String.format(""); } else { expectedDomainSufix = String.format("%s", lang); } assertEquals(cnw1.getDomainSufix(), "fandom.com/" + expectedDomainSufix); String wikiName = cnw1.getWikiName(); cnw1.typeInWikiName(wikiName); cnw1.verifyNextButtonEnabled(); CreateNewWikiPageObjectStep2 cnw2 = cnw1.submit(); cnw2.selectCategory(CreateWikiMessages.WIKI_CATEGORY_ID); CreateNewWikiPageObjectStep3 cnw3 = cnw2.submit(); cnw3.selectThemeByName(CreateWikiMessages.WIKI_THEME); cnw3.logWikiTaskId(); ArticlePageObject article = cnw3.submit(); article.verifyWikiTitleOnCongratualtionsLightBox(wikiName); article.closeNewWikiCongratulationsLightBox(); article.verifyWikiTitleHeader(wikiName); new WikiFactory().setIsTestWiki(article.getWikiID(), true); article.verifyUserLoggedIn(User.USER_CNW.getUserName()); }
Source:
private void cleanUpActivity(final ArrayList<TimeData> activityData, final boolean isIndoorTour) { Collections.sort(activityData, new Comparator<TimeData>() { @Override public int compare(final TimeData firstTimeData, final TimeData secondTimeData) { return firstTimeData.absoluteTime > secondTimeData.absoluteTime ? 1 : (firstTimeData.absoluteTime < secondTimeData.absoluteTime) ? -1 : 0; } }); final Iterator<TimeData> sampleListIterator = activityData.iterator(); long previousAbsoluteTime = 0; while (sampleListIterator.hasNext()) { final TimeData currentTimeData = sampleListIterator.next(); if (currentTimeData.marker == 0 && (!isIndoorTour && currentTimeData.longitude == Double.MIN_VALUE && currentTimeData.latitude == Double.MIN_VALUE) || (isIndoorTour && currentTimeData.absoluteAltitude == Float.MIN_VALUE) || currentTimeData.absoluteTime == previousAbsoluteTime) { sampleListIterator.remove(); } else { previousAbsoluteTime = currentTimeData.absoluteTime; } } if (_lapCounter != 0) { final TimeData lastTimeData = activityData.get(activityData.size() - 1); lastTimeData.marker = 1; lastTimeData.markerLabel = Integer.toString(++_lapCounter); } }

Target:
private void cleanUpActivity(final ArrayList<TimeData> activityData, final boolean isIndoorTour) { Collections.sort(activityData, new Comparator<TimeData>() { @Override public int compare(final TimeData firstTimeData, final TimeData secondTimeData) { return firstTimeData.absoluteTime > secondTimeData.absoluteTime ? 1 : (firstTimeData.absoluteTime < secondTimeData.absoluteTime) ? -1 : 0; } }); final Iterator<TimeData> sampleListIterator = activityData.iterator(); long previousAbsoluteTime = 0; while (sampleListIterator.hasNext()) { final TimeData currentTimeData = sampleListIterator.next(); if (currentTimeData.marker == 0 && (!isIndoorTour && currentTimeData.longitude == Double.MIN_VALUE && currentTimeData.latitude == Double.MIN_VALUE) || (isIndoorTour && currentTimeData.absoluteAltitude == Float.MIN_VALUE) || currentTimeData.absoluteTime == previousAbsoluteTime) { sampleListIterator.remove(); } else { previousAbsoluteTime = currentTimeData.absoluteTime; } } if (_numLaps != 0) { final TimeData lastTimeData = activityData.get(activityData.size() - 1); lastTimeData.marker = 1; lastTimeData.markerLabel = Integer.toString(++_numLaps); } }
Source:
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { String name = JcaBootstrapContextDefinition.BootstrapCtxParameters.NAME.getAttribute().resolveModelAttribute(context, model).asString(); String workmanager = JcaBootstrapContextDefinition.BootstrapCtxParameters.WORKMANAGER.getAttribute().resolveModelAttribute(context, model).asString(); boolean usingDefaultWm = false; CloneableBootstrapContext ctx; if (DEFAULT_NAME.equals( workmanager)) { usingDefaultWm = true; ctx = new NamedBootstrapContext(name); } else { ctx = new NamedBootstrapContext(name,workmanager); } ServiceTarget serviceTarget = context.getServiceTarget(); final BootStrapContextService bootCtxService = new BootStrapContextService(ctx, name, usingDefaultWm); serviceTarget .addService(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append(name), bootCtxService) .addDependency(ServiceBuilder.DependencyType.REQUIRED, ConnectorServices.WORKMANAGER_SERVICE.append(workmanager), WorkManager.class, bootCtxService.getWorkManagerValueInjector()) .addDependency(TxnServices.JBOSS_TXN_XA_TERMINATOR, JBossXATerminator.class, bootCtxService.getXaTerminatorInjector()) .addDependency(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER, com.arjuna.ats.jbossatx.jta.TransactionManagerService.class, bootCtxService.getTxManagerInjector()) .addDependency(ConnectorServices.CONNECTOR_CONFIG_SERVICE, JcaSubsystemConfiguration.class, bootCtxService.getJcaConfigInjector()) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }

Target:
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { String name = JcaBootstrapContextDefinition.BootstrapCtxParameters.NAME.getAttribute().resolveModelAttribute(context, model).asString(); String workmanager = JcaBootstrapContextDefinition.BootstrapCtxParameters.WORKMANAGER.getAttribute().resolveModelAttribute(context, model).asString(); boolean usingDefaultWm = false; if (DEFAULT_NAME.equals( workmanager)) { usingDefaultWm = true; } ServiceTarget serviceTarget = context.getServiceTarget(); CloneableBootstrapContext ctx = new NamedBootstrapContext(name); final BootStrapContextService bootCtxService = new BootStrapContextService(ctx, name, usingDefaultWm); serviceTarget .addService(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append(name), bootCtxService) .addDependency(ServiceBuilder.DependencyType.REQUIRED, ConnectorServices.WORKMANAGER_SERVICE.append(workmanager), WorkManager.class, bootCtxService.getWorkManagerValueInjector()) .addDependency(TxnServices.JBOSS_TXN_XA_TERMINATOR, JBossXATerminator.class, bootCtxService.getXaTerminatorInjector()) .addDependency(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER, com.arjuna.ats.jbossatx.jta.TransactionManagerService.class, bootCtxService.getTxManagerInjector()) .addDependency(ConnectorServices.CONNECTOR_CONFIG_SERVICE, JcaSubsystemConfiguration.class, bootCtxService.getJcaConfigInjector()) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); }
Source:
public void stop() { INSTANCE = null; }

Target:
public void stop() { instance = null; }
Source:
private static void ChaosServiceStart(Configuration conf, ChaosServiceName serviceName) { switch (serviceName) { case chaosagent: ChaosAgent.stopChaosAgent.set(false); try { Thread t = new Thread(new ChaosAgent(conf, ChaosUtils.getZKQuorum(conf), ChaosUtils.getHostName())); t.start(); t.join(); } catch (InterruptedException | UnknownHostException e) { LOG.error("Failed while executing next task execution of ChaosAgent on : " + serviceName + " : " + e); } break; default: LOG.error("Service Name not known : " + serviceName.toString()); } }

Target:
private static void ChaosServiceStart(Configuration conf, ChaosServiceName serviceName) { switch (serviceName) { case CHAOSAGENT: ChaosAgent.stopChaosAgent.set(false); try { Thread t = new Thread(new ChaosAgent(conf, ChaosUtils.getZKQuorum(conf), ChaosUtils.getHostName())); t.start(); t.join(); } catch (InterruptedException | UnknownHostException e) { LOG.error("Failed while executing next task execution of ChaosAgent on : {}", serviceName, e); } break; default: LOG.error("Service Name not known : " + serviceName.toString()); } }
Source:
public Entity<TreeReference> getEntity(TreeReference data) { EvaluationContext nodeContext = new EvaluationContext(ec, data); if (inDebugMode) { nodeContext.setDebugModeOn(reporter); } detail.populateEvaluationContextVariables(nodeContext); int length = detail.getHeaderForms().length; String extraKey = loadCalloutDataMapKey(nodeContext); Object[] fieldData = new Object[length]; String[] sortData = new String[length]; boolean[] relevancyData = new boolean[length]; int count = 0; for (DetailField f : detail.getFields()) { try { fieldData[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); if (sortText == null) { sortData[count] = null; } else { sortData[count] = sortText.evaluate(nodeContext); } relevancyData[count] = f.isRelevant(nodeContext); } catch (XPathSyntaxException | XPathException e) { XPathException xe = new XPathException(e); throw xe; } count++; } return new Entity<>(fieldData, sortData, relevancyData, data, extraKey, detail.evaluateFocusFunction(nodeContext)); }

Target:
public Entity<TreeReference> getEntity(TreeReference data) { EvaluationContext nodeContext = new EvaluationContext(ec, data); if (inDebugMode) { nodeContext.setDebugModeOn(reporter); } detail.populateEvaluationContextVariables(nodeContext); int length = detail.getHeaderForms().length; String extraKey = loadCalloutDataMapKey(nodeContext); Object[] fieldData = new Object[length]; String[] sortData = new String[length]; boolean[] relevancyData = new boolean[length]; int count = 0; for (DetailField f : detail.getFields()) { try { fieldData[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); if (sortText == null) { sortData[count] = null; } else { sortData[count] = sortText.evaluate(nodeContext); } relevancyData[count] = f.isRelevant(nodeContext); } catch (XPathSyntaxException e) { XPathException xe = new XPathException(e); throw xe; } count++; } return new Entity<>(fieldData, sortData, relevancyData, data, extraKey, detail.evaluateFocusFunction(nodeContext)); }
Source:
public int validateOkToDelete(DeleteConflictList theDeleteConflicts, ResourceTable theEntity, boolean theForValidate) { DeleteConflictList newConflicts = new DeleteConflictList(); boolean tryAgain = findAndHandleConflicts(newConflicts, theEntity, theForValidate, MIN_QUERY_RESULT_COUNT); int retryCount = 0; while (tryAgain && retryCount < MAX_RETRY_ATTEMPTS) { newConflicts = new DeleteConflictList(); tryAgain = findAndHandleConflicts(newConflicts, theEntity, theForValidate, MAX_RETRY_COUNT); ++retryCount; } theDeleteConflicts.addAll(newConflicts); return retryCount; }

Target:
public int validateOkToDelete(DeleteConflictList theDeleteConflicts, ResourceTable theEntity, boolean theForValidate) { DeleteConflictList newConflicts = new DeleteConflictList(); boolean tryAgain = findAndHandleConflicts(newConflicts, theEntity, theForValidate, FIRST_QUERY_RESULT_COUNT); int retryCount = 0; while (tryAgain && retryCount < MAX_RETRY_ATTEMPTS) { newConflicts = new DeleteConflictList(); tryAgain = findAndHandleConflicts(newConflicts, theEntity, theForValidate, RETRY_QUERY_RESULT_COUNT); ++retryCount; } theDeleteConflicts.addAll(newConflicts); return retryCount; }
Source:
public void testTextQueryLimitedConcurrent() throws Exception { final IgniteEx ignite = grid(0); final String clause = "1*"; Set<Integer> exp = populateCache(ignite, false, MAX_ITEM_COUNT, (IgnitePredicate<Integer>)x -> String.valueOf(x).startsWith("1")); ExecutorService executor = Executors.newFixedThreadPool(N_THREADS); IntStream.range(0, N_THREADS).forEach((i) -> executor.submit(textQueryTask(ignite, clause, exp))); executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); clearCache(ignite); }

Target:
public void testTextQueryLimitedConcurrent() throws Exception { final IgniteEx ignite = grid(0); final String clause = "1*"; Set<Integer> exp = populateCache(ignite, false, MAX_ITEM_COUNT, (IgnitePredicate<Integer>)x -> String.valueOf(x).startsWith("1")); GridTestUtils.runMultiThreaded(textQueryTask(ignite, clause, exp), N_THREADS, "text-query-test"); clearCache(ignite); }
Source:
public static void main(String[] args) { Blade.me() .get("/json", (request, response) -> response.json(new Message())) .get("/db", (request, response) -> { final Random random = ThreadLocalRandom.current(); response.json(new World().find(random.nextInt(DB_ROWS) + 1)); }) .get("/queries", (request, response) -> { int queries = getQueries(request.queryInt("queries")); final World[] worlds = new World[queries]; final Random random = ThreadLocalRandom.current(); for (int i = 0; i < queries; i++) { worlds[i] = new World().find(random.nextInt(DB_ROWS) + 1); } response.json(worlds); }) .get("/plaintext", (request, response) -> response.body(Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_HELLO_TEXT)).duplicate())) .listen(8080).start(Application.class, args); }

Target:
public static void main(String[] args) { Blade.me() .get("/json", (request, response) -> response.json(new Message())) .get("/db", (request, response) -> { final Random random = ThreadLocalRandom.current(); response.json(new World().find(random.nextInt(DB_ROWS) + 1)); }) .get("/queries", (request, response) -> { int queries = getQueries(request.queryInt("queries")); final World[] worlds = new World[queries]; final Random random = ThreadLocalRandom.current(); for (int i = 0; i < queries; i++) { worlds[i] = new World().find(random.nextInt(DB_ROWS) + 1); } response.json(worlds); }) .get("/plaintext", (request, response) -> response.body(Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_HELLO_TEXT)).duplicate())) .start(Application.class, args); }
Source:
public int[] write(ClassWriter cw, MethodVisitor mv, Method method, Parameter param, int local) { mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, "org/spongepowered/api/event/cause/CauseTracked"); mv.visitMethodInsn(INVOKEINTERFACE, "org/spongepowered/api/event/cause/CauseTracked", "getCause", "()Lorg/spongepowered/api/event/cause/Cause;", true); Class<?> targetType = param.getType(); insertCauseCall(mv, param, targetType); int paramLocal = local++; mv.visitVarInsn(ASTORE, paramLocal); insertCheck(mv, param, targetType, paramLocal); insertTransform(mv, param, targetType, paramLocal); return new int[] {local, paramLocal}; }

Target:
public Tuple<Integer, Integer> write(ClassWriter cw, MethodVisitor mv, Method method, Parameter param, int local) { mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(CauseTracked.class)); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(CauseTracked.class), "getCause", "()" + Type.getDescriptor(Cause.class), true); Class<?> targetType = param.getType(); insertCauseCall(mv, param, targetType); int paramLocal = local++; mv.visitVarInsn(ASTORE, paramLocal); insertCheck(mv, param, targetType, paramLocal); insertTransform(mv, param, targetType, paramLocal); return new Tuple<>(local, paramLocal); }
Source:
public void testColourMapEmpty() throws Exception { String yaml = "raster: \n" + " color-map:\n" + " type: values\n" + " entries:\n" + " - "+tuple("#ff0000", "1.0", "0", "start")+"\n" + " - "+tuple("#00ff00", "", "500", "middle")+"\n" + " - "+tuple("#0000ff", null, "1000", "end")+"\n" + ""; StyledLayerDescriptor sld = Ysld.parse(yaml); FeatureTypeStyle fs = SLD.defaultStyle(sld).featureTypeStyles().get(0); RasterSymbolizer symb = (RasterSymbolizer) fs.rules().get(0).symbolizers().get(0); ColorMap map = (ColorMap) symb.getColorMap(); System.out.println(map.getColorMapEntry(0).getColor().evaluate(null)); String colour1 = (String) map.getColorMapEntry(0).getColor().evaluate(null); String colour2 = (String) map.getColorMapEntry(1).getColor().evaluate(null); String colour3 = (String) map.getColorMapEntry(2).getColor().evaluate(null); assertThat(colour1, is("#FF0000")); assertThat(colour2, is("#00FF00")); assertThat(colour3, is("#0000FF")); }

Target:
public void testColourMapEmpty() throws Exception { String yaml = "raster: \n" + " color-map:\n" + " type: values\n" + " entries:\n" + " - "+tuple("#ff0000", "1.0", "0", "start")+"\n" + " - "+tuple("#00ff00", "", "500", "middle")+"\n" + " - "+tuple("#0000ff", null, "1000", "end")+"\n" + ""; StyledLayerDescriptor sld = Ysld.parse(yaml); FeatureTypeStyle fs = SLD.defaultStyle(sld).featureTypeStyles().get(0); RasterSymbolizer symb = (RasterSymbolizer) fs.rules().get(0).symbolizers().get(0); ColorMap map = (ColorMap) symb.getColorMap(); System.out.println(map.getColorMapEntry(0).getColor().evaluate(null)); Color colour1 = (Color) map.getColorMapEntry(0).getColor().evaluate(null); Color colour2 = (Color) map.getColorMapEntry(1).getColor().evaluate(null); Color colour3 = (Color) map.getColorMapEntry(2).getColor().evaluate(null); assertThat(colour1, is(Color.RED)); assertThat(colour2, is(Color.GREEN)); assertThat(colour3, is(Color.BLUE)); }
Source:
FunctionSymbolImpl(FunctionDef functionDef, @Nullable String fullyQualifiedName) { super(functionDef.name().name(), fullyQualifiedName); setKind(Kind.FUNCTION); isInstanceMethod = isInstanceMethod(functionDef); hasDecorators = !functionDef.decorators().isEmpty(); ParameterList parameters = functionDef.parameters(); if (parameters != null) { createParameterNames(parameters.all()); } }

Target:
FunctionSymbolImpl(FunctionDef functionDef, @Nullable String fullyQualifiedName) { super(functionDef.name().name(), fullyQualifiedName); setKind(Kind.FUNCTION); isInstanceMethod = isInstanceMethod(functionDef); hasDecorators = !functionDef.decorators().isEmpty(); ParameterList parametersList = functionDef.parameters(); if (parametersList != null) { createParameterNames(parametersList.all()); } }
Source:
public SubSequenceStrategyBuilder subSequence(InputTypeStrategy inputTypeStrategy) { Optional<Integer> maxCount = inputTypeStrategy.getArgumentCount().getMaxCount(); Optional<Integer> minCount = inputTypeStrategy.getArgumentCount().getMinCount(); if (!maxCount.isPresent() || !minCount.isPresent() || !maxCount.get().equals(minCount.get())) { throw new IllegalArgumentException("Both the minimum and maximum number of expected arguments must" + " be defined and equal to each other."); } argumentsSplits.add(new ArgumentsSplit(currentPos, currentPos + maxCount.get(), inputTypeStrategy)); currentPos += maxCount.get(); return this; }

Target:
public SubSequenceStrategyBuilder subSequence(InputTypeStrategy inputTypeStrategy) { Preconditions.checkArgument(inputTypeStrategy.getArgumentCount() instanceof ConstantArgumentCount); Optional<Integer> maxCount = inputTypeStrategy.getArgumentCount().getMaxCount(); Optional<Integer> minCount = inputTypeStrategy.getArgumentCount().getMinCount(); if (!maxCount.isPresent() || !minCount.isPresent() || !maxCount.get().equals(minCount.get())) { throw new IllegalArgumentException("Both the minimum and maximum number of expected arguments must" + " be defined and equal to each other."); } argumentsSplits.add(new ArgumentsSplit(currentPos, currentPos + maxCount.get(), inputTypeStrategy)); currentPos += maxCount.get(); return this; }
Source:
public void create(final EventTypeBase eventType) throws TopicCreationException, InternalNakadiException, NoSuchPartitionStrategyException, DuplicatedEventTypeNameException, InvalidEventTypeException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot create event type: write operations on DB " + "are blocked by feature flag."); } setDefaultEventTypeOptions(eventType); validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); authorizationValidator.validateAuthorization(eventType.getAuthorization()); eventTypeRepository.saveEventType(eventType); try { timelineService.createDefaultTimeline(eventType.getName(), partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); } catch (final Exception e) { try { eventTypeRepository.removeEventType(eventType.getName()); } catch (final NoSuchEventTypeException e1) { LOG.error("Error creating event type {}", eventType, e1); } throw e; } nakadiKpiPublisher.publish(etLogEventType, () -> new JSONObject() .put("event_type", eventType.getName()) .put("status", "created") .put("category", eventType.getCategory()) .put("authz", identifyAuthzState(eventType)) .put("compatibility_mode", eventType.getCompatibilityMode())); }

Target:
public void create(final EventTypeBase eventType) throws TopicCreationException, InternalNakadiException, NoSuchPartitionStrategyException, DuplicatedEventTypeNameException, InvalidEventTypeException, DbWriteOperationsBlockedException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot create event type: write operations on DB " + "are blocked by feature flag."); } setDefaultEventTypeOptions(eventType); validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); authorizationValidator.validateAuthorization(eventType.getAuthorization()); eventTypeRepository.saveEventType(eventType); try { timelineService.createDefaultTimeline(eventType.getName(), partitionsCalculator.getBestPartitionsCount(eventType.getDefaultStatistic()), eventType.getOptions().getRetentionTime()); } catch (final Exception e) { try { eventTypeRepository.removeEventType(eventType.getName()); } catch (final NoSuchEventTypeException e1) { LOG.error("Error creating event type {}", eventType, e1); } throw e; } nakadiKpiPublisher.publish(etLogEventType, () -> new JSONObject() .put("event_type", eventType.getName()) .put("status", "created") .put("category", eventType.getCategory()) .put("authz", identifyAuthzState(eventType)) .put("compatibility_mode", eventType.getCompatibilityMode())); }
Source:
public void updateFromItem(final InfoItem infoItem, final HistoryRecordManager historyRecordManager) { if (!(infoItem instanceof PlaylistInfoItem)) return; final PlaylistInfoItem item = (PlaylistInfoItem) infoItem; itemTitleView.setText(item.getName()); itemStreamCountView.setText(Localization.localizeStreamCount(itemStreamCountView.getContext(), item.getStreamCount())); itemUploaderView.setText(item.getUploaderName()); itemBuilder.getImageLoader() .displayImage(item.getThumbnailUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS); itemView.setOnClickListener(view -> { if (itemBuilder.getOnPlaylistSelectedListener() != null) { itemBuilder.getOnPlaylistSelectedListener().selected(item); } }); itemView.setLongClickable(true); itemView.setOnLongClickListener(view -> { if (itemBuilder.getOnPlaylistSelectedListener() != null) { itemBuilder.getOnPlaylistSelectedListener().held(item); } return true; }); }

Target:
public void updateFromItem(final InfoItem infoItem, final HistoryRecordManager historyRecordManager) { if (!(infoItem instanceof PlaylistInfoItem)) { return; } final PlaylistInfoItem item = (PlaylistInfoItem) infoItem; itemTitleView.setText(item.getName()); itemStreamCountView.setText(Localization .localizeStreamCountMini(itemStreamCountView.getContext(), item.getStreamCount())); itemUploaderView.setText(item.getUploaderName()); itemBuilder.getImageLoader() .displayImage(item.getThumbnailUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS); itemView.setOnClickListener(view -> { if (itemBuilder.getOnPlaylistSelectedListener() != null) { itemBuilder.getOnPlaylistSelectedListener().selected(item); } }); itemView.setLongClickable(true); itemView.setOnLongClickListener(view -> { if (itemBuilder.getOnPlaylistSelectedListener() != null) { itemBuilder.getOnPlaylistSelectedListener().held(item); } return true; }); }
Source:
protected void flush() throws Exception { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); Assert.assertTrue(Framework.getService(AuditLogger.class).await(5, TimeUnit.SECONDS)); }

Target:
protected void flush() throws Exception { txFeature.nextTransaction(); }
Source:
public static Node create(int createdIndex, boolean dir, List<Node> nodes, String expiration, String key, int modifiedIndex, int ttl, String value) { if (nodes == null) nodes = ImmutableList.of(); return new AutoValue_Node(createdIndex, dir, ImmutableList.copyOf(nodes), expiration, key, modifiedIndex, ttl, value); }

Target:
public static Node create(int createdIndex, boolean dir, List<Node> nodes, String expiration, String key, int modifiedIndex, int ttl, String value) { return new AutoValue_Node(createdIndex, dir, nodes != null ? ImmutableList.copyOf(nodes) : ImmutableList.<Node> of(), expiration, key, modifiedIndex, ttl, value); }
Source:
public Map.Entry<K, V> map(ResultSet rs, StatementContext ctx) throws SQLException { return ImmutableEntry.of(keyMapper.map(rs, ctx), valueMapper.map(rs, ctx)); }

Target:
public Map.Entry<K, V> map(ResultSet rs, StatementContext ctx) throws SQLException { return new AbstractMap.SimpleImmutableEntry<>(keyMapper.map(rs, ctx), valueMapper.map(rs, ctx)); }
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context != null && !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME)); }

Target:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME)); }
Source:
public AccessToken refreshAccessToken() throws IOException { if (refreshToken == null) { throw new IOException("UserCredentials instance cannot refresh because no refresh token was" +" specified in constructor."); } GenericData tokenRequest = new GenericData(); tokenRequest.set("client_id", clientId); tokenRequest.set("client_secret", clientSecret); tokenRequest.set("refresh_token", refreshToken); tokenRequest.set("grant_type", GRANT_TYPE); UrlEncodedContent content = new UrlEncodedContent(tokenRequest); HttpRequestFactory requestFactory = transport.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(tokenServerUrl, content); request.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY)); HttpResponse response = request.execute(); GenericData responseData = response.parseAs(GenericData.class); String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX); int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; AccessToken access = new AccessToken(accessToken, new Date(expiresAtMilliseconds)); return access; }

Target:
public AccessToken refreshAccessToken() throws IOException { if (refreshToken == null) { throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token."); } GenericData tokenRequest = new GenericData(); tokenRequest.set("client_id", clientId); tokenRequest.set("client_secret", clientSecret); tokenRequest.set("refresh_token", refreshToken); tokenRequest.set("grant_type", GRANT_TYPE); UrlEncodedContent content = new UrlEncodedContent(tokenRequest); HttpRequestFactory requestFactory = transport.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(tokenServerUrl, content); request.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY)); HttpResponse response = request.execute(); GenericData responseData = response.parseAs(GenericData.class); String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX); int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX); long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000; AccessToken access = new AccessToken(accessToken, new Date(expiresAtMilliseconds)); return access; }