auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void prepareCache(final CountDownLatch releaseLocksLatch) { RpcManager rpcManager = new ControlledRpcManager(advancedCache(1).getRpcManager()) { @Override public Map<Address, Response> invokeRemotely(Collection<Address> recipients, ReplicableCommand rpcCommand, boolean sync, boolean usePriorityQueue) { if (rpcCommand instanceof TxCompletionNotificationCommand) { releaseLocksLatch.countDown(); return null; } else { return realOne.invokeRemotely(recipients, rpcCommand, sync, usePriorityQueue); } } @Override public Map<Address, Response> invokeRemotely(Collection<Address> recipients, ReplicableCommand rpc, RpcOptions options) { if (rpc instanceof TxCompletionNotificationCommand) { releaseLocksLatch.countDown(); return null; } else { return realOne.invokeRemotely(recipients, rpc, options); } } }; final TransactionTable transactionTable = TestingUtil.getTransactionTable(cache(1)); TestingUtil.replaceField(rpcManager, "rpcManager", transactionTable, TransactionTable.class); TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); txControlInterceptor.prepareProgress.countDown(); txControlInterceptor.commitProgress.countDown(); advancedCache(1).addInterceptor(txControlInterceptor, 1); }

Target:
protected void prepareCache(final CountDownLatch releaseLocksLatch) { RpcManager rpcManager = new ControlledRpcManager(advancedCache(1).getRpcManager()) { @Override public Map<Address, Response> invokeRemotely(Collection<Address> recipients, ReplicableCommand rpc, RpcOptions options) { if (rpc instanceof TxCompletionNotificationCommand) { releaseLocksLatch.countDown(); return null; } else { return realOne.invokeRemotely(recipients, rpc, options); } } }; final TransactionTable transactionTable = TestingUtil.getTransactionTable(cache(1)); TestingUtil.replaceField(rpcManager, "rpcManager", transactionTable, TransactionTable.class); TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); txControlInterceptor.prepareProgress.countDown(); txControlInterceptor.commitProgress.countDown(); advancedCache(1).addInterceptor(txControlInterceptor, 1); }
Source:
public static List<String> getTables(Connection conn, Set<String> types) throws SQLException { DatabaseMetaData metadata = conn.getMetaData(); ResultSet rs = metadata.getTables(null, null, "%", null); List<String> tableNames = new ArrayList<>(); try { while (rs.next()) { if (types.contains(rs.getString(GET_TABLES_TYPE_COLUMN))) { String colName = rs.getString(GET_TABLES_NAME_COLUMN); if (metadata.getDatabaseProductName().equals("SQLite") && colName.startsWith("sqlite_")) { continue; } tableNames.add(colName); } } } finally { rs.close(); } return tableNames; }

Target:
public static List<String> getTables(Connection conn, Set<String> types) throws SQLException { DatabaseMetaData metadata = conn.getMetaData(); try (ResultSet rs = metadata.getTables(null, null, "%", null)) { List<String> tableNames = new ArrayList<>(); while (rs.next()) { if (types.contains(rs.getString(GET_TABLES_TYPE_COLUMN))) { String colName = rs.getString(GET_TABLES_NAME_COLUMN); if (metadata.getDatabaseProductName().equals("SQLite") && colName.startsWith("sqlite_")) { continue; } tableNames.add(colName); } } return tableNames; } }
Source:
public void verifyTopbarButton(WebElement element) { waitForElementByElement(topbarLoginButton); element.click(); Assertion.assertEquals("block", curtain.getCssValue("display"), "menu is not opened"); element.click(); Assertion.assertEquals("none", curtain.getCssValue("display"), "menu is not closed"); }

Target:
private void verifyTopbarButton(WebElement element) { waitForElementByElement(topbarLoginButton); element.click(); waitForElementNotPresent(curtainNotOpened); Assertion.assertEquals("block", curtain.getCssValue("display"), "menu is not opened"); element.click(); waitForElementByElement(curtainClosed); Assertion.assertEquals("none", curtain.getCssValue("display"), "menu is not closed"); }
Source:
public Long getActiveJobCountForUser(@NotBlank final String user) throws GenieException { log.debug("Called for jobs with user {}", user); if (StringUtils.isEmpty(StringUtils.trimToEmpty(user))) { throw new IllegalArgumentException("User cannot be null or empty"); } return this.jobRepository.countJobsByUserAndStatusIn(user, JobStatus.getActiveStatuses()); }

Target:
public long getActiveJobCountForUser(@NotBlank final String user) throws GenieException { log.debug("Called for jobs with user {}", user); final Long count = this.jobRepository.countJobsByUserAndStatusIn(user, JobStatus.getActiveStatuses()); if (count == null || count < 0) { throw new GenieServerException( "Count query for user " + user + "produced an unexpected result: " + count ); } return count; }
Source:
public synchronized void updatePoolDomains(Set<Guid> domains) { for (Guid domainId : domains) { if (!domainsVisibility.containsKey(domainId)) { domainsVisibility.put(domainId, new HashMap<Guid, Status>()); } } Iterator<Guid> domainsIterator = domainsVisibility.keySet().iterator(); while (domainsIterator.hasNext()) { if (!domains.contains(domainsIterator.next())) { domainsIterator.remove(); } } }

Target:
public synchronized void updatePoolDomains(Set<Guid> domains) { for (Guid domainId : domains) { if (!domainsVisibility.containsKey(domainId)) { domainsVisibility.put(domainId, new HashMap<Guid, Status>()); } } domainsVisibility.keySet().retainAll(domains); }
Source:
protected void handleStartupFailure(BackOffExecution backOffExecution) throws Exception { long recoveryInterval = backOffExecution != null ? backOffExecution.nextBackOff() : DEFAULT_RECOVERY_INTERVAL; if (BackOffExecution.STOP == recoveryInterval) { synchronized (this) { if (isActive()) { logger.warn("stopping container - restart recovery attempts exhausted"); stop(); } } return; } try { if (logger.isDebugEnabled() && isActive()) { logger.debug("Recovering consumer in " + recoveryInterval + " ms."); } long timeout = System.currentTimeMillis() + recoveryInterval; while (isActive() && System.currentTimeMillis() < timeout) { Thread.sleep(200); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Unrecoverable interruption on consumer restart"); } }

Target:
protected void handleStartupFailure(BackOffExecution backOffExecution) throws Exception { long recoveryInterval = backOffExecution.nextBackOff(); if (BackOffExecution.STOP == recoveryInterval) { synchronized (this) { if (isActive()) { logger.warn("stopping container - restart recovery attempts exhausted"); stop(); } } return; } try { if (logger.isDebugEnabled() && isActive()) { logger.debug("Recovering consumer in " + recoveryInterval + " ms."); } long timeout = System.currentTimeMillis() + recoveryInterval; while (isActive() && System.currentTimeMillis() < timeout) { Thread.sleep(200); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Unrecoverable interruption on consumer restart"); } }
Source:
private void createPathwayEdgesAndAddThemToGraph(Graph graph) { for (Pathway pathway : transitService.getAllPathways()) { Vertex fromVertex = stopNodes.get(pathway.getFromStop()); Vertex toVertex = stopNodes.get(pathway.getToStop()); if (fromVertex != null && toVertex != null) { if (pathway.getPathwayMode() == 5) { createElevatorEdgesAndAddThemToGraph(graph, pathway, fromVertex, toVertex); } else { new PathwayEdge( fromVertex, toVertex, pathway.getName(), pathway.getTraversalTime(), pathway.getLength(), pathway.getStairCount(), pathway.getSlope(), pathway.getPathwayMode() != 2 && pathway.getPathwayMode() != 4 ); if (pathway.isBidirectional()) { new PathwayEdge( toVertex, fromVertex, pathway.getReversedName(), pathway.getTraversalTime(), pathway.getLength(), -1 * pathway.getStairCount(), -1 * pathway.getSlope(), pathway.getPathwayMode() != 2 && pathway.getPathwayMode() != 4 ); } } } else { if (fromVertex == null) { LOG.warn("The 'fromVertex' is missing for pathway from stop: " + pathway .getFromStop() .getId()); } if (toVertex == null) { LOG.warn("The 'toVertex' is missing for pathway to stop: " + pathway .getToStop() .getId()); } } } }

Target:
private void createPathwayEdgesAndAddThemToGraph(Graph graph) { for (Pathway pathway : transitService.getAllPathways()) { Vertex fromVertex = stationElementNodes.get(pathway.getFromStop()); Vertex toVertex = stationElementNodes.get(pathway.getToStop()); if (fromVertex != null && toVertex != null) { if (pathway.getPathwayMode() == 5) { createElevatorEdgesAndAddThemToGraph(graph, pathway, fromVertex, toVertex); } else { new PathwayEdge( fromVertex, toVertex, pathway.getName(), pathway.getTraversalTime(), pathway.getLength(), pathway.getStairCount(), pathway.getSlope(), pathway.isPathwayModeWheelchairAccessible() ); if (pathway.isBidirectional()) { new PathwayEdge( toVertex, fromVertex, pathway.getReversedName(), pathway.getTraversalTime(), pathway.getLength(), -1 * pathway.getStairCount(), -1 * pathway.getSlope(), pathway.isPathwayModeWheelchairAccessible() ); } } } else { if (fromVertex == null) { LOG.warn("The 'fromVertex' is missing for pathway from stop: " + pathway .getFromStop() .getId()); } if (toVertex == null) { LOG.warn("The 'toVertex' is missing for pathway to stop: " + pathway .getToStop() .getId()); } } } }
Source:
private void checkGetter(String fieldName, MethodTree methodTree) { Symbol.TypeSymbol getterOwner = ((Symbol.TypeSymbol) methodTree.symbol().owner()); if (getterOwner.lookupSymbols(fieldName).stream() .filter(Symbol::isPrivate) .noneMatch(symbol -> fieldName.equals(symbol.name()))) { return; } firstAndOnlyStatement(methodTree) .filter(statementTree -> statementTree.is(Tree.Kind.RETURN_STATEMENT)) .map(statementTree -> ((ReturnStatementTree) statementTree).expression()) .flatMap(GettersSettersOnRightFieldCheck::symbolFromExpression) .filter(returnSymbol -> !fieldName.equals(returnSymbol.name())) .ifPresent(returnedSymbol -> context.reportIssue(this, methodTree.simpleName(), "Refactor this getter so that it actually refers to the field \"" + fieldName + "\".")); }

Target:
private void checkGetter(String fieldName, MethodTree methodTree) { Symbol.TypeSymbol getterOwner = ((Symbol.TypeSymbol) methodTree.symbol().owner()); if (!hasPrivateFieldWithName(fieldName, getterOwner)) { return; } firstAndOnlyStatement(methodTree) .filter(statementTree -> statementTree.is(Tree.Kind.RETURN_STATEMENT)) .map(statementTree -> ((ReturnStatementTree) statementTree).expression()) .flatMap(GettersSettersOnRightFieldCheck::symbolFromExpression) .filter(returnSymbol -> !fieldName.equals(returnSymbol.name())) .ifPresent(returnedSymbol -> context.reportIssue(this, methodTree.simpleName(), "Refactor this getter so that it actually refers to the field \"" + fieldName + "\".")); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); try { final IFile buildFile = Central.getWorkspaceBuildFile(); if (buildFile == null) { MessageDialog.openError(window.getShell(), "Error", "Unable to refresh repositories: workspace build file is missing."); return null; } window.run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { buildFile.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { List<RepositoryPlugin> repos = RepositoryUtils.listRepositories(true); for (RepositoryPlugin i : repos) { if (i instanceof RemoteRepositoryPlugin) { ((RemoteRepositoryPlugin) i).refreshCacheMetadata(); } } buildFile.touch(monitor); } }, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (Exception e) { logger.logError("Error refreshing repositories.", e); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); try { final IFile buildFile = Central.getWorkspaceBuildFile(); if (buildFile == null) { MessageDialog.openError(window.getShell(), "Error", "Unable to refresh repositories: workspace build file is missing."); return null; } window.run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { buildFile.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { List<RepositoryPlugin> repos = RepositoryUtils.listRepositories(true); for (RepositoryPlugin i : repos) { if (i instanceof Refreshable) { boolean success = false; try { success = ((Refreshable) i).refresh(); } catch (Exception e) { logger.logError("Exception while refreshing repository: " + i.getName(), e); } if (!success) { logger.logError("Failed to refresh repository: " + i.getName(), null); } } } buildFile.touch(monitor); } }, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (Exception e) { logger.logError("Error refreshing repositories.", e); } return null; }
Source:
public RawType(byte[] bytes) { this(bytes, null); }

Target:
public RawType(byte[] bytes) { this(bytes, DEFAULT_MIME_TYPE); }
Source:
public void responseBoB(BoBIQ requestBoBIQ, BoBData bobData) throws NotConnectedException, InterruptedException, NotLoggedInException { BoBIQ responseBoBIQ = new BoBIQ(requestBoBIQ.getBoBHash(), bobData); responseBoBIQ.setType(Type.result); responseBoBIQ.setTo(requestBoBIQ.getFrom()); XMPPConnection connection = getAuthenticatedConnectionOrThrow(); connection.sendStanza(responseBoBIQ); }

Target:
private BoBIQ responseBoB(BoBIQ requestBoBIQ, BoBData bobData) throws NotConnectedException, InterruptedException, NotLoggedInException { BoBIQ responseBoBIQ = new BoBIQ(requestBoBIQ.getBoBHash(), bobData); responseBoBIQ.setType(Type.result); responseBoBIQ.setTo(requestBoBIQ.getFrom()); return responseBoBIQ; }
Source:
public ModelAndView setupForm(@PathVariable Long poolId, ModelMap model) throws IOException { try { User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); Pool pool = null; if (poolId == AbstractPool.UNSAVED_ID) { pool = dataObjectFactory.getPool(user); model.put("title", "New Pool"); } else { pool = requestManager.getPoolById(poolId); model.put("title", "Pool " + poolId); } if (pool == null) { throw new SecurityException("No such Pool"); } if (!pool.userCanRead(user)) { throw new SecurityException("Permission denied."); } model.put("formObj", pool); model.put("pool", pool); model.put("availableDilutions", populateAvailableDilutions(pool)); model.put("accessibleExperiments", populateExperiments(null, pool)); model.put("owners", LimsSecurityUtils.getPotentialOwners(user, pool, securityManager.listAllUsers())); model.put("accessibleUsers", LimsSecurityUtils.getAccessibleUsers(user, pool, securityManager.listAllUsers())); model.put("accessibleGroups", LimsSecurityUtils.getAccessibleGroups(user, pool, securityManager.listAllGroups())); Collection<SequencingParametersDto> sequencingParameters = Dtos.asSequencingParametersDtos(sequencingParametersService.getAll()); model.put("sequencingParameters", sequencingParameters); JSONArray array = new JSONArray(); array.addAll(sequencingParameters); model.put("sequencingParametersJson", array.toString()); model.put("platforms", getFilteredPlatforms(pool.getPlatformType())); return new ModelAndView("/pages/editPool.jsp", model); } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to show pool", ex); } throw ex; } }

Target:
public ModelAndView setupForm(@PathVariable Long poolId, ModelMap model) throws IOException { try { User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); Pool pool = null; if (poolId == AbstractPool.UNSAVED_ID) { pool = dataObjectFactory.getPool(user); model.put("title", "New Pool"); } else { pool = requestManager.getPoolById(poolId); model.put("title", "Pool " + poolId); } if (pool == null) { throw new SecurityException("No such Pool"); } if (!pool.userCanRead(user)) { throw new SecurityException("Permission denied."); } model.put("formObj", pool); model.put("pool", pool); model.put("availableDilutions", populateAvailableDilutions(pool)); model.put("accessibleExperiments", populateExperiments(null, pool)); model.put("owners", LimsSecurityUtils.getPotentialOwners(user, pool, securityManager.listAllUsers())); model.put("accessibleUsers", LimsSecurityUtils.getAccessibleUsers(user, pool, securityManager.listAllUsers())); model.put("accessibleGroups", LimsSecurityUtils.getAccessibleGroups(user, pool, securityManager.listAllGroups())); model.put("platforms", getFilteredPlatforms(pool.getPlatformType())); model.put("ordercompletions", poolOrderCompletionService.getOrderCompletionForPool(poolId)); return new ModelAndView("/pages/editPool.jsp", model); } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to show pool", ex); } throw ex; } }
Source:
public synchronized void connectionLost(@Nullable Throwable exception) { assert exception != null; if (exception instanceof MqttException) { MqttException e = (MqttException) exception; logger.info("MQTT connection to '{}' was lost: : ReasonCode : Cause : {}", host, e.getMessage(), e.getReasonCode(), (e.getCause() == null ? "Unknown" : e.getCause().getMessage())); } else { logger.info("MQTT connection to '{}' was lost: {}", host, exception.getMessage()); } connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.DISCONNECTED, exception)); if (reconnectStrategy != null) { reconnectStrategy.lostConnection(); } }

Target:
public synchronized void connectionLost(@Nullable Throwable exception) { if (exception instanceof MqttException) { MqttException e = (MqttException) exception; logger.info("MQTT connection to '{}' was lost: : ReasonCode : Cause : {}", host, e.getMessage(), e.getReasonCode(), (e.getCause() == null ? "Unknown" : e.getCause().getMessage())); } else if (exception != null) { logger.info("MQTT connection to '{}' was lost: {}", host, exception.getMessage()); } connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.DISCONNECTED, exception)); if (reconnectStrategy != null) { reconnectStrategy.lostConnection(); } }
Source:
public List<ProcessDTO> findLinkableParentProcesses(String searchInput, int projectId, int rulesetId) throws DataException { BoolQueryBuilder query = new BoolQueryBuilder() .should(new MatchQueryBuilder(ProcessTypeField.ID.getKey(), searchInput)) .should(new MatchQueryBuilder(ProcessTypeField.TITLE.getKey(), "*" + searchInput + "*")) .must(new MatchQueryBuilder(ProcessTypeField.PROJECT_ID.getKey(), projectId)) .must(new MatchQueryBuilder(ProcessTypeField.RULESET.getKey(), rulesetId)); List<ProcessDTO> linkableParentProcesses = findByQuery(query, false); return linkableParentProcesses; }

Target:
public List<ProcessDTO> findLinkableParentProcesses(String searchInput, int projectId, int rulesetId) throws DataException { BoolQueryBuilder query = new BoolQueryBuilder() .must(new BoolQueryBuilder().should(new MatchQueryBuilder(ProcessTypeField.ID.getKey(), searchInput)) .should(createSimpleWildcardQuery(ProcessTypeField.TITLE.getKey(), searchInput))) .must(new MatchQueryBuilder(ProcessTypeField.PROJECT_ID.getKey(), projectId)) .must(new MatchQueryBuilder(ProcessTypeField.RULESET.getKey(), rulesetId)); List<ProcessDTO> linkableParentProcesses = findByQuery(query, false); return linkableParentProcesses; }
Source:
public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target) { String kind = determineKind(optionContext); SpringXDOperations springXDOperations = xdShell.getSpringXDOperations(); DeployedCriteria criteria = DeployedCriteria.parse(optionContext); boolean kindSupported = true; try { if ("stream".equals(kind)) { populate(completions, springXDOperations.streamOperations().list(), criteria, "Streams"); } else if ("job".equals(kind)) { populate(completions, springXDOperations.jobOperations().list(), criteria, "Jobs"); } else if ("counter".equals(kind)) { populate(completions, springXDOperations.counterOperations().list(), criteria, "Counters"); } else if ("fvc".equals(kind)) { populate(completions, springXDOperations.fvcOperations().list(), criteria, "Field Value Counters"); } else if ("gauge".equals(kind)) { populate(completions, springXDOperations.gaugeOperations().list(), criteria, "Gauges"); } else if ("rich-gauge".equals(kind)) { populate(completions, springXDOperations.richGaugeOperations().list(), criteria, "Rich Gauges"); } else if ("aggregate-counter".equals(kind)) { populate(completions, springXDOperations.aggrCounterOperations().list(), criteria, "Aggregate Counters"); } else { kindSupported = false; } } catch (Exception e) { return false; } Assert.isTrue(kindSupported, "Unsupported kind: " + kind); return true; }

Target:
public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target) { String kind = determineKind(optionContext); SpringXDOperations springXDOperations = xdShell.getSpringXDOperations(); DeployedCriteria criteria = DeployedCriteria.parse(optionContext); boolean kindSupported = true; try { if ("stream".equals(kind)) { populate(completions, springXDOperations.streamOperations().list(), criteria, "Streams"); } else if ("job".equals(kind)) { populate(completions, springXDOperations.jobOperations().list(), criteria, "Jobs"); } else if ("counter".equals(kind)) { populate(completions, springXDOperations.counterOperations().list(), criteria, "Counters"); } else if ("fvc".equals(kind)) { populate(completions, springXDOperations.fvcOperations().list(), criteria, "Field Value Counters"); } else if ("gauge".equals(kind)) { populate(completions, springXDOperations.gaugeOperations().list(), criteria, "Gauges"); } else if ("rich-gauge".equals(kind)) { populate(completions, springXDOperations.richGaugeOperations().list(), criteria, "Rich Gauges"); } else if ("aggregate-counter".equals(kind)) { populate(completions, springXDOperations.aggrCounterOperations().list(), criteria, "Aggregate Counters"); } else { kindSupported = false; } } catch (Exception e) { LOGGER.warning(String.format("Completion unavailable (%s)", e.getMessage())); return false; } Assert.isTrue(kindSupported, "Unsupported kind: " + kind); return true; }
Source:
public synchronized void upgradeAttributes( final boolean force ) { if ( isUpgradeRunning() ) { return; } if ( !isLegacyAttributesDirectoryPresent() ) { getLogger().debug( "Legacy attribute directory not present, no need for attribute upgrade." ); } else { if ( isUpgradeDone( getLegacyAttributesDirectory(), null ) ) { getLogger().info( "Legacy attribute directory present, but is marked already as upgraded. Please delete, move or rename the \"{}\" folder.", getLegacyAttributesDirectory().getAbsolutePath() ); } else { if ( force || UPGRADE ) { if ( force ) { getLogger().info( "Legacy attribute directory present, and upgrade is needed and if forced. Starting background upgrade." ); } else { getLogger().info( "Legacy attribute directory present, and upgrade is needed. Starting background upgrade." ); } this.upgraderThread = new AttributeUpgraderThread( getLegacyAttributesDirectory(), repositoryRegistry, upgradeThrottleUps ); this.upgraderThread.start(); } else { getLogger().info( "Legacy attribute directory present, but upgrade prevented by system property. Not upgrading it." ); } } } }

Target:
public synchronized void upgradeAttributes( final boolean force ) { if ( isUpgradeRunning() ) { return; } if ( !isLegacyAttributesDirectoryPresent() ) { getLogger().debug( "Legacy attribute directory not present, no need for attribute upgrade." ); } else { if ( isUpgradeFinished() ) { getLogger().info( "Legacy attribute directory present, but is marked already as upgraded. Please delete, move or rename the \"{}\" directory.", getLegacyAttributesDirectory().getAbsolutePath() ); } else { if ( force || UPGRADE ) { if ( force ) { getLogger().info( "Legacy attribute directory present, and upgrade is needed and if forced. Starting background upgrade." ); } else { getLogger().info( "Legacy attribute directory present, and upgrade is needed. Starting background upgrade." ); } this.upgraderThread = new AttributeUpgraderThread( getLegacyAttributesDirectory(), repositoryRegistry, upgradeThrottleUps ); this.upgraderThread.start(); } else { getLogger().info( "Legacy attribute directory present, but upgrade prevented by system property. Not upgrading it." ); } } } }
Source:
public static BlockingTimeLimitedLockService create(CloseableLockService lockService, long blockingTimeLimitMillis) { return new BlockingTimeLimitedLockService( lockService, SimpleTimeLimiter.create(Executors.newCachedThreadPool()), blockingTimeLimitMillis); }

Target:
public static BlockingTimeLimitedLockService create(CloseableLockService lockService, long blockingTimeLimitMillis) { return new BlockingTimeLimitedLockService( lockService, SimpleTimeLimiter.create(PTExecutors.newCachedThreadPool()), blockingTimeLimitMillis); }
Source:
public void retryIncBootstrapExternalTablesFromDifferentDumpWithoutCleanTablesConfig() throws Throwable { List<String> dumpWithClause = Collections.singletonList( "'" + HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname + "'='false'" ); List<String> loadWithClause = externalTableBasePathWithClause(); WarehouseInstance.Tuple tupleBootstrapWithoutExternal = primary .run("use " + primaryDbName) .run("create external table t1 (id int)") .run("insert into table t1 values (1)") .run("create table t2 as select * from t1") .dump(primaryDbName, null, dumpWithClause); replica.load(replicatedDbName, tupleBootstrapWithoutExternal.dumpLocation, loadWithClause); dumpWithClause = Arrays.asList("'" + HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname + "'='true'", "'" + HiveConf.ConfVars.REPL_BOOTSTRAP_EXTERNAL_TABLES.varname + "'='true'"); WarehouseInstance.Tuple tupleIncWithExternalBootstrap = primary.run("use " + primaryDbName) .run("create table t3 as select * from t1") .dump(primaryDbName, tupleBootstrapWithoutExternal.lastReplicationId, dumpWithClause); WarehouseInstance.Tuple tupleNewIncWithExternalBootstrap = primary.dump(primaryDbName, tupleBootstrapWithoutExternal.lastReplicationId, dumpWithClause); replica.load(replicatedDbName, tupleIncWithExternalBootstrap.dumpLocation, loadWithClause); replica.loadFailure(replicatedDbName, tupleNewIncWithExternalBootstrap.dumpLocation, loadWithClause, ErrorMsg.REPL_BOOTSTRAP_LOAD_PATH_NOT_VALID.getErrorCode()); }

Target:
public void retryIncBootstrapExternalTablesFromDifferentDumpWithoutCleanTablesConfig() throws Throwable { List<String> dumpWithClause = Collections.singletonList( "'" + HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname + "'='false'" ); List<String> loadWithClause = externalTableBasePathWithClause(); WarehouseInstance.Tuple tupleBootstrapWithoutExternal = primary .dump(primaryDbName, null, dumpWithClause); replica.load(replicatedDbName, tupleBootstrapWithoutExternal.dumpLocation, loadWithClause); dumpWithClause = Arrays.asList("'" + HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname + "'='true'", "'" + HiveConf.ConfVars.REPL_BOOTSTRAP_EXTERNAL_TABLES.varname + "'='true'"); WarehouseInstance.Tuple tupleIncWithExternalBootstrap = primary.run("use " + primaryDbName) .run("create external table t1 (id int)") .run("insert into table t1 values (1)") .run("create table t2 as select * from t1") .dump(primaryDbName, tupleBootstrapWithoutExternal.lastReplicationId, dumpWithClause); WarehouseInstance.Tuple tupleNewIncWithExternalBootstrap = primary.dump(primaryDbName, tupleBootstrapWithoutExternal.lastReplicationId, dumpWithClause); replica.load(replicatedDbName, tupleIncWithExternalBootstrap.dumpLocation, loadWithClause); replica.loadFailure(replicatedDbName, tupleNewIncWithExternalBootstrap.dumpLocation, loadWithClause, ErrorMsg.REPL_BOOTSTRAP_LOAD_PATH_NOT_VALID.getErrorCode()); }
Source:
public <T> SlimAnnotatedTypeContext<T> loadAnnotatedType(String className, String bdaId) { try { final ClassFileInfo classFileInfo = classFileServices.getClassFileInfo(className); final boolean checkTypeModifiers = isJandexSetFlagsAvailable(); if ((classFileInfo.getModifiers() & BytecodeUtils.ANNOTATION) != 0) { return null; } if (classFileInfo.isVetoed()) { return null; } if(!checkTypeModifiers){ BootstrapLogger.LOG.usingOldJandexVersion(); } Set<ExtensionObserverMethodImpl<?, ?>> observerMethods = Collections.emptySet(); if (containerLifecycleEvents.isProcessAnnotatedTypeObserved()) { observerMethods = resolver.resolveProcessAnnotatedTypeObservers(classFileServices, className); if (!observerMethods.isEmpty()) { return createContext(className, classFileInfo, observerMethods, bdaId); } } if (Beans.isDecoratorDeclaringInAppropriateConstructor(classFileInfo)) { BootstrapLogger.LOG.decoratorWithNonCdiConstructor(classFileInfo.getClassName()); } if (Beans.isTypeManagedBeanOrDecoratorOrInterceptor(classFileInfo, checkTypeModifiers)) { return createContext(className, classFileInfo, observerMethods, bdaId); } return null; } catch (ClassFileInfoException e) { BootstrapLogger.LOG.exceptionLoadingAnnotatedType(e.getMessage()); return fallback.loadAnnotatedType(className, bdaId); } }

Target:
public <T> SlimAnnotatedTypeContext<T> loadAnnotatedType(String className, String bdaId) { try { final ClassFileInfo classFileInfo = classFileServices.getClassFileInfo(className); if ((classFileInfo.getModifiers() & BytecodeUtils.ANNOTATION) != 0) { return null; } if (classFileInfo.isVetoed()) { return null; } Set<ExtensionObserverMethodImpl<?, ?>> observerMethods = Collections.emptySet(); if (containerLifecycleEvents.isProcessAnnotatedTypeObserved()) { observerMethods = resolver.resolveProcessAnnotatedTypeObservers(classFileServices, className); if (!observerMethods.isEmpty()) { return createContext(className, classFileInfo, observerMethods, bdaId); } } if (Beans.isDecoratorDeclaringInAppropriateConstructor(classFileInfo)) { BootstrapLogger.LOG.decoratorWithNonCdiConstructor(classFileInfo.getClassName()); } if (Beans.isTypeManagedBeanOrDecoratorOrInterceptor(classFileInfo, checkTypeModifiers)) { return createContext(className, classFileInfo, observerMethods, bdaId); } return null; } catch (ClassFileInfoException e) { BootstrapLogger.LOG.exceptionLoadingAnnotatedType(e.getMessage()); return fallback.loadAnnotatedType(className, bdaId); } }
Source:
public void init() { super.initialize(); initFileSystem(); registerAppDefinitions(); final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams && !diagrams.isEmpty() ) { for ( Diagram diagram : diagrams ) { getRegistry().register( diagram ); } } }

Target:
public void init() { super.initialize(); initFileSystem(); registerAppDefinitions(); final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams ) { diagrams.forEach( diagram -> getRegistry().register( diagram ) ); } }
Source:
public void generateCompiledAlphaNetwork(KieBaseModelImpl kBaseModel, InternalKieModule kModule, InternalKnowledgeBase kBase) { final String configurationProperty = kBaseModel.getKModule().getConfigurationProperty("drools.alphaNetworkCompiler"); final Boolean isAlphaNetworkEnabled; if(configurationProperty != null) { isAlphaNetworkEnabled = Boolean.valueOf(configurationProperty); } else { isAlphaNetworkEnabled = false; } if (isAlphaNetworkEnabled) { KnowledgeBuilder kbuilder = kModule.getKnowledgeBuilderForKieBase(kBaseModel.getName()); kBase.getRete().getEntryPointNodes().values().stream() .flatMap(ep -> ep.getObjectTypeNodes().values().stream()) .filter(f -> !InitialFact.class.isAssignableFrom(f.getObjectType().getClassType())) .forEach(otn -> otn.setCompiledNetwork(ObjectTypeNodeCompiler.compile(((KnowledgeBuilderImpl) kbuilder), otn))); } }

Target:
public void generateCompiledAlphaNetwork(KieBaseModelImpl kBaseModel, InternalKieModule kModule, InternalKnowledgeBase kBase) { final String configurationProperty = kBaseModel.getKModule().getConfigurationProperty(ALPHA_NETWORK_COMPILER_OPTION); final Boolean isAlphaNetworkEnabled = Boolean.valueOf(configurationProperty); if (isAlphaNetworkEnabled) { KnowledgeBuilder kbuilder = kModule.getKnowledgeBuilderForKieBase(kBaseModel.getName()); kBase.getRete().getEntryPointNodes().values().stream() .flatMap(ep -> ep.getObjectTypeNodes().values().stream()) .filter(f -> !InitialFact.class.isAssignableFrom(f.getObjectType().getClassType())) .forEach(otn -> otn.setCompiledNetwork(ObjectTypeNodeCompiler.compile(((KnowledgeBuilderImpl) kbuilder), otn))); } }
Source:
public void checkAbilityToBuildServiceWithDefinedParametersAndNodeSetInProperties(){ try { String definedNode = findDefaultNode().getAbsolutePath(); System.setProperty(AppiumServiceBuilder.APPIUM_NODE_PROPERTY, definedNode); AppiumDriverLocalService.buildService(new AppiumServiceBuilder().withIPAddress("127.0.0.1"). usingPort(4000).withArgument(GeneralServerFlag.TEMP_DIRECTORY, "C:/Windows/Temp")); } finally { System.clearProperty(AppiumServiceBuilder.APPIUM_NODE_PROPERTY); } }

Target:
public void checkAbilityToBuildServiceWithDefinedParametersAndNodeSetInProperties(){ try { String definedNode = findCustomNode().getAbsolutePath(); System.setProperty(AppiumServiceBuilder.APPIUM_NODE_PROPERTY, definedNode); AppiumDriverLocalService.buildService(new AppiumServiceBuilder().withIPAddress("127.0.0.1"). usingPort(4000).withArgument(GeneralServerFlag.LOG_TIMESTAMP,"")); } finally { System.clearProperty(AppiumServiceBuilder.APPIUM_NODE_PROPERTY); } }
Source:
protected void postConnect(OneTimeCallback callback) throws ClientConnectionException { try { final int interestedOps = SelectionKey.OP_READ; reactor.wakeup(); final ReactorClient client = this; final FutureTask<SelectionKey> task = scheduleTask(new Retryable<SelectionKey>( new Callable<SelectionKey>() { @Override public SelectionKey call() throws ClosedChannelException { int ops = interestedOps | SelectionKey.OP_WRITE; return channel.register(selector, ops , client); } }, this.policy)); key = task.get(); this.nioEngine = new SSLEngineNioHelper(channel, createSSLEngine(this.client), callback, this); this.nioEngine.beginHandshake(); } catch (SSLException | InterruptedException | ExecutionException e) { log.error("Connection issues during ssl client creation", e); throw new ClientConnectionException(e); } if (key == null) { throw new ClientConnectionException("Connection issue during post connect"); } }

Target:
protected void postConnect(OneTimeCallback callback) throws ClientConnectionException { try { final ReactorClient client = this; final FutureTask<SelectionKey> task = scheduleTask(new Retryable<SelectionKey>( new Callable<SelectionKey>() { @Override public SelectionKey call() throws ClosedChannelException { return channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE , client); } }, this.policy)); key = task.get(); this.nioEngine = new SSLEngineNioHelper(channel, createSSLEngine(this.client), callback, this); this.nioEngine.beginHandshake(); } catch (SSLException | InterruptedException | ExecutionException e) { log.error("Connection issues during ssl client creation", e); throw new ClientConnectionException(e); } if (key == null) { throw new ClientConnectionException("Connection issue during post connect"); } }
Source:
private void start() { synchronized (lock) { if (manager != null) { throw new IllegalStateException("Cache pool has already been started"); } try { System.setProperty("net.sf.ehcache.skipUpdateCheck", "" + true); } catch (SecurityException e) { } manager = new CacheManager(new Factory().toConfiguration()); for (CacheProvider<?, ?> p : caches.values()) { Ehcache eh = manager.getEhcache(p.getName()); EntryCreator<?, ?> c = p.getEntryCreator(); if (c != null) { if (p.disk()) { p.bind(new PopulatingProtobufCache(eh, c, p.getKeyClass(), p .getValueClass(), p.getValueProvider())); } else { p.bind(new PopulatingCache(eh, c)); } } else { if (p.disk()) { p.bind(new SimpleProtobufCache(eh, p.getKeyClass(), p .getValueClass(), p.getValueProvider())); } else { p.bind(new SimpleCache(eh)); } } } } }

Target:
private void start() { synchronized (lock) { if (manager != null) { throw new IllegalStateException("Cache pool has already been started"); } try { System.setProperty("net.sf.ehcache.skipUpdateCheck", "" + true); } catch (SecurityException e) { } manager = new CacheManager(new Factory().toConfiguration()); for (CacheProvider<?, ?> p : caches.values()) { Ehcache eh = manager.getEhcache(p.getName()); EntryCreator<?, ?> c = p.getEntryCreator(); if (c != null && p.disk()) { c = new ProtobufEntryCreator(c, p.getKeyClass(), p.getValueClass()); } Cache m; if (c != null) { m = new PopulatingCache(eh, c); } else { m = new SimpleCache(eh); } if (p.disk()) { m = new ProtobufCache(m, p.getKeyClass(), p.getValueClass(), p .getValueProvider()); } p.bind(m); } } }
Source:
public boolean testFinished(final Class<?> testClass) { return finishedTests.contains(testClass.getName()); }

Target:
private boolean testFinished(final Class<?> testClass) { return finishedTests.contains(testClass.getName()); }
Source:
public ProjectCacheCleaner(final File projectCacheDir, final double percentageOfDisk, final double throttlePercentage) { Preconditions.checkNotNull(projectCacheDir); Preconditions.checkArgument(projectCacheDir.exists()); Preconditions.checkArgument(percentageOfDisk > 0 && percentageOfDisk <= 1); this.projectCacheDir = projectCacheDir; this.percentageOfDisk = percentageOfDisk; this.throttlePercentage = throttlePercentage; log.info("ProjectCacheCleaner constructor called. ProjectCacheDir = {}, thresh-hold = %, throttle at %", projectCacheDir.toPath(), this.percentageOfDisk, this.throttlePercentage); cachedProjects = new HashMap<>(); projectsUnderDeletion = new ConcurrentHashMap<>(); barrier = new ReentrantLock(); emptyQCond = barrier.newCondition(); deletionService = Executors.newFixedThreadPool(CLEANING_SERVICE_THREAD_NUM); }

Target:
public ProjectCacheCleaner(final File projectCacheDir, final double percentageOfDisk, final double throttlePercentage) { Preconditions.checkNotNull(projectCacheDir); Preconditions.checkArgument(projectCacheDir.exists()); Preconditions.checkArgument(percentageOfDisk > 0 && percentageOfDisk <= 1); this.projectCacheDir = projectCacheDir; this.percentageOfDisk = percentageOfDisk; this.throttlePercentage = throttlePercentage; log.info("ProjectCacheCleaner constructor called. ProjectCacheDir = {}, thresh-hold = %, throttle at %", projectCacheDir.toPath(), this.percentageOfDisk, this.throttlePercentage); emptyQCond = barrier.newCondition(); deletionService = Executors.newFixedThreadPool(CLEANING_SERVICE_THREAD_NUM); }
Source:
public static void setup() { try { privateKey = KeyFactory.getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec( SignatureHeaderUtils.loadPEM(privateKeyString.getBytes()))); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { e.printStackTrace(); } messageVerifier = new MessageVerifier(true); messageVerifier.setPublicKeyProvider(new MockPublicKeyProvider()); messageVerifier.setExceptionHandler(new MockExceptionHandler()); messageVerifier.setSecurityProvider(new MockSecurityProvider()); messageVerifier.setAlgorithmProvider(new MockAlgorithmProvider()); messageSigner = new MessageSigner(DefaultSignatureConstants.SIGNING_ALGORITHM, DefaultSignatureConstants.DIGEST_ALGORITHM); }

Target:
public static void setup() { try { final KeyPair keyPair = KeyPairGenerator.getInstance(KEY_PAIR_GENERATOR_ALGORITHM) .generateKeyPair(); messageVerifier = new MessageVerifier(new MockPublicKeyProvider(keyPair.getPublic())); messageVerifier.setSecurityProvider(new MockSecurityProvider()); messageVerifier.setAlgorithmProvider(new MockAlgorithmProvider()); messageSigner = new MessageSigner(keyPair.getPrivate(), KEY_ID); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
Source:
public boolean testBytes(byte[] value, int offset, int length) { long hashCode = hash(value, offset, length); if (!testBloom(hashCode)) { return false; } int position = (int) (hashCode & (hashTableSizeMask)); for (int i = position; i <= position + hashTableSizeMask; i++) { int index = i & (hashTableSizeMask); byte[] entry = hashTable[index]; if (entry == null) { return false; } if (compareRanges(value, offset, length, entry, 0, entry.length) == 0) { return true; } } return false; }

Target:
public boolean testBytes(byte[] value, int offset, int length) { long hashCode = hash(value, offset, length); if (!testBloom(hashCode)) { return false; } int position = (int) (hashCode & hashTableSizeMask); for (int i = position; i <= position + hashTableSizeMask; i++) { int index = i & hashTableSizeMask; byte[] entry = hashTable[index]; if (entry == null) { return false; } if (compareRanges(value, offset, length, entry, 0, entry.length) == 0) { return true; } } return false; }
Source:
public void testRequiredTypeAdapterNull() { RequiredTypeAdapterModel expected = new RequiredTypeAdapterModel(); expected.uri = null; RequiredTypeAdapterModel result = unmarshal(RequiredTypeAdapterModel.class, marshal(expected)); assertThat(result, nullValue()); }

Target:
public void testRequiredTypeAdapterNull() { RequiredTypeAdapterModel expected = new RequiredTypeAdapterModel(); RequiredTypeAdapterModel result = unmarshal(gson, RequiredTypeAdapterModel.class, marshal(gson, expected)); assertThat(result, nullValue()); }
Source:
public List<ValidationMessage> validate( final Path resourcePath, final String content ) { final KieProject kieProject = projectService.resolveProject( resourcePath ); final Validator validator = new Validator( new ValidatorFileSystemProvider( resourcePath, new ByteArrayInputStream( content != null ? content.getBytes( Charsets.UTF_8 ) : content.getBytes() ), kieProject, ioService, new JavaFileFilter() ) ); final List<ValidationMessage> validationMessages = validator.validate(); if ( validationMessages.isEmpty() ) { final ValidationMessage validationMessage = createSolverFactory( resourcePath, validator, kieProject ); if ( validationMessage != null ) { validationMessages.add( validationMessage ); } } return validationMessages; }

Target:
public List<ValidationMessage> validate( final Path resourcePath, final String content ) { try { final KieProject kieProject = projectService.resolveProject( resourcePath ); final Validator validator = getValidator( resourcePath, content, kieProject ); final List<ValidationMessage> validationMessages = validator.validate(); if ( validationMessages.isEmpty() ) { return buildSolver( resourcePath, kieProject, validator ); } else { return validationMessages; } } catch ( NoProjectException e ) { return new ArrayList<ValidationMessage>(); } }
Source:
public BridgeHandler getHandler() { BridgeHandler bridgeHandler = null; if (super.getHandler() instanceof BridgeHandler) { bridgeHandler = (BridgeHandler) super.getHandler(); } else if (super.getHandler() != null) { logger.warn("Handler of bridge '{}' must implement BridgeHandler interface.", getUID()); } return bridgeHandler; }

Target:
public BridgeHandler getHandler() { BridgeHandler bridgeHandler = null; ThingHandler thingHandler = super.getHandler(); if (thingHandler instanceof BridgeHandler) { bridgeHandler = (BridgeHandler) thingHandler; } else if (thingHandler != null) { logger.warn("Handler of bridge '{}' must implement BridgeHandler interface.", getUID()); } return bridgeHandler; }
Source:
public static void clearProperty(Enum<? extends ConfigDefaults> name) { clearProperty(name.toString()); }

Target:
public void clearProperty(Enum<? extends ConfigDefaults> name) { clearProperty(name.toString()); }
Source:
public <C> List<Validation<E, C>> traverseList(F<T, List<C>> f){ return isSuccess() ? f.f(success()).map(c -> Validation.<E, C>success(c)) : list(Validation.<E, C>fail(e.left().value())); }

Target:
public <C> List<Validation<E, C>> traverseList(F<T, List<C>> f){ return isSuccess() ? f.f(success()).map(Validation::success) : list(fail(e.left().value())); }
Source:
public void populateDAG(DAG dag, Configuration conf) { JMSStringInputOperator amqInput = dag.addOperator("amqIn", new JMSStringInputOperator()); amqInput.setSubject(conf.get(QUEUE_NAME_PROPERTY)); amqInput.getConnectionFactoryProperties().put("brokerURL", "vm://localhost"); LineOutputOperator out = dag.addOperator("fileOut", new LineOutputOperator()); dag.addStream("data", amqInput.output, out.input); }

Target:
public void populateDAG(DAG dag, Configuration conf) { JMSStringInputOperator amqInput = dag.addOperator("amqIn", new JMSStringInputOperator()); LineOutputOperator out = dag.addOperator("fileOut", new LineOutputOperator()); dag.addStream("data", amqInput.output, out.input); }
Source:
public static byte[] createQRCodeWithDescription(String text, String description) { try { InputStream fi = new ClassPathResource("/alfio/font/DejaVuSansMono.ttf").getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); QrCode qr = QrCode.encodeText(text, QrCode.Ecc.HIGH); int paddedSize = qr.size + BORDER * 2; int scale = Math.min(WIDTH, HEIGHT) / paddedSize; BufferedImage bufferedImage = qr.toImage(scale, BORDER); BufferedImage scaled = new BufferedImage(200, 230, BufferedImage.TYPE_INT_ARGB); Graphics g = scaled.createGraphics(); g.drawImage(bufferedImage, (WIDTH - paddedSize * scale) / 2, (HEIGHT - paddedSize * scale) / 2, null); g.dispose(); Graphics2D graphics = (Graphics2D) scaled.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.drawImage(bufferedImage, 0, 0, null); graphics.setColor(Color.WHITE); graphics.fillRect(0, 200, 200, 30); graphics.setColor(Color.BLACK); graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(14f)); graphics.drawString(center(truncate(description, 23), 25), 0, 215); ImageIO.write(scaled, "png", baos); return baos.toByteArray(); } catch (IOException | FontFormatException e) { throw new IllegalStateException(e); } }

Target:
public static byte[] createQRCodeWithDescription(String text, String description) { try(InputStream fi = new ClassPathResource("/alfio/font/DejaVuSansMono.ttf").getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { QrCode qr = QrCode.encodeText(text, QrCode.Ecc.HIGH); int paddedSize = qr.size + BORDER * 2; int scale = Math.min(WIDTH, HEIGHT) / paddedSize; BufferedImage bufferedImage = qr.toImage(scale, BORDER); BufferedImage scaled = new BufferedImage(200, 230, BufferedImage.TYPE_INT_ARGB); Graphics g = scaled.createGraphics(); g.drawImage(bufferedImage, (WIDTH - paddedSize * scale) / 2, (HEIGHT - paddedSize * scale) / 2, null); g.dispose(); Graphics2D graphics = (Graphics2D) scaled.getGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.drawImage(bufferedImage, 0, 0, null); graphics.setColor(Color.WHITE); graphics.fillRect(0, 200, 200, 30); graphics.setColor(Color.BLACK); graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(14f)); graphics.drawString(center(truncate(description, 23), 25), 0, 215); ImageIO.write(scaled, "png", baos); return baos.toByteArray(); } catch (IOException | FontFormatException e) { throw new IllegalStateException(e); } }
Source:
private void populateAboutThisCourse() { getCourseDetailCall = courseApi.getCourseDetail(courseDetail.course_id); getCourseDetailCall.enqueue(new ErrorHandlingCallback<CourseDetail>( getActivity(), new SnackbarErrorNotification(courseAbout)) { @Override protected void onResponse(@NonNull final CourseDetail courseDetail) { if (courseDetail.overview != null && !courseDetail.overview.isEmpty()) { populateAboutThisCourse(courseDetail.overview); } else { courseAbout.setVisibility(View.GONE); } } }); }

Target:
private void populateAboutThisCourse() { getCourseDetailCall = courseApi.getCourseDetail(courseDetail.course_id); final Activity activity = getActivity(); final TaskProgressCallback pCallback = activity instanceof TaskProgressCallback ? (TaskProgressCallback) activity : null; final TaskMessageCallback mCallback = activity instanceof TaskMessageCallback ? (TaskMessageCallback) activity : null; getCourseDetailCall.enqueue(new ErrorHandlingCallback<CourseDetail>(getActivity(), pCallback, mCallback, CallTrigger.LOADING_CACHED) { @Override protected void onResponse(@NonNull final CourseDetail courseDetail) { if (courseDetail.overview != null && !courseDetail.overview.isEmpty()) { populateAboutThisCourse(courseDetail.overview); } else { courseAbout.setVisibility(View.GONE); } } }); }