auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testRepoManifestCopyfile() throws Exception { Repository localDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\">") .append("<copyfile src=\"hello.txt\" dest=\"Hello\" />") .append("</project>") .append("</manifest>"); JGitTestUtil.writeTrashFile(localDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(localDb); command.setPath(localDb.getWorkTree() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree() + "/foo/hello.txt"); assertTrue(hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); assertTrue(content.startsWith("world")); hello = <START> new File(localDb.getWorkTree() + "/Hello"); <END> assertTrue(hello.exists()); reader = new BufferedReader(new FileReader(hello)); content = reader.readLine(); assertTrue(content.startsWith("world")); }</code><technical_language>string concat a file a string. new File(localDb.getWorkTree(), "Hello") is preferred join file paths platform specific directory separator automatically inserted</technical_language>

Target:
public void testRepoManifestCopyfile() throws Exception { Repository localDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\">") .append("<copyfile src=\"hello.txt\" dest=\"Hello\" />") .append("</project>") .append("</manifest>"); JGitTestUtil.writeTrashFile(localDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(localDb); command.setPath(localDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("The original file exists", hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); reader.close(); assertEquals("The original file has expected content", "world", content); hello = new File(localDb.getWorkTree(), "Hello"); assertTrue("The destination file exists", hello.exists()); reader = new BufferedReader(new FileReader(hello)); content = reader.readLine(); reader.close(); assertEquals("The destination file has expected content", "world", content); }
Source:
<code>public Builder entryPoint(final String entrypoint) { <START> if (entrypoint != null && !entrypoint.isEmpty()) { <END> return entryPoint(entrypoint.split(" ")); } return this; }</code><technical_language>do entryPoint empty</technical_language>

Target:
public Builder entryPoint(final String entrypoint) { if (entrypoint != null && !entrypoint.isEmpty()) { return entryPoint(entrypoint.split(" ")); } else { this.entrypoint = null; } return this; }
Source:
<code>public void mergeAndStore(final Path metadataBasePath, final Metadata mergeMetadata) { doInLock(metadataBasePath, path -> { if (Files.exists(metadataBasePath)) { try { final Metadata metadata = readMetadata(metadataBasePath); mergeAndStore(metadataBasePath, metadata, mergeMetadata); return; } catch (Exception e) { <START> logger.error("Unable to merge the metadata to " + metadataBasePath + " by source metadata" + <END> ReflectionToStringBuilder.toString(mergeMetadata) + " Continuing with storing new metadata", e); } } try { Files.createDirectories(metadataBasePath); } catch (IOException e) { throw Throwables.propagate(e); } storeMetadata(metadataBasePath, null, mergeMetadata, MetadataType.ARTIFACT_ROOT_LEVEL); }); }</code><technical_language>Cosmetic: a missing space in " source metadata" dot " Continuing..."</technical_language>

Target:
public void mergeAndStore(final Path metadataBasePath, final Metadata mergeMetadata) { doInLock(metadataBasePath, path -> { if (Files.exists(metadataBasePath)) { try { final Metadata metadata = readMetadata(metadataBasePath); mergeAndStore(metadataBasePath, metadata, mergeMetadata); return; } catch (Exception e) { logger.error("Unable to merge the metadata to " + metadataBasePath + " by source metadata " + ReflectionToStringBuilder.toString(mergeMetadata) + ". Continuing with storing new metadata ...", e); } } try { Files.createDirectories(metadataBasePath); } catch (IOException e) { throw Throwables.propagate(e); } storeMetadata(metadataBasePath, null, mergeMetadata, MetadataType.ARTIFACT_ROOT_LEVEL); }); }
Source:
<code>void doIt( Object obj ) throws Exception; } <START> public static <E extends Exception> void forAll( ActionAble actionable, Object... accessors ) throws E <END> { List<E> error = Arrays.stream( accessors ).map( accessor -> { try { actionable.doIt( accessor ); return null; } catch ( Throwable t ) { return (E) t; } } ).filter( Objects::nonNull ).collect( Collectors.toList() ); if ( !error.isEmpty() ) { throw error.get(0); } }</code><technical_language>This is nice! parameter name accessors is a bit misleading. subjects targets</technical_language>

Target:
void doIt( Object obj ) throws Exception; } public static <E extends Exception> void forAll( ActionAble actionable, Object... subjects ) throws E { List<E> error = Arrays.stream( subjects ).map( accessor -> { try { actionable.doIt( accessor ); return null; } catch ( Throwable t ) { return (E) t; } } ).filter( Objects::nonNull ).collect( Collectors.toList() ); if ( !error.isEmpty() ) { throw error.get(0); } }
Source:
<code>private void updateStringValuesToDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { PreparedStatement prepStmt = null; boolean localConnection = false; try { if (dbConnection == null) { localConnection = true; dbConnection = getDBConnection(); } prepStmt = dbConnection.prepareStatement(sqlStmt); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Invalid data provided"); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Date) { prepStmt.setTimestamp(i + 1,new Timestamp(System.currentTimeMillis())); } else if (param instanceof Boolean) { prepStmt.setBoolean(i + 1, (Boolean) param); } } } int count = prepStmt.executeUpdate(); if(count == 0) { log.info("No rows were updated"); } if (log.isDebugEnabled()) { log.debug("Executed querry is " + sqlStmt + " and number of updated rows :: " + count); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { <START> throw new UserStoreException("Error occurred while updating String values to database", e); <END> } finally { if (localConnection) { DatabaseUtil.closeAllConnections(dbConnection); } DatabaseUtil.closeAllConnections(null, prepStmt); } }</code><technical_language>debug logs</technical_language>

Target:
private void updateStringValuesToDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { PreparedStatement prepStmt = null; boolean localConnection = false; try { if (dbConnection == null) { localConnection = true; dbConnection = getDBConnection(); } prepStmt = dbConnection.prepareStatement(sqlStmt); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Invalid data provided"); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Date) { prepStmt.setTimestamp(i + 1,new Timestamp(System.currentTimeMillis())); } else if (param instanceof Boolean) { prepStmt.setBoolean(i + 1, (Boolean) param); } } } int count = prepStmt.executeUpdate(); if(count == 0) { log.info("No rows were updated"); } if (log.isDebugEnabled()) { log.debug("Executed querry is " + sqlStmt + " and number of updated rows :: " + count); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Error occurred while updating String values to database"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { if (localConnection) { DatabaseUtil.closeAllConnections(dbConnection); } DatabaseUtil.closeAllConnections(null, prepStmt); } }
Source:
<code>public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); <START> this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null")); <END> }</code><technical_language>Perhaps, check rowCount >= 0</technical_language>

Target:
public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); if (!rowCount.isUnknown() && rowCount.getValue() < 0) { throw new IllegalArgumentException(format("rowCount must be greater than or equal to 0: %s", rowCount.getValue())); } this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null")); }
Source:
<code>public Response resetEmulatedMachine(Action action) { VdcQueryReturnValue result = runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(guid)); if (result != null && result.getSucceeded() && result.getReturnValue() != null) { VdsGroupOperationParameters param = new VdsGroupOperationParameters((VDSGroup)result.getReturnValue()); param.setForceResetEmulatedMachine(true); return doAction(VdcActionType.UpdateVdsGroup, param, action); } else { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("Couldn't locate a cluster with the specified id.") <START> .build()); <END> } }</code><technical_language>If problem is entity exist resulting HTTP code 404, status NOT_FOUND, INTERNAL_SERVER_ERROR. is need for error message. If want error message localized, adding a constant "Messages" class text "Messages.properties" file</technical_language>

Target:
public Response resetEmulatedMachine(Action action) { VdcQueryReturnValue result = runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(guid)); if (result != null && result.getSucceeded() && result.getReturnValue() != null) { VdsGroupOperationParameters param = new VdsGroupOperationParameters((VDSGroup)result.getReturnValue()); param.setForceResetEmulatedMachine(true); return doAction(VdcActionType.UpdateVdsGroup, param, action); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }
Source:
<code>protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); <START> } catch (PortletException ex) { <END> logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }</code><technical_language>Opportunity JDK 7 multicatch catch (IOException | PortletException ex)</technical_language>

Target:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException | PortletException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }
Source:
<code>public Opt<Identity> enter(final Request request) throws IOException { final String decoded = new String( DatatypeConverter.parseBase64Binary( PATTERN.split( new RqHeaders.Smart( new RqHeaders.Base(request) ) <START> .single("authorization") <END> )[1] ), StandardCharsets.UTF_8 ).trim(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }</code><technical_language>@dalifreire join this previous line</technical_language>

Target:
public Opt<Identity> enter(final Request request) throws IOException { final String decoded = new String( DatatypeConverter.parseBase64Binary( AUTH.split( new RqHeaders.Smart( new RqHeaders.Base(request) ).single("authorization") )[1] ), StandardCharsets.UTF_8 ).trim(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }
Source:
<code>public Map<String, RoleManagementRules> loadPerunRolesManagement() { Map<String, RoleManagementRules> rolesManagementRules = new HashMap<>(); JsonNode rootNode = loadConfigurationFile(); JsonNode rolesNodes = rootNode.get("perun_roles_management"); <START> Iterator<String> roleNames =rolesNodes.fieldNames(); <END> while(roleNames.hasNext()) { String roleName = roleNames.next(); JsonNode roleNode = rolesNodes.get(roleName); List<Map<String, String>> privilegedRoles = new ArrayList<>(); JsonNode privilegedRolesNode = roleNode.get("privileged_roles"); for (JsonNode privilegedRoleNode : privilegedRolesNode) { Map<String, String> innerRoleMap = createmapFromJsonNode(privilegedRoleNode); privilegedRoles.add(innerRoleMap); } Map<String, String> entitiesToManage = createmapFromJsonNode(roleNode.get("entities_to_manage")); Map<String, String> objectsToAssign = createmapFromJsonNode(roleNode.get("assign_to_objects")); rolesManagementRules.put(roleName, new RoleManagementRules(roleName, privilegedRoles, entitiesToManage, objectsToAssign)); } return rolesManagementRules; }</code><technical_language>Missing space</technical_language>

Target:
public Map<String, RoleManagementRules> loadPerunRolesManagement() { Map<String, RoleManagementRules> rolesManagementRules = new HashMap<>(); try { JsonNode rootNode = loadConfigurationFile(); JsonNode rolesNodes = rootNode.get("perun_roles_management"); Iterator<String> roleNames = rolesNodes.fieldNames(); while (roleNames.hasNext()) { String roleName = roleNames.next(); JsonNode roleNode = rolesNodes.get(roleName); List<Map<String, String>> privilegedRoles = new ArrayList<>(); JsonNode privilegedRolesNode = roleNode.get("privileged_roles"); for (JsonNode privilegedRoleNode : privilegedRolesNode) { Map<String, String> innerRoleMap = createmapFromJsonNode(privilegedRoleNode); privilegedRoles.add(innerRoleMap); } Map<String, String> entitiesToManage = createmapFromJsonNode(roleNode.get("entities_to_manage")); Map<String, String> objectsToAssign = createmapFromJsonNode(roleNode.get("assign_to_objects")); rolesManagementRules.put(roleName, new RoleManagementRules(roleName, privilegedRoles, entitiesToManage, objectsToAssign)); } } catch(RuntimeException e) { throw new InternalErrorException("The configuration file " + configurationPath.getFilename() + " has invalid syntax.", e); } return rolesManagementRules; }
Source:
<code>public static boolean isInitialized() { <START> waitInitialized(); <END> return sCameraX.mInitialized.get(); }</code><technical_language>a confusing isInitialized() call waitInitialized(). isInitialized() returning CameraX finished initializing not</technical_language>

Target:
public static boolean isInitialized() { synchronized (sInitDeinitLock) { return sInstance != null && sInstance.mInitialized.get(); } }
Source:
<code>public <C> void dispatch(CommandMessage<C> command) { if (NoOpMessageMonitor.INSTANCE.equals(messageMonitor)) { CommandMessage<? extends C> interceptedCommand = intercept(command); Member destination = commandRouter.findDestination(interceptedCommand) .orElseThrow(() -> new NoHandlerForCommandException( <START> "No node known to accept " + interceptedCommand.getCommandName())); <END> try { connector.send(destination, interceptedCommand); } catch (Exception e) { destination.suspect(); throw new CommandDispatchException(DISPATCH_ERROR_MESSAGE + ": " + e.getMessage(), e); } } else { dispatch(command, null); } }</code><technical_language>Nit: I wrap failing bit in square brackets clarify _thing_ work, this: new NoHandlerForCommandException(String.format("No node accept [%s]", interceptedCommand.getCommandName()))</technical_language>

Target:
public <C> void dispatch(CommandMessage<C> command) { if (NoOpMessageMonitor.INSTANCE.equals(messageMonitor)) { CommandMessage<? extends C> interceptedCommand = intercept(command); Member destination = commandRouter.findDestination(interceptedCommand) .orElseThrow(() -> new NoHandlerForCommandException( format("No node known to accept [%s]", interceptedCommand.getCommandName()))); try { connector.send(destination, interceptedCommand); } catch (Exception e) { destination.suspect(); throw new CommandDispatchException(DISPATCH_ERROR_MESSAGE + ": " + e.getMessage(), e); } } else { dispatch(command, null); } }
Source:
<code><START> static public boolean compareDoubleWithAccuracy(final double lhs, final double rhs, final double accuracy) { <END> if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); return abs(lhs - rhs) / (abs(lhs) + abs(rhs) + EPSILON) < accuracy; }</code><technical_language>proper order is public static boolean</technical_language>

Target:
public static boolean compareDoubleWithAccuracy(final double lhs, final double rhs, final double accuracy) { if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); return abs(lhs - rhs) / (abs(lhs) + abs(rhs) + EPSILON) < accuracy; }
Source:
<code>public static void register(AggregationImplModule mod) { final BinaryOperator<Long> add = Math::addExact; <START> final BinaryOperator<Long> subsctact = Math::subtractExact; <END> mod.register(new SumAggregation<Float>(DataTypes.FLOAT, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<Double>(DataTypes.DOUBLE, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<>(DataTypes.BYTE, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.SHORT, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.INTEGER, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.LONG, add, subsctact)); }</code><technical_language>suggestion final BinaryOperator<Long> subtract = Math::subtractExact;</technical_language>

Target:
public static void register(AggregationImplModule mod) { final BinaryOperator<Long> add = Math::addExact; final BinaryOperator<Long> substract = Math::subtractExact; mod.register(new SumAggregation<Float>(DataTypes.FLOAT, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<Double>(DataTypes.DOUBLE, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<>(DataTypes.BYTE, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.SHORT, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.INTEGER, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.LONG, add, substract)); }
Source:
<code>public void addPartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.add(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionAdded(partitionId); } logger.info("Partition is added to current VCR: {}. Assigned partitions: {}", partitionIdStr, <START> vcrInstanceName, assignedPartitionIds); <END> } else { logger.info("Partition exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on add.", partitionIdStr); metrics.partitionIdNotInClusterMapOnAdd.inc(); } }</code><technical_language>assignedPartitionIds get large. want log set in debug mode, in case addPartition called times startup</technical_language>

Target:
public void addPartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.add(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionAdded(partitionId); } logger.info("Partition is added to current VCR: {}. Number of assigned partitions: {}", partitionIdStr, vcrInstanceName, assignedPartitionIds.size()); logger.debug("Assigned Partitions: {}", assignedPartitionIds); } else { logger.info("Partition exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on add.", partitionIdStr); metrics.partitionIdNotInClusterMapOnAdd.inc(); } }
Source:
<code>boolean match(String algorithm) { <START> String normalizedName = algorithm.replaceAll("-", "").toLowerCase(Locale.ROOT); <END> return normalizedName.contains(name().toLowerCase(Locale.ROOT)); }</code><technical_language>Locale.ENGLISH (the everywhere, Locale.ROOT is in some other parts)</technical_language>

Target:
boolean match(String algorithm) { return "DSA".equals(algorithm); }
Source:
<code>public static boolean confirmHardReset(Shell shell, final Repository repo) { String question = UIText.ResetTargetSelectionDialog_ResetConfirmQuestion; ILaunchConfiguration launch = LaunchFinder .getRunningLaunchConfiguration(Collections.singleton(repo), null); if (launch != null) { question = MessageFormat.format(question, "\n\n" + MessageFormat.format( UIText.LaunchFinder_RunningLaunchMessage, launch.getName())); } else { question = MessageFormat.format(question, ""); } MessageDialog messageDialog = new MessageDialog(shell, UIText.ResetTargetSelectionDialog_ResetQuestion, null, question, MessageDialog.QUESTION, 0, UIText.CommandConfirmationHardResetDialog_resetButtonLabel, IDialogConstants.NO_LABEL); return messageDialog.open() == <START> 0; <END> }</code><technical_language>This Window.OK</technical_language>

Target:
public static boolean confirmHardReset(Shell shell, final Repository repo) { String question = UIText.ResetTargetSelectionDialog_ResetConfirmQuestion; ILaunchConfiguration launch = LaunchFinder .getRunningLaunchConfiguration(Collections.singleton(repo), null); if (launch != null) { question = MessageFormat.format(question, "\n\n" + MessageFormat.format( UIText.LaunchFinder_RunningLaunchMessage, launch.getName())); } else { question = MessageFormat.format(question, ""); } MessageDialog messageDialog = new MessageDialog(shell, UIText.ResetTargetSelectionDialog_ResetQuestion, null, question, MessageDialog.QUESTION, 0, UIText.CommandConfirmationHardResetDialog_resetButtonLabel, IDialogConstants.NO_LABEL); return messageDialog.open() == Window.OK; }
Source:
<code>public void visitFormatSpecifier(FormatSpecifier formatSpecifier) { <START> scan(formatSpecifier.columnToken()); <END> scan(formatSpecifier.formatExpressions()); }</code><technical_language>visit tokens in BaseTreeVisitor, I do for this stay consistent (it impact)</technical_language>

Target:
public void visitFormatSpecifier(FormatSpecifier formatSpecifier) { scan(formatSpecifier.formatExpressions()); }
Source:
<code>private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = StudentProfileAttributes.builder().build(); editedProfile.googleId = account.googleId; editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); if ("".equals(editedProfile.nationality)) { editedProfile.nationality = getRequestParamValue("existingNationality"); } <START> String value = Const.ParamsNames.STUDENT_GENDER; <END> if ("male".equals(value) || "female".equals(value) || "other".equals(value)) { editedProfile.gender = Gender.valueOf(getRequestParamValue(Const.ParamsNames.STUDENT_GENDER)); } else { editedProfile.gender = Gender.none; } editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; preprocessParameters(editedProfile); validatePostParameters(editedProfile); return editedProfile; }</code><technical_language>do getRequestParamValue(Const.ParamsNames.STUDENT_GENDER) instead? this redundant</technical_language>

Target:
private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = StudentProfileAttributes.builder(account.googleId).build(); editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); if ("".equals(editedProfile.nationality)) { editedProfile.nationality = getRequestParamValue("existingNationality"); } editedProfile.gender = Gender.parseToGender(getRequestParamValue(Const.ParamsNames.STUDENT_GENDER)); editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; preprocessParameters(editedProfile); validatePostParameters(editedProfile); return editedProfile; }
Source:
<code>public void run(StreamGraphBuilder app) { try { StreamGraph streamGraph = new StreamGraphImpl(this, config); app.init(streamGraph, config); ExecutionPlanner planner = new ExecutionPlanner(config); ProcessorGraph processorGraph = planner.plan(streamGraph); <START> <END> processorGraph.getProcessors().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), config); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Fail to run application", t); } }</code><technical_language>I expected stream creation here. is happening</technical_language>

Target:
public void run(StreamGraphBuilder app) { try { StreamGraph streamGraph = new StreamGraphImpl(this, config); app.init(streamGraph, config); ExecutionPlanner planner = new ExecutionPlanner(config); ProcessorGraph processorGraph = planner.plan(streamGraph); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), config); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Fail to run application", t); } }
Source:
<code>public static boolean install(List<ConnectorDescriptor> descriptors, IRunnableContext context) { try { IRunnableWithProgress runner = createInstallJob(descriptors); context.run(true, true, runner); new DiscoveryFeedbackJob(descriptors).schedule(); recordInstalled(descriptors); } catch (InvocationTargetException e) { <START> IStatus status = new Status(IStatus.ERROR, DiscoveryUi.ID_PLUGIN, NLS.bind( <END> Messages.ConnectorDiscoveryWizard_installProblems, new Object[] { e.getCause().getMessage() }), e.getCause()); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG); return false; } catch (InterruptedException e) { return false; } return true; }</code><technical_language>DiscoveryUi.ID_PLUGIN here, mylyn</technical_language>

Target:
public static boolean install(List<ConnectorDescriptor> descriptors, IRunnableContext context) { try { IRunnableWithProgress runner = createInstallJob(descriptors); context.run(true, true, runner); new DiscoveryFeedbackJob(descriptors).schedule(); recordInstalled(descriptors); } catch (InvocationTargetException e) { IStatus status = new Status(IStatus.ERROR, JBossCentralActivator.PLUGIN_ID, NLS.bind( Messages.ConnectorDiscoveryWizard_installProblems, new Object[] { e.getCause().getMessage() }), e.getCause()); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG); return false; } catch (InterruptedException e) { return false; } return true; }
Source:
<code>private void waitForFutureCompletion( GroupByQuery query, ListenableFuture<?> future, IncrementalIndex<?> closeOnFailure ) { try { queryWatcher.registerQuery(query, future); final long timeout = QueryContexts.getTimeout(query); <START> if (QueryContexts.isNoTimeout(timeout)) { <END> future.get(); } else { future.get(timeout, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (CancellationException e) { closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (TimeoutException e) { closeOnFailure.close(); log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { closeOnFailure.close(); throw Throwables.propagate(e.getCause()); } }</code><technical_language>I clearer here: java if (QueryContext.hasTimeout(query)) { future.get(QueryContext.getTimeout(query), TimUnit.MILLISECONDS); } else { future.get(); } This is true for other places isNoTimeout() is used, in ChainedExecutionQueryRunner</technical_language>

Target:
private void waitForFutureCompletion( GroupByQuery query, ListenableFuture<?> future, IncrementalIndex<?> closeOnFailure ) { try { queryWatcher.registerQuery(query, future); if (QueryContexts.hasTimeout(query)) { future.get(QueryContexts.getTimeout(query), TimeUnit.MILLISECONDS); } else { future.get(); } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (CancellationException e) { closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (TimeoutException e) { closeOnFailure.close(); log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { closeOnFailure.close(); throw Throwables.propagate(e.getCause()); } }
Source:
<code>public static void addMembers(AccountGroup.UUID groupUUID, Set<String> members, final AsyncCallback<NativeList<MemberInfo>> cb) { if (members.size() == 1) { addMember(groupUUID, members.iterator().next(), new AsyncCallback<MemberInfo>() { @Override public void onSuccess(MemberInfo result) { cb.onSuccess(NativeList.of(result)); } @Override public void onFailure(Throwable caught) { cb.onFailure(caught); } }); } else { MemberInput input = MemberInput.create(); for (String member : members) { input.add_member(member); } <START> new RestApi(membersBase(groupUUID) + ".add").data(input).put(cb); <END> } }</code><technical_language>this post(cb) now</technical_language>

Target:
public static void addMembers(AccountGroup.UUID groupUUID, Set<String> members, final AsyncCallback<NativeList<MemberInfo>> cb) { if (members.size() == 1) { addMember(groupUUID, members.iterator().next(), new AsyncCallback<MemberInfo>() { @Override public void onSuccess(MemberInfo result) { cb.onSuccess(NativeList.of(result)); } @Override public void onFailure(Throwable caught) { cb.onFailure(caught); } }); } else { MemberInput input = MemberInput.create(); for (String member : members) { input.add_member(member); } new RestApi(membersBase(groupUUID) + ".add").data(input).post(cb); } }
Source:
<code>private Predicate<Diff> <START> resourceAttachmentMoveDiff(final <END> String name) { return new Predicate<Diff>() { public boolean apply(Diff input) { if (input.getMatch().toString().contains(name)) { return true; } else { return false; } } }; }</code><technical_language>name of predicate method is misleading check for resource attachment changes of type move</technical_language>

Target:
private Predicate<Diff> resourceAttachmentMoveDiff(final String name) { return new Predicate<Diff>() { public boolean apply(Diff input) { if (input instanceof ResourceAttachmentChange && DifferenceKind.MOVE.equals(input.getKind())) { final ResourceAttachmentChange change = (ResourceAttachmentChange) input; final EObject left = change.getMatch().getLeft(); if (left instanceof Diagram) { return name.equals(((Diagram) left).getName()); } } return false; } }; }
Source:
<code>public void removeListener() { if (!stereotypeList.isEmpty()) { for (Stereotype stereotype : stereotypeList) { Node compartment = helper.getStereotypeCompartment(hostView, stereotype); if (null != compartment && null != stereotype) { <START> getDiagramEventBroker().removeNotificationListener(compartment, this); <END> EList<Property> properties = stereotype.allAttributes(); for (Property property : properties) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeProperty(hostView, stereotype, property), this); } } } } }</code><technical_language>unsubscribe()</technical_language>

Target:
public void removeListener() { if (!stereotypeList.isEmpty()) { for (Stereotype stereotype : stereotypeList) { Node compartment = helper.getStereotypeCompartment(hostView, stereotype); if (null != compartment && null != stereotype) { unsubscribe(compartment); EList<Property> properties = stereotype.allAttributes(); for (Property property : properties) { unsubscribe(helper.getStereotypeProperty(hostView, stereotype, property)); } } } } }
Source:
<code>public void testBlobIdFlag() throws Exception { boolean[] isEncryptedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncryptedValues) { BlobId blobId = new BlobId(version, type, referenceDatacenterId, referenceAccountId, referenceContainerId, <START> referencePartitionId, isEncrypted, null); <END> BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEncrypted should match the original", version == BLOB_ID_V3 ? false : isEncrypted, BlobId.isEncrypted(blobId.getID())); } } } if (version >= BLOB_ID_V5) { for (BlobDataType dataType : BlobDataType.values()) { BlobId blobId = new BlobId(version, BlobIdType.NATIVE, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, false, dataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The data type should match the original's", dataType, blobIdSerDed.getBlobDataType()); } } }</code><technical_language>this test a problem NPE</technical_language>

Target:
public void testBlobIdFlag() throws Exception { boolean[] isEncryptedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncryptedValues) { BlobId blobId = new BlobId(version, type, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, isEncrypted, referenceDataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEncrypted should match the original", version == BLOB_ID_V3 ? false : isEncrypted, BlobId.isEncrypted(blobId.getID())); } } } if (version >= BLOB_ID_V5) { for (BlobDataType dataType : BlobDataType.values()) { BlobId blobId = new BlobId(version, BlobIdType.NATIVE, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, false, dataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The data type should match the original's", dataType, blobIdSerDed.getBlobDataType()); } } }
Source:
<code>protected void assertExceptionIsThrown(String sql, String expectedMsgPattern) { final SqlNode sqlNode; final SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql); try { sqlNode = SqlParserFactory.parse(sap.sql); } catch (Throwable e) { <START> checkParseEx(e, expectedMsgPattern, sap.sql); <END> return; } Throwable thrown = null; try { m_validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } SqlTests.checkEx(thrown, expectedMsgPattern, sap, SqlTests.Stage.VALIDATE); }</code><technical_language>change throw mapException(e, expectedMsgPattern, sap.sql);</technical_language>

Target:
protected void assertExceptionIsThrown(String sql, String expectedMsgPattern) { final SqlNode sqlNode; final SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql); try { sqlNode = SqlParserFactory.parse(sap.sql); } catch (Throwable e) { throw mapException(e, expectedMsgPattern, sap.sql); } Throwable thrown = null; try { m_validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } SqlTests.checkEx(thrown, expectedMsgPattern, sap, SqlTests.Stage.VALIDATE); }
Source:
<code>public synchronized Rewriter apply(Module module) { <START> TermContext initializingContext = TermContext.builder(new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING)) <END> .freshCounter(0).build(); Definition evaluatedDef = initializeDefinition.invoke(module, kem, initializingContext.global()); GlobalContext rewritingContext = new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING); rewritingContext.setDefinition(evaluatedDef); return new SymbolicRewriterGlue(module, evaluatedDef, kompileOptions, javaOptions, initializingContext.getCounterValue(), rewritingContext, kem); }</code><technical_language>This right. I reviewed rest of this code I get work in morning, this break impure functions handled, completely rewritten this code somehow</technical_language>

Target:
public synchronized Rewriter apply(Module module) { TermContext initializingContext = TermContext.builder(new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.INITIALIZING)) .freshCounter(0).build(); Definition evaluatedDef = initializeDefinition.invoke(module, kem, initializingContext.global()); GlobalContext rewritingContext = new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING); rewritingContext.setDefinition(evaluatedDef); return new SymbolicRewriterGlue(module, evaluatedDef, kompileOptions, javaOptions, initializingContext.getCounterValue(), rewritingContext, kem); }
Source:
<code>public static ZonedDateTime parse(String dateString) { int n = 0; for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { <START> n++; <END> continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }</code><technical_language>n variable do here</technical_language>

Target:
public static ZonedDateTime parse(String dateString) { for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }
Source:
<code>public void testTimeout() { EvaluationException e = assertThrows(EvaluationException.class, () -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"), "Loop was not stopped."); <START> assertTrue(e.getMessage().contains("Calculations exceeded time limit")); <END> }</code><technical_language>change, noticed this changed ExpressionTimeoutException instead of depending message</technical_language>

Target:
public void testTimeout() { ExpressionTimeoutException e = assertThrows(ExpressionTimeoutException.class, () -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"), "Loop was not stopped."); assertTrue(e.getMessage().contains("Calculations exceeded time limit")); }
Source:
<code>private Predicate<String> createPredicate() { <START> if(includeLists != null) { <END> return e -> includeLists.contains(e); } else if (excludeLists != null) { return e -> !excludeLists.contains(e); } else { return e -> true; } }</code><technical_language>Missing a blank "if" If propertyToList returns empty list, check if (!includeLists.isEmpty())</technical_language>

Target:
private Predicate<String> createPredicate() { if (includeLists.isPresent()) { return e -> includeLists.get().contains(e); } else if (excludeLists.isPresent()) { return e -> !excludeLists.get().contains(e); } else { return e -> true; } }
Source:
<code>public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException { if (log.isDebugEnabled()) { log.debug("Sending enrollment invitation mail to existing user."); } DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); try { int i; <START> for (i = 0; i < usernames.size(); i++) { <END> EmailMessageProperties emailMessageProperties = new EmailMessageProperties(); emailMessageProperties .setFirstName(getClaimValue(usernames.get(i), Constants.USER_CLAIM_FIRST_NAME)); emailMessageProperties.setUserName(usernames.get(i)); String[] mailAddress = new String[1]; mailAddress[0] = getClaimValue(usernames.get(i), Constants.USER_CLAIM_EMAIL_ADDRESS); if (StringUtils.isNotEmpty(mailAddress[0])) { emailMessageProperties.setMailTo(mailAddress); deviceManagementProviderService.sendEnrolmentInvitation(emailMessageProperties); } } } catch (UserStoreException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } catch (DeviceManagementException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); }</code><technical_language>Move int i declaration loop. This loop counter visible loop body</technical_language>

Target:
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException { if (log.isDebugEnabled()) { log.debug("Sending enrollment invitation mail to existing user."); } DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); try { for (int i = 0; i < usernames.size(); i++) { EmailMessageProperties emailMessageProperties = new EmailMessageProperties(); emailMessageProperties .setFirstName(getClaimValue(usernames.get(i), Constants.USER_CLAIM_FIRST_NAME)); emailMessageProperties.setUserName(usernames.get(i)); String[] mailAddress = new String[1]; mailAddress[0] = getClaimValue(usernames.get(i), Constants.USER_CLAIM_EMAIL_ADDRESS); if (StringUtils.isNotEmpty(mailAddress[0])) { emailMessageProperties.setMailTo(mailAddress); deviceManagementProviderService.sendEnrolmentInvitation(emailMessageProperties); } } } catch (UserStoreException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } catch (DeviceManagementException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); }
Source:
<code>private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() <START> .filter(x -> x.getCommandStatus().isDuringExecution()) <END> .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }</code><technical_language>i a problem here- a command async operations, for example - UpdateVmCommand. command locks acquired released get endAction() method (as task a callback). need handle commands callbacks only, for regular commands need acquire locks operations perform reboot</technical_language>

Target:
private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() .filter(x -> x.isCallbackEnabled()) .filter(x -> x.getCommandStatus().isDuringExecution()) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }
Source:
<code>public void filter(final ContainerRequestContext requestContext) throws IOException { if (!denyAll) { if (scopesAllowed.length > 0 && requestContext.getSecurityContext().getUserPrincipal() == null) { throw new NotAuthorizedException(LocalizationMessages.USER_NOT_AUTHORIZED()); } for (final OAuthScope role : scopesAllowed) { if (requestContext.getSecurityContext().isUserInRole(role.toString())) { return; } } } <START> LOGGER.warn("Access Token not authorized for any of the allowed scopes."); <END> throw new ForbiddenException(); }</code><technical_language>log details here. access token, account, app</technical_language>

Target:
public void filter(final ContainerRequestContext requestContext) throws IOException { if (!denyAll) { if (scopesAllowed.length > 0 && requestContext.getSecurityContext().getUserPrincipal() == null) { throw new NotAuthorizedException(LocalizationMessages.USER_NOT_AUTHORIZED()); } for (final OAuthScope role : scopesAllowed) { if (requestContext.getSecurityContext().isUserInRole(role.toString())) { return; } } } final AccessToken token = (AccessToken) requestContext.getSecurityContext().getUserPrincipal(); LOGGER.warn("Token ({}) not authorized for any of the allowed scopes {}. Account ID: {}, App ID: {}", token.token, scopesAllowed, token.accountId, token.appId); throw new ForbiddenException(); }