auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private <Q, R> List<MessageHandler<? super QueryMessage<?, ?>>> getHandlersForMessage( QueryMessage<Q, R> queryMessage) { ResponseType<R> responseType = queryMessage.getResponseType(); <START> return subscriptions.getOrDefault(queryMessage.getQueryName(), new CopyOnWriteArrayList<>()) <END> .stream() .filter(querySubscription -> responseType.matches(querySubscription.getResponseType())) .map((Function<QuerySubscription, MessageHandler>) QuerySubscription::getQueryHandler) .map(queryHandler -> (MessageHandler<? super QueryMessage<?, ?>>) queryHandler) .collect(Collectors.toList()); }</code><technical_language>try getOrCompute instead. Besides delaying creation of collection moment a key found, stored result in map, making faster for consecutive invocations</technical_language>

Target:
private <Q, R> List<MessageHandler<? super QueryMessage<?, ?>>> getHandlersForMessage( QueryMessage<Q, R> queryMessage) { ResponseType<R> responseType = queryMessage.getResponseType(); return subscriptions.computeIfAbsent(queryMessage.getQueryName(), k -> new CopyOnWriteArrayList<>()) .stream() .filter(querySubscription -> responseType.matches(querySubscription.getResponseType())) .map((Function<QuerySubscription, MessageHandler>) QuerySubscription::getQueryHandler) .map(queryHandler -> (MessageHandler<? super QueryMessage<?, ?>>) queryHandler) .collect(Collectors.toList()); }
Source:
<code>public void testUseDatabase() throws Exception { <START> TestingExecutor executor = new TestingExecutorBuilder() .setUseDatabaseConsumer((ignored1, databaseName) -> { if (!databaseName.equals("db")) { throw new SqlExecutionException("unexpected database name: " + databaseName); } }) .build(); InputStream inputStream = new ByteArrayInputStream("use db;\n".getBytes()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256); CliClient cliClient = null; SessionContext sessionContext = new SessionContext("test-session", new Environment()); String sessionId = executor.openSession(sessionContext); <END> try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) { cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath()); cliClient.open(); assertThat(executor.getNumUseDatabaseCalls(), is(1)); String output = new String(outputStream.toByteArray()); assertFalse(output.contains("unexpected database name")); } finally { if (cliClient != null) { cliClient.close(); } } }</code><technical_language>extract this code a function for reuse purpose</technical_language>

Target:
public void testUseDatabase() throws Exception { TestingExecutor executor = new TestingExecutorBuilder() .setUseDatabaseConsumer((ignored1, databaseName) -> { if (!databaseName.equals("db")) { throw new SqlExecutionException("unexpected database name: " + databaseName); } }) .build(); String output = testExecuteSql(executor, "use db;"); assertThat(executor.getNumUseDatabaseCalls(), is(1)); assertFalse(output.contains("unexpected database name")); }
Source:
<code>private void controlLoop() { try { kafkaConsumer.subscribe(Collections.singleton(topic), new RebalanceListener()); while (running) { ConsumerRecords<?, ?> records = flowControlledPoll(); addRecordsToStream(records); Map<TopicPartition, OffsetAndMetadata> offsets = acknowledgmentHandler.getAcknowledged(); commitOffsets(offsets); } } catch (WakeupException e) { log.info("Wakeup, controlLoop exiting"); } catch (InterruptedException e) { log.info("Interrupted, controlLoop exiting"); } catch (Throwable t) { log.error("controlLoop error, exiting", t); throw t; } finally { running = false; synchronized (this) { <START> this.notifyAll(); <END> } try { Map<TopicPartition, OffsetAndMetadata> finalOffsets = new HashMap<>(); if (failedOffset != null) { finalOffsets.putAll(failedOffset); } finalOffsets.putAll(acknowledgmentHandler.removePartitions(kafkaConsumer.assignment())); try { log.info("closing offset size committed: " + finalOffsets.size()); try { kafkaConsumer.commitSync(finalOffsets); } catch (WakeupException expected) { log.info("controlLoop wakeup on closing commitSync, retrying"); kafkaConsumer.commitSync(finalOffsets); } } catch (Throwable e) { log.error("controlLoop error commiting sync", e); } } catch (InterruptedException e) { log.info("controlLoop failed to commit offsets on shutdown", e); } log.info("controlLoop closing kafkaConsumer"); kafkaConsumer.close(); } }</code><technical_language>I waits woken this notify</technical_language>

Target:
private void controlLoop() { try { kafkaConsumer.subscribe(Collections.singleton(topic), new RebalanceListener()); while (running) { ConsumerRecords<?, ?> records = flowControlledPoll(); addRecordsToStream(records); Map<TopicPartition, OffsetAndMetadata> offsets = acknowledgmentHandler.getAcknowledged(); commitOffsets(offsets); } } catch (WakeupException e) { log.info("Wakeup, controlLoop exiting"); } catch (InterruptedException e) { log.info("Interrupted, controlLoop exiting"); } catch (Throwable t) { log.error("controlLoop error, exiting", t); throw t; } finally { running = false; try { Map<TopicPartition, OffsetAndMetadata> finalOffsets = new HashMap<>(); if (failedOffset != null) { finalOffsets.putAll(failedOffset); } finalOffsets.putAll(acknowledgmentHandler.removePartitions(kafkaConsumer.assignment())); try { log.info("closing offset size committed: " + finalOffsets.size()); try { kafkaConsumer.commitSync(finalOffsets); } catch (WakeupException expected) { log.info("controlLoop wakeup on closing commitSync, retrying"); kafkaConsumer.commitSync(finalOffsets); } } catch (Throwable e) { log.error("controlLoop error commiting sync", e); } } catch (InterruptedException e) { log.info("controlLoop failed to commit offsets on shutdown", e); } log.info("controlLoop closing kafkaConsumer"); kafkaConsumer.close(); } }
Source:
<code>public void initTest() { EnvConfig envConfig = EnvConfig.getDefaultEnvConfig(); ControlMessage lastControlMessage = new ControlMessage(); lastControlMessage.setId("1"); lastControlMessage.setOffset(1l); when(consumerUtilsCore.getLastEvent(envConfig.getControlTopicName(), envConfig.getPollTimeout())).thenReturn(lastControlMessage); when(defaultSessionSnapShooter.getLastSnapshotTime()).thenReturn(LocalDateTime.now()); when(handler.initializeKieSessionFromSnapshotOnDemand(any(EnvConfig.class), any(SnapshotInfos.class))).thenReturn(Boolean.TRUE); <START> consumer = new DefaultKafkaConsumer(EnvConfig.getDefaultEnvConfig(), producer, primaryConsumer, secondaryConsumer, consumerUtilsCore, defaultSessionSnapShooter, snapshotOnDemandUtils, handler); <END> }</code><technical_language>spy(...)</technical_language>

Target:
public void initTest() { EnvConfig envConfigTest = EnvConfig.getDefaultEnvConfig(); ControlMessage lastControlMessage = new ControlMessage(); lastControlMessage.setId("1"); lastControlMessage.setOffset(1l); when(consumerUtilsCoreMock.getLastEvent(envConfigTest.getControlTopicName(), envConfigTest.getPollTimeout())).thenReturn(lastControlMessage); when(defaultSessionSnapShooterMock.getLastSnapshotTime()).thenReturn(LocalDateTime.now()); when(handlerMock.initializeKieSessionFromSnapshotOnDemand(any(EnvConfig.class), any(SnapshotInfos.class))).thenReturn(Boolean.TRUE); spy = Mockito.spy(new DefaultKafkaConsumer(){ { this.envConfig = envConfigTest; this.producer = mockProducer; this.consumerUtilsCore = consumerUtilsCoreMock; this.snapShooter = defaultSessionSnapShooterMock; this.snapshotOnDemandUtils = snapshotOnDemandUtilsMock; this.consumerHandler = handlerMock; initKafkaConsumer(); updateKafkaSecondaryConsumer(); } @Override public void initKafkaConsumer() { this.kafkaConsumer = primaryConsumerMock; } @Override public void updateKafkaSecondaryConsumer() { this.kafkaSecondaryConsumer = secondaryConsumerMock; } }); }
Source:
<code><START> public void getSetBits(int batchSize, boolean[] vector, boolean[] isNull) <END> throws IOException { for (int i = 0; i < batchSize; i++) { if (!isNull[i]) { vector[i] = nextBit(); } } }</code><technical_language>Recently, @yingsu00 removed of of related form of getUnsetBits isNull vector. change a good effect memory pressure, in some cases increased performance. I suggest pattern introduced in this new code</technical_language>

Target:
public int getSetBits(int batchSize, boolean[] vector, boolean[] isNull) throws IOException { int count = 0; for (int i = 0; i < batchSize; i++) { if (!isNull[i]) { vector[i] = nextBit(); count += vector[i] ? 1 : 0; } } return count; }
Source:
<code>public boolean equals(Object obj) { if (obj instanceof PanStampBindingSettings) { PanStampBindingSettings other = (PanStampBindingSettings) obj; return !serialDiffers(other) && (networkChannel == other.networkChannel) && (networkId == other.networkId) <START> && (networkDeviceAddress == other.networkDeviceAddress) <END> && (networkSecurityOption == other.networkSecurityOption) && xmlDir.equals(other.xmlDir) && (debugPort == other.debugPort) && (debugEnabled == other.debugEnabled); } return false; }</code><technical_language>replace 4 lines (3 above, 1 below) !networkDiffers(other) eliminate duplicate logic</technical_language>

Target:
public boolean equals(Object obj) { if (obj instanceof PanStampBindingSettings) { PanStampBindingSettings other = (PanStampBindingSettings) obj; return !serialDiffers(other) && !networkDiffers(other) && !debugDiffers(other) && !directoriesDiffers(other); } return false; }
Source:
<code>public void setup(Context.OperatorContext context) { <START> if (scanService == null) { <END> scanService = Executors.newSingleThreadExecutor(); } sleepMillis = context.getValue(Context.OperatorContext.SPIN_MILLIS); if (filePatternRegularExp != null) { regex = Pattern.compile(filePatternRegularExp); } if (ignoreFilePatternRegularExp != null) { ignoreRegex = Pattern.compile(this.ignoreFilePatternRegularExp); } try { fs = getFSInstance(); } catch (IOException e) { throw new RuntimeException("opening fs", e); } }</code><technical_language>is necessary check for null? condition null? I platform calls setup/terminate deployment. IMO, is safer create new execution service time setup is called possibly assert throw RuntimeException if scanService is null avoid misusage in unit tests</technical_language>

Target:
public void setup(Context.OperatorContext context) { if (scanService != null) { throw new RuntimeException("multiple calls to setup() detected!"); } scanService = Executors.newSingleThreadExecutor(); discoveredFiles = new LinkedBlockingDeque<>(); atomicThrowable = new AtomicReference<>(); ignoredFiles = Sets.newHashSet(); sleepMillis = context.getValue(Context.OperatorContext.SPIN_MILLIS); if (filePatternRegularExp != null) { regex = Pattern.compile(filePatternRegularExp); } if (ignoreFilePatternRegularExp != null) { ignoreRegex = Pattern.compile(this.ignoreFilePatternRegularExp); } try { fs = getFSInstance(); } catch (IOException e) { throw new RuntimeException("opening fs", e); } }
Source:
<code>public static <T> int chooseTaskIndex(List<T> keys, int numTasks) { <START> return Math.abs(listHashCode(keys) % numTasks); <END> }</code><technical_language>JDK 1.8, Math.floorMod(listHashCode(keys), numTasks) right implementation distribution consistent 1.x version line. <LINK_0> <LINK_1> <LINK_2> Math.abs(listHashCode(keys) % numTasks) != Math.floorMod(listHashCode(keys), numTasks), Math.floorMod(listHashCode(keys), numTasks) == (mod listHashCode(keys) numTasks). implementation right guaranteeing positive index faster, namespace in states (being for stateful bolts) task id changing hash function requires state resharding. worth measure performance difference is? provide state resharding support change of task parallelism. (though changing hash function requires of end-users run once.)</technical_language>

Target:
public static <T> int chooseTaskIndex(List<T> keys, int numTasks) { return Math.floorMod(listHashCode(keys), numTasks); }
Source:
<code>public void initialize(Config config, TopologyAPI.Topology inputTopology) { this.topology = inputTopology; setPackingConfigs(config); LOG.info(String.format("Initalizing Packing: \n" + "Max number of instances per container: %d \n" <START> + "Default instance CPU: %f, Default instance RAM: %s, Default instance DISK: %s \n" <END> + "Paddng: %s \n" + "Container CPU: %f, Container RAM: %s, Container DISK: %s", this.maxNumInstancesPerContainer, this.defaultInstanceResources.getCpu(), this.defaultInstanceResources.getRam().toString(), this.defaultInstanceResources.getDisk().toString(), this.padding.toString(), this.maxContainerResources.getCpu(), this.maxContainerResources.getRam().toString(), this.maxContainerResources.getDisk().toString())); }</code><technical_language>"Default instance resource, CPU: %f, RAM: %s, DSIK: %s"</technical_language>

Target:
public void initialize(Config config, TopologyAPI.Topology inputTopology) { this.topology = inputTopology; setPackingConfigs(config); LOG.info(String.format("Initalizing Packing: \n" + "Max number of instances per container: %d \n" + "Default instance resource, CPU: %f, RAM: %s, DISK: %s \n" + "Paddng: %s \n" + "Container resource, CPU: %f, RAM: %s, DISK: %s", this.maxNumInstancesPerContainer, this.defaultInstanceResources.getCpu(), this.defaultInstanceResources.getRam().toString(), this.defaultInstanceResources.getDisk().toString(), this.padding.toString(), this.maxContainerResources.getCpu(), this.maxContainerResources.getRam().toString(), this.maxContainerResources.getDisk().toString())); }
Source:
<code>private boolean checkListTypes() { for (VariableElement field : fields) { if (Utils.isRealmList(field)) { if (Utils.getGenericType(field) == null) { Utils.error("No generic type supplied for field", field); return false; } TypeMirror fieldType = field.asType(); List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments(); String genericCanonicalType = typeArguments.get(0).toString(); TypeElement typeElement = elements.getTypeElement(genericCanonicalType); if (typeElement.getSuperclass().getKind() == TypeKind.NONE) { <START> Utils.error("Only concrete Realm classes are allowed in Lists. Neither " + <END> "interfaces nor abstract classes can be used.", field); return false; } } } return true; }</code><technical_language>minor: _are allowed in RealmCollection_</technical_language>

Target:
private boolean checkListTypes() { for (VariableElement field : fields) { if (Utils.isRealmList(field)) { if (Utils.getGenericType(field) == null) { Utils.error("No generic type supplied for field", field); return false; } TypeMirror fieldType = field.asType(); List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments(); String genericCanonicalType = typeArguments.get(0).toString(); TypeElement typeElement = elements.getTypeElement(genericCanonicalType); if (typeElement.getSuperclass().getKind() == TypeKind.NONE) { Utils.error("Only concrete Realm classes are allowed in RealmLists. Neither " + "interfaces nor abstract classes can be used.", field); return false; } } } return true; }
Source:
<code>public static <N extends Node> ParameterizedMetricKey<N> getInstance(MetricKey<N> key, MetricVersion version) { <START> int code = code(key, version); <END> if (!POOL.containsKey(code)) { POOL.put(code, new ParameterizedMetricKey<>(key, version)); } return (ParameterizedMetricKey<N>) POOL.get(code); }</code><technical_language>this line - this a theoretical problem: code (hashCode) unique get collisions. sure, if this is a real problem, in theory, exists. Assuming, pool this class for performance reasons, ensure, instance exists (so compare ParametrizedMetricKeys a simple ==): a HashMap<ParametrizedMetricKey, ParameterizedMetricKey>. (temporarily) a new instance of ParameterizedMetricKey, return hashMap, if exists... HashMap takes care of potential collisions</technical_language>

Target:
public static <N extends Node> ParameterizedMetricKey<N> getInstance(MetricKey<N> key, MetricVersion version) { ParameterizedMetricKey<N> tmp = new ParameterizedMetricKey<>(key, version); if (!POOL.containsKey(tmp)) { POOL.put(tmp, tmp); } @SuppressWarnings("unchecked") ParameterizedMetricKey<N> result = (ParameterizedMetricKey<N>) POOL.get(tmp); return result; }
Source:
<code>private void pollExecution() { if (this.executorId == -1) { if (AzkabanExecutorServer.getApp() != null) { try { final Executor executor = requireNonNull(FlowRunnerManager.this.executorLoader .fetchExecutor(AzkabanExecutorServer.getApp().getHost(), AzkabanExecutorServer.getApp().getPort()), "The executor can not be null"); this.executorId = executor.getId(); } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to fetch executor ", e); } } } else if (FlowRunnerManager.this.active) { FlowRunnerManager.this.preparingFlowCount.getAndIncrement(); if (FlowRunnerManager.this.active) { try { final int execId = FlowRunnerManager.this.executorLoader .selectAndUpdateExecution(this.executorId); if (execId != -1) { FlowRunnerManager.logger.info("Submitting flow " + execId); Thread.sleep(1000 * 30); submitFlow(execId); } } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to submit flow ", e); } finally { FlowRunnerManager.this.preparingFlowCount.getAndDecrement(); } } else { FlowRunnerManager.this.preparingFlowCount.getAndDecrement(); <START> } <END> } }</code><technical_language>please file a JIRA ticket for tracking</technical_language>

Target:
private void pollExecution() { if (this.executorId == -1) { if (AzkabanExecutorServer.getApp() != null) { try { final Executor executor = requireNonNull(FlowRunnerManager.this.executorLoader .fetchExecutor(AzkabanExecutorServer.getApp().getHost(), AzkabanExecutorServer.getApp().getPort()), "The executor can not be null"); this.executorId = executor.getId(); } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to fetch executor ", e); } } } else { try { final int execId = FlowRunnerManager.this.executorLoader .selectAndUpdateExecution(this.executorId, FlowRunnerManager.this.active); if (execId != -1) { FlowRunnerManager.logger.info("Submitting flow " + execId); submitFlow(execId); commonMetrics.markDispatchSuccess(); } } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to submit flow ", e); commonMetrics.markDispatchFail(); } } }
Source:
<code>private boolean accepts(final Resource resource) throws RepositoryException { if (resource == null) { return false; } ValueMap props = resource.getValueMap(); if (!props.get("jcr:primaryType", "").equals("dam:AssetContent")) { return false; } if (!props.get("isRemoteAsset", false)) { return false; } if (remoteResourcesSyncing.contains(resource.getPath())) { return false; } Calendar lastFailure = props.get("remoteSyncFailed", (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (this.config.getRetryDelay() * 60000))) { return false; } for (String syncPath : this.config.getDamSyncPaths()) { if (!resource.getPath().startsWith(syncPath)) { continue; } <START> Session session = resource.getResourceResolver().adaptTo(Session.class); <END> String userId = session.getUserID(); if (userId.equals("admin")) { LOG.debug("Avoiding binary sync for admin user"); continue; } if (this.config.getWhitelistedServiceUsers().contains(userId)) { return true; } User currentUser = (User) AccessControlUtil.getUserManager(session).getAuthorizable(userId); if (currentUser != null && !currentUser.isSystemUser()) { return true; } else { LOG.debug("Avoiding binary sync b/c this is a non-whitelisted service user: {}", session.getUserID()); } } return false; }</code><technical_language>lines 154 - 170 checked loop? doesnt change based sync path</technical_language>

Target:
private boolean accepts(final Resource resource) throws RepositoryException { if (resource == null) { return false; } ValueMap props = resource.getValueMap(); if (!DamConstants.NT_DAM_ASSETCONTENT.equals(props.get(JcrConstants.JCR_PRIMARYTYPE))) { return false; } if (!props.get(RemoteAssets.IS_REMOTE_ASSET, false)) { return false; } Calendar lastFailure = props.get(RemoteAssets.REMOTE_SYNC_FAILED, (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (this.config.getRetryDelay() * 60000))) { return false; } boolean matchesSyncPath = false; for (String syncPath : this.config.getDamSyncPaths()) { if (resource.getPath().startsWith(syncPath)) { matchesSyncPath = true; } } if (matchesSyncPath) { Session session = resource.getResourceResolver().adaptTo(Session.class); String userId = session.getUserID(); if (!userId.equals(UserConstants.DEFAULT_ADMIN_ID)) { if (this.config.getWhitelistedServiceUsers().contains(userId)) { return true; } User currentUser = (User) AccessControlUtil.getUserManager(session).getAuthorizable(userId); if (currentUser != null && !currentUser.isSystemUser()) { return true; } else { LOG.debug("Avoiding binary sync b/c this is a non-whitelisted service user: {}", session.getUserID()); } } else { LOG.debug("Avoiding binary sync for admin user"); } } return false; }
Source:
<code>public NettyHttpClientPipelineFactory(TLSClientParameters clientParameters, int readTimeout) { <START> this(clientParameters, readTimeout, 1048576); <END> }</code><technical_language>refer a single constant (DEFAULT_MAX_RESPONSE_CONTENT_LENGTH)</technical_language>

Target:
public NettyHttpClientPipelineFactory(TLSClientParameters clientParameters, int readTimeout) { this(clientParameters, readTimeout, NettyHttpConduit.DEFAULT_MAX_RESPONSE_CONTENT_LENGTH); }
Source:
<code>private void createPluginVersionChangeTask(Project p, SarosEclipseExtension e) { String qualifier = e.getPluginVersionQualifier(); <START> if (e.getPluginVersionQualifier() == null || qualifier.isEmpty()) return; <END> p.getTasks() .register( PLUGIN_VERSION_CHANGE_TASK_NAME, (task) -> { task.getInputs().property("versionQualifier", qualifier); task.doLast( (t) -> { methodRequiresManifest("set version qualifier", e); new EclipseVersionConfigurator(e.getManifest()).addQualifier(qualifier); }); }); Task jarTask = p.getTasks().findByPath("jar"); if (jarTask == null) throw new GradleException("Unable to find jar task in project " + p.getName()); jarTask.dependsOn(PLUGIN_VERSION_CHANGE_TASK_NAME); }</code><technical_language>Nit: suggestion if (qualifier == null || qualifier.trim().isEmpty()) return;</technical_language>

Target:
private void createPluginVersionChangeTask(Project p, SarosEclipseExtension e) { String qualifier = e.getPluginVersionQualifier(); if (qualifier == null || qualifier.trim().isEmpty()) return; p.getTasks() .register( PLUGIN_VERSION_CHANGE_TASK_NAME, (task) -> { task.getInputs().property("versionQualifier", qualifier); task.doLast( (t) -> { methodRequiresManifest("set version qualifier", e); new OsgiBundleVersionConfigurator(e.getManifest()).addQualifier(qualifier); }); }); Task jarTask = p.getTasks().findByPath("jar"); if (jarTask == null) throw new GradleException("Unable to find jar task in project " + p.getName()); jarTask.dependsOn(PLUGIN_VERSION_CHANGE_TASK_NAME); }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { try { savedAnnouncements = savedInstanceState.getParcelableArrayList(Router.EXTRA_ANNOUNCEMENTS); } catch (Exception ex) { logger.error(ex); } } try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_COURSE_DATA); FacebookProvider fbProvider = new FacebookProvider(); if (courseData != null) { if (savedAnnouncements == null) { loadAnnouncementData(courseData); } else { populateAnnouncements(savedAnnouncements); } } <START> if (environment.getConfig().arePushNotificationEnabled() <END> && courseData != null && courseData.getCourse() != null) { notificationSettingRow.setVisibility(View.VISIBLE); final String courseId = courseData.getCourse().getId(); final String subscriptionId = courseData.getCourse().getSubscription_id(); boolean isSubscribed = environment.getNotificationDelegate().isSubscribedByCourseId(courseId); notificationSwitch.setChecked(isSubscribed); notificationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { environment.getNotificationDelegate().changeNotificationSetting( courseId, subscriptionId, isChecked); } }); } else { notificationSwitch.setOnCheckedChangeListener(null); notificationSettingRow.setVisibility(View.GONE); } } catch (Exception ex) { logger.error(ex); } }</code><technical_language>@staubina This check needs depth, controlled 'PUSH_NOTIFICATIONS' feature flag, needs history, this settings do connect FCM integration</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { try { savedAnnouncements = savedInstanceState.getParcelableArrayList(Router.EXTRA_ANNOUNCEMENTS); } catch (Exception ex) { logger.error(ex); } } try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_COURSE_DATA); FacebookProvider fbProvider = new FacebookProvider(); if (courseData != null) { if (savedAnnouncements == null) { loadAnnouncementData(courseData); } else { populateAnnouncements(savedAnnouncements); } } } catch (Exception ex) { logger.error(ex); } }
Source:
<code>JsonNode readJsonNode(File file) { JsonNode node = null; try { node = mapper.readValue(file, JsonNode.class); } catch (IOException e) { <START> log.warn("Cannot read/parse JSON file '{}'", file.getAbsolutePath()); END> log.warn("Exception", e); } return node; }</code><technical_language>add : e.getMessage()</technical_language>

Target:
JsonNode readJsonNode(File file) { JsonNode node = null; try { node = mapper.readValue(file, JsonNode.class); } catch (IOException e) { log.warn("Cannot read/parse JSON file '{}': {}", file.getAbsolutePath(), e.getMessage()); log.debug("Exception", e); } return node; }
Source:
<code>public void loadGroupsInOffice(int office, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getGroupsByOffice(office, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Group>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); <START> try { <END> if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Group> groups) { getMvpView().showProgressbar(false); getMvpView().showGroupsInOffice(groups); } })); }</code><technical_language>this utils method show error <LINK_0></technical_language>

Target:
public void loadGroupsInOffice(int office, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getGroupsByOffice(office, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Group>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Group> groups) { getMvpView().showProgressbar(false); getMvpView().showGroupsInOffice(groups); } })); }
Source:
<code>private ContentResponse execute(Request req, boolean uriIsSecret) { String safeUri = safeUri(req, uriIsSecret); logger.info("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res; try { res = send(req); } catch (HttpResponseException e) { throw error(req, uriIsSecret, e.getResponse()); } catch (RuntimeException e) { logger.info("Exception without response: {}", req.getMethod(), safeUri); <START> if(retry){ <END> throw e; } else { throw new TaskExecutionException(e.toString()); } } logger.info("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else { throw error(req, uriIsSecret, res); } }</code><technical_language>put spaces before/after parentheses</technical_language>

Target:
private ContentResponse execute(Request req, boolean uriIsSecret) { String safeUri = safeUri(req, uriIsSecret); logger.info("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res; try { res = send(req); } catch (HttpResponseException e) { throw error(req, uriIsSecret, e.getResponse()); } catch (RuntimeException e) { logger.warn("Exception without response: {}", req.getMethod(), safeUri); if (retry) { throw e; } else { throw new TaskExecutionException(e); } } logger.info("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else { throw error(req, uriIsSecret, res); } }
Source:
<code>public static Function<GHEventsSubscriber, Set<GHEvent>> extractEvents() { return new Function<GHEventsSubscriber, Set<GHEvent>>() { @Override public Set<GHEvent> apply(GHEventsSubscriber subscriber) { <START> if (subscriber == null) { <END> return Collections.emptySet(); } return defaultIfNull(subscriber.events(), Collections.<GHEvent>emptySet()); } }; }</code><technical_language>this happen. Validate.notNull() lang3 - throw exc fixed if</technical_language>

Target:
public static Function<GHEventsSubscriber, Set<GHEvent>> extractEvents() { return new Function<GHEventsSubscriber, Set<GHEvent>>() { @Override public Set<GHEvent> apply(GHEventsSubscriber subscriber) { return defaultIfNull(notNull(subscriber).events(), Collections.<GHEvent>emptySet()); } }; }
Source:
<code>private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); if (testFileFolder.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFileFolder); } else if (testFileFolder.endsWith(Constants.TEST_FOLDER_EXTENSION)) { String testFolderPath = testFileFolder.split("\\$")[0]; File folder = new File(testFolderPath); File[] listOfFiles = folder.listFiles(); <START> if (listOfFiles != null) { <END> for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFolderPath + filename); } } } } return fileNamesWithPaths; }</code><technical_language>folder.listFiles() return empty array if files in directory. do need do a null check testFolderPath path a directory</technical_language>

Target:
private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); if (testFileFolder.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFileFolder); } else if (testFileFolder.endsWith(Constants.TEST_FOLDER_EXTENSION)) { String testFolderPath = testFileFolder.split("\\$")[0]; File folder = new File(testFolderPath); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFolderPath + filename); } } } return fileNamesWithPaths; }
Source:
<code>public void show(final String name) { nameField.innerHTML = name.replaceAll("\\n", "<br>").replaceAll("\\s", "&nbsp;"); setVisible(); <START> nameField.focus(); <END> }</code><technical_language>this logic set presenter</technical_language>

Target:
public void show(final String name) { nameField.textContent = ""; nameField.innerHTML = ""; nameField.innerHTML = name; setVisible(); }
Source:
<code>protected JPanel getWorkPanel() { if (mainPanel == null) { mainPanel = new JPanel(new BorderLayout()); tabbedPane = new JTabbedPane(); <START> if (jScrollPane == null) { <END> jScrollPane = new JScrollPane(); jScrollPane.setName("ActiveScanMessagePane"); jScrollPane.setViewportView(getMessagesTable()); } if (filterPane == null) { filterPane = new JScrollPane(); filterPane.setName("FilterMessagePane"); filterPane.setViewportView(getFilterMessageTable()); } tabbedPane.add( Constant.messages.getString("ascan.panel.tab.scannedMessages"), jScrollPane); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.filteredMessages"), filterPane); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane); } return mainPanel; }</code><technical_language>removed</technical_language>

Target:
protected JPanel getWorkPanel() { if (mainPanel == null) { mainPanel = new JPanel(new BorderLayout()); tabbedPane = new JTabbedPane(); JScrollPane jScrollPane = new JScrollPane(); jScrollPane.setName("ActiveScanMessagePane"); jScrollPane.setViewportView(getMessagesTable()); JScrollPane filterPane = new JScrollPane(); filterPane.setName("FilterMessagePane"); filterPane.setViewportView(getFilterMessageTable()); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.scannedMessages"), jScrollPane); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.filteredMessages"), filterPane); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane); } return mainPanel; }
Source:
<code>public String toString() { return "ScanQuery{" + "dataSource='" + getDataSource() + '\'' + ", querySegmentSpec=" + getQuerySegmentSpec() + ", virtualColumns=" + getVirtualColumns() + ", resultFormat='" + resultFormat + '\'' + ", batchSize=" + batchSize + <START> ", limit=" + scanRowsLimit + <END> ", dimFilter=" + dimFilter + ", columns=" + columns + ", legacy=" + legacy + '}'; }</code><technical_language>compatibility concerns in toString(), please change key</technical_language>

Target:
public String toString() { switch (this) { case RESULT_FORMAT_LIST: return "list"; case RESULT_FORMAT_COMPACTED_LIST: return "compactedList"; case RESULT_FORMAT_VALUE_VECTOR: return "valueVector"; default: return ""; } }
Source:
<code>@Override public void consumeMessage(String sequenceName) throws InterruptedException { Subscription subscription; String queueGroup = natsProperties.getProperty(NatsConstants.QUEUE_GROUP); if (StringUtils.isNotEmpty(queueGroup)) { subscription = connection.subscribe(subject, queueGroup); } else { subscription = connection.subscribe(subject); } Message natsMessage = subscription.nextMessage(Duration.ZERO); <START> String message = new String(natsMessage.getData(), StandardCharsets.UTF_8); <END> log.info("Message Received to NATS Inbound EP: " + message); injectHandler.invoke(message.getBytes(), sequenceName, natsMessage.getReplyTo(), connection); }</code><technical_language>proceed message, a null check. API return null if message. If null, add a DEBUG log</technical_language>

Target:
@Override public void consumeMessage(String sequenceName) throws InterruptedException { Subscription subscription; String queueGroup = natsProperties.getProperty(NatsConstants.QUEUE_GROUP); if (StringUtils.isNotEmpty(queueGroup)) { subscription = connection.subscribe(subject, queueGroup); } else { subscription = connection.subscribe(subject); } Message natsMessage = subscription.nextMessage(Duration.ofMillis(100)); if (natsMessage != null) { String message = new String(natsMessage.getData(), StandardCharsets.UTF_8); printDebugLog("Message Received to NATS Inbound EP: " + message); injectHandler.invoke(message.getBytes(), sequenceName, natsMessage.getReplyTo(), connection); } else { printDebugLog("Message is null."); } }
Source:
<code>public void beforeClass() throws Exception { super.beforeClass(); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); <START> _store = new MockAssignmentMetadataStore(_manager.getMetadataStoreConnectionString(), <END> _manager.getClusterName()); }</code><technical_language>Moreover, I need this mock, for testAvoidingRedundantWrite() only. for other test method, original assignment store class</technical_language>

Target:
public void beforeClass() throws Exception { super.beforeClass(); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _store = new AssignmentMetadataStore(_manager.getMetadataStoreConnectionString(), _manager.getClusterName()); }
Source:
<code>public void run(StreamApplication streamApp) { JmxServer jmxServer = null; try { jmxServer = new JmxServer(); ContainerModel containerModel = jobModel.getContainers().get(containerId); Object taskFactory = TaskFactoryUtil.createTaskFactory(config, streamApp, this); SamzaContainer container = SamzaContainer$.MODULE$.apply( containerModel, config, jobModel.maxChangeLogStreamPartitions, jmxServer, Util.<String, MetricsReporter>javaMapAsScalaMap(new HashMap<>()), taskFactory); container.setContainerListener( new SamzaContainerListener() { @Override public void onContainerStart() { log.info("Container Started"); } @Override public void onContainerStop(boolean invokedExternally) { log.info("Container Stopped"); } @Override public void onContainerFailed(Throwable t) { log.info("Container Failed"); <START> } <END> }); container.run(); } finally { if (jmxServer != null) { jmxServer.stop(); } } }</code><technical_language>This needs handled for yarn case. Previously container.run() throw exception is a failure. logic is changed exception is populated in callback. need store exception a var throw container.run(). like: LocalConatinerRunner { Throwable throwable; ... container setContainerListener(new SamzaContainerListener() { ... onContainerFailed(Throwable t) { throwable = t; } } container.run(); if(throwable != null) { throw throwable } ..</technical_language>

Target:
public void run(StreamApplication streamApp) { JmxServer jmxServer = null; try { jmxServer = new JmxServer(); ContainerModel containerModel = jobModel.getContainers().get(containerId); Object taskFactory = TaskFactoryUtil.createTaskFactory(config, streamApp, this); SamzaContainer container = SamzaContainer$.MODULE$.apply( containerModel, config, jobModel.maxChangeLogStreamPartitions, jmxServer, Util.<String, MetricsReporter>javaMapAsScalaMap(new HashMap<>()), taskFactory); container.setContainerListener( new SamzaContainerListener() { @Override public void onContainerStart() { log.info("Container Started"); } @Override public void onContainerStop(boolean invokedExternally) { log.info("Container Stopped"); } @Override public void onContainerFailed(Throwable t) { log.info("Container Failed"); containerException = t; } }); container.run(); } finally { if (jmxServer != null) { jmxServer.stop(); } } if (containerException != null) { log.error("Container stopped with Exception. Exiting process now.", containerException); System.exit(1); } }
Source:
<code>public void testEncryptDecrypt() throws DecryptionException, BuilderException, EncryptionException { AESKeyVersion keyversion = new AESKeyVersion.Builder().build(); testEncryptDecryptKeyVersion(keyversion); <START> for (KeySize keySize : KeySize.values()) { <END> keyversion = new AESKeyVersion.Builder() .keySize(keySize) .padding(Padding.PKCS5).build(); testEncryptDecryptKeyVersion(keyversion); } for (KeySize keySize : KeySize.values()) { for (Mode mode : Mode.values()) { keyversion = new AESKeyVersion.Builder() .keySize(keySize) .padding(Padding.PKCS5).mode(mode).build(); testEncryptDecryptKeyVersion(keyversion); } } }</code><technical_language>This is a property of a key. is a property of key VERSION. Please do mix terms is confusing. consistently</technical_language>

Target:
public void testEncryptDecrypt() throws DecryptionException, BuilderException, EncryptionException { AESKeyVersion keyversion = new AESKeyVersion.Builder().build(); testEncryptDecryptKeyVersion(keyversion); for (Integer keyVersionLength : new Integer[] {16, 24, 32}) { keyversion = new AESKeyVersion.Builder() .keyVersionLengthInBytes(keyVersionLength) .padding(Padding.PKCS5).build(); testEncryptDecryptKeyVersion(keyversion); } for (Integer keyVersionLength : new Integer[] {16, 24, 32}) { for (Mode mode : Mode.values()) { keyversion = new AESKeyVersion.Builder() .keyVersionLengthInBytes(keyVersionLength) .padding(Padding.PKCS5).mode(mode).build(); testEncryptDecryptKeyVersion(keyversion); } } }
Source:
<code>private static void addAttachments(List<? extends Attachment> attachments, Map<String, Object> map, int revpos) { LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>(); map.put("_attachments", attsMap); for (Attachment att : attachments) { SavedAttachment savedAtt = (SavedAttachment)att; HashMap<String, Object> theAtt = new HashMap<String, Object>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream bos = new Base64OutputStream(baos, true, 0, null); try { InputStream fis = savedAtt.getInputStream(); int bufSiz = 1024; byte[] buf = new byte[bufSiz]; int n = 0; do { n = fis.read(buf); if (n > 0) { bos.write(buf, 0, n); } } while (n > 0); if (savedAtt.revpos < revpos) { <START> theAtt.put("stub", true); <END> } else { theAtt.put("data", baos.toString()); } theAtt.put("content_type", savedAtt.type); theAtt.put("revpos", savedAtt.revpos); } catch (FileNotFoundException fnfe) { continue; } catch (IOException ioe) { continue; } attsMap.put(att.name, theAtt); } }</code><technical_language>need read file in a buffer in this case</technical_language>

Target:
private static void addAttachments(List<? extends Attachment> attachments, Map<String, Object> map, int revpos) { LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>(); map.put("_attachments", attsMap); for (Attachment att : attachments) { SavedAttachment savedAtt = (SavedAttachment)att; HashMap<String, Object> theAtt = new HashMap<String, Object>(); try { if (savedAtt.revpos < revpos) { theAtt.put("stub", true); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream bos = new Base64OutputStream(baos, true, 0, null); InputStream fis = savedAtt.getInputStream(); int bufSiz = 1024; byte[] buf = new byte[bufSiz]; int n = 0; do { n = fis.read(buf); if (n > 0) { bos.write(buf, 0, n); } } while (n > 0); theAtt.put("data", baos.toString()); } theAtt.put("content_type", savedAtt.type); theAtt.put("revpos", savedAtt.revpos); } catch (IOException ioe) { Log.w(LOG_TAG, "Caught IOException in addAttachments whilst reading attachment " + att + ", skipping it: " + ioe); continue; } attsMap.put(att.name, theAtt); } }
Source:
<code>public void testParseDisplayName() throws Exception { String directory = System.getenv("WinDir"); IntByReference pchEaten = new IntByReference(); PointerByReference ppidl = new PointerByReference(); IntByReference pdwAttributes = new IntByReference(); PointerByReference desktopFolder = new PointerByReference(); WinNT.HRESULT hResult = Shell32.INSTANCE.SHGetDesktopFolder(desktopFolder); assertEquals(COMUtils.S_OK, hResult.intValue()); IShellFolder shellFolder = IShellFolder.Converter.PointerToIShellFolder(desktopFolder); <START> hResult = shellFolder.ParseDisplayName(new WinDef.HWND(Pointer.NULL), Pointer.NULL, directory, pchEaten, ppidl, <END> pdwAttributes); assertEquals(COMUtils.S_OK, hResult.intValue()); }</code><technical_language>This simplified hResult = shellFolder.ParseDisplayName(null, null, directory, pchEaten, ppidl,</technical_language>

Target:
public void testParseDisplayName() throws Exception { String directory = System.getenv("WinDir"); IntByReference pchEaten = new IntByReference(); PointerByReference ppidl = new PointerByReference(); IntByReference pdwAttributes = new IntByReference(); PointerByReference desktopFolder = new PointerByReference(); WinNT.HRESULT hResult = Shell32.INSTANCE.SHGetDesktopFolder(desktopFolder); assertEquals(COMUtils.S_OK, hResult.intValue()); IShellFolder shellFolder = IShellFolder.Converter.PointerToIShellFolder(desktopFolder); hResult = shellFolder.ParseDisplayName(null, null, directory, pchEaten, ppidl, pdwAttributes); assertEquals(COMUtils.S_OK, hResult.intValue()); }
Source:
<code>public static synchronized String getRSAPublicString(String name, int length) { final SharedPreferences prefs = SalesforceSDKManager.getInstance().getAppContext().getSharedPreferences(ASYMM_SHARED_PREF_FILE, 0); final String id = prefs.getString(getSharedPrefKey(name), null); if (id != null) { RSA_IDS.put(name, id); return id; } else { String publicKeyBase64 = null; KeyPair keyPair = getKeyPair(name, length); if (keyPair != null) { PublicKey publicKey = keyPair.getPublic(); <START> publicKeyBase64 = Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP); <END> } prefs.edit().putString(getSharedPrefKey(name), publicKeyBase64).commit(); RSA_IDS.put(name, publicKeyBase64); return publicKeyBase64; } }</code><technical_language>Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE in flags here, sending this server</technical_language>

Target:
public static synchronized String getRSAPublicString(String name, int length) { String publicKeyBase64 = null; createRSAKeysIfNecessary(name, length); try { publicKeyBase64 = Base64.encodeToString(loadKeyStore().getCertificate(name).getPublicKey().getEncoded(), Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Security exception thrown", e); } return publicKeyBase64; }
Source:
<code>public static CredentialsProvider getCredentialsProvider() { return new CredentialsProvider() { @Override public String getHeaderName() { return javax.ws.rs.core.HttpHeaders.AUTHORIZATION; } @Override public String getAuthorization() { Principal principal = SecurityIntegrationFilter.getRequest().getUserPrincipal(); if (principal instanceof KeycloakPrincipal) { <START> return new KeyCloakTokenCredentialsProvider().getAuthorization(); <END> } else { return new SubjectCredentialsProvider().getAuthorization(); } } }; }</code><technical_language>This objects created for request? create reuse instance</technical_language>

Target:
public static CredentialsProvider getCredentialsProvider() { return new CredentialsProvider() { KeyCloakTokenCredentialsProvider keyCloakProvider = new KeyCloakTokenCredentialsProvider(); SubjectCredentialsProvider subjectProvider = new SubjectCredentialsProvider(); @Override public String getHeaderName() { return javax.ws.rs.core.HttpHeaders.AUTHORIZATION; } @Override public String getAuthorization() { Principal principal = SecurityIntegrationFilter.getRequest().getUserPrincipal(); if (principal instanceof KeycloakPrincipal) { return keyCloakProvider.getAuthorization(); } else { return subjectProvider.getAuthorization(); } } }; }