auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handle(ServerNotification notification) { SonarLintTelemetry telemetry = SonarLintUtils.getService(SonarLintTelemetry.class); boolean isSonarCloud; <START> try { ProjectBindingManager bindingManager = SonarLintUtils.getService(myProject, ProjectBindingManager.class); ServerConnection server = bindingManager.getServerConnection(); isSonarCloud = server.isSonarCloud(); } catch (InvalidBindingException e) { return; } <END> telemetry.devNotificationsReceived(); Notification notif = SERVER_NOTIFICATIONS_GROUP.createNotification( "<b>" + (isSonarCloud ? "SonarCloud" : "SonarQube") + " Notification</b>", createMessage(notification, isSonarCloud), NotificationType.INFORMATION, new NotificationListener.UrlOpeningListener(false) { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { SonarLintTelemetry telemetry = SonarLintUtils.getService(SonarLintTelemetry.class); telemetry.devNotificationsClicked(); super.hyperlinkActivated(notification, event); notification.hideBalloon(); } }); notif.setIcon(isSonarCloud ? SonarLintIcons.ICON_SONARCLOUD_16 : SonarLintIcons.ICON_SONARQUBE_16); notif.setImportant(true); notif.notify(myProject); }</code><technical_language>a bit strange retrieve connection notification, registered. simpler if notification.getServer() notification.getConnection(). connection a field of EventListener register</technical_language>

Target:
public void handle(ServerNotification notification) { SonarLintTelemetry telemetry = SonarLintUtils.getService(SonarLintTelemetry.class); telemetry.devNotificationsReceived(); Notification notif = SERVER_NOTIFICATIONS_GROUP.createNotification( "<b>" + (isSonarCloud ? "SonarCloud" : "SonarQube") + " Notification</b>", createMessage(notification, isSonarCloud), NotificationType.INFORMATION, new NotificationListener.UrlOpeningListener(false) { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { SonarLintTelemetry telemetry = SonarLintUtils.getService(SonarLintTelemetry.class); telemetry.devNotificationsClicked(); super.hyperlinkActivated(notification, event); notification.hideBalloon(); } }); notif.setIcon(isSonarCloud ? SonarLintIcons.ICON_SONARCLOUD_16 : SonarLintIcons.ICON_SONARQUBE_16); notif.setImportant(true); notif.notify(myProject); }
Source:
<code>private void doAdvertisement() throws IOException, ServiceNotAuthorizedException { PacketLineOut pktLineOut = new PacketLineOut(out); try { String line; while ((line = in.readString()) != PacketLineIn.END) { if (!line.startsWith("repositoryaccess ")) throw new TransportException(MessageFormat.format( JGitText.get().expectedGot, "repositoryaccess", line)); Repository r = null; try { r = openRepository(line.substring( <START> "repositoryaccess ".length())); <END> } finally { if (r != null) r.close(); } } pktLineOut.writeString("ACK"); } catch (TransportException e) { pktLineOut.writeString("ERR " + e.getMessage()); } catch (ServiceNotEnabledException e) { pktLineOut.writeString("ERR " + e.getMessage()); } finally { pktLineOut.flush(); } }</code><technical_language>need a try finally for this. if open throws exception, repository open if do open repository close execute. Repository r = openRepository(line.substring("repositoryaccess ".length())); r.close();</technical_language>

Target:
private void doAdvertisement() throws IOException, ServiceNotAuthorizedException { PacketLineOut pktLineOut = new PacketLineOut(out); try { String line; while ((line = in.readString()) != PacketLineIn.END) { if (!line.startsWith("repositoryaccess ")) throw new TransportException(MessageFormat.format( JGitText.get().expectedGot, "repositoryaccess", line)); Repository r = openRepository( line.substring("repositoryaccess ".length())); r.close(); } pktLineOut.writeString("ACK"); } catch (TransportException e) { pktLineOut.writeString("ERR " + e.getMessage()); } catch (ServiceNotEnabledException e) { pktLineOut.writeString("ERR " + e.getMessage()); } finally { pktLineOut.flush(); } }
Source:
<code>static RedshiftConnectionConfig configure(SecretProvider secrets, Config params) { return ImmutableRedshiftConnectionConfig.builder() .host(secrets.getSecretOptional("host").or(() -> params.get("host", String.class))) .port(secrets.getSecretOptional("port").transform(Integer::parseInt).or(() -> params.get("port", int.class, 5439))) .user(secrets.getSecretOptional("user").or(() -> params.get("user", String.class))) <START> .password(secrets.getSecretOptional("password").or(params.getOptional("password", String.class))) <END> .database(secrets.getSecretOptional("database").or(() -> params.get("database", String.class))) .ssl(secrets.getSecretOptional("ssl").transform(Boolean::parseBoolean).or(() -> params.get("ssl", boolean.class, false))) .connectTimeout(secrets.getSecretOptional("connect_timeout").transform(DurationParam::parse).or(() -> params.get("connect_timeout", DurationParam.class, DurationParam.of(Duration.ofSeconds(30))))) .socketTimeout(secrets.getSecretOptional("socket_timeout").transform(DurationParam::parse).or(() -> params.get("socket_timeout", DurationParam.class, DurationParam.of(Duration.ofSeconds(1800))))) .schema(secrets.getSecretOptional("schema").or(params.getOptional("schema", String.class))) .build(); }</code><technical_language>Do allow password in params</technical_language>

Target:
public static RedshiftConnectionConfig configure(SecretProvider secrets, Config params) { return ImmutableRedshiftConnectionConfig.builder() .host(secrets.getSecretOptional("host").or(() -> params.get("host", String.class))) .port(secrets.getSecretOptional("port").transform(Integer::parseInt).or(() -> params.get("port", int.class, 5439))) .user(secrets.getSecretOptional("user").or(() -> params.get("user", String.class))) .password(secrets.getSecretOptional("password")) .database(secrets.getSecretOptional("database").or(() -> params.get("database", String.class))) .ssl(secrets.getSecretOptional("ssl").transform(Boolean::parseBoolean).or(() -> params.get("ssl", boolean.class, false))) .connectTimeout(params.get("connect_timeout", DurationParam.class, DurationParam.of(Duration.ofSeconds(30)))) .socketTimeout(params.get("socket_timeout", DurationParam.class, DurationParam.of(Duration.ofSeconds(1800)))) .schema(secrets.getSecretOptional("schema").or(params.getOptional("schema", String.class))) .build(); }
Source:
<code>private boolean isEndOfScope(final DetailAST lastAnnotationNode, final DetailAST node) { DetailAST checkNode = node; while (!checkNode.equals(lastAnnotationNode)) { switch (checkNode.getType()) { case TokenTypes.RCURLY: case TokenTypes.RBRACK: while (checkNode.getNextSibling() == null) { checkNode = checkNode.getParent(); } checkNode = checkNode.getNextSibling(); break; default: <START> return false; <END> } } return true; }</code><technical_language>single return point method is required</technical_language>

Target:
private boolean isEndOfScope(final DetailAST lastAnnotationNode, final DetailAST node) { DetailAST checkNode = node; boolean endOfScope = true; while (endOfScope && !checkNode.equals(lastAnnotationNode)) { switch (checkNode.getType()) { case TokenTypes.RCURLY: case TokenTypes.RBRACK: while (checkNode.getNextSibling() == null) { checkNode = checkNode.getParent(); } checkNode = checkNode.getNextSibling(); break; default: endOfScope = false; } } return endOfScope; }
Source:
<code>public void extractBackgroundValues() { <START> List<InstanceGiven> backgroundGivens = runnerHelper.extractBackgroundValues(background, <END> classLoader, expressionEvaluatorFactory); assertEquals(3, backgroundGivens.size()); for (InstanceGiven backgroundGiven : backgroundGivens) { if (backgroundGiven.getFactIdentifier().equals(personFactIdentifier)) { assertEquals(personFactIdentifier, backgroundGiven.getFactIdentifier()); Person person = (Person) backgroundGiven.getValue(); assertEquals(NAME, person.getFirstName()); } else if (backgroundGiven.getFactIdentifier().equals(disputeFactIdentifier)) { assertEquals(disputeFactIdentifier, backgroundGiven.getFactIdentifier()); Dispute dispute = (Dispute) backgroundGiven.getValue(); assertEquals(AMOUNT, dispute.getAmount(), 0.1); } else { fail(); } } FactMappingValue notValid = backgroundData1.addOrUpdateMappingValue(disputeFactIdentifier, amountGivenExpressionIdentifier, "notValid"); assertThatThrownBy(() -> runnerHelper.extractBackgroundValues(background, classLoader, expressionEvaluatorFactory)) .isInstanceOf(ScenarioException.class) .hasMessage("Error in BACKGROUND data"); assertEquals(FactMappingValueStatus.FAILED_WITH_EXCEPTION, notValid.getStatus()); assertTrue(notValid.getExceptionMessage().startsWith("Impossible to parse")); }</code><technical_language>add a check for empty in bkg</technical_language>

Target:
public void extractBackgroundValues() { Background emptyBackground = new Background(); List<InstanceGiven> emptyBackgroundGivens = runnerHelper.extractBackgroundValues(emptyBackground, classLoader, expressionEvaluatorFactory); assertEquals(0, emptyBackgroundGivens.size()); emptyBackground.addData(); emptyBackgroundGivens = runnerHelper.extractBackgroundValues(emptyBackground, classLoader, expressionEvaluatorFactory); assertEquals(0, emptyBackgroundGivens.size()); List<InstanceGiven> backgroundGivens = runnerHelper.extractBackgroundValues(this.background, classLoader, expressionEvaluatorFactory); assertEquals(3, backgroundGivens.size()); for (InstanceGiven backgroundGiven : backgroundGivens) { if (backgroundGiven.getFactIdentifier().equals(personFactIdentifier)) { assertEquals(personFactIdentifier, backgroundGiven.getFactIdentifier()); Person person = (Person) backgroundGiven.getValue(); assertEquals(NAME, person.getFirstName()); } else if (backgroundGiven.getFactIdentifier().equals(disputeFactIdentifier)) { assertEquals(disputeFactIdentifier, backgroundGiven.getFactIdentifier()); Dispute dispute = (Dispute) backgroundGiven.getValue(); assertEquals(AMOUNT, dispute.getAmount(), 0.1); } else { fail(); } } FactMappingValue notValid = backgroundData1.addOrUpdateMappingValue(disputeFactIdentifier, amountGivenExpressionIdentifier, "notValid"); assertThatThrownBy(() -> runnerHelper.extractBackgroundValues(this.background, classLoader, expressionEvaluatorFactory)) .isInstanceOf(ScenarioException.class) .hasMessage("Error in BACKGROUND data"); assertEquals(FactMappingValueStatus.FAILED_WITH_EXCEPTION, notValid.getStatus()); assertTrue(notValid.getExceptionMessage().startsWith("Impossible to parse")); }
Source:
<code>public LoggerServiceImpl() { <START> args = new HashMap<>(); <END> actions = new HashMap<>(); actions.put( "log-record", new Runnable() { @Override public void run() { logrecord(); } } ); }</code><technical_language>need. private Map<String, Object> args = new HashMap<>();</technical_language>

Target:
public LoggerServiceImpl() { actions.put( "log-record", new Runnable() { @Override public void run() { logrecord(); } } ); }
Source:
<code>public RawType(byte[] bytes, String mimeType) { <START> this.bytes = bytes; <END> this.mimeType = mimeType; }</code><technical_language>throw NPE if mimeType == null</technical_language>

Target:
public RawType(byte[] bytes, String mimeType) { if (mimeType == null) { throw new IllegalArgumentException("mimeType argument must not be null"); } else if (mimeType.isEmpty()) { throw new IllegalArgumentException("mimeType argument must not be blank"); } this.bytes = bytes; this.mimeType = mimeType; }
Source:
<code>public ActionResponse execute(Query parameter) { List<String> ids = new ArrayList<>(); try { SearchRequest searchRequest = getRequestBuilder(parameter); SearchResponse searchResponse = getConnection() .getClient() .search(searchRequest, RequestOptions.DEFAULT); String scrollId = searchResponse.getScrollId(); SearchHits searchHits = searchResponse.getHits(); for(SearchHit searchHit : searchHits) { ids.add(searchHit.getId()); } <START> while(ids.size() < parameter.getLimit()){ <END> SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); scrollRequest.scroll(TimeValue.timeValueSeconds(elasticsearchTuningConfig.getScrollTimeInSeconds())); SearchResponse searchScrollResponse = getConnection().getClient().scroll(scrollRequest, RequestOptions.DEFAULT); scrollId = searchScrollResponse.getScrollId(); SearchHits hits = searchScrollResponse.getHits(); if (hits.getHits().length == 0){ return getResponse(parameter, searchHits, ids); } for(SearchHit searchHit : hits) { ids.add(searchHit.getId()); } } if (ids.size() > parameter.getLimit()){ ids = new ArrayList<>(ids.subList(0, parameter.getLimit())); } return getResponse(parameter, searchHits, ids); }catch (IOException e){ throw FoxtrotExceptions.createQueryExecutionException(parameter, e); } }</code><technical_language>This happen if applied filters expected results well</technical_language>

Target:
public ActionResponse execute(Query parameter) { if (parameter.isScrollRequest()) { return executeScrollRequest(parameter); } return executeRequest(parameter); }
Source:
<code>private boolean updateRngDevice() { if (!getParameters().isUpdateRngDevice()) { <START> return true; <END> } VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = runInternalAction(VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent()); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = runInternalAction(VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent()); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = runInternalAction(VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent()); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { return false; } return true; }</code><technical_language>this is a bit confusing - update (of VM) done way. this method return a result (logging done internally). I suggest change this method "void", this is done update graphics</technical_language>

Target:
private void updateRngDevice() { if (!getParameters().isUpdateRngDevice()) { return; } VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = runInternalAction(VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent()); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = runInternalAction(VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent()); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = runInternalAction(VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent()); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { log.error("Updating RNG device of VM ({}) failed. Old RNG device = {}. New RNG device = {}.", getVm().getName(), getVm().getId(), rngDevs.isEmpty() ? null : rngDevs.get(0), getParameters().getRngDevice()); } }
Source:
<code>protected void processRecord(ComputationContext context, Record record) { try { BulkCommand command = getBulkCommandJson(record.data); if (!kvStore.compareAndSet(record.key + STATE, SCHEDULED.toString(), BUILDING.toString())) { log.error("Discard record: " + record + " because it's already building"); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); docIds.forEach(docId -> context.produceRecord(command.getOperation(), record.key + '/' + docId, record.data)); documentCount += docIds.size(); scroll = session.scroll(scroll.getScrollId()); <START> TransactionHelper.commitOrRollbackTransaction(); <END> TransactionHelper.startTransaction(); } context.askForCheckpoint(); kvStore.put(record.key + STATE, COMPLETED.toString()); kvStore.put(record.key + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }</code><technical_language>ok for impl adding command in record is overhead millions of ids. option for next version is output record multiple ids. this point I if need a key instead of simply roundrobin partition if need command</technical_language>

Target:
protected void processRecord(ComputationContext context, Record record) { KeyValueStore kvStore = getKeyValueStore(); try { BulkCommand command = getBulkCommandJson(record.data); if (!kvStore.compareAndSet(record.key + STATE, SCHEDULED.toString(), BUILDING.toString())) { log.error("Discard record: " + record + " because it's already building"); return; } try (CloseableCoreSession session = CoreInstance.openCoreSession(command.getRepository(), command.getUsername())) { ScrollResult<String> scroll = session.scroll(command.getQuery(), scrollBatchSize, scrollKeepAliveSeconds); long documentCount = 0; while (scroll.hasResults()) { List<String> docIds = scroll.getResults(); docIds.forEach(docId -> context.produceRecord(command.getOperation(), record.key + '/' + docId, record.data)); documentCount += docIds.size(); context.askForCheckpoint(); scroll = session.scroll(scroll.getScrollId()); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } kvStore.put(record.key + STATE, COMPLETED.toString()); kvStore.put(record.key + SCROLLED_DOCUMENT_COUNT, documentCount); } } catch (NuxeoException e) { log.error("Discard invalid record: " + record, e); } }
Source:
<code>public void whenListVersionsListedOrdered() throws Exception { final EventTypeSchemaBase schemaBase = new EventTypeSchemaBase(EventTypeSchemaBase.Type.JSON_SCHEMA, "schema"); final EventType eventType = EventTypeTestBuilder.builder() .name("test_et_name_schemarepositorytest") .schema(new EventTypeSchema(schemaBase, "1.0.2", DateTime.now())) .build(); insertEventType(eventType); insertSchema(eventType); eventType.setSchema(new EventTypeSchema(schemaBase, "2.10.3", DateTime.now())); insertSchema(eventType); <START> eventType.setSchema(new EventTypeSchema(schemaBase, "10.0.0", DateTime.now())); <END> insertSchema(eventType); final List<EventTypeSchema> schemas = repository.getSchemas("test_et_name_schemarepositorytest", 0, 3); Assert.assertEquals(3, schemas.size()); Assert.assertEquals(new Version("10.0.0"), schemas.get(0).getVersion()); Assert.assertEquals(new Version("2.10.3"), schemas.get(1).getVersion()); Assert.assertEquals(new Version("1.0.2"), schemas.get(2).getVersion()); final int count = repository.getSchemasCount("test_et_name_schemarepositorytest"); Assert.assertEquals(3, count); }</code><technical_language>afraid this test fail if runs fast. If precision of DateTime.now() is low, generate lines 35, 39 41. sense</technical_language>

Target:
public void whenListVersionsListedOrdered() throws Exception { final EventTypeSchemaBase schemaBase = new EventTypeSchemaBase(EventTypeSchemaBase.Type.JSON_SCHEMA, "schema"); final EventType eventType = EventTypeTestBuilder.builder() .name("test_et_name_schemarepositorytest") .build(); insertEventType(eventType); eventType.setSchema(new EventTypeSchema(schemaBase, "1.0.2", DateTime.parse("2016-12-07T10:44:16.378+01:00"))); insertSchema(eventType); eventType.setSchema(new EventTypeSchema(schemaBase, "2.10.3", DateTime.parse("2016-12-07T10:54:16.778+01:00"))); insertSchema(eventType); eventType.setSchema(new EventTypeSchema(schemaBase, "10.0.0", DateTime.parse("2016-12-07T10:57:16.200+01:00"))); insertSchema(eventType); final List<EventTypeSchema> schemas = repository.getSchemas("test_et_name_schemarepositorytest", 0, 3); Assert.assertEquals(3, schemas.size()); Assert.assertEquals(new Version("10.0.0"), schemas.get(0).getVersion()); Assert.assertEquals(new Version("2.10.3"), schemas.get(1).getVersion()); Assert.assertEquals(new Version("1.0.2"), schemas.get(2).getVersion()); final int count = repository.getSchemasCount("test_et_name_schemarepositorytest"); Assert.assertEquals(3, count); }
Source:
<code>public void reloadConfig() { EventBuilder ebldr = new EventBuilder(EventConstants.RELOAD_DAEMON_CONFIG_SUCCESSFUL_UEI, getName()); ebldr.addParam(EventConstants.PARM_DAEMON_NAME, "DroolsCorrelationEngine-" + m_name); try { LOG.info("Reloading configuration for engine {}", m_name); EngineConfiguration cfg = JaxbUtils.unmarshal(EngineConfiguration.class, m_configPath); Optional<RuleSet> opt = cfg.getRuleSetCollection().stream().filter(rs -> rs.getName().equals(getName())).findFirst(); if (opt.isPresent()) { marshallStateToDisk(true); opt.get().updateEngine(this); initialize(); } else { ebldr.setUei(EventConstants.RELOAD_DAEMON_CONFIG_FAILED_UEI); ebldr.addParam(EventConstants.PARM_REASON, "RuleSet not found on " + m_configPath); } } catch (Exception e) { ebldr.setUei(EventConstants.RELOAD_DAEMON_CONFIG_FAILED_UEI); ebldr.addParam(EventConstants.PARM_REASON, e.getMessage()); } finally { <START> if (ebldr != null) sendEvent(ebldr.getEvent()); <END> } }</code><technical_language>ebldr null here</technical_language>

Target:
public void reloadConfig() { EventBuilder ebldr = new EventBuilder(EventConstants.RELOAD_DAEMON_CONFIG_SUCCESSFUL_UEI, getName()); ebldr.addParam(EventConstants.PARM_DAEMON_NAME, "DroolsCorrelationEngine-" + m_name); try { LOG.info("Reloading configuration for engine {}", m_name); EngineConfiguration cfg = JaxbUtils.unmarshal(EngineConfiguration.class, m_configPath); Optional<RuleSet> opt = cfg.getRuleSetCollection().stream().filter(rs -> rs.getName().equals(getName())).findFirst(); if (opt.isPresent()) { marshallStateToDisk(true); opt.get().updateEngine(this); initialize(); } else { ebldr.setUei(EventConstants.RELOAD_DAEMON_CONFIG_FAILED_UEI); ebldr.addParam(EventConstants.PARM_REASON, "RuleSet not found on " + m_configPath); } } catch (Exception e) { ebldr.setUei(EventConstants.RELOAD_DAEMON_CONFIG_FAILED_UEI); ebldr.addParam(EventConstants.PARM_REASON, e.getMessage()); } finally { sendEvent(ebldr.getEvent()); } }
Source:
<code>private long timeDelay(SyncTimer timer) { long start = System.currentTimeMillis(); timer.delay(); <START> return System.currentTimeMillis() - start; <END> }</code><technical_language>Technically speaking, "one-time" variables debug values. I set a breakpoint "at return statement" delay value. variable is inlined breakpoint harder. I this change simplifies JUnit5->JUnit4 migration :-/</technical_language>

Target:
private long timeDelay(SyncTimer timer) { long start = System.currentTimeMillis(); timer.delay(); long duration = System.currentTimeMillis() - start; return duration; }
Source:
<code>public CommitUpdate getCommitUpdate(long startTs) { Optional<IdentifiedVersion> startVersion = timestampMap.getStartVersion(startTs); Optional<CommitInfo> maybeCommitInfo = timestampMap.getCommitInfo(startTs); <START> checkConditionOrThrow(!maybeCommitInfo.isPresent() || !startVersion.isPresent(), <END> "start or commit info not processed for start timestamp"); CommitInfo commitInfo = maybeCommitInfo.get(); ClientLogEvents update = eventLog.getEventsBetweenVersions(startVersion, commitInfo.commitVersion()); if (update.clearCache()) { return ImmutableInvalidateAll.builder().build(); } return constructCommitUpdate(commitInfo, update.events()); }</code><technical_language>~~This a hard failure, a bug?~~ Actually, hard know, this is legitimate a leader switch cleared cache. Good catch</technical_language>

Target:
public CommitUpdate getCommitUpdate(long startTs) { Optional<IdentifiedVersion> startVersion = timestampStateStore.getStartVersion(startTs); Optional<CommitInfo> maybeCommitInfo = timestampStateStore.getCommitInfo(startTs); assertTrue(maybeCommitInfo.isPresent() && startVersion.isPresent(), "start or commit info not processed for start timestamp"); CommitInfo commitInfo = maybeCommitInfo.get(); ClientLogEvents update = eventLog.getEventsBetweenVersions(startVersion, commitInfo.commitVersion()); if (update.clearCache()) { return ImmutableInvalidateAll.builder().build(); } return createCommitUpdate(commitInfo, update.events()); }
Source:
<code>public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int horizontalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_horizontal_margin); <START> int verticalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_vertical_margin); <END> outRect.left = horizontalMargin; outRect.right = horizontalMargin; outRect.top = verticalMargin; outRect.bottom = verticalMargin; }</code><technical_language>cleaner export fields decoration class</technical_language>

Target:
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = horizontalMargin; outRect.right = horizontalMargin; outRect.top = verticalMargin; outRect.bottom = verticalMargin; }
Source:
<code>protected ScanInterpreter getInterpreter(final CommandLine cl, final String tableName, final Shell shellState) throws Exception { Class<? extends ScanInterpreter> clazz = null; try { if (cl.hasOption(interpreterOpt.getOpt())) { shellState.getReader().println( <START> "WARNING: Scan Interpreter option is deprecated and will be removed in 2.1.\n"); <END> clazz = AccumuloVFSClassLoader.loadClass(cl.getOptionValue(interpreterOpt.getOpt()), ScanInterpreter.class); } else if (cl.hasOption(formatterInterpeterOpt.getOpt())) { shellState.getReader().println( "WARNING: Scan Interpreter option is deprecated and will be removed in 2.1.\n"); clazz = AccumuloVFSClassLoader.loadClass(cl.getOptionValue(formatterInterpeterOpt.getOpt()), ScanInterpreter.class); } } catch (ClassNotFoundException e) { shellState.getReader().println("Interpreter class could not be loaded.\n" + e.getMessage()); } if (clazz == null) clazz = InterpreterCommand.getCurrentInterpreter(tableName, shellState); if (clazz == null) clazz = DefaultScanInterpreter.class; return clazz.newInstance(); }</code><technical_language>I deprecation is reasonable, keen promising removal in a non-major release. Shell commands public API me, treated way. '3.0' better. Also, if this is case, I remember I initial work shell I STDOUT result of command run, STDERR (or least, logger, configured STDERR) for informational stuff shell output of a command. In principle, this for scripting/automation, if shell retained design principle time I significant work it</technical_language>

Target:
protected ScanInterpreter getInterpreter(final CommandLine cl, final String tableName, final Shell shellState) throws Exception { Class<? extends ScanInterpreter> clazz = null; try { if (cl.hasOption(interpreterOpt.getOpt())) { Shell.log.warn( "Scan Interpreter option is deprecated and will be removed in a future version.\n"); clazz = AccumuloVFSClassLoader.loadClass(cl.getOptionValue(interpreterOpt.getOpt()), ScanInterpreter.class); } else if (cl.hasOption(formatterInterpeterOpt.getOpt())) { Shell.log.warn( "Scan Interpreter option is deprecated and will be removed in a future version.\n"); clazz = AccumuloVFSClassLoader.loadClass(cl.getOptionValue(formatterInterpeterOpt.getOpt()), ScanInterpreter.class); } } catch (ClassNotFoundException e) { shellState.getReader().println("Interpreter class could not be loaded.\n" + e.getMessage()); } if (clazz == null) clazz = InterpreterCommand.getCurrentInterpreter(tableName, shellState); if (clazz == null) clazz = DefaultScanInterpreter.class; return clazz.newInstance(); }
Source:
<code>public boolean appliesToAlert(Alert alert) { if (!isEnabled()) { log.debug("Filter disabled"); return false; } if (getRuleId() != alert.getPluginId()) { <START> log.debug( <END> "Filter didnt match plugin id: " + getRuleId() + " != " + alert.getPluginId()); return false; } if (!matchesStringOrRegex("URL", getUrl(), isUrlRegex(), alert.getUri())) { return false; } if (!matchesStringOrRegex( "Parameter", getParameter(), isParameterRegex(), alert.getParam())) { return false; } if (!matchesStringOrRegex("Attack", getAttack(), isAttackRegex(), alert.getAttack())) { return false; } if (!matchesStringOrRegex( "Evidence", getEvidence(), isEvidenceRegex(), alert.getEvidence())) { return false; } return true; }</code><technical_language>This others in matchesStringOrRegex check if debug is enabled (to avoid creating strings)</technical_language>

Target:
public boolean appliesToAlert(Alert alert) { if (!isEnabled()) { if (log.isDebugEnabled()) { log.debug("Filter disabled"); } return false; } if (getRuleId() != alert.getPluginId()) { if (log.isDebugEnabled()) { log.debug( "Filter didnt match plugin id: " + getRuleId() + " != " + alert.getPluginId()); } return false; } if (!matchesStringOrRegex("URL", getUrl(), isUrlRegex(), alert.getUri())) { return false; } if (!matchesStringOrRegex( "Parameter", getParameter(), isParameterRegex(), alert.getParam())) { return false; } if (!matchesStringOrRegex("Attack", getAttack(), isAttackRegex(), alert.getAttack())) { return false; } if (!matchesStringOrRegex( "Evidence", getEvidence(), isEvidenceRegex(), alert.getEvidence())) { return false; } return true; }
Source:
<code>public void testPrimaryOwnerChangingDuringRemove() throws Exception { <START> doTest(TestWriteOperation.REMOVE_EXACT); <END> }</code><technical_language>this _EXACT</technical_language>

Target:
public void testPrimaryOwnerChangingDuringRemove() throws Exception { doTest(TestWriteOperation.REMOVE); }
Source:
<code>public void testCookieForStateLessClientForAnonUser() throws HttpException, IOException { GlobalConfigurationResource settings = SettingsMessageUtil.getCurrentSettings(); settings.setSecurityAnonymousAccessEnabled( true ); SettingsMessageUtil.save( settings ); TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; Header header = new Header("User-Agent", "Java/1.6" ); HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod( url ); getMethod.addRequestHeader( header ); Assert.assertEquals( httpClient.executeMethod( getMethod ), 200 ); <START> <END> Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNull( sessionCookie, "Session Cookie is set" ); }</code><technical_language>method get released</technical_language>

Target:
public void testCookieForStateLessClientForAnonUser() throws HttpException, IOException { GlobalConfigurationResource settings = SettingsMessageUtil.getCurrentSettings(); settings.setSecurityAnonymousAccessEnabled( true ); SettingsMessageUtil.save( settings ); TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; Header header = new Header("User-Agent", "Java/1.6" ); HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod( url ); getMethod.addRequestHeader( header ); Assert.assertEquals( executeAndRelease( httpClient, getMethod ), 200 ); Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNull( sessionCookie, "Session Cookie is set" ); }
Source:
<code>public Collection<RepositoryResource> getMatchingResources(FilterPredicate... predicates) throws RepositoryBackendException { <START> ResourceCollector<RepositoryResource> resources = <END> new ResourceCollector<RepositoryResource>(DuplicatePolicy.ALLOW_DUPLICATES); Map<FilterableAttribute, Collection<String>> filters = new HashMap<FilterableAttribute, Collection<String>>(); for (FilterPredicate predicate : predicates) { filters.put(predicate.getAttribute(), predicate.getValues()); } RepositoryReadableClient client = createClient(); try { Collection<Asset> assets = client.getFilteredAssets(filters); for (Asset ass : assets) { RepositoryResource res = ResourceFactory.getInstance().createResourceFromAsset(ass, this); resources.add(res); } } catch (IOException ioe) { throw new RepositoryBackendIOException("Failed to obtain the assets from massive", ioe, this); } catch (RequestFailureException e) { throw new RepositoryBackendRequestFailureException(e, this); } return resources.getResourceCollection(); }</code><technical_language>I need a ResourceCollector here. A standard collection fine. ResourceCollector (IIRC) is for de-duplication. done hurt I need it</technical_language>

Target:
public Collection<RepositoryResource> getMatchingResources(FilterPredicate... predicates) throws RepositoryBackendException { List<RepositoryResource> resources = new ArrayList<RepositoryResource>(); Map<FilterableAttribute, Collection<String>> filters = new HashMap<FilterableAttribute, Collection<String>>(); for (FilterPredicate predicate : predicates) { filters.put(predicate.getAttribute(), predicate.getValues()); } RepositoryReadableClient client = createClient(); try { Collection<Asset> assets = client.getFilteredAssets(filters); for (Asset ass : assets) { RepositoryResource res = ResourceFactory.getInstance().createResourceFromAsset(ass, this); resources.add(res); } } catch (IOException ioe) { throw new RepositoryBackendIOException("Failed to obtain the assets from massive", ioe, this); } catch (RequestFailureException e) { throw new RepositoryBackendRequestFailureException(e, this); } return resources; }
Source:
<code>public DataSet<ExecRow> writeORCFile(int[] baseColumnMap, int[] partitionBy, String location, String compression, OperationContext context) { try { Dataset<Row> insertDF = SpliceSpark.getSession().createDataFrame( rdd.map(new SparkSpliceFunctionWrapper<>(new CountWriteFunction(context))).map(new LocatedRowToRowFunction()), context.getOperation().getExecRowDefinition().schema()); String[] partitionByCols = new String[partitionBy.length]; <START> StructField[] fields = context.getOperation().getExecRowDefinition().schema().fields(); <END> for (int i = 0; i < partitionBy.length; i++) { partitionByCols[i] = fields[partitionBy[i]].name(); } if (partitionBy.length > 0) { List<Column> repartitionCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { repartitionCols.add(new Column(fields[partitionBy[i]].name())); } insertDF = insertDF.repartition(scala.collection.JavaConversions.asScalaBuffer(repartitionCols).toList()); } insertDF.write().option(SPARK_COMPRESSION_OPTION,compression) .partitionBy(partitionByCols) .mode(SaveMode.Append).orc(location); ValueRow valueRow=new ValueRow(1); valueRow.setColumn(1,new SQLLongint(context.getRecordsWritten())); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>GetExecRowDefinition() is called lines 830 833, is some unnecessary overhead. save schema time re-use line 833</technical_language>

Target:
public DataSet<ExecRow> writeORCFile(int[] baseColumnMap, int[] partitionBy, String location, String compression, OperationContext context) { try { String[] colNames = ((DMLWriteOperation) context.getOperation()).getColumnNames(); DataValueDescriptor[] dvds = context.getOperation().getExecRowDefinition().getRowArray(); StructField[] fields = new StructField[colNames.length]; for (int i=0 ; i<colNames.length ; i++){ fields[i] = dvds[i].getStructField(colNames[i]); } StructType tableSchema = DataTypes.createStructType(fields); Dataset<Row> insertDF = SpliceSpark.getSession().createDataFrame( rdd.map(new SparkSpliceFunctionWrapper<>(new CountWriteFunction(context))).map(new LocatedRowToRowFunction()), tableSchema); String[] partitionByCols = new String[partitionBy.length]; for (int i = 0; i < partitionBy.length; i++) { partitionByCols[i] = colNames[partitionBy[i]]; } if (partitionBy.length > 0) { List<Column> repartitionCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { repartitionCols.add(new Column(colNames[partitionBy[i]])); } insertDF = insertDF.repartition(scala.collection.JavaConversions.asScalaBuffer(repartitionCols).toList()); } insertDF.write().option(SPARK_COMPRESSION_OPTION,compression) .partitionBy(partitionByCols) .mode(SaveMode.Append).orc(location); ValueRow valueRow=new ValueRow(1); valueRow.setColumn(1,new SQLLongint(context.getRecordsWritten())); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public OptimalAssignment convertFrom(ClusterModel clusterModel) { _optimalAssignableNodes = new ArrayList<>(clusterModel.getAssignableNodes().values()); return this; <START> } <END></code><technical_language>This depends PR #440, I think</technical_language>

Target:
public OptimalAssignment convertFrom(ClusterModel clusterModel) { return this; }
Source:
<code>private boolean addMedia(Uri mediaUri) { if (mediaUri != null && !MediaUtils.isInMediaStore(mediaUri) && !mediaUri.toString().startsWith("/")) { mediaUri = MediaUtils.downloadExternalMedia(this, mediaUri); } if (mediaUri == null) { return false; } boolean isVideo = MediaUtils.isVideo(mediaUri.toString()); <START> boolean isLocal = !URLUtil.isNetworkUrl(mediaUri.toString()); <END> trackAddMediaEvents(isVideo, false); if (mShowNewEditor) { return addMediaVisualEditor(mediaUri); } else { return addMediaLegacyEditor(mediaUri, isVideo); } }</code><technical_language>This variable is unused</technical_language>

Target:
private boolean addMedia(Uri mediaUri) { if (mediaUri != null && !MediaUtils.isInMediaStore(mediaUri) && !mediaUri.toString().startsWith("/")) { mediaUri = MediaUtils.downloadExternalMedia(this, mediaUri); } if (mediaUri == null) { return false; } boolean isVideo = MediaUtils.isVideo(mediaUri.toString()); trackAddMediaEvents(isVideo, false); if (mShowNewEditor) { return addMediaVisualEditor(mediaUri); } else { return addMediaLegacyEditor(mediaUri, isVideo); } }
Source:
<code>public JavaDocContextType() { addResolver(new GlobalTemplateVariables.Cursor()); addResolver(new <START> Selection(org.eclipse.jface.text.templates.GlobalTemplateVariables.LineSelection.NAME, <END> JavaTemplateMessages.CompilationUnitContextType_variable_description_line_selection)); addResolver(new Selection(org.eclipse.jface.text.templates.GlobalTemplateVariables.WordSelection.NAME, JavaTemplateMessages.JavaDocContextType_variable_description_word_selection)); addResolver(new GlobalTemplateVariables.Dollar()); addResolver(new GlobalTemplateVariables.Date()); addResolver(new GlobalTemplateVariables.Year()); addResolver(new GlobalTemplateVariables.Time()); addResolver(new GlobalTemplateVariables.User()); addResolver(new File()); addResolver(new PrimaryTypeName()); addResolver(new Method()); addResolver(new ReturnType()); addResolver(new Arguments()); addResolver(new Type()); addResolver(new Package()); addResolver(new Project()); }</code><technical_language>Please GlobalTemplateVariables.Selection</technical_language>

Target:
public JavaDocContextType() { addResolver(new GlobalTemplateVariables.Cursor()); addResolver(new GlobalTemplateVariables.Selection(GlobalTemplateVariables.LineSelection.NAME, JavaTemplateMessages.CompilationUnitContextType_variable_description_line_selection)); addResolver(new GlobalTemplateVariables.Selection(GlobalTemplateVariables.WordSelection.NAME, JavaTemplateMessages.JavaDocContextType_variable_description_word_selection)); addResolver(new GlobalTemplateVariables.Dollar()); addResolver(new GlobalTemplateVariables.Date()); addResolver(new GlobalTemplateVariables.Year()); addResolver(new GlobalTemplateVariables.Time()); addResolver(new GlobalTemplateVariables.User()); addResolver(new File()); addResolver(new PrimaryTypeName()); addResolver(new Method()); addResolver(new ReturnType()); addResolver(new Arguments()); addResolver(new Type()); addResolver(new Package()); addResolver(new Project()); }
Source:
<code>protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(StompWebSocketClientPageHandler.INSTANCE) .addLast(new WebSocketServerProtocolHandler(chatPath, StompVersion.SUB_PROTOCOLS)) <START> .addLast("stompWebSocketProtocolCodec", stompWebSocketProtocolCodec); <END> }</code><technical_language>nit: explicit name ? dont do this for other handlers well</technical_language>

Target:
protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(StompWebSocketClientPageHandler.INSTANCE) .addLast(new WebSocketServerProtocolHandler(chatPath, StompVersion.SUB_PROTOCOLS)) .addLast(stompWebSocketProtocolCodec); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); setContentView(R.layout.site_picker_activity); restoreSavedInstanceState(savedInstanceState); setupActionBar(); setupRecycleView(); <START> initSwipeToRefreshHelper(findViewById(android.R.id.content)); <END> }</code><technical_language>I noticed refresh indicator is preserved rotating device. slower connections confusing so, add support for rotation, wdyt? Thanks</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); setContentView(R.layout.site_picker_activity); restoreSavedInstanceState(savedInstanceState); setupActionBar(); setupRecycleView(); initSwipeToRefreshHelper(findViewById(android.R.id.content)); if (savedInstanceState != null) { mSwipeToRefreshHelper.setRefreshing(savedInstanceState.getBoolean(KEY_REFRESHING, false)); } }
Source:
<code>protected void prepareHandlers(Context context) { super.prepareHandlers(context); addHandler(Attributes.CheckBox.Text, new StringAttributeProcessor<T>() { @Override public void handle(ParserContext parserContext, String attributeKey, String attributeValue, T view) { view.setText(attributeValue); } }); addHandler(Attributes.TextView.TextColor, new StringAttributeProcessor<T>() { @Override public void handle(ParserContext parserContext, String attributeKey, String attributeValue, T view) { view.setTextColor(ParseHelper.parseColor(attributeValue)); } }); <START> addHandler(Attributes.CheckBox.Button , new ResourceReferenceProcessor<T>(context) { <END> @Override public void setDrawable(T view, Drawable drawable) { view.setButtonDrawable(drawable); } }); addHandler(Attributes.CheckBox.Checked, new StringAttributeProcessor<T>() { @Override public void handle(ParserContext parserContext, String attributeKey, String attributeValue, T view) { view.setChecked(Boolean.parseBoolean(attributeValue)); } }); }</code><technical_language>move button parser</technical_language>

Target:
protected void prepareHandlers(Context context) { super.prepareHandlers(context); addHandler(Attributes.CheckBox.Button , new ResourceReferenceProcessor<T>(context) { @Override public void setDrawable(T view, Drawable drawable) { view.setButtonDrawable(drawable); } }); addHandler(Attributes.CheckBox.Checked, new StringAttributeProcessor<T>() { @Override public void handle(ParserContext parserContext, String attributeKey, String attributeValue, T view) { view.setChecked(Boolean.parseBoolean(attributeValue)); } }); }
Source:
<code><START> public void RTEDisabledEditorEntryCKPreferredTests_002_MainEditEntry() { <END> ArticlePageObject article = base.openArticleByName(wikiURL, PageContent.articleNamePrefix + base.getTimeStamp()); SourceEditModePageObject src = article.openSrcModeWithMainEditButton(); src.verifySourceOnlyMode(); }</code><technical_language>Test RTEDisabledEditorEntryCKPreferredTests_002 RTEDisabledEditorEntryCKPreferredTests_001</technical_language>

Target:
public void RTEDisabledEditorEntryCKPreferredTests_002_MainEditEntry() { ArticlePageObject article = base.openArticleByName(wikiURL, PageContent.articleNamePrefix + base.getTimeStamp()); SourceEditModePageObject src = article.editArticleInSrcUsingDropdown(); src.verifySourceOnlyMode(); }
Source:
<code>public void addQueues(Queue... queues) { <START> this.addQueueNames(collectQueueNames(queues)); <END> }</code><technical_language>this. method calls; previous code bad; generally clean modifying code</technical_language>

Target:
public final void addQueues(Queue... queues) { addQueueNames(collectQueueNames(queues)); }
Source:
<code>private void assertDataIdentity() { Assert.assertEquals("Number of chunks should match", numChunks, compositeBuffers.size()); int i = 0; ByteBuffer dest = ByteBuffer.allocate(totalSizeWritten); for (Map.Entry<Integer, ByteBuffer> entry : compositeBuffers.entrySet()) { int j = entry.getKey(); <START> Assert.assertEquals("All chunks should have come in", i, j); <END> i++; ByteBuffer buf = entry.getValue(); buf.flip(); dest.put(buf); } Assert.assertTrue("Filled chunk contents must exactly match the input buffer ", Arrays.equals(putContent, dest.array())); }</code><technical_language>compositeBuffers a List</technical_language>

Target:
private void assertDataIdentity() { ByteBuffer dest = ByteBuffer.allocate(totalSizeWritten); for (ByteBuffer buf : compositeBuffers) { Assert.assertNotNull("All chunks should have come in", buf); buf.flip(); dest.put(buf); } Assert.assertTrue("Filled chunk contents must exactly match the input buffer ", Arrays.equals(putContent, dest.array())); }
Source:
<code>public Response systemScopesScopeNameGet(String scope, String username, MessageContext messageContext) throws APIManagementException { ScopeSettingsDTO scopeSettingsDTO = new ScopeSettingsDTO(); APIAdmin apiAdmin = new APIAdminImpl(); <START> String decodedScope = new String(Base64.getDecoder().decode(scope)); <END> boolean existence; if (username == null) { existence = apiAdmin.isScopeExists(RestApiUtil.getLoggedInUsername(), decodedScope); if (existence) { scopeSettingsDTO.setName(decodedScope); } else { throw new APIManagementException("Scope Not Found. Scope : " + decodedScope + ExceptionCodes.SCOPE_NOT_FOUND); } } else { existence = apiAdmin.isScopeExistsForUser(username, decodedScope); if (existence) { scopeSettingsDTO.setName(decodedScope); } else { throw new APIManagementException("User does not have scope. Username : " + username + " Scope : " + decodedScope, ExceptionCodes.SCOPE_NOT_FOUND_FOR_USER); } } return Response.ok().entity(scopeSettingsDTO).build(); }</code><technical_language>ExceptionCodes.SCOPE_NOT_FOUND a separate argument Constructor</technical_language>

Target:
public Response systemScopesScopeNameGet(String scope, String username, MessageContext messageContext) throws APIManagementException { ScopeSettingsDTO scopeSettingsDTO = new ScopeSettingsDTO(); APIAdmin apiAdmin = new APIAdminImpl(); String decodedScope = new String(Base64.getDecoder().decode(scope)); boolean existence; if (username == null) { existence = apiAdmin.isScopeExists(RestApiUtil.getLoggedInUsername(), decodedScope); if (existence) { scopeSettingsDTO.setName(decodedScope); } else { throw new APIManagementException("Scope Not Found. Scope : " + decodedScope, ExceptionCodes.SCOPE_NOT_FOUND); } } else { existence = apiAdmin.isScopeExistsForUser(username, decodedScope); if (existence) { scopeSettingsDTO.setName(decodedScope); } else { throw new APIManagementException("User does not have scope. Username : " + username + " Scope : " + decodedScope, ExceptionCodes.SCOPE_NOT_FOUND_FOR_USER); } } return Response.ok().entity(scopeSettingsDTO).build(); }