auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private long sumOfChangelogOffsets(final TaskId id, final Map<TopicPartition, Long> changelogOffsets) { long offsetSum = 0L; for (final Map.Entry<TopicPartition, Long> changelogEntry : changelogOffsets.entrySet()) { final long offset = changelogEntry.getValue(); if (offset == Task.LATEST_OFFSET) { return Task.LATEST_OFFSET; } else { offsetSum += offset; if (offsetSum < 0) { log.warn("Sum of changelog offsets for task overflowed, pinning to Long.MAX_VALUE", id); return Long.MAX_VALUE; } } } return offsetSum; }

Target:
private long sumOfChangelogOffsets(final TaskId id, final Map<TopicPartition, Long> changelogOffsets) { long offsetSum = 0L; for (final Map.Entry<TopicPartition, Long> changelogEntry : changelogOffsets.entrySet()) { final long offset = changelogEntry.getValue(); if (offset == Task.LATEST_OFFSET) { return Task.LATEST_OFFSET; } else { if (offset < 0) { throw new IllegalStateException("Offset should not be negative."); } offsetSum += offset; if (offsetSum < 0) { log.warn("Sum of changelog offsets for task overflowed, pinning to Long.MAX_VALUE", id); return Long.MAX_VALUE; } } } return offsetSum; }
Source:
private TaskExecutor createTaskExecutor(TaskManagerServices taskManagerServices, HeartbeatServices heartbeatServices, TaskExecutorPartitionTracker taskExecutorPartitionTracker) { return new TaskExecutor( rpc, TaskManagerConfiguration.fromConfiguration(configuration, TM_RESOURCE_SPEC), haServices, taskManagerServices, ExternalResourceInfoProvider.EMPTY_PROVIDER, heartbeatServices, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), null, dummyBlobCacheService, testingFatalErrorHandler, taskExecutorPartitionTracker, TaskManagerRunner.createBackPressureSampleService(configuration, rpc.getScheduledExecutor())); }

Target:
private TaskExecutor createTaskExecutor(TaskManagerServices taskManagerServices, HeartbeatServices heartbeatServices, TaskExecutorPartitionTracker taskExecutorPartitionTracker) { return new TaskExecutor( rpc, TaskManagerConfiguration.fromConfiguration( configuration, TM_RESOURCE_SPEC, InetAddress.getLoopbackAddress().getHostAddress()), haServices, taskManagerServices, ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES, heartbeatServices, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), null, dummyBlobCacheService, testingFatalErrorHandler, taskExecutorPartitionTracker, TaskManagerRunner.createBackPressureSampleService(configuration, rpc.getScheduledExecutor())); }
Source:
public List<ProjectData> call() throws OrmException { final List<ProjectData> result = new ArrayList<ProjectData>(); for(final Project p : db.projects().all().toList()) { boolean canBeDeleted = false; final List<Change> changes = db.changes().byProjectHaschange(p.getNameKey()).toList(); try { final ProjectControl c = projectControlFactory.controlFor(p.getNameKey()); if (c.isVisible() || c.isOwner()) { if (c.isOwner() && changes.size() == 0) { canBeDeleted = true; } final ProjectData projectData = new ProjectData(p.getNameKey(), p.getDescription(), canBeDeleted); result.add(projectData); } } catch (NoSuchProjectException e) { continue; } } Collections.sort(result, new Comparator<ProjectData>() { public int compare(final ProjectData a, final ProjectData b) { return a.getName().compareTo(b.getName()); } }); return result; }

Target:
public List<ProjectData> call() throws OrmException, RepositoryNotFoundException { final List<ProjectData> result = new ArrayList<ProjectData>(); for(final Project p : db.projects().all().toList()) { boolean canBeDeleted = false; try { final ProjectControl c = projectControlFactory.controlFor(p.getNameKey()); if (c.isVisible() || c.isOwner()) { if (c.isOwner() && (!c.getProjectState().isSpecialWildProject())) { try { final Repository repo = repoManager.openRepository(p.getName()); final Map<String, Ref> refs = repo.getAllRefs(); repo.close(); if (refs.isEmpty()) { canBeDeleted = true; } } catch (RepositoryNotFoundException e) { log.error("Repository " + p.getName() + " was not found"); } } result.add(new ProjectData(p.getNameKey(), p.getDescription(), canBeDeleted)); } } catch (NoSuchProjectException e) { continue; } } Collections.sort(result, new Comparator<ProjectData>() { public int compare(final ProjectData a, final ProjectData b) { return a.getName().compareTo(b.getName()); } }); return result; }
Source:
public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); final OutputStream out = storage.create(filename, true); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } finally { try { close(); } catch (Throwable t) { log.error("Could not close Record Writer", t); } } } @Override public void close() { try { writer.close(); } catch (IOException e) { throw new DataException(e); } } @Override public void commit() }; }

Target:
public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); final OutputStream out = storage.create(filename, true); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } } @Override public void close() { try { writer.close(); } catch (IOException e) { throw new DataException(e); } } @Override public void commit() }; }
Source:
private void showOnboardingInstruction() { InstructionDialogFragment.newInstance( onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME, true).show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }

Target:
private void showOnboardingInstruction() { int instructionType = onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME; InstructionDialogFragment.newInstance(instructionType, true) .show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }
Source:
public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) { if(fileSpan == null) return clone(); if(!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare "); final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan; if(bamFileSpan.isEmpty()) return clone(); validateSorted(); final BAMFileSpan trimmedChunkList = new BAMFileSpan(); final long chunkEnd = bamFileSpan.chunks.get(0).getChunkEnd(); for(final Chunk chunkToTrim: chunks) { if(chunkToTrim.getChunkStart() < chunkEnd) { if(chunkToTrim.getChunkEnd() <= chunkEnd) { trimmedChunkList.add(chunkToTrim.clone()); } else { trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(),chunkEnd)); } } } return trimmedChunkList; }

Target:
public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) { if(fileSpan == null) return clone(); if(!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare "); final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan; if(bamFileSpan.isEmpty()) return clone(); validateSorted(); final BAMFileSpan trimmedChunkList = new BAMFileSpan(); final long chunkEnd = bamFileSpan.chunks.get(bamFileSpan.chunks.size() - 1).getChunkEnd(); for(final Chunk chunkToTrim: chunks) { if(chunkToTrim.getChunkStart() < chunkEnd) { if(chunkToTrim.getChunkEnd() <= chunkEnd) { trimmedChunkList.add(chunkToTrim.clone()); } else { trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(),chunkEnd)); } } } return trimmedChunkList; }
Source:
protected BaseReceivePack(final Repository into) { db = into; walk = new RevWalk(db); final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY); objectChecker = cfg.newObjectChecker(); allowCreates = cfg.allowCreates; allowAnyDeletes = true; allowBranchDeletes = cfg.allowDeletes; allowNonFastForwards = cfg.allowNonFastForwards; allowOfsDelta = cfg.allowOfsDelta; advertiseRefsHook = AdvertiseRefsHook.DEFAULT; refFilter = RefFilter.DEFAULT; advertisedHaves = new HashSet<ObjectId>(); clientShallowCommits = new HashSet<ObjectId>(); String dirPath = db.getDirectory() != null ? db.getDirectory().getPath() : "" ; pushCertificateParser = new PushCertificateParser(into, cfg, dirPath); }

Target:
protected BaseReceivePack(final Repository into) { db = into; walk = new RevWalk(db); final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY); objectChecker = cfg.newObjectChecker(); allowCreates = cfg.allowCreates; allowAnyDeletes = true; allowBranchDeletes = cfg.allowDeletes; allowNonFastForwards = cfg.allowNonFastForwards; allowOfsDelta = cfg.allowOfsDelta; advertiseRefsHook = AdvertiseRefsHook.DEFAULT; refFilter = RefFilter.DEFAULT; advertisedHaves = new HashSet<ObjectId>(); clientShallowCommits = new HashSet<ObjectId>(); pushCertificateParser = new PushCertificateParser(db, cfg); }
Source:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { return fileSystem.openFile(path, hiveFileContext); }

Target:
public FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext) throws Exception { URIStatus uriStatus = mFileSystem.getStatus(getAlluxioPath(path)); AlluxioURIStatus alluxioURIStatus = new AlluxioURIStatus(uriStatus.getFileInfo(), hiveFileContext); FileInStream fileInStream = mFileSystem.openFile(alluxioURIStatus, OpenFilePOptions.getDefaultInstance()); return new FSDataInputStream(new AlluxioCachingHdfsFileInputStream(fileInStream)); }
Source:
private DoubleArray strikesShifted(double forward, double shiftOutput, DoubleArray strikesLike, ValueType strikeType) { int nbStrikes = strikesLike.size(); double[] strikes = new double[nbStrikes]; if (strikeType.equals(ValueType.STRIKE)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.SIMPLE_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward + strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.LOG_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward * strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } throw new IllegalArgumentException("Strike type not supported"); }

Target:
private DoubleArray strikesShifted(double forward, double shiftOutput, DoubleArray strikesLike, ValueType strikeType) { int nbStrikes = strikesLike.size(); double[] strikes = new double[nbStrikes]; if (strikeType.equals(ValueType.STRIKE)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.SIMPLE_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward + strikesLike.get(i) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } if (strikeType.equals(ValueType.LOG_MONEYNESS)) { for (int i = 0; i < nbStrikes; i++) { strikes[i] = forward * Math.exp(strikesLike.get(i)) + shiftOutput; } return DoubleArray.ofUnsafe(strikes); } throw new IllegalArgumentException("Strike type not supported"); }
Source:
public String getCategoryId() { return "itemcategory-standaloneprojects"; }

Target:
public String getCategoryId() { return "standaloneprojects"; }
Source:
private ParseTree getPermissionExpressionTree(Class<? extends Annotation> annotationClass, Annotation annotation) { try { if (annotationClass == SharePermission.class) { return null; } String expression = (String) annotationClass.getMethod("expression").invoke(annotation); boolean hasExpression = !expression.isEmpty(); if (!hasExpression) { log.warn("Poorly configured permission: {}", annotationClass.getName(), "no checks specified."); throw new IllegalArgumentException("Poorly configured permission '" + annotationClass.getName() + "'"); } return parseExpression(expression); } catch (ReflectiveOperationException e) { log.warn("Unknown permission: {}, {}", annotationClass.getName(), e); throw new IllegalArgumentException("Unknown permission '" + annotationClass.getName() + "'", e); } }

Target:
private ParseTree getPermissionExpressionTree(Class<? extends Annotation> annotationClass, Annotation annotation) { try { String expression = (String) annotationClass.getMethod("expression").invoke(annotation); boolean hasExpression = !expression.isEmpty(); if (!hasExpression) { log.warn("Poorly configured permission: {}", annotationClass.getName(), "no checks specified."); throw new IllegalArgumentException("Poorly configured permission '" + annotationClass.getName() + "'"); } return parseExpression(expression); } catch (ReflectiveOperationException e) { log.warn("Unknown permission: {}, {}", annotationClass.getName(), e); throw new IllegalArgumentException("Unknown permission '" + annotationClass.getName() + "'", e); } }
Source:
public void testDeactivation() { assertTrue("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); providers.get("com.adobe.acs.commons.mcp.model.SimpleModelOne").doDeactivate(); assertFalse("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); }

Target:
public void testDeactivation() { assertTrue("Should resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); providers.get("com.adobe.acs.commons.mcp.model.SimpleModelOne").doDeactivate(); assertFalse("Should not resolve model one dialog", resourceExists("/apps/test/model1/cq:dialog")); }
Source:
public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { m.setContactBlocked(contact_number, false); } if(ns.<String>getList("group") != null) { for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, false); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }

Target:
public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { try { m.setContactBlocked(contact_number, false); } catch (InvalidNumberException e) { System.err.println(e.getMessage()); } } if (ns.<String>getList("group") != null) { for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, false); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }
Source:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; } else { return false; } }

Target:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; } return false; }
Source:
protected String getTypeLabel() { return checkNotNull("type"); }

Target:
protected String getTypeLabel() { return Objects.requireNonNull(Messages.CallingContextTreeViewer_LabelType); }
Source:
public Object queries(@QueryParam("queries") String queriesParam) throws InterruptedException, ExecutionException { final int queries = getQueries(queriesParam); final World[] worlds = new World[queries]; Callable<World[]> callable = () -> { Session session = emf.createEntityManager().unwrap(Session.class); session.setDefaultReadOnly(true); try { final AtomicInteger i = new AtomicInteger(0); ThreadLocalRandom.current().ints(1, 10000).distinct().limit(queries).forEach( (randomValue)->worlds[i.getAndAdd(1)] = (World) session.byId(World.class).load(randomValue) ); return worlds; } finally { session.close(); } }; Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable); return futureWorlds.get(); }

Target:
public Object queries(@QueryParam("queries") String queriesParam) throws InterruptedException, ExecutionException { final int queries = getQueries(queriesParam); final World[] worlds = new World[queries]; Callable<World[]> callable = () -> { Session session = emf.createEntityManager().unwrap(Session.class); session.setDefaultReadOnly(true); try { final AtomicInteger i = new AtomicInteger(0); ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach( (randomValue)->worlds[i.getAndAdd(1)] = (World) session.byId(World.class).load(randomValue) ); return worlds; } finally { session.close(); } }; Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable); return futureWorlds.get(); }
Source:
public Observable<T> subscribeChannel(String channelName, Object... args) { final String channelId = getSubscriptionUniqueId(channelName, args); LOG.info("Subscribing to channel {}", channelId); return Observable.<T>create( e -> { if (webSocketChannel == null || !webSocketChannel.isOpen()) { e.onError(new NotConnectedException()); } channels.computeIfAbsent( channelId, cid -> { Subscription newSubscription = new Subscription(e, channelName, args); try { sendMessage(getSubscribeMessage(channelName, args)); } catch ( Exception throwable) { e.onError(throwable); } return newSubscription; }); }) .doOnDispose( () -> { if (channels.remove(channelId) != null) { try { sendMessage(getUnsubscribeMessage(channelId)); } catch (IOException e) { LOG.error("Failed to unsubscribe channel: {}", channelId); } } }) .share(); }

Target:
public Observable<T> subscribeChannel(String channelName, Object... args) { final String channelId = getSubscriptionUniqueId(channelName, args); LOG.info("Subscribing to channel {}", channelId); return Observable.<T>create( e -> { if (webSocketChannel == null || !webSocketChannel.isOpen()) { e.onError(new NotConnectedException()); } channels.computeIfAbsent( channelId, cid -> { Subscription newSubscription = new Subscription(e, channelName, args); try { sendMessage(getSubscribeMessage(channelName, args)); } catch ( Exception throwable) { e.onError(throwable); } return newSubscription; }); }) .doOnDispose( () -> { if (channels.remove(channelId) != null) { try { sendMessage(getUnsubscribeMessage(channelId)); } catch (IOException e) { LOG.debug("Failed to unsubscribe channel: {}", channelId, e.toString()); } catch (Exception e) { LOG.warn("Failed to unsubscribe channel: {}", channelId, e); } } }) .share(); }
Source:
public static void checkPartitionStrategy(Schema schema, PartitionStrategy strategy) { if (strategy == null) { return; } Preconditions.checkState(schema.getType() == Schema.Type.RECORD, "Cannot partition non-records: " + schema); for (org.kitesdk.data.spi.FieldPartitioner fp : strategy.getFieldPartitioners()) { Schema.Field field = schema.getField(fp.getSourceName()); Preconditions.checkState(field != null, "Cannot partition on (missing from schema)", fp.getSourceName()); Preconditions.checkState( SchemaUtil.checkType(field.schema().getType(), fp.getSourceType()), "Field type does not match partitioner {}", field.schema().getType(), fp); } }

Target:
private static void checkPartitionStrategy(Schema schema, PartitionStrategy strategy) { if (strategy == null) { return; } Preconditions.checkState(schema.getType() == Schema.Type.RECORD, "Cannot partition non-records: " + schema); for (org.kitesdk.data.spi.FieldPartitioner fp : strategy.getFieldPartitioners()) { Schema.Field field = schema.getField(fp.getSourceName()); Preconditions.checkState(field != null, "Cannot partition on (missing from schema)", fp.getSourceName()); Preconditions.checkState( SchemaUtil.checkType(field.schema().getType(), fp.getSourceType()), "Field type does not match partitioner {}", field.schema().getType(), fp); } }
Source:
public List<SnapshotInfo> getSnapshots(long volumeId, DataStoreRole role) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByVolume(volumeId, role); if (snapshotStore == null) { return null; } DataStore store = storeMgr.getDataStore(snapshotStore.getDataStoreId(), role); List<SnapshotVO> volSnapShots = snapshotDao.listByVolumeId(volumeId); List<SnapshotInfo> infos = new ArrayList<>(); for(SnapshotVO snapshot: volSnapShots) { SnapshotObject info = SnapshotObject.getSnapshotObject(snapshot, store); infos.add(info); } return infos; }

Target:
public List<SnapshotInfo> getSnapshots(long volumeId, DataStoreRole role) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByVolume(volumeId, role); if (snapshotStore == null) { return new ArrayList<>(); } DataStore store = storeMgr.getDataStore(snapshotStore.getDataStoreId(), role); List<SnapshotVO> volSnapShots = snapshotDao.listByVolumeId(volumeId); List<SnapshotInfo> infos = new ArrayList<>(); for(SnapshotVO snapshot: volSnapShots) { SnapshotObject info = SnapshotObject.getSnapshotObject(snapshot, store); infos.add(info); } return infos; }
Source:
public boolean isAuthenticated(Request request) { String authheader = request.getHeader(Constants.AUTHORIZATION_HEADER); if (authheader != null && authheader.startsWith(Constants.BEARER_AUTH_HEADER)) { String accessToken = authheader.substring(Constants.BEARER_AUTH_HEADER.length()).trim(); try { OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken); OAuth2TokenValidationResponseDTO validationResponse = null; if (validationApp != null) { validationResponse = validationApp.getAccessTokenValidationResponse(); } if (validationResponse != null) { if (validationResponse.isValid()) { String userName = validationResponse.getAuthorizedUser(); return true; } } } catch (Exception e) { log.error("Error when calling the remote service ",e); } } return false; }

Target:
public boolean isAuthenticated(Request request) { String authheader = request.getHeader(Constants.AUTHORIZATION_HEADER); if (authheader != null && authheader.startsWith(Constants.BEARER_AUTH_HEADER)) { String accessToken = authheader.substring(Constants.BEARER_AUTH_HEADER.length()).trim(); try { OAuth2ClientApplicationDTO validationApp = validateAccessToken(accessToken); OAuth2TokenValidationResponseDTO validationResponse = null; if (validationApp != null) { validationResponse = validationApp.getAccessTokenValidationResponse(); } if (validationResponse != null) { if (validationResponse.isValid()) { String userName = validationResponse.getAuthorizedUser(); return true; } } } catch (RemoteException e) { log.error("Error when calling the remote service", e); } } return false; }
Source:
public String[] getCredentials() { String[] credential = new String[2]; log.info("generate new valid token for admin"); try { Response response; WebTarget wr = this.client.target(url); String payload = "{\"auth\": {\"tenantName\": \"" + tenant + "\", \"" + "passwordCredentials\":{\"username\": \"" + user + "\"," + " \"password\": \"" + pass + "\"}}}"; Invocation.Builder builder = wr.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = builder.post(Entity.entity(payload, MediaType.APPLICATION_JSON)); if (response.getStatus() == 200) { JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class)); jsonObject = (JSONObject) jsonObject.get("access"); if (jsonObject.containsKey("token")) { JSONObject tokenObject = (JSONObject) jsonObject.get("token"); token = (String) tokenObject.get("id"); tenantId = (String) ((JSONObject) tokenObject.get("tenant")).get("id"); credential[0] = token; credential[1] = tenantId; log.info("generated new token for tenantId:" + tenantId); } } else { String exceptionMessage = "Failed : HTTP error code : (" + url + ")" + response.getStatus() + " message: " + response; log.error(exceptionMessage); throw new AuthenticationConnectionException(exceptionMessage); } } catch (Exception ex) { throw new AuthenticationConnectionException("Error in authentication: " + ex); } return credential; }

Target:
public String[] getCredentials() { String[] credential = new String[2]; log.info("generate new valid token for admin"); try { Response response; WebTarget wr = this.client.target(url); String payload = "{\"auth\": {\"tenantName\": \"" + tenant + "\", \"" + "passwordCredentials\":{\"username\": \"" + user + "\"," + " \"password\": \"" + pass + "\"}}}"; Invocation.Builder builder = wr.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); response = builder.post(Entity.entity(payload, MediaType.APPLICATION_JSON)); if ((response.getStatus() == CODE_200) || (response.getStatus() == CODE_203)) { JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class)); jsonObject = (JSONObject) jsonObject.get("access"); if (jsonObject.containsKey("token")) { JSONObject tokenObject = (JSONObject) jsonObject.get("token"); token = (String) tokenObject.get("id"); tenantId = (String) ((JSONObject) tokenObject.get("tenant")).get("id"); credential[0] = token; credential[1] = tenantId; log.info("generated new token for tenantId:" + tenantId); } } else { String exceptionMessage = "Failed : HTTP error code : (" + url + ")" + response.getStatus() + " message: " + response; log.error(exceptionMessage); throw new AuthenticationConnectionException(exceptionMessage); } } catch (Exception ex) { throw new AuthenticationConnectionException("Error in authentication: " + ex); } return credential; }
Source:
private byte[] fromBytesPayload(Message<byte[]> message) throws UnsupportedEncodingException, Exception { byte[] headers = this.objectMapper.writeValueAsBytes(message.getHeaders()); byte[] payload = message.getPayload(); ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]); buffer.putInt(headers.length); buffer.put(headers); buffer.putInt(payload.length); buffer.put(payload); return buffer.array(); }

Target:
private byte[] fromBytesPayload(Message<byte[]> message) throws Exception { byte[] headers = this.objectMapper.writeValueAsBytes(message.getHeaders()); byte[] payload = message.getPayload(); ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]); buffer.putInt(headers.length); buffer.put(headers); buffer.putInt(payload.length); buffer.put(payload); return buffer.array(); }
Source:
private KubernetesNamespaceMeta asNamespaceMeta(Namespace namespace) { Map<String, String> attributes = new HashMap<>(); if (namespace.getStatus() != null && namespace.getStatus().getPhase() != null) { attributes.put(PHASE_ATTRIBUTE, namespace.getStatus().getPhase()); } return new KubernetesNamespaceMetaImpl(namespace.getMetadata().getName(), attributes); }

Target:
private KubernetesNamespaceMeta asNamespaceMeta(Namespace namespace) { Map<String, String> attributes = new HashMap<>(2); if (namespace.getStatus() != null && namespace.getStatus().getPhase() != null) { attributes.put(PHASE_ATTRIBUTE, namespace.getStatus().getPhase()); } return new KubernetesNamespaceMetaImpl(namespace.getMetadata().getName(), attributes); }
Source:
public void testTableName() { final Config config = new Config() { @Override public String getUser() { return "testTableName"; } @Override public Environment getEnvironment() { return Environment.LOCAL; } @Override public String get(String key) { return null; } @Override public int getInt(String key) { return 0; } @Override public List<String> getList(String key) { return null; } }; final String fqTableName = DynamoUtils.getFullyQualifiedTableName(TestHealthDataRecord.class, config); assertEquals("local-testTableName-TestHealthDataRecord", fqTableName); final String simpleTableName = DynamoUtils.getSimpleTableName(fqTableName, config); assertEquals("TestHealthDataRecord", simpleTableName); assertEquals(fqTableName, DynamoUtils.getFullyQualifiedTableName(simpleTableName, config)); }

Target:
public void testTableName() { final Config config = mock(Config.class); when(config.getUser()).thenReturn("testTableName"); when(config.getEnvironment()).thenReturn(Environment.LOCAL); final String fqTableName = DynamoUtils.getFullyQualifiedTableName(TestHealthDataRecord.class, config); assertEquals("local-testTableName-TestHealthDataRecord", fqTableName); final String simpleTableName = DynamoUtils.getSimpleTableName(fqTableName, config); assertEquals("TestHealthDataRecord", simpleTableName); assertEquals(fqTableName, DynamoUtils.getFullyQualifiedTableName(simpleTableName, config)); }
Source:
public String toString() { return "(" + name + " " + lambdaExpr + ", " + argsExpr + ")"; }

Target:
public String toString() { return StringUtils.format("(%s %s, %s)", name, lambdaExpr, argsExpr); }
Source:
public boolean hasCurrency(String name) { return true; }

Target:
public boolean hasCurrency(String name) { return name.equalsIgnoreCase(ess.getSettings().getCurrencySingular()); }
Source:
public FileSystemContextReinitializer(FileSystemContext context) { mContext = context; mExecutor = new ConfigHashSync(context); REINIT_EXECUTOR.submit( new HeartbeatThread(HeartbeatContext.META_MASTER_CONFIG_HASH_SYNC, mContext.getId(), mExecutor, mContext.getClientContext().getClusterConf().getMs( PropertyKey.USER_CONF_SYNC_INTERVAL), mContext.getClientContext().getClusterConf(), mContext.getClientContext().getUserState())); }

Target:
public FileSystemContextReinitializer(FileSystemContext context) { mContext = context; mExecutor = new ConfigHashSync(context); mFuture = REINIT_EXECUTOR.scheduleAtFixedRate(() -> { try { mExecutor.heartbeat(); } catch (Exception e) { LOG.error("Uncaught exception in config hearbeat executor, shutting down", e); } }, 0, mContext.getClientContext().getClusterConf().getMs(PropertyKey.USER_CONF_SYNC_INTERVAL), TimeUnit.MILLISECONDS); }
Source:
public void setFilter(String filter) { if(filter.equals(null)) { throw new IllegalArgumentException("Invalid filter value"); } String[] allowedFilters = {"Point", "Hermite", "Cubic", "Box", "Gaussian", "Catrom", "Triangle", "Quadratic", "Mitchell"}; for (int i = 0; i < allowedFilters.length; i++) { if(filter.equalsIgnoreCase(allowedFilters[i])) { this.filter = filter; return; } } throw new IllegalArgumentException("Invalid filter value"); }

Target:
public void setFilter(String filter) { if(filter.equals(null)) { throw new IllegalArgumentException("Filter value cannot be null. Valid values are point, hermite, " + "cubic, box, gaussian, catrom, triangle, quadratic and mitchell."); } String[] allowedFilters = {"Point", "Hermite", "Cubic", "Box", "Gaussian", "Catrom", "Triangle", "Quadratic", "Mitchell"}; for (int i = 0; i < allowedFilters.length; i++) { if(filter.equalsIgnoreCase(allowedFilters[i])) { this.filter = filter; return; } } throw new IllegalArgumentException("Invalid filter value. Valid values are point, hermite, " + "cubic, box, gaussian, catrom, triangle, quadratic and mitchell."); }
Source:
public static RuleChain setupCompositionWithTimelock( Class<?> eteClass, String composeFile, List<String> availableClientNames, Map<String, String> environment) { waitDuration = Duration.TEN_MINUTES; return setup(eteClass, composeFile, availableClientNames, environment, true); }

Target:
public static RuleChain setupCompositionWithTimelock( Class<?> eteClass, String composeFile, List<String> availableClientNames, Map<String, String> environment) { waitDuration = Duration.TWO_MINUTES; return setup(eteClass, composeFile, availableClientNames, environment, true); }
Source:
public void testSerdeForConsumerPropertiesWithPasswords() throws Exception { String jsonStr = "{\n" + " \"type\": \"kafka\",\n" + " \"topic\": \"my-topic\",\n" + " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"," + " \"ssl.truststore.password\":\"mytruststorepassword\"," + " \"ssl.keystore.password\":\"mykeystorepassword\"," + " \"ssl.key.password\":\"mykeypassword\"}\n" + "}"; KafkaSupervisorIOConfig config = mapper.readValue( mapper.writeValueAsString( mapper.readValue( jsonStr, KafkaSupervisorIOConfig.class ) ), KafkaSupervisorIOConfig.class ); Assert.assertEquals("my-topic", config.getTopic()); Map<String, Object> consumerPropertyMap = config.getConsumerProperties(); DefaultPasswordProvider trustStorePasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.truststore.password"))); DefaultPasswordProvider keyStorePasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.keystore.password"))); DefaultPasswordProvider keyPasswordProvider = new DefaultPasswordProvider(String.valueOf(consumerPropertyMap.get( "ssl.key.password"))); Assert.assertEquals("localhost:9092", consumerPropertyMap.get("bootstrap.servers")); Assert.assertEquals("mytruststorepassword", trustStorePasswordProvider.getPassword()); Assert.assertEquals("mykeystorepassword", keyStorePasswordProvider.getPassword()); Assert.assertEquals("mykeypassword", keyPasswordProvider.getPassword()); }

Target:
public void testSerdeForConsumerPropertiesWithPasswords() throws Exception { String jsonStr = "{\n" + " \"type\": \"kafka\",\n" + " \"topic\": \"my-topic\",\n" + " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\",\n" + " \"ssl.truststore.password\":{\"type\": \"default\", \"password\": \"mytruststorepassword\"},\n" + " \"ssl.keystore.password\":{\"type\": \"default\", \"password\": \"mykeystorepassword\"},\n" + " \"ssl.key.password\":\"mykeypassword\"}\n" + "}"; KafkaSupervisorIOConfig config = mapper.readValue( jsonStr, KafkaSupervisorIOConfig.class ); Properties props = new Properties(); KafkaIndexTask.addConsumerPropertiesFromConfig(props, mapper, config.getConsumerProperties()); Assert.assertEquals("my-topic", config.getTopic()); Assert.assertEquals("localhost:9092", props.getProperty("bootstrap.servers")); Assert.assertEquals("mytruststorepassword", props.getProperty("ssl.truststore.password")); Assert.assertEquals("mykeystorepassword", props.getProperty("ssl.keystore.password")); Assert.assertEquals("mykeypassword", props.getProperty("ssl.key.password")); }
Source:
private ProjectState lookup(final Project.NameKey key) throws OrmException { final ReviewDb db = schema.open(); try { final Project p = db.projects().get(key); if (p == null) { return null; } final List<RefRight> rights = Collections.unmodifiableList(db.refRights().byProject( p.getNameKey()).toList()); return projectStateFactory.create(p, rights, inheritedRights); } finally { db.close(); } }

Target:
private ProjectState lookup(final Project.NameKey key) throws OrmException { final ReviewDb db = schema.open(); try { final Project p = db.projects().get(key); if (p == null) { return null; } final Collection<RefRight> rights = Collections.unmodifiableCollection(db.refRights().byProject( p.getNameKey()).toList()); return projectStateFactory.create(p, rights, inheritedRights); } finally { db.close(); } }
Source:
public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (RabbitFuture.this.channel != null) { AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(RabbitFuture.this.channel, false, null); } return super.cancel(mayInterruptIfRunning); }

Target:
public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (this.channel != null && AsyncRabbitTemplate.this.directReplyToContainer != null) { AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(this.channel, false, null); } return super.cancel(mayInterruptIfRunning); }
Source:
private boolean getEncodecoordinatesMeasures(Configuration configuration) { org.geotools.gml3.v3_2.GMLConfiguration config; if (configuration instanceof org.geotools.gml3.v3_2.GMLConfiguration) { config = (org.geotools.gml3.v3_2.GMLConfiguration) configuration; } else { config = configuration.getDependency(org.geotools.gml3.v3_2.GMLConfiguration.class); } if (config == null) { return true; } else { return config.getEncodeCoordinatesMeasures(); } }

Target:
private boolean getEncodecoordinatesMeasures(Configuration configuration) { org.geotools.gml3.v3_2.GMLConfiguration config; if (configuration instanceof org.geotools.gml3.v3_2.GMLConfiguration) { config = (org.geotools.gml3.v3_2.GMLConfiguration) configuration; } else { config = configuration.getDependency(org.geotools.gml3.v3_2.GMLConfiguration.class); } if (config == null) { return false; } else { return config.getEncodeMeasures(); } }
Source:
private void loadMainActivity(){ settings = getSharedPreferences("prefs", 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("firstRun", false); editor.commit(); Intent intent = new Intent(this, StartActivity.class); startActivity(intent); finish(); }

Target:
private void loadMainActivity() { sharedPreferences = getSharedPreferences("prefs", 0); SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit(); sharedPreferencesEditor.putBoolean("firstRun", false); sharedPreferencesEditor.commit(); startActivity(new Intent(this, StartActivity.class)); finish(); }
Source:
public void onFlush(FlushEvent event) { getCurrentWorkPlan( state.getContextProvider(), event.getSession() ).prepare(); Session session = event.getSession(); Synchronization synchronization = flushSynch.get( session ); if ( synchronization != null ) { flushSynch.remove( session ); log.debug( "flush event causing index update out of transaction" ); synchronization.beforeCompletion(); synchronization.afterCompletion( Status.STATUS_COMMITTED ); } }

Target:
public void onFlush(FlushEvent event) { HibernateOrmListenerContextProvider contextProvider = state.getContextProvider(); EventSource session = event.getSession(); PojoWorkPlan currentWorkPlan = getCurrentWorkPlan( contextProvider, session ); currentWorkPlan.prepare(); if ( !session.isTransactionInProgress() ) { AutomaticIndexingSynchronizationStrategy synchronizationStrategy = contextProvider.getSynchronizationStrategy(); synchronizationStrategy.handleFuture( currentWorkPlan.execute() ); } }
Source:
public List<String> getDeletions() { return deletes; }

Target:
public List<OpenEngSBModel> getDeletions() { return deletes; }
Source:
public BookieSocketAddress replaceBookie(List<BookieSocketAddress> existingBookies, int bookieIdx) throws BKNotEnoughBookiesException { BookieSocketAddress addr = existingBookies.get(bookieIdx); try { List<BookieSocketAddress> existingAndQuarantinedBookies = Lists.newArrayList(); existingAndQuarantinedBookies.addAll(existingBookies); existingAndQuarantinedBookies.addAll(quarantinedBookies.asMap().keySet()); return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingAndQuarantinedBookies)); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingBookies)); } }

Target:
public BookieSocketAddress replaceBookie(List<BookieSocketAddress> existingBookies, int bookieIdx) throws BKNotEnoughBookiesException { BookieSocketAddress addr = existingBookies.get(bookieIdx); try { Set<BookieSocketAddress> existingAndQuarantinedBookies = new HashSet<BookieSocketAddress>(existingBookies); existingAndQuarantinedBookies.addAll(quarantinedBookies.asMap().keySet()); return placementPolicy.replaceBookie(addr, existingAndQuarantinedBookies); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.replaceBookie(addr, new HashSet<BookieSocketAddress>(existingBookies)); } }
Source:
public Proposal(List<Command> cmds) { this.commands = cmds; }

Target:
public Proposal(List<Command> cmds) { commands = Collections.unmodifiableList(new ArrayList<>(cmds)); }
Source:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); request.setServletPath("/destination"); request.setQueryString("param1=a&param2=b&param3=1122"); return request; }

Target:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); request.setQueryString("param1=a&param2=b&param3=1122"); return request; }
Source:
public Void performTask() throws Throwable { SavedPage savedPage = new SavedPage(title); savedPage.writeToFileSystem(page); SavedPagePersister persister = (SavedPagePersister) app.getPersister(SavedPage.class); persister.upsert(savedPage); try { ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()).extractUrls(page).build(); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); } catch (HttpRequest.HttpRequestException e) { Log.e(TAG, "image download failed", e); } return null; }

Target:
public Boolean performTask() throws Throwable { SavedPage savedPage = new SavedPage(title); savedPage.writeToFileSystem(page); SavedPagePersister persister = (SavedPagePersister) app.getPersister(SavedPage.class); persister.upsert(savedPage); try { ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()).extractUrls(page).build(); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); return true; } catch (HttpRequest.HttpRequestException e) { Log.e(TAG, "image download failed", e); return false; } }
Source:
public void shouldGenerateVepInput() throws Exception { mongoRule.restoreDump(getResourceUrl(MONGO_DUMP), jobOptions.getDbName()); File vepOutputFolder = temporaryFolderRule.newFolder(); File vepInputFile = new File(VepUtils.resolveVepInput(vepOutputFolder.getAbsolutePath(), STUDY_ID, FILE_ID)); if (vepInputFile.exists()) vepInputFile.delete(); assertFalse(vepInputFile.exists()); JobParameters jobParameters = new EvaJobParameterBuilder() .collectionVariantsName("variants") .databaseName("VepInputGeneratorStepTest") .inputStudyId(STUDY_ID) .inputVcfId(FILE_ID) .outputDirAnnotation(vepOutputFolder.getAbsolutePath()) .toJobParameters(); JobExecution jobExecution = jobLauncherTestUtils.launchStep(BeanNames.GENERATE_VEP_INPUT_STEP, jobParameters); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(vepInputFile.exists()); assertEquals("20\t60343\t60343\tG/A\t+", readFirstLine(vepInputFile)); }

Target:
public void shouldGenerateVepInput() throws Exception { String randomTemporaryDatabaseName = mongoRule.restoreDumpInTemporaryDatabase(getResourceUrl(MONGO_DUMP)); File vepOutputFolder = temporaryFolderRule.newFolder(); File vepInputFile = new File(VepUtils.resolveVepInput(vepOutputFolder.getAbsolutePath(), STUDY_ID, FILE_ID)); if (vepInputFile.exists()) vepInputFile.delete(); assertFalse(vepInputFile.exists()); JobParameters jobParameters = new EvaJobParameterBuilder() .collectionVariantsName("variants") .databaseName(randomTemporaryDatabaseName) .inputStudyId(STUDY_ID) .inputVcfId(FILE_ID) .outputDirAnnotation(vepOutputFolder.getAbsolutePath()) .toJobParameters(); JobExecution jobExecution = jobLauncherTestUtils.launchStep(BeanNames.GENERATE_VEP_INPUT_STEP, jobParameters); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(vepInputFile.exists()); assertEquals("20\t60343\t60343\tG/A\t+", readFirstLine(vepInputFile)); }
Source:
public Request authenticate(Route route, Response response) throws IOException { if (requiresAuth(response.request())) { userSessionInfoProvider.reauthenticate(); return addBridgeHeaders(response.request()); } return null; }

Target:
public Request authenticate(Route route, Response response) throws IOException { if (requiresAuth(response.request(), false)) { userSessionInfoProvider.reauthenticate(); return addBridgeHeaders(response.request()); } return null; }
Source:
public void run() { Builder builder = new Builder(); builder.build(); Dataset dataset = new Dataset(); dataset.read(); Learner learner = new Learner(builder.parser, builder.params, dataset); learner.learn(); if (server) { Master master = new Master(builder); Server server = new Server(master); server.run(); } if (interactiveLearning) { Master master = new InteractiveMaster(builder); InteractiveServer server = new InteractiveServer(master); server.run(); master.runInteractivePrompt(); } if (interactive) { Master master = new InteractiveMaster(builder); master.runInteractivePrompt(); } }

Target:
public void run() { Builder builder = new Builder(); builder.build(); Dataset dataset = new Dataset(); dataset.read(); Learner learner = new Learner(builder.parser, builder.params, dataset); learner.learn(); if (server || interactive) { Master master = createMaster(masterType, builder); if (server) master.runServer(); if (interactive) master.runInteractivePrompt(); } }
Source:
public void doAddRoleWithID(String roleName, String[] userIDList, boolean shared) throws UserStoreException { List<String> userList = getUserNamesFromUserIDs(Arrays.asList(userIDList)); String userStoreDomain = getUserStoreOfRoles(roleName).getDomainName(); boolean containsInvalidUsernames = userList.stream() .anyMatch(username -> !UserCoreUtil.extractDomainFromName(username).equalsIgnoreCase(userStoreDomain)); if (containsInvalidUsernames) { throw new UserStoreException("One or more users in the users list: " + userList + " do not belong to the" + " user store: " + userStoreDomain); } userList = userList.stream().map(UserCoreUtil::removeDomainFromName).collect(Collectors.toList()); RoleContext roleContext; roleContext = createRoleContext(roleName); roleContext.setMembers(userList.toArray(new String[0])); addLDAPRole(roleContext); if (shared && isSharedGroupEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); roleName = roleName + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain; roleContext = createRoleContext(roleName); addLDAPRole(roleContext); } }

Target:
public void doAddRoleWithID(String roleName, String[] userIDList, boolean shared) throws UserStoreException { List<String> userList = getUserNamesFromUserIDs(Arrays.asList(userIDList)); String userStoreDomain = getMyDomainName(); boolean containsInvalidUsernames = userList.stream() .anyMatch(username -> !UserCoreUtil.extractDomainFromName(username).equalsIgnoreCase(userStoreDomain)); if (containsInvalidUsernames) { throw new UserStoreException("One or more users in the users list: " + userList + " do not belong to the" + " user store: " + userStoreDomain); } userList = userList.stream().map(UserCoreUtil::removeDomainFromName).collect(Collectors.toList()); RoleContext roleContext; roleContext = createRoleContext(roleName); roleContext.setMembers(userList.toArray(new String[0])); addLDAPRole(roleContext); if (shared && isSharedGroupEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); roleName = roleName + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain; roleContext = createRoleContext(roleName); addLDAPRole(roleContext); } }