auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void commitAllConnection() { List<DataSource> listOfDataSource = new ArrayList<>(); for (DataSource dataSource : activeConnection.keySet()) { try { Connection connection = activeConnection.get(dataSource); if (connection != null) { listOfDataSource.add(dataSource); connection.commit(); } } catch (SQLException e) { log.error("Error occurred while committing the connection. Connection: " + activeConnection .get(dataSource) + ". We have committed few transaction before error occurs. Committed " + "dataSource are: " + listOfDataSource.toString(), e); } } }

Target:
void commitAllConnection() { StringBuilder commitErrorHandling = null; List<DataSource> listOfCommittedDataSource = null; HashMap<DataSource, Connection> rollBackConnections = null; for (Map.Entry entry : activeConnection.entrySet()) { try { Connection connection = (Connection) entry.getValue(); if (connection != null) { connection.commit(); } } catch (SQLException e) { if (commitErrorHandling.equals(null)) { commitErrorHandling = new StringBuilder(); } if (listOfCommittedDataSource.equals(null)) { listOfCommittedDataSource = new ArrayList<>(); } if (rollBackConnections.equals(null)) { rollBackConnections = new HashMap(); } for (Map.Entry activeEntry : activeConnection.entrySet()) { if (!entry.getKey().equals(activeEntry.getKey())) { listOfCommittedDataSource.add((DataSource) activeEntry.getKey()); } else { break; } } commitErrorHandling.append("Error occurred while committing the connection. Connection: ") .append(entry.getValue()) .append(". We have committed few transaction before error occurred. Committed dataSource : ") .append(listOfCommittedDataSource.toString()).append(". "); for (Map.Entry activeEntry : activeConnection.entrySet()) { if (!listOfCommittedDataSource.contains(activeEntry.getKey())) { rollBackConnections.put((DataSource) activeEntry.getKey(), (Connection) activeEntry.getValue()); } } internalRollbackConnection(rollBackConnections, commitErrorHandling); log.error(commitErrorHandling.toString(), e); } } }
Source:
public void testByte() throws Exception { runTest("test_flat_map/flat_map_byte.orc", TinyintType.TINYINT, getExpectedValues(Integer::byteValue)); }

Target:
public void testByte() throws Exception { runTest("test_flat_map/flat_map_byte.dwrf", TinyintType.TINYINT, ExpectedValuesBuilder.get(Integer::byteValue)); }
Source:
public String toString() { return "OutboundTransferTask{" + "topologyId=" + topologyId + ", destination=" + destination + ", segments=" + new IntSet(segments) + ", chunkSize=" + chunkSize + ", timeout=" + timeout + ", cacheName='" + cacheName + '\'' + '}'; }

Target:
public String toString() { return "OutboundTransferTask{" + "topologyId=" + topologyId + ", destination=" + destination + ", segments=" + new SmallIntSet(segments) + ", chunkSize=" + chunkSize + ", timeout=" + timeout + ", cacheName='" + cacheName + '\'' + '}'; }
Source:
public void selectParentCategory(int catValue) { waitForElementClickableByElement(mainParentCategorySelector); mainParentCategorySelector.click(); WebElement parentSelected = parentCatOption.get(catValue); waitForElementVisibleByElement(parentSelected); parentSelected.click(); }

Target:
public void selectParentCategory(int catValue) { waitForElementClickableByElement(mainParentCategorySelector); mainParentCategorySelector.click(); WebElement parentSelected = parentCatOption.get(catValue); waitForElementVisibleByElement(parentSelected); parentSelected.click(); PageObjectLogging.log("selectParentCategory", "Parent category selected", true); }
Source:
public Optional<FileReference> getManifest() { Path manifest = componentDirectory.resolve(FILE_NAME_MANIFEST); if (Files.exists(manifest)) { return Optional.of(new ArtifactFileReference(manifest, appReference)); } else { return Optional.empty(); } }

Target:
public Optional<FileReference> getManifest() { Path componentManifest = componentDirectory.resolve(FILE_NAME_MANIFEST); if (Files.exists(componentManifest)) { return Optional.of(new ArtifactFileReference(componentManifest, appReference)); } else { return Optional.empty(); } }
Source:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { boolean newFragment = false; if (newList.size() > currentList.size()) { newFragment = true; } return newFragment; }

Target:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { return (newList.size() > currentList.size()); }
Source:
public PlanNodeCostEstimate visitJoin(JoinNode node, Void context) { return calculateJoinCost( node.getLeft(), node.getRight(), node.getDistributionType().orElse(JoinNode.DistributionType.PARTITIONED).equals(JoinNode.DistributionType.REPLICATED)); }

Target:
public PlanNodeCostEstimate visitJoin(JoinNode node, Void context) { return calculateJoinCost( node.getLeft(), node.getRight(), Objects.equals(node.getDistributionType(), Optional.of(JoinNode.DistributionType.REPLICATED))); }
Source:
public void init(Context context) { TranslatorContext translatorContext = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); this.msgConverter = translatorContext.getMsgConverter(streamName); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTime = new SamzaHistogram(metricsRegistry, logicalOpId, TranslatorConstants.PROCESSING_TIME_NAME); inputEvents = metricsRegistry.newCounter(logicalOpId, TranslatorConstants.INPUT_EVENTS_NAME); inputEvents.clear(); queryInputEvents = metricsRegistry.newCounter(queryLogicalId, TranslatorConstants.INPUT_EVENTS_NAME); queryInputEvents.clear(); }

Target:
public void init(Context context) { TranslatorContext translatorContext = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); this.msgConverter = translatorContext.getMsgConverter(streamName); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTime = new SamzaHistogram(metricsRegistry, logicalOpId, TranslatorConstants.PROCESSING_TIME_NAME); queryInputEvents = metricsRegistry.newCounter(queryLogicalId, TranslatorConstants.INPUT_EVENTS_NAME); queryInputEvents.clear(); }
Source:
private ProgressIndicator createTaskIndicator() { ProgressIndicator indicator = new ProgressIndicator(1); indicator.progressProperty().bind(stateManager.tasksProgressBinding); indicator.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { TaskProgressDialog taskProgressDialog = new TaskProgressDialog(); taskProgressDialog.setTitle("Task progress"); Window dialogWindow = taskProgressDialog.getDialogPane().getScene().getWindow(); dialogWindow.setOnCloseRequest(windowEvent -> dialogWindow.hide()); taskProgressDialog.showAndWait(); } }); return indicator; }

Target:
private Group createTaskIndicator() { ProgressIndicator indicator = new ProgressIndicator(); indicator.getStyleClass().add("progress-indicatorToolbar"); indicator.progressProperty().bind(stateManager.getTasksProgress()); Tooltip someTasksRunning = new Tooltip(Localization.lang("Background Tasks are running")); Tooltip noTasksRunning = new Tooltip(Localization.lang("Background Tasks are done")); indicator.setTooltip(noTasksRunning); stateManager.getAnyTaskRunning().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue.booleanValue()) { indicator.setTooltip(someTasksRunning); } else { indicator.setTooltip(noTasksRunning); } } }); indicator.widthProperty().addListener((observable, oldValue, newValue) -> { if (!indicator.isIndeterminate()) { indicator.setPrefWidth(newValue.doubleValue()); } if (newValue.doubleValue() > 0) { Rectangle clip = new Rectangle(newValue.doubleValue(), newValue.doubleValue()); indicator.setClip(clip); } }); indicator.setOnMouseClicked(event -> { TaskProgressView taskProgressView = new TaskProgressView(); EasyBind.listBind(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(true); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); PopOver progressViewPopOver = new PopOver(taskProgressView); progressViewPopOver.setTitle(Localization.lang("Background Tasks")); progressViewPopOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_TOP); progressViewPopOver.show(indicator); }); return new Group(indicator); }
Source:
public void onJailBlockBreak(final BlockBreakEvent event) { final User user = ess.getUser(event.getPlayer()); if (user.isJailed() && !event.getPlayer().hasPermission("essentials.jail.allow-break")) { event.setCancelled(true); } }

Target:
public void onJailBlockBreak(final BlockBreakEvent event) { final User user = ess.getUser(event.getPlayer()); if (user.isJailed() && !user.isAuthorized("essentials.jail.allow-break")) { event.setCancelled(true); } }
Source:
public static Group map(DbGroup entity, Group template) { Group model = template != null ? template : new Group(); model.setName(entity.getName()); model.setId(entity.getId().toString()); if (!StringUtils.isEmpty(entity.getDomain())) { Domain dom = new Domain(); dom.setName(entity.getDomain()); dom.setId(DirectoryEntryIdUtils.encode(dom.getName())); } model.setDomainEntryId(DirectoryEntryIdUtils.encode(entity.getExternalId())); model.setNamespace(entity.getNamespace()); return model; }

Target:
public static Group map(DbGroup entity, Group template) { Group model = template != null ? template : new Group(); model.setName(entity.getName()); model.setId(entity.getId().toString()); if (!StringUtils.isEmpty(entity.getDomain())) { Domain dom = new Domain(); dom.setName(entity.getDomain()); dom.setId(DirectoryEntryIdUtils.encode(dom.getName())); model.setDomain(dom); } model.setDomainEntryId(DirectoryEntryIdUtils.encode(entity.getExternalId())); model.setNamespace(entity.getNamespace()); return model; }
Source:
public String getAbsolutePath() { if (artifactFile == null) { return ""; } return artifactFile.getAbsolutePath(); }

Target:
public String getAbsolutePath() { return (artifactFile == null) ? "" : artifactFile.getAbsolutePath(); }
Source:
public void testProjectNameBehindAFolderDisplayName() throws Exception { final String projectName1 = "job-1"; final String displayName1 = "job-1"; final String projectName2 = "job-2"; final String displayName2 = "job-2"; FreeStyleProject project1 = j.createFreeStyleProject(projectName1); project1.setDisplayName(displayName1); FreeStyleProject project2 = j.createFolder("my-folder-1").createProject(FreeStyleProject.class, projectName2); project2.setDisplayName(displayName2); WebClient wc = j.createWebClient(); Page result = wc.goTo("job/my-folder-1/search/suggest?query=" + projectName1, "application/json"); assertNotNull(result); j.assertGoodStatus(result); String content = result.getWebResponse().getContentAsString(); JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content); assertNotNull(jsonContent); JSONArray jsonArray = jsonContent.getJSONArray("suggestions"); assertNotNull(jsonArray); assertEquals(1, jsonArray.size()); boolean foundProjectName = false; boolean foundDisplayName = false; for(Object suggestion : jsonArray) { JSONObject jsonSuggestion = (JSONObject)suggestion; String name = (String)jsonSuggestion.get("name"); if(projectName1.equals(name)) { foundProjectName = true; } if(displayName1.equals(name)) { foundDisplayName = true; } } assertTrue(foundProjectName); assertTrue(foundDisplayName); }

Target:
public void testProjectNameBehindAFolderDisplayName() throws Exception { final String projectName1 = "job-1"; final String displayName1 = "job-1 display"; final String projectName2 = "job-2"; final String displayName2 = "job-2 display"; FreeStyleProject project1 = j.createFreeStyleProject(projectName1); project1.setDisplayName(displayName1); MockFolder myMockFolder = j.createFolder("my-folder-1"); FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2); project2.setDisplayName(displayName2); WebClient wc = j.createWebClient(); Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName1, "application/json"); assertNotNull(result); j.assertGoodStatus(result); String content = result.getWebResponse().getContentAsString(); JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content); assertNotNull(jsonContent); JSONArray jsonArray = jsonContent.getJSONArray("suggestions"); assertNotNull(jsonArray); assertEquals(2, jsonArray.size()); boolean foundDisplayName = false; for(Object suggestion : jsonArray) { JSONObject jsonSuggestion = (JSONObject)suggestion; String name = (String)jsonSuggestion.get("name"); if(projectName1.equals(name)) { foundDisplayName = true; } } assertTrue(foundDisplayName); }
Source:
public void testWhenDaemonIsUsedEndOfTheBuildIsNotReached() throws InterruptedException, TimeoutException { final InvocationRequest request = new DefaultInvocationRequest(); Invoker invoker = new DefaultInvoker(); request.setPomFile(new File(pathToJarSamplePom)); request.setGoals(Arrays.asList(new String[] { "clean", "verify" })); request.setProperties(getPropertiesWithSkipTests()); EmbeddedMaven .withMavenInvokerSet(request, invoker) .useAsDaemon() .build(); Thread.sleep(1000); Assertions.assertThat(outContent.toString()).contains("Embedded Maven build started"); Assertions.assertThat(outContent.toString()).doesNotContain("Embedded Maven build stopped"); }

Target:
public void testWhenDaemonIsUsedEndOfTheBuildIsNotReached() throws InterruptedException { final InvocationRequest request = new DefaultInvocationRequest(); Invoker invoker = new DefaultInvoker(); request.setPomFile(new File(pathToJarSamplePom)); request.setGoals(Arrays.asList(new String[] { "clean", "package" })); request.setProperties(getPropertiesWithSkipTests()); final DaemonBuild daemonBuild = EmbeddedMaven .withMavenInvokerSet(request, invoker) .useAsDaemon() .build(); Awaitility.await("Wait till maven build is started").atMost(5, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return outContent.toString().contains("Embedded Maven build started"); } }); Assertions.assertThat(outContent.toString()).doesNotContain("Embedded Maven build stopped"); Awaitility.await("Wait till project is not be null").atMost(20, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return daemonBuild.getBuiltProject() != null; } }); Assertions.assertThat(daemonBuild.isAlive()).isFalse(); }
Source:
public void azureCliCredentialAzNotLogInException() throws Exception { TokenRequestContext request = new TokenRequestContext().addScopes("AzureNotLogin"); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithAzureCli(request)) .thenReturn(Mono.error(new Exception("Azure not Login"))); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); AzureCliCredential credential = new AzureCliCredentialBuilder().build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof CredentialUnavailableException && e.getMessage().contains("Azure not Login")) .verify(); }

Target:
public void azureCliCredentialAzNotLogInException() throws Exception { TokenRequestContext request = new TokenRequestContext().addScopes("AzureNotLogin"); IdentityClient identityClient = PowerMockito.mock(IdentityClient.class); when(identityClient.authenticateWithAzureCli(request)) .thenReturn(Mono.error(new Exception("Azure not Login"))); PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient); AzureCliCredential credential = new AzureCliCredentialBuilder().build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof Exception && e.getMessage().contains("Azure not Login")) .verify(); }
Source:
public void provideUniquePodsNames() throws Exception { when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID); final HashMap<String, Pod> pods = new HashMap<>(); pods.put(POD_NAME, newPod()); doReturn(pods).when(osEnv).getPods(); uniqueNamesProvisioner.provision(environment, osEnv, runtimeIdentity); final String expected = WORKSPACE_ID + SEPARATOR + POD_NAME; assertEquals(osEnv.getPods().get(expected).getMetadata().getName(), expected); }

Target:
public void provideUniquePodsNames() throws Exception { when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID); final HashMap<String, Pod> pods = new HashMap<>(); pods.put(POD_NAME, newPod()); doReturn(pods).when(osEnv).getPods(); uniqueNamesProvisioner.provision(environment, osEnv, runtimeIdentity); final String expected = WORKSPACE_ID + SEPARATOR + POD_NAME; final ObjectMeta podMeta = osEnv.getPods().get(expected).getMetadata(); assertEquals(podMeta.getName(), expected); assertEquals(podMeta.getLabels().get(CHE_ORIGINAL_NAME_LABEL), POD_NAME); }
Source:
public boolean isApplicable(VDSGroup oldCluster, VDSGroup newCluster) { if (!newCluster.supportsVirtService() || !oldCluster.supportsVirtService()) { return true; } newCpuName = newCluster.getCpuName(); final String oldCpuName = oldCluster.getCpuName(); return !newCpuName.equals(oldCpuName); }

Target:
public boolean isApplicable(VDSGroup oldCluster, VDSGroup newCluster) { if (!newCluster.supportsVirtService() || !oldCluster.supportsVirtService()) { return false; } newCpuName = newCluster.getCpuName(); final String oldCpuName = oldCluster.getCpuName(); return !newCpuName.equals(oldCpuName); }
Source:
public void readsFromFile() throws IOException { final File file = new File(this.folder.newFolder(), "readable"); final String content = "read"; Files.write(content.getBytes(), file); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); new MkDoc(file, "", "").read(stream); MatcherAssert.assertThat( new String(stream.toByteArray()), Matchers.equalTo(content) ); }

Target:
public void readsFromFile() throws IOException { final File file = new File(this.folder.newFolder(), "readable"); final String content = "read"; Files.write(content.getBytes(StandardCharsets.UTF_8), file); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); new MkDoc(file, "", "").read(stream); MatcherAssert.assertThat( new String(stream.toByteArray(), StandardCharsets.UTF_8), Matchers.equalTo(content) ); }
Source:
public boolean start() throws Exception { if (step.label != null && !step.label.isEmpty() && step.resource != null && !step.resource.isEmpty()) { throw new Exception("Label and resource name cannot be specified simultaneously."); } if (step.label == null && LockableResourcesManager.get().createResource(step.resource)) { listener.getLogger().println("Resource [" + step + "] did not exist. Created."); } listener.getLogger().println("Trying to acquire lock on [" + step + "]"); List<String> resources = new ArrayList<String>(); if (step.resource != null) { resources.add(step.resource); } LockableResourcesStruct resourceHolder = new LockableResourcesStruct(resources, step.label, step.quantity); List<LockableResource> available = LockableResourcesManager.get().checkResourcesAvailability(resourceHolder, listener.getLogger(), null); if (available == null || !LockableResourcesManager.get().lock(available, run, getContext(), step.toString(), step.inversePrecedence)) { listener.getLogger().println("[" + step + "] is locked, waiting..."); LockableResourcesManager.get().queueContext(getContext(), resourceHolder, step.toString()); } return false; }

Target:
public boolean start() throws Exception { step.validate(); listener.getLogger().println("Trying to acquire lock on [" + step + "]"); List<String> resources = new ArrayList<String>(); if (step.resource != null) { if (LockableResourcesManager.get().createResource(step.resource)) { listener.getLogger().println("Resource [" + step + "] did not exist. Created."); } resources.add(step.resource); } LockableResourcesStruct resourceHolder = new LockableResourcesStruct(resources, step.label, step.quantity); List<LockableResource> available = LockableResourcesManager.get().checkResourcesAvailability(resourceHolder, listener.getLogger(), null); if (available == null || !LockableResourcesManager.get().lock(available, run, getContext(), step.toString(), step.inversePrecedence)) { listener.getLogger().println("[" + step + "] is locked, waiting..."); LockableResourcesManager.get().queueContext(getContext(), resourceHolder, step.toString()); } return false; }
Source:
public RemoteTableDescriptor<K, V> withReadRetryPolicy(TableRetryPolicy retryPolicy) { Preconditions.checkNotNull(readFn, "null read function"); Preconditions.checkNotNull(retryPolicy, "null retry policy"); this.readRetryPolicy = retryPolicy; this.readRetryPolicy.setTableId(String.format("%s.%s", tableId, READ_RETRY_POLICY)); return this; }

Target:
public RemoteTableDescriptor<K, V> withReadRetryPolicy(TableRetryPolicy retryPolicy) { Preconditions.checkNotNull(readFn, "null read function"); Preconditions.checkNotNull(retryPolicy, "null retry policy"); this.readRetryPolicy = retryPolicy; return this; }
Source:
private boolean writeNode(BinaryRawWriterEx writer, ClusterNode node) { if (node.isClient()) return false; Object port = node.attribute(ClientListenerProcessor.CLIENT_LISTENER_PORT); if (!(port instanceof Integer)) return false; writeUuid(writer, node.id()); writer.writeInt((int) port); Collection<String> addrs = node.addresses(); Collection<String> hosts = node.hostNames(); writer.writeInt(addrs.size() + hosts.size()); for (String addr : addrs) writer.writeString(addr); for (String host : hosts) writer.writeString(host); return true; }

Target:
private static boolean writeNode(BinaryRawWriterEx writer, ClusterNode node) { if (node.isClient()) return false; Object port = node.attribute(ClientListenerProcessor.CLIENT_LISTENER_PORT); if (!(port instanceof Integer)) return false; writeUuid(writer, node.id()); writer.writeInt((int) port); Collection<String> addrs = node.addresses(); Collection<String> hosts = node.hostNames(); writer.writeInt(addrs.size() + hosts.size()); for (String addr : addrs) writer.writeString(addr); for (String host : hosts) writer.writeString(host); return true; }
Source:
public void first_withDefault() { AllJavaTypes defaultObject = collection.get(0); collection = createEmptyCollection(realm, collectionClass); assertEquals(defaultObject, collection.first(defaultObject)); assertEquals(null, collection.first(null)); }

Target:
public void first_withDefault() { AllJavaTypes defaultObject = new AllJavaTypes(); collection = createEmptyCollection(realm, collectionClass); assertEquals(defaultObject, collection.first(defaultObject)); assertEquals(null, collection.first(null)); }
Source:
@NotNull private Runnable textQueryTask(IgniteEx ignite, String clause, Set<Integer> exp) { return () -> { try { TextQuery qry = new TextQuery<>(Person.class, clause).setLocal(false); validateQueryResults(ignite, qry, exp, false); } catch (Exception e) { fail(e.getMessage()); } }; }

Target:
@NotNull private Runnable textQueryTask(IgniteEx ignite, String clause, Set<Integer> exp) { return () -> { try { TextQuery qry = new TextQuery<>(Person.class, clause); validateQueryResults(ignite, qry, exp, false); } catch (Exception e) { fail(e.getMessage()); } }; }
Source:
public void write( @Suspended AsyncResponse asyncResponse, @PathParam("tenantId") String tenantId, List<InfluxObject> influxObjects ) { LOG.info("WRITE REQUEST"); if (influxObjects == null) { asyncResponse.resume(errorResponse(BAD_REQUEST, "Null objects")); return; } try { objectValidator.validateInfluxObjects(influxObjects); } catch (InvalidObjectException e) { asyncResponse.resume(errorResponse(BAD_REQUEST, Throwables.getRootCause(e).getMessage())); return; } Observable<GaugeMetric> input = Observable.from(influxObjects) .map(InfluxSeriesHandler::influxToGauge) .map(gauge -> gauge.setTenantId(tenantId)); metricsService.addGaugeData(input).subscribe(new WriteObserver(asyncResponse)); }

Target:
public void write( @Suspended AsyncResponse asyncResponse, @PathParam("tenantId") String tenantId, List<InfluxObject> influxObjects ) { if (influxObjects == null) { asyncResponse.resume(errorResponse(BAD_REQUEST, "Null objects")); return; } try { objectValidator.validateInfluxObjects(influxObjects); } catch (InvalidObjectException e) { asyncResponse.resume(errorResponse(BAD_REQUEST, Throwables.getRootCause(e).getMessage())); return; } Observable<Metric<Double>> input = Observable.from(influxObjects) .map(influxObject -> influxToGauge(tenantId, influxObject)); metricsService.addGaugeData(input).subscribe(new WriteObserver(asyncResponse)); }
Source:
private SettingsGroup makeRenameGroup() { JCheckBox renameCaseSensitive = new JCheckBox(); renameCaseSensitive.setSelected(settings.isRenameCaseSensitive()); renameCaseSensitive.addItemListener(e -> { settings.setRenameCaseSensitive(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); JCheckBox renameValid = new JCheckBox(); renameValid.setSelected(settings.isRenameValid()); renameValid.addItemListener(e -> { settings.setRenameValid(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); JCheckBox renamePrintable = new JCheckBox(); renamePrintable.setSelected(settings.isRenamePrintable()); renamePrintable.addItemListener(e -> { settings.setRenamePrintable(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); SettingsGroup group = new SettingsGroup(NLS.str("preferences.rename")); JLabel renameCaseSensitiveLabel = group.addRow(NLS.str("preferences.rename_case"), renameCaseSensitive); group.addRow(NLS.str("preferences.rename_valid"), renameValid); group.addRow(NLS.str("preferences.rename_printable"), renamePrintable); File dir = FileUtils.createTempDir("jadx"); if (FileUtils.isCaseSensitiveFS(dir)) { renameCaseSensitive.setSelected(false); renameCaseSensitive.setEnabled(false); renameCaseSensitiveLabel.setEnabled(false); } try { Files.delete(dir.toPath()); } catch (IOException e) { } return group; }

Target:
private SettingsGroup makeRenameGroup() { JCheckBox renameCaseSensitive = new JCheckBox(); renameCaseSensitive.setSelected(settings.isRenameCaseSensitive()); renameCaseSensitive.addItemListener(e -> { settings.setRenameCaseSensitive(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); JCheckBox renameValid = new JCheckBox(); renameValid.setSelected(settings.isRenameValid()); renameValid.addItemListener(e -> { settings.setRenameValid(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); JCheckBox renamePrintable = new JCheckBox(); renamePrintable.setSelected(settings.isRenamePrintable()); renamePrintable.addItemListener(e -> { settings.setRenamePrintable(e.getStateChange() == ItemEvent.SELECTED); needReload(); }); SettingsGroup group = new SettingsGroup(NLS.str("preferences.rename")); group.addRow(NLS.str("preferences.rename_case"), renameCaseSensitive); group.addRow(NLS.str("preferences.rename_valid"), renameValid); group.addRow(NLS.str("preferences.rename_printable"), renamePrintable); return group; }
Source:
public void testExplicitCloseFrameSentWhenServerChannelClosed() throws Exception { WebSocketCloseStatus closeStatus = WebSocketCloseStatus.ENDPOINT_UNAVAILABLE; EmbeddedChannel client = createClient(); EmbeddedChannel server = createServer(); assertFalse(server.writeInbound(client.readOutbound())); assertFalse(client.writeInbound(server.readOutbound())); server.writeOutbound(new CloseWebSocketFrame(closeStatus)); server.close(); assertTrue(client.writeInbound(server.readOutbound())); assertFalse(server.isOpen()); CloseWebSocketFrame closeMessage = client.readInbound(); assertEquals(closeMessage.statusCode(), closeStatus.code()); closeMessage.release(); client.close(); assertTrue(ReferenceCountUtil.release(client.readOutbound())); assertFalse(client.finishAndReleaseAll()); assertFalse(server.finishAndReleaseAll()); }

Target:
public void testExplicitCloseFrameSentWhenServerChannelClosed() throws Exception { WebSocketCloseStatus closeStatus = WebSocketCloseStatus.ENDPOINT_UNAVAILABLE; EmbeddedChannel client = createClient(); EmbeddedChannel server = createServer(); assertFalse(server.writeInbound(client.readOutbound())); assertFalse(client.writeInbound(server.readOutbound())); assertTrue(server.writeOutbound(new CloseWebSocketFrame(closeStatus))); server.close(); assertTrue(client.writeInbound(server.readOutbound())); assertFalse(server.isOpen()); CloseWebSocketFrame closeMessage = client.readInbound(); assertEquals(closeMessage.statusCode(), closeStatus.code()); closeMessage.release(); client.close(); assertTrue(ReferenceCountUtil.release(client.readOutbound())); assertFalse(client.finishAndReleaseAll()); assertFalse(server.finishAndReleaseAll()); }
Source:
private JsonReportWriter( final Path outputDir, final String testClassName, final String testName) { this.testClassName = testClassName; this.testName = testName; final String logFilename = format("%s.%s.json", testClassName, testName).replace('$', '_'); final File logFile = outputDir.resolve(logFilename).toFile(); JsonGenerator jg = null; try { jg = new JsonFactory().createGenerator(logFile, JsonEncoding.UTF8); jg.writeStartArray(); } catch (IOException e) { log.error("exception creating event log: - {}", logFile.getAbsolutePath(), e); } finally { this.jg = jg; } }

Target:
private JsonReportWriter( final Path outputDir, final String testClassName, final String testName) { this.testClassName = testClassName; this.testName = testName; final String logFilename = format("%s.%s.json", testClassName, testName).replace('$', '_'); final File logFile = outputDir.resolve(logFilename).toFile(); JsonGenerator jg = null; try { jg = new JsonFactory().createGenerator(logFile, JsonEncoding.UTF8); jg.writeStartArray(); } catch (IOException e) { log.error("exception creating event log: - {}", logFile.getAbsolutePath(), e); } this.jg = jg; }
Source:
public String getCurrencyName() { if (currencyCode.equalsIgnoreCase("VES")) { return "Venezuelan Bolívar"; } if (currencyCode.equalsIgnoreCase("USDC")) { return "USD Coin (USDC)"; } if (currencyName == null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { currencyName = getCurrency().getDisplayName(); } else { currencyName = ""; } } return currencyName; }

Target:
public String getCurrencyName() { if (currencyCode.equalsIgnoreCase("VES")) { return "Venezuelan Bolívar"; } if (currencyName == null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { currencyName = getCurrency().getDisplayName(); } else { currencyName = ""; } } return currencyName; }
Source:
private boolean[] determineSlotsAndDispatchables(final Object[] mixins, final HashSet<SlotDefinition> instanceSlots, final HashMap<SSymbol, Dispatchable> dispatchables) { boolean mixinsIncludeValue = false; boolean mixinsIncludeTransferObject = false; if (mixins != null) { HashMap<SSymbol, SlotDefinition> mixinSlots = new HashMap<>(); for (int i = 1; i < mixins.length; i++) { SClass mixin = (SClass) mixins[i]; if (mixin == Classes.valueClass) { mixinsIncludeValue = true; } else if (mixin == Classes.transferClass) { mixinsIncludeTransferObject = true; } MixinDefinition cdef = mixin.getMixinDefinition(); if (cdef.slots != null) { mixinSlots.putAll(cdef.slots); } for (Entry<SSymbol, Dispatchable> e : cdef.instanceDispatchables.entrySet()) { if (!e.getValue().isInitializer()) { dispatchables.put(e.getKey(), e.getValue()); } } SInitializer mixinInit = cdef.assembleMixinInitializer(i, this); dispatchables.put(mixinInit.getSignature(), mixinInit); } instanceSlots.addAll(mixinSlots.values()); dispatchables.putAll(instanceScope.getDispatchables()); if (slots != null) { instanceSlots.addAll(slots.values()); } } else { dispatchables.putAll(instanceScope.getDispatchables()); } if (slots != null) { instanceSlots.addAll(slots.values()); } return new boolean[] {mixinsIncludeValue, mixinsIncludeTransferObject}; }

Target:
private boolean[] determineSlotsAndDispatchables(final Object[] mixins, final HashSet<SlotDefinition> instanceSlots, final HashMap<SSymbol, Dispatchable> dispatchables) { boolean mixinsIncludeValue = false; boolean mixinsIncludeTransferObject = false; if (mixins != null) { HashMap<SSymbol, SlotDefinition> mixinSlots = new HashMap<>(); for (int i = 1; i < mixins.length; i++) { SClass mixin = (SClass) mixins[i]; if (mixin == Classes.valueClass) { mixinsIncludeValue = true; } else if (mixin == Classes.transferClass) { mixinsIncludeTransferObject = true; } MixinDefinition cdef = mixin.getMixinDefinition(); if (cdef.slots != null) { mixinSlots.putAll(cdef.slots); } for (Entry<SSymbol, Dispatchable> e : cdef.instanceDispatchables.entrySet()) { if (!e.getValue().isInitializer()) { dispatchables.put(e.getKey(), e.getValue()); } } SInitializer mixinInit = cdef.assembleMixinInitializer(i); dispatchables.put(mixinInit.getSignature(), mixinInit); } instanceSlots.addAll(mixinSlots.values()); dispatchables.putAll(instanceScope.getDispatchables()); if (slots != null) { instanceSlots.addAll(slots.values()); } } else { dispatchables.putAll(instanceScope.getDispatchables()); } if (slots != null) { instanceSlots.addAll(slots.values()); } return new boolean[] {mixinsIncludeValue, mixinsIncludeTransferObject}; }
Source:
private Map<String, Object> getKieMap() { try { Map<String, Object> kieMap = (Map) container.lookup(Map.class, "java.util.HashMap", "kieMap"); return Optional.ofNullable(kieMap).orElse(Collections.emptyMap()); } catch (ComponentLookupException cle) { getLog().info("kieMap not present with compilationID and container present"); return Collections.emptyMap(); } }

Target:
private Map<String, Object> getKieMap() { try { Map<String, Object> kieMap = (Map) container.lookup(Map.class, "java.util.HashMap", "kieMap"); return Optional.ofNullable(kieMap).orElse(Collections.emptyMap()); } catch (ComponentLookupException cle) { getLog().info("kieMap not present"); return Collections.emptyMap(); } }
Source:
public void logins() throws IOException { final String tokenpath = "/uas/oauth2/accessToken"; final String peoplepath = "/v1/people"; final String firstname = "firstName"; final String lastname = "lastName"; final String frodo = "Frodo"; final String baggins = "Baggins"; final String code = RandomStringUtils.randomAlphanumeric(10); final String lapp = RandomStringUtils.randomAlphanumeric(10); final String lkey = RandomStringUtils.randomAlphanumeric(10); final String identifier = RandomStringUtils.randomAlphanumeric(10); final Take take = new TkFork( new FkRegex( tokenpath, new TokenTake(code, lapp, lkey, tokenpath) ), new FkRegex( peoplepath, new PeopleTake(identifier, firstname, lastname, frodo, baggins) ) ); new FtRemote(take).exec( new LinkedinScript( code, lapp, lkey, identifier, firstname, lastname, frodo, baggins ) ); }

Target:
public void logins() throws IOException { final String tokenpath = "/uas/oauth2/accessToken"; final String firstname = "firstName"; final String lastname = "lastName"; final String frodo = "Frodo"; final String baggins = "Baggins"; final String code = RandomStringUtils.randomAlphanumeric(10); final String lapp = RandomStringUtils.randomAlphanumeric(10); final String lkey = RandomStringUtils.randomAlphanumeric(10); final String identifier = RandomStringUtils.randomAlphanumeric(10); final Take take = new TkFork( new FkRegex( tokenpath, new TokenTake(code, lapp, lkey, tokenpath) ), new FkRegex( "/v1/people", new PeopleTake(identifier, firstname, lastname, frodo, baggins) ) ); new FtRemote(take).exec( new LinkedinScript( code, lapp, lkey, identifier, firstname, lastname, frodo, baggins ) ); }
Source:
public RelDistribution toDistribution(Map<String, Object> map) { final RelDistribution.Type type = Util.enumVal(RelDistribution.Type.class, (String) map.get("type")); ImmutableIntList list = EMPTY; if (map.containsKey("keys")) { List<Object> keysJson = (List<Object>) map.get("keys"); ArrayList<Integer> keys = new ArrayList<>(keysJson.size()); for (Object o : keysJson) { keys.add((Integer) o); } list = ImmutableIntList.copyOf(keys); } return RelDistributions.with(type, list); }

Target:
public RelDistribution toDistribution(Map<String, Object> map) { final RelDistribution.Type type = Util.enumVal(RelDistribution.Type.class, (String) map.get("type")); ImmutableIntList list = EMPTY; if (map.containsKey("keys")) { List<Object> keysJson = (List<Object>) map.get("keys"); ArrayList<Integer> keys = new ArrayList<>(keysJson.size()); for (Object o : keysJson) { keys.add((Integer) o); } list = ImmutableIntList.copyOf(keys); } return RelDistributions.of(type, list); }
Source:
private void saveSyntaxHighlighting(SensorContext context, List<HighlightingData> highlightingDataList, InputFile inputFile) { NewHighlighting highlighting = context.newHighlighting().onFile(inputFile); for (HighlightingData highlightingData : highlightingDataList) { highlighting.highlight(highlightingData.startOffset(), highlightingData.endOffset(), highlightingData.highlightCode()); } highlighting.save(); }

Target:
private static void saveSyntaxHighlighting(SensorContext context, List<HighlightingData> highlightingDataList, InputFile inputFile) { NewHighlighting highlighting = context.newHighlighting().onFile(inputFile); for (HighlightingData highlightingData : highlightingDataList) { highlighting.highlight(highlightingData.startOffset(), highlightingData.endOffset(), highlightingData.highlightCode()); } highlighting.save(); }
Source:
public WebServer(Config config) { initServer(config); ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); int sessionTimeout = config.getInteger("web.sessionTimeout"); if (sessionTimeout > 0) { servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout); } initApi(config, servletHandler); if (config.getBoolean("web.console")) { servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*"); } initWebApp(config, servletHandler); servletHandler.setErrorHandler(new ErrorHandler() { @Override protected void handleErrorPage( HttpServletRequest request, Writer writer, int code, String message) throws IOException { writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>" + code + " - " + HttpStatus.getMessage(code) + "</body></html>"); } }); HandlerList handlers = new HandlerList(); initClientProxy(config, handlers); handlers.addHandler(servletHandler); handlers.addHandler(new GzipHandler()); server.setHandler(handlers); if (config.getBoolean("web.logRequests")) { NCSARequestLog requestLog = new NCSARequestLog("./logs/jetty-yyyy_mm_dd.request.log"); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogTimeZone("GMT"); requestLog.setLogLatency(true); requestLog.setRetainDays(7); server.setRequestLog(requestLog); } }

Target:
public WebServer(Config config) { initServer(config); ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); int sessionTimeout = config.getInteger("web.sessionTimeout"); if (sessionTimeout > 0) { servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout); } initApi(config, servletHandler); if (config.getBoolean("web.console")) { servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*"); } initWebApp(config, servletHandler); servletHandler.setErrorHandler(new ErrorHandler() { @Override protected void handleErrorPage( HttpServletRequest request, Writer writer, int code, String message) throws IOException { writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>" + code + " - " + HttpStatus.getMessage(code) + "</body></html>"); } }); HandlerList handlers = new HandlerList(); initClientProxy(config, handlers); handlers.addHandler(servletHandler); handlers.addHandler(new GzipHandler()); server.setHandler(handlers); if (config.getBoolean(Keys.WEB_REQUEST_LOG_ENABLE)) { NCSARequestLog requestLog = new NCSARequestLog(config.getString(Keys.WEB_REQUEST_LOG_PATH)); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogLatency(true); requestLog.setRetainDays(config.getInteger(Keys.WEB_REQUEST_LOG_RETAIN_DAYS)); server.setRequestLog(requestLog); } }
Source:
private void handleTitlePanel(String eventType, Element parent) { if (title == "") { return; } titlePanel.setWidget(new Label(title)); if (BrowserEvents.MOUSEOVER.equals(eventType)) { titlePanel.showRelativeTo(parent); } else if (BrowserEvents.MOUSEOUT.equals(eventType)) { titlePanel.hide(); } }

Target:
private void handleTitlePanel(String eventType, Element parent) { if (title.isEmpty()) { return; } titlePanel.setWidget(new Label(title)); if (BrowserEvents.MOUSEOVER.equals(eventType)) { titlePanel.showRelativeTo(parent); } else if (BrowserEvents.MOUSEOUT.equals(eventType)) { titlePanel.hide(); } }
Source:
protected IStatus run(IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 3); String javaVersion = getUrlSafeProperty("java.version"); String operatingSystem = getUrlSafeProperty("os.name"); String operatingSystemVersion = getUrlSafeProperty("os.version"); String proxyProvider = ProxySelector.getDefaultProvider(); try { URI proxyTestUri = new URL(PROXY_TEST_URL).toURI(); String proxyHostConfigured = getProxyHost(proxyTestUri).isPresent() ? "proxy-host-configured" : "noProxyHostConfigured"; String proxyUsernameConfigured = Proxies.getProxyUser(proxyTestUri).isPresent() ? "proxyUsernameConfigured" : "noProxyUsernameConfigured"; String proxyPasswordConfigured = Proxies.getProxyPassword(proxyTestUri).isPresent() ? "proxyPasswordConfigured" : "noProxyPasswordConfigured"; String authentication = getRequiredAuthentication(proxyTestUri, progress.newChild(1)); doApacheHeadRequest(toUri(format(REQUEST_URL, APACHE_HTTP_REQUEST_PART, javaVersion, operatingSystem, operatingSystemVersion, proxyProvider, authentication, proxyHostConfigured, proxyUsernameConfigured, proxyPasswordConfigured)), progress.newChild(1)); doP2HeadRequest(toUri(format(REQUEST_URL, P2_HTTP_REQUEST_PART, javaVersion, operatingSystem, operatingSystemVersion, proxyProvider, authentication, proxyHostConfigured, proxyUsernameConfigured, proxyPasswordConfigured)), progress.newChild(1)); } catch (Exception e) { Logs.log(LogMessages.ERROR_NETWORK_COMMUNICATION_URL_PARSING_FAILED, e); } return Status.OK_STATUS; }

Target:
protected IStatus run(IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 3); String javaVersion = getUrlSafeProperty("java.version"); String operatingSystem = getUrlSafeProperty("os.name"); String operatingSystemVersion = getUrlSafeProperty("os.version"); String proxyProvider = ProxySelector.getDefaultProvider(); try { URI proxyTestUri = new URL(PROXY_TEST_URL).toURI(); String proxyHostConfigured = getProxyHost(proxyTestUri).isPresent() ? "proxyHost" : "noProxyHost"; String proxyUsernameConfigured = Proxies.getProxyUser(proxyTestUri).isPresent() ? "proxyUsername" : "noProxyUsername"; String proxyPasswordConfigured = Proxies.getProxyPassword(proxyTestUri).isPresent() ? "proxyPassword" : "noProxyPassword"; String authentication = getRequiredAuthentication(proxyTestUri, progress.newChild(1)); doApacheHeadRequest(toUri(format(REQUEST_URL, APACHE_HTTP_REQUEST_PART, javaVersion, operatingSystem, operatingSystemVersion, proxyProvider, authentication, proxyHostConfigured, proxyUsernameConfigured, proxyPasswordConfigured)), progress.newChild(1)); doP2HeadRequest(toUri(format(REQUEST_URL, P2_HTTP_REQUEST_PART, javaVersion, operatingSystem, operatingSystemVersion, proxyProvider, authentication, proxyHostConfigured, proxyUsernameConfigured, proxyPasswordConfigured)), progress.newChild(1)); } catch (Exception e) { Logs.log(LogMessages.ERROR_NETWORK_COMMUNICATION_URL_PARSING_FAILED, e); } return Status.OK_STATUS; }
Source:
public void testParsePureUnit() { assertThat(UnitUtils.parseUnit("°F"), is(ImperialUnits.FAHRENHEIT)); assertThat(UnitUtils.parseUnit("m"), is(SIUnits.METRE)); assertThat(UnitUtils.parseUnit("%"), is(SmartHomeUnits.PERCENT)); }

Target:
public void testParsePureUnit() { assertThat(UnitUtils.parseUnit("DU"), is(SmartHomeUnits.DOBSON_UNIT)); assertThat(UnitUtils.parseUnit("°F"), is(ImperialUnits.FAHRENHEIT)); assertThat(UnitUtils.parseUnit("m"), is(SIUnits.METRE)); assertThat(UnitUtils.parseUnit("%"), is(SmartHomeUnits.PERCENT)); }
Source:
private Object getEntityFieldAsObject(JsonNode parentNode, String fieldName) { JsonNode valueNode = parentNode.get(fieldName); if (!TablesConstants.METADATA_KEYS.contains(fieldName) && !fieldName.endsWith("@odata.type")) { JsonNode typeNode = parentNode.get(fieldName + "@odata.type"); if (typeNode != null) { String type = typeNode.asText(); switch (type) { case "Edm.DateTime": try { return OffsetDateTime.parse(valueNode.asText()); } catch (DateTimeParseException e) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "'%s' value is not a valid OffsetDateTime.", TablesConstants.TIMESTAMP_KEY), e)); } default: logger.warning("'%s' value has unknown OData type '%s'", fieldName, type); break; } } } return valueNode.asText(); }

Target:
private Object getEntityFieldAsObject(JsonNode parentNode, String fieldName) { JsonNode valueNode = parentNode.get(fieldName); if (!TablesConstants.METADATA_KEYS.contains(fieldName) && !fieldName.endsWith("@odata.type")) { JsonNode typeNode = parentNode.get(fieldName + "@odata.type"); if (typeNode != null) { String type = typeNode.asText(); switch (type) { case "Edm.DateTime": try { return OffsetDateTime.parse(valueNode.asText()); } catch (DateTimeParseException e) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "'%s' value is not a valid OffsetDateTime.", TablesConstants.TIMESTAMP_KEY), e)); } default: logger.warning(String.format("'%s' value has unknown OData type '%s'", fieldName, type)); break; } } } return valueNode.asText(); }
Source:
public Response chatStatus() { if (!sessionController.isLoggedIn()) { return Response.status(Status.FORBIDDEN).entity("Must be logged in").build(); } SchoolDataIdentifier identifier = sessionController.getLoggedUser(); if (identifier == null) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Couldn't find logged user").build(); } String enabledUsersCsv = pluginSettingsController.getPluginSetting("chat", "enabledUsers"); if (enabledUsersCsv == null) { return null; } List<String> enabledUsers = Arrays.asList(enabledUsersCsv.split(",")); boolean chatEnabled = false; if (!enabledUsers.contains(identifier.toId())) { return Response.ok(new StatusRESTModel(false, false, null)).build(); } UserChatSettings userChatSettings = chatController.findUserChatSettings(identifier); if (userChatSettings != null) { UserChatVisibility visibility = userChatSettings.getVisibility(); if (visibility.toString().equals("VISIBLE_TO_ALL")) { chatEnabled = true; } } User user = userController.findUserByIdentifier(identifier); if (user == null) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Logged user doesn't exist").build(); } if (chatEnabled) { return Response.ok(new StatusRESTModel(true, true, user.getDisplayName())).build(); } else { return Response.ok(new StatusRESTModel(false, true, null)).build(); } }

Target:
public Response chatStatus() { if (!sessionController.isLoggedIn()) { return Response.status(Status.FORBIDDEN).entity("Must be logged in").build(); } SchoolDataIdentifier identifier = sessionController.getLoggedUser(); if (identifier == null) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Couldn't find logged user").build(); } String enabledUsersCsv = pluginSettingsController.getPluginSetting("chat", "enabledUsers"); if (enabledUsersCsv == null) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } List<String> enabledUsers = Arrays.asList(enabledUsersCsv.split(",")); boolean chatEnabled = false; if (!enabledUsers.contains(identifier.toId())) { return Response.ok(new StatusRESTModel(false, false, null)).build(); } UserChatSettings userChatSettings = chatController.findUserChatSettings(identifier); if (userChatSettings != null) { UserChatVisibility visibility = userChatSettings.getVisibility(); if (visibility == UserChatVisibility.VISIBLE_TO_ALL) { chatEnabled = true; } } User user = userController.findUserByIdentifier(identifier); if (user == null) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Logged user doesn't exist").build(); } if (chatEnabled) { return Response.ok(new StatusRESTModel(true, true, user.getDisplayName())).build(); } else { return Response.ok(new StatusRESTModel(false, true, null)).build(); } }