auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void filterAnyTextFieldCache() { Set<String> filteredList = new HashSet<>(); ConfigurationStore config = ConfigurationStore.getInstance(); List<String> anyTextFieldWhitelist = config.getAnyTextFieldWhitelist(); List<String> anyTextFieldBlacklist = config.getAnyTextFieldBlacklist(); if (!anyTextFieldWhitelist.isEmpty()) { for (String whitelistField : anyTextFieldWhitelist) { String whitelist; if (!whitelistField.endsWith(SchemaFields.TEXT_SUFFIX)) { whitelist = whitelistField + SchemaFields.TEXT_SUFFIX; } else { whitelist = whitelistField; } filteredList.addAll( anyTextFieldsCache .stream() .filter(field -> field.matches(whitelist)) .collect(Collectors.toList())); } } else if (!anyTextFieldBlacklist.isEmpty()) { filteredList.addAll(anyTextFieldsCache); for (String blacklistField : anyTextFieldBlacklist) { String blacklist; if (!blacklistField.endsWith(SchemaFields.TEXT_SUFFIX)) { blacklist = blacklistField + SchemaFields.TEXT_SUFFIX; } else { blacklist = blacklistField; } filteredList.removeAll( anyTextFieldsCache .stream() .filter(field -> field.matches(blacklist)) .collect(Collectors.toList())); } } else { filteredList.addAll(anyTextFieldsCache); } filteredAnyTextFieldsCache = filteredList; }

Target:
private void filterAnyTextFieldCache() { Set<String> filteredList = new HashSet<>(); ConfigurationStore config = ConfigurationStore.getInstance(); List<String> anyTextFieldWhitelist = config.getAnyTextFieldWhitelist(); List<String> anyTextFieldBlacklist = config.getAnyTextFieldBlacklist(); if (!anyTextFieldBlacklist.isEmpty()) { filteredList.addAll(anyTextFieldsCache); for (String blacklistField : anyTextFieldBlacklist) { String blacklist; if (!blacklistField.endsWith(SchemaFields.TEXT_SUFFIX)) { blacklist = blacklistField + SchemaFields.TEXT_SUFFIX; } else { blacklist = blacklistField; } filteredList.removeAll( anyTextFieldsCache .stream() .filter(field -> field.matches(blacklist)) .collect(Collectors.toList())); } } if (!anyTextFieldWhitelist.isEmpty()) { for (String whitelistField : anyTextFieldWhitelist) { String whitelist; if (!whitelistField.endsWith(SchemaFields.TEXT_SUFFIX)) { whitelist = whitelistField + SchemaFields.TEXT_SUFFIX; } else { whitelist = whitelistField; } filteredList.addAll( anyTextFieldsCache .stream() .filter(field -> field.matches(whitelist)) .collect(Collectors.toList())); } } if (anyTextFieldBlacklist.isEmpty() && anyTextFieldWhitelist.isEmpty()) { filteredList.addAll(anyTextFieldsCache); } filteredAnyTextFieldsCache = filteredList; }
Source:
public Iterable<IClasspathEntry> load(IJavaProject project) throws FileNotFoundException, CoreException { Iterable<IClasspathEntry> classpath = super.load(project); if(configuration.isDownloadJavaDoc()) { return attacher.attach(project, classpath); } return classpath; }

Target:
public Iterable<IClasspathEntry> load(IJavaProject project) throws FileNotFoundException { Iterable<IClasspathEntry> classpath = super.load(project); if(configuration.isDownloadJavaDoc()) { return attacher.attach(project, classpath); } return classpath; }
Source:
private void validate(ImmutableList<UpdaterConfiguration> configurations) { Set<Publisher> configuredSources = Sets.newHashSet(); for (UpdaterConfiguration configuration : configurations) { if (configuredSources.contains(configuration.getSource())) { throw new IllegalArgumentException(format( "Found duplicate updater configuration for source %s. Keeping last added", configuration.getSource() )); } configuredSources.add(configuration.getSource()); } }

Target:
private static void validate(ImmutableList<UpdaterConfiguration> configurations) { Set<Publisher> configuredSources = Sets.newHashSet(); for (UpdaterConfiguration configuration : configurations) { if (configuredSources.contains(configuration.getSource())) { throw new IllegalArgumentException(format( "Found duplicate updater configuration for source %s", configuration.getSource() )); } configuredSources.add(configuration.getSource()); } }
Source:
synchronized private Semaphore getSemaphore() { if (sem == null) { sem = new Semaphore(maxThreadPermits); } return sem; }

Target:
public Semaphore getSemaphore() { int writeThreads = getServerConfig().getConfiguration().getCount(Property.TSERV_MAX_WRITETHREADS); if (writeThreads == 0) writeThreads = Integer.MAX_VALUE; if (sem == null || maxThreadPermits != writeThreads) { synchronized (this) { maxThreadPermits = writeThreads; sem = new Semaphore(maxThreadPermits); } } return sem; }
Source:
protected String delete(String path, String ...params) { path = getPath(path, params); try { HttpDelete get = new HttpDelete(); setupCommonHeaders(get); get.setURI(uri.resolve(path)); return getJSON(get); } catch (IOException e) { throw new HttpClientException(e); } }

Target:
protected String delete(String path, String ...params) { path = getPath(path, params); try { HttpDelete delete = new HttpDelete(); setupCommonHeaders(delete); delete.setURI(uri.resolve(path)); return getJSON(delete); } catch (IOException e) { throw new HttpClientException(e); } }
Source:
protected void updateStorageDomainFormatIfNeeded(StorageDomain domain) { final StorageDomainType sdType = domain.getStorageDomainType(); if (sdType != StorageDomainType.Data && sdType != StorageDomainType.Master) { log.debug("Skipping format update for domain '{}' (type '{}')", getStorageDomain().getId(), sdType); return; } final StorageDomainStatic storageStaticData = domain.getStorageStaticData(); final StorageFormatType targetFormat = getStoragePool().getStoragePoolFormatType(); if (storageStaticData.getStorageFormat() != targetFormat) { log.info("Updating storage domain '{}' (type '{}') to format '{}'", getStorageDomain().getId(), sdType, targetFormat); storageStaticData.setStorageFormat(targetFormat); getStorageDomainStaticDAO().update(storageStaticData); } else { log.debug("Skipping format update for domain '{}' format is '{}'", getStorageDomain().getId(), storageStaticData.getStorageFormat()); } }

Target:
protected void updateStorageDomainFormatIfNeeded(StorageDomain domain) { final StorageDomainType sdType = domain.getStorageDomainType(); if (!sdType.isDataDomain()) { log.debug("Skipping format update for domain '{}' (type '{}')", getStorageDomain().getId(), sdType); return; } final StorageDomainStatic storageStaticData = domain.getStorageStaticData(); final StorageFormatType targetFormat = getStoragePool().getStoragePoolFormatType(); if (storageStaticData.getStorageFormat() != targetFormat) { log.info("Updating storage domain '{}' (type '{}') to format '{}'", getStorageDomain().getId(), sdType, targetFormat); storageStaticData.setStorageFormat(targetFormat); getStorageDomainStaticDAO().update(storageStaticData); } else { log.debug("Skipping format update for domain '{}' format is '{}'", getStorageDomain().getId(), storageStaticData.getStorageFormat()); } }
Source:
protected void onPostExecute(final StringWriter stringWriter) { mTextView.setText(new String(stringWriter.getBuffer())); mTextView.setVisibility(View.VISIBLE); dismissLoadingDialog(); }

Target:
protected void onPostExecute(final StringWriter stringWriter) { final TextView textView = mTextViewReference.get(); if (textView != null) { textView.setText(new String(stringWriter.getBuffer())); textView.setVisibility(View.VISIBLE); } dismissLoadingDialog(); }
Source:
public RangerCloudIdentitySyncStatus setAzureCloudIdentityMapping(String envCrn, Map<String, String> azureUserMapping) { Optional<SdxCluster> sdxCluster = getSdxCluster(envCrn); if (sdxCluster.isEmpty()) { return sucessfulCloudIdSyncStatus("No datlakes associated with the environment."); } return setAzureCloudIdentityMapping(envCrn, sdxCluster.get(), azureUserMapping); }

Target:
public RangerCloudIdentitySyncStatus setAzureCloudIdentityMapping(String envCrn, Map<String, String> azureUserMapping) { Optional<SdxCluster> sdxCluster = getSdxCluster(envCrn); if (sdxCluster.isEmpty()) { return newSyncStatus(RangerCloudIdentitySyncState.NOT_APPLICABLE, "No datalakes associated with the environment."); } return setAzureCloudIdentityMapping(envCrn, sdxCluster.get(), azureUserMapping); }
Source:
public void shouldCreateOnlyOneRepartitionTopicWhenRepartitionIsFollowedByGroupByKey() throws ExecutionException, InterruptedException { final String repartitionName = "new-partitions"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); final Repartitioned<String, String> repartitioned = Repartitioned.<String, String>as(repartitionName) .withKeySerde(Serdes.String()) .withValueSerde(Serdes.String()) .withNumberOfPartitions(1); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .selectKey((key, value) -> key.toString()) .repartition(repartitioned) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); final String topology = builder.build().describe().toString(); validateReceivedMessages( new StringDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>("1", 1L), new KeyValue<>("2", 1L) ) ); assertTrue(topicExists(toRepartitionTopicName(repartitionName))); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*-repartition")); }

Target:
public void shouldCreateOnlyOneRepartitionTopicWhenRepartitionIsFollowedByGroupByKey() throws Exception { final String repartitionName = "new-partitions"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); final Repartitioned<String, String> repartitioned = Repartitioned.<String, String>as(repartitionName) .withKeySerde(Serdes.String()) .withValueSerde(Serdes.String()) .withNumberOfPartitions(1); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .selectKey((key, value) -> key.toString()) .repartition(repartitioned) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); final String topology = builder.build().describe().toString(); validateReceivedMessages( new StringDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>("1", 1L), new KeyValue<>("2", 1L) ) ); assertTrue(topicExists(toRepartitionTopicName(repartitionName))); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*-repartition")); }
Source:
private ContentCategory getContentCategory(String mimetype, String extension) { if (mimetype == null) return ContentCategory.unknown; int index = mimetype.indexOf('/'); if (index != -1) { String mimetypeType = mimetype.substring(0, index); if (mimetypeType.equals("image")) return ContentCategory.image; if (mimetypeType.equals("video")) return ContentCategory.video; if (mimetypeType.equals("audio")) return ContentCategory.audio; } String contentCategory = (String) contentTypeProperties.get("mime." + mimetype); if (contentCategory == null) contentCategory = (String) contentTypeProperties.get("ext." + extension); return ContentCategory.getContentCategory(contentCategory); }

Target:
private ContentCategory getContentCategory(String mimetype, String extension) { if (mimetype == null) { return ContentCategory.unknown; } int index = mimetype.indexOf('/'); if (index != -1) { String mimetypeType = mimetype.substring(0, index); if (mimetypeType.equals("image")) { return ContentCategory.image; } if (mimetypeType.equals("video")) { return ContentCategory.video; } if (mimetypeType.equals("audio")) { return ContentCategory.audio; } } String contentCategory = (String) contentTypeProperties.get("mime." + mimetype); contentCategory = (String) contentTypeProperties.get("ext." + extension); return ContentCategory.getContentCategory(contentCategory); }
Source:
private static boolean isException(ClassTree classTree) { Type type = classTree.symbol().type(); return type.isSubtypeOf("java.lang.Exception") || type.isSubtypeOf("java.lang.Error"); }

Target:
private static boolean isException(ClassTree classTree) { return classTree.simpleName() != null && classTree.symbol().type().isSubtypeOf("java.lang.Throwable"); }
Source:
private PollingResult compare(Launcher launcher, TaskListener listener, MercurialTagAction baseline, PrintStream output, Node node, FilePath repository, AbstractProject<?,?> project) throws IOException, InterruptedException { HgExe hg = new HgExe(findInstallation(getInstallation()), getCredentials(project), launcher, node, listener, new EnvVars()); String _branch = getBranchExpanded(project); String remote = hg.tip(repository, _branch); String rev = hg.tipNumber(repository, _branch); if(!(project instanceof MatrixProject)) { Change change = null; for(AbstractComparator s : AbstractComparator.all()) { Change c = s.compare(this, launcher, listener, baseline, output, node, repository, project); if(c != null) { if(change == null || c.compareTo(change) > 0){ change = c; } } } if(change != null) { return new PollingResult(baseline, new MercurialTagAction(remote, rev, subdir), change); } } if (remote == null) { throw new IOException("failed to find ID of branch head"); } if (rev == null) { throw new IOException("failed to find revision of branch head"); } if (remote.equals(baseline.id)) { return new PollingResult(baseline, new MercurialTagAction(remote, rev, subdir), Change.NONE); } Set<String> changedFileNames = parseStatus(hg.popen(repository, listener, false, new ArgumentListBuilder("status", "--rev", baseline.id, "--rev", remote))); MercurialTagAction cur = new MercurialTagAction(remote, rev, subdir); return new PollingResult(baseline,cur,computeDegreeOfChanges(changedFileNames,output)); }

Target:
private PollingResult compare(Launcher launcher, TaskListener listener, MercurialTagAction baseline, PrintStream output, Node node, FilePath repository, AbstractProject<?,?> project) throws IOException, InterruptedException { HgExe hg = new HgExe(findInstallation(getInstallation()), getCredentials(project), launcher, node, listener, new EnvVars()); String _branch = getBranchExpanded(project); String remote = hg.tip(repository, _branch); String rev = hg.tipNumber(repository, _branch); Change change = null; for(ChangeComparator s : ChangeComparator.all()) { Change c = s.compare(this, launcher, listener, baseline, output, node, repository, project); if(c != null) { if(change == null || c.compareTo(change) > 0){ change = c; } } } if(change != null) { return new PollingResult(change); } if (remote == null) { throw new IOException("failed to find ID of branch head"); } if (rev == null) { throw new IOException("failed to find revision of branch head"); } if (remote.equals(baseline.id)) { return new PollingResult(baseline, new MercurialTagAction(remote, rev, subdir), Change.NONE); } Set<String> changedFileNames = parseStatus(hg.popen(repository, listener, false, new ArgumentListBuilder("status", "--rev", baseline.id, "--rev", remote))); MercurialTagAction cur = new MercurialTagAction(remote, rev, subdir); return new PollingResult(baseline,cur,computeDegreeOfChanges(changedFileNames,output)); }
Source:
public AnnotationMemberDeclaration asAnnotationMemberDeclaration() { return (AnnotationMemberDeclaration) this; }

Target:
public AnnotationMemberDeclaration asAnnotationMemberDeclaration() { throw new IllegalStateException(f("%s is not an AnnotationMemberDeclaration", this)); }
Source:
public RealmObjectSchema addRealmListField(String fieldName, Class<?> primitiveType) { checkLegalName(fieldName); checkFieldNameIsAvailable(fieldName); FieldMetaData metadata = SUPPORTED_SIMPLE_FIELDS.get(primitiveType); if (metadata == null) { if (primitiveType.equals(RealmObjectSchema.class)) { throw new IllegalArgumentException("Use 'addRealmListField(String name, RealmObjectSchema schema)' instead to add lists that link to other RealmObjects: " + fieldName); } else { throw new IllegalArgumentException(String.format(Locale.US, "RealmList does not support lists with this type: %s(%s)", fieldName, primitiveType)); } } table.addColumn(metadata.listType, fieldName, metadata.defaultNullable); return this; }

Target:
public RealmObjectSchema addRealmListField(String fieldName, Class<?> primitiveType) { checkLegalName(fieldName); checkFieldNameIsAvailable(fieldName); FieldMetaData metadata = SUPPORTED_SIMPLE_FIELDS.get(primitiveType); if (metadata == null) { if (primitiveType.equals(RealmObjectSchema.class) || RealmModel.class.isAssignableFrom(primitiveType)) { throw new IllegalArgumentException("Use 'addRealmListField(String name, RealmObjectSchema schema)' instead to add lists that link to other RealmObjects: " + fieldName); } else { throw new IllegalArgumentException(String.format(Locale.US, "RealmList does not support lists with this type: %s(%s)", fieldName, primitiveType)); } } table.addColumn(metadata.listType, fieldName, metadata.defaultNullable); return this; }
Source:
private static Block createBlock(int positionCount, Type type) { BlockBuilder blockBuilder = type.createBlockBuilder(null, positionCount); if (type instanceof VarcharType) { for (int i = 0; i < positionCount; i++) { type.writeSlice(blockBuilder, Slices.utf8Slice(String.valueOf(ThreadLocalRandom.current().nextInt()))); } } else if (type == BIGINT) { for (int i = 0; i < positionCount; i++) { type.writeLong(blockBuilder, ThreadLocalRandom.current().nextLong()); } } else { throw new UnsupportedOperationException(); } return blockBuilder.build(); }

Target:
private static Block createBlock(int positionCount, Type type) { BlockBuilder blockBuilder = type.createBlockBuilder(null, positionCount); if (type instanceof VarcharType) { for (int i = 0; i < positionCount; i++) { type.writeSlice(blockBuilder, utf8Slice(String.valueOf(ThreadLocalRandom.current().nextInt()))); } } else if (type == BIGINT) { for (int i = 0; i < positionCount; i++) { type.writeLong(blockBuilder, ThreadLocalRandom.current().nextLong()); } } else { throw new UnsupportedOperationException(); } return blockBuilder.build(); }
Source:
private static <T> T invoke(Method method, Object obj, Object... args) { try { return (T)method.invoke(obj, args); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Can't invoke method " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Can't invoke method " + method.getName(), e); } }

Target:
private static Object invoke(Method method, Object obj, Object... args) { try { return method.invoke(obj, args); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Can't invoke method " + method.getName(), e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Can't invoke method " + method.getName(), e); } }
Source:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; case WARNING: warnings++; tool.warning(msg); break; case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }

Target:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: if ( errorTypes.contains(etype) ) break; case WARNING: warnings++; tool.warning(msg); break; case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }
Source:
private void validateSearchParam(String theFieldName, String theTheResourceType, String theTheSearchParam) { if ("*".equals(theTheResourceType)) { validateResourceSearchParam(theFieldName, "Patient", theTheSearchParam); validateResourceSearchParam(theFieldName, "Practitioner", theTheSearchParam); } else { validateResourceSearchParam(theFieldName, theTheResourceType, theTheSearchParam); } }

Target:
private void validateSearchParam(String theFieldName, String theTheResourceType, String theTheSearchParam) { if (EmpiConstants.ALL_RESOURCE_SEARCH_PARAM_TYPE.equals(theTheResourceType)) { validateResourceSearchParam(theFieldName, "Patient", theTheSearchParam); validateResourceSearchParam(theFieldName, "Practitioner", theTheSearchParam); } else { validateResourceSearchParam(theFieldName, theTheResourceType, theTheSearchParam); } }
Source:
public String getFullViewPath() { if (null == assetRoot || "".equals(assetRoot)) { return viewPath; } return URI.create(assetRoot + "/" + viewPath).normalize().toString(); }

Target:
public String getFullViewPath() { if (StringUtils.isBlank(assetRoot)) { return viewPath; } return URI.create(assetRoot + "/" + viewPath).normalize().toString(); }
Source:
protected boolean validateAttachment() { NetworkClusterValidator validator = new NetworkClusterValidator(getNetworkCluster(), getClusterVersion()); return (!NetworkUtils.isManagementNetwork(getNetwork()) || validate(validator.managementNetworkAttachment(getNetworkName()))) && validate(validator.migrationPropertySupported(getNetworkName())) && (!getNetwork().isExternal() || validateExternalNetwork(validator)); }

Target:
protected boolean validateAttachment() { NetworkClusterValidator validator = new NetworkClusterValidator(getNetworkCluster(), getClusterVersion()); return (!NetworkUtils.isManagementNetwork(getNetworkName()) || validate(validator.managementNetworkAttachment(getNetworkName()))) && validate(validator.migrationPropertySupported(getNetworkName())) && (!getPersistedNetwork().isExternal() || validateExternalNetwork(validator)); }
Source:
public PlanNodeCostEstimate visitSemiJoin(SemiJoinNode node, Void context) { return calculateJoinCost( node.getSource(), node.getFilteringSource(), node.getDistributionType().orElse(SemiJoinNode.DistributionType.PARTITIONED).equals(SemiJoinNode.DistributionType.REPLICATED)); }

Target:
public PlanNodeCostEstimate visitSemiJoin(SemiJoinNode node, Void context) { return calculateJoinCost( node.getSource(), node.getFilteringSource(), Objects.equals(node.getDistributionType(), Optional.of(SemiJoinNode.DistributionType.REPLICATED))); }
Source:
public void processRecord(ComputationContext context, String inputStreamName, Record record) { Work work = deserialize(record.getData()); try { if (work.isIdempotent() && workIds.contains(work.getId())) { log.warn("Duplicate work id: " + work.getId() + " skipping"); } else { new WorkHolder(work).run(); workIds.add(work.getId()); KeyValueStore kvStore = Framework.getService(KeyValueService.class) .getKeyValueStore(StreamWorkManager.KV_NAME); kvStore.put(work.getId() + StreamWorkManager.STATE, Work.State.RUNNING.toString()); kvStore.setTTL(work.getId() + StreamWorkManager.STATE, 60 * 60L); } work.cleanUp(true, null); context.askForCheckpoint(); } catch (Exception e) { if (ExceptionUtils.hasInterruptedCause(e)) { Thread.currentThread().interrupt(); log.warn( String.format("Work id: %s title: %s, has been interrupted, it will be rescheduled, record: %s", work.getId(), work.getTitle(), record)); } else { log.error(String.format("Work id: %s title: %s is in error, the work is skipped, record: %s", work.getId(), work.getTitle(), record)); context.askForCheckpoint(); } log.debug("Exception during work " + work.getId(), e); work.cleanUp(false, e); } finally { workTimer.update(work.getCompletionTime() - work.getStartTime(), TimeUnit.MILLISECONDS); } }

Target:
public void processRecord(ComputationContext context, String inputStreamName, Record record) { Work work = deserialize(record.getData()); try { if (work.isIdempotent() && workIds.contains(work.getId())) { log.warn("Duplicate work id: " + work.getId() + " skipping"); } else { boolean storeState = Boolean.parseBoolean( Framework.getService(ConfigurationService.class).getProperty(STORESTATE_KEY)); if (storeState) { StreamWorkManager.setState(work.getId(), Work.State.RUNNING.toString(), stateTTL); } new WorkHolder(work).run(); if (storeState) { KeyValueStore kvStore = Framework.getService(KeyValueService.class).getKeyValueStore(KV_NAME); kvStore.put(work.getId() + STATE_SUFFIX, (String) null); } workIds.add(work.getId()); } work.cleanUp(true, null); context.askForCheckpoint(); } catch (Exception e) { if (ExceptionUtils.hasInterruptedCause(e)) { Thread.currentThread().interrupt(); log.warn( String.format("Work id: %s title: %s, has been interrupted, it will be rescheduled, record: %s", work.getId(), work.getTitle(), record)); } else { log.error(String.format("Work id: %s title: %s is in error, the work is skipped, record: %s", work.getId(), work.getTitle(), record)); context.askForCheckpoint(); } log.debug("Exception during work " + work.getId(), e); work.cleanUp(false, e); } finally { workTimer.update(work.getCompletionTime() - work.getStartTime(), TimeUnit.MILLISECONDS); } }
Source:
protected void stopParticipant(int i) { if (_participants.length <= i) { throw new HelixException(String .format("Can't stop participant %s, only %s participants" + "were set up.", i, _participants.length)); } if (_participants[i] != null) { if (_participants[i].isConnected()) { _participants[i].syncStop(); } StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); if (stateMachine != null) { StateModelFactory stateModelFactory = stateMachine.getStateModelFactory("Task"); if (stateModelFactory != null && stateModelFactory instanceof TaskStateModelFactory) { ((TaskStateModelFactory) stateModelFactory).shutdownNow(); } } } }

Target:
protected void stopParticipant(int i) { if (_participants.length <= i) { throw new HelixException(String .format("Can't stop participant %s, only %s participants" + "were set up.", i, _participants.length)); } if (_participants[i] != null) { if (_participants[i].isConnected()) { _participants[i].syncStop(); } StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); if (stateMachine != null) { StateModelFactory stateModelFactory = stateMachine.getStateModelFactory(TaskConstants.STATE_MODEL_NAME); if (stateModelFactory != null && stateModelFactory instanceof TaskStateModelFactory) { ((TaskStateModelFactory) stateModelFactory).shutdownNow(); } } } }
Source:
public Response createIssue(@Context HttpServletRequest request, @FormParam("title") String title, @FormParam("description") String description, @FormParam("assignee") String assigneeNetID) throws IOException{ Issue issue = new Issue(); issue.setTitle(title); issue.setDescription(description); issue.setOpen(true); if (!assigneeNetID.isEmpty()) { User assignee = users.findByNetId(assigneeNetID); checkCollaborator(assignee); issue.setAssignee(assignee); } issue.setRepository(getRepositoryEntity()); issueBackend.createIssue(getRepositoryApi(getRepositoryEntity()), issue); return redirect(issue.getURI().toString()); }

Target:
public Response createIssue(@Context HttpServletRequest request, @FormParam("title") String title, @FormParam("description") String description, @FormParam("assignee") String assigneeNetID) throws IOException{ Issue issue = new Issue(); issue.setTitle(title); issue.setDescription(description); issue.setOpen(true); if (!Strings.isNullOrEmpty(assigneeNetID)) { User assignee = users.findByNetId(assigneeNetID); checkCollaborator(assignee); issue.setAssignee(assignee); } else { issue.setAssignee(null); } issue.setRepository(getRepositoryEntity()); issueBackend.createIssue(getRepositoryApi(getRepositoryEntity()), issue); return redirect(issue.getURI().toString()); }
Source:
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { boolean swipe = false; int dx = (int)(e2.getX() - e1.getX()); if(dx > SWIPE_MIN_DISTANCE && velocityX > velocityY){ if(getPlaylistService().getCurrentEntry()!= null && getPlaylistService().getCurrentEntry().equals(entry)){ getPlaylistService().skip(); } getPlaylistService().removeSong(entry); animateView(dx); swipe=true; } Log.i("Swipe Removal", "distance " + dx); return swipe; }

Target:
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { boolean swipe = false; if(isSwipe(e1, e2, velocityX, velocityY)){ if(getPlaylistService().getCurrentEntry()!= null && getPlaylistService().getCurrentEntry().equals(entry)){ getPlaylistService().skip(); } getPlaylistService().removeSong(entry); animateDragging((int)e2.getX()); swipe=true; } return swipe; }
Source:
public Object2LongMap<String> getSegmentAvailability() { final Object2LongOpenHashMap<String> retVal = new Object2LongOpenHashMap<>(); if (segmentReplicantLookup == null) { return retVal; } for (DataSegment segment : getAvailableDataSegments()) { if (segmentReplicantLookup.getTotalReplicants(segment.getIdentifier()) == 0) { retVal.addTo(segment.getDataSource(), 1); } } return retVal; }

Target:
public Object2LongMap<String> getSegmentAvailability() { final Object2LongOpenHashMap<String> retVal = new Object2LongOpenHashMap<>(); if (segmentReplicantLookup == null) { return retVal; } for (DataSegment segment : getAvailableDataSegments()) { if (segmentReplicantLookup.getTotalReplicants(segment.getIdentifier()) == 0) { retVal.addTo(segment.getDataSource(), 1); } else { retVal.addTo(segment.getDataSource(), 0); } } return retVal; }
Source:
public void run() { m_licenseApi = MiscUtils.licenseApiFactory(); String type = getLicenseType(m_licenseApi); String issuer = "VoltDB"; String licensee = m_licenseApi.licensee(); Calendar issueDate = m_licenseApi.issued(); String key; Calendar expirationDate = m_licenseApi.expires(); int hostCount = m_licenseApi.maxHostcount(); Boolean commandLoggingEnabled = m_licenseApi.isCommandLoggingAllowed(); Boolean activePassiveDREnabled; Boolean activeActiveDREnabled = m_licenseApi.isDrActiveActiveAllowed(); Boolean isDrReplicationAllowed = m_licenseApi.isDrReplicationAllowed(); hostLog.info("LICENSE INFORMATION: " + type + " license issued by " + issuer + " to " + licensee + " on " + issueDate); hostLog.info("LICENSE EXPIRES: " + expirationDate); hostLog.info("LICENSE CONSTRAINTS: " + hostCount + "nodes"); hostLog.info("LICENCE FEATURES: " + "commandLoggingEnabled=" + commandLoggingEnabled + ", activeActiveDREnabled=" + activeActiveDREnabled + ", isDrReplicationAllowed=" + isDrReplicationAllowed); m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); hostLog.info("URL of deployment info: " + m_config.m_pathToDeployment); hostLog.info("Cluster uptime: " + MiscUtils.formatUptime(getClusterUptime())); logDebuggingInfo(m_config, m_httpPortExtraLogMessage, m_jsonEnabled); logSystemSettingFromCatalogContext(); scheduleDailyLoggingWorkInNextCheckTime(); EnterpriseMaintenance em = EnterpriseMaintenance.get(); if (em != null) { em.dailyMaintenaceTask(); } }

Target:
public void run() { logLicensingInfo(); m_myHostId = m_messenger.getHostId(); hostLog.info(String.format("Host id of this node is: %d", m_myHostId)); hostLog.info("URL of deployment info: " + m_config.m_pathToDeployment); hostLog.info("Cluster uptime: " + MiscUtils.formatUptime(getClusterUptime())); logDebuggingInfo(m_config, m_httpPortExtraLogMessage, m_jsonEnabled); logSystemSettingFromCatalogContext(); scheduleDailyLoggingWorkInNextCheckTime(); EnterpriseMaintenance em = EnterpriseMaintenance.get(); if (em != null) { em.dailyMaintenaceTask(); } }
Source:
public void testRemove() throws Exception{ String fileID = store.remove(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); fileID = store.remove(file1); assertNotNull(fileID); assertEquals(file1Id, fileID); }

Target:
public void testRemove() throws Exception { String fileID = store.remove(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); fileID = store.remove(file1); assertNotNull(fileID); assertEquals(file1Id, fileID); fileID = store.get(file1); assertNull(fileID); }
Source:
private static boolean isNullLiteral(ExpressionTree lastArgument) { ExpressionTree arg = ExpressionUtils.skipParentheses(lastArgument); return arg.is(Tree.Kind.NULL_LITERAL) || (arg.is(Tree.Kind.TYPE_CAST) && ((TypeCastTree) arg).expression().is(Tree.Kind.NULL_LITERAL)); }

Target:
private static boolean isNullLiteral(ExpressionTree lastArgument) { ExpressionTree arg = ExpressionUtils.skipParentheses(lastArgument); return arg.is(Tree.Kind.NULL_LITERAL) || (arg.is(Tree.Kind.TYPE_CAST) && isNullLiteral(((TypeCastTree) arg).expression())); }
Source:
private String getParamJsonString(String param, String[] params) throws JSONException { JSONObject internal = new JSONObject(), external = new JSONObject(); internal.put(params[0], params[1]); external.put(param, internal); return external.toString(); }

Target:
private static String getParamJsonString(String param, String[] params) throws JSONException { JSONObject internal = new JSONObject(), external = new JSONObject(); internal.put(params[0], params[1]); external.put(param, internal); return external.toString(); }
Source:
@Override public ClientResponse process(ClientConnectionContext ctx) { ClientTxContext txCtx = ctx.txContext(txId); if (txCtx == null && !committed) return super.process(ctx); if (txCtx == null) throw new IgniteClientException(ClientStatus.TX_NOT_FOUND, "Transaction with id " + txId + " not found."); try (GridNearTxLocal tx = txCtx.tx()) { if (committed) tx.commit(); else tx.rollback(); } catch (IgniteCheckedException e) { throw new IgniteClientException(ClientStatus.FAILED, e.getMessage(), e); } finally { ctx.removeTxContext(txId); } return super.process(ctx); }

Target:
@Override public ClientResponse process(ClientConnectionContext ctx) { ClientTxContext txCtx = ctx.txContext(txId); if (txCtx == null && !committed) return super.process(ctx); if (txCtx == null) throw new IgniteClientException(ClientStatus.TX_NOT_FOUND, "Transaction with id " + txId + " not found."); try { txCtx.acquire(committed); try (GridNearTxLocal tx = txCtx.tx()) { if (committed) tx.commit(); else tx.rollback(); } } catch (IgniteCheckedException e) { throw new IgniteClientException(ClientStatus.FAILED, e.getMessage(), e); } finally { ctx.removeTxContext(txId); try { txCtx.release(false); } catch (IgniteCheckedException ignore) { } } return super.process(ctx); }
Source:
public UnweightedDoubleReservoirSample(int maxSamples) { checkArgument(maxSamples > 0, "Number of samples must be positive"); checkArgument(maxSamples <= MAX_SAMPLES_LIMIT, "Maximum number of reservoir samples is capped"); this.count = 0; this.samples = new double[maxSamples]; }

Target:
public UnweightedDoubleReservoirSample(int maxSamples) { checkArgument( maxSamples > 0, format("Maximum number of samples must be positive: %s", maxSamples)); checkArgument( maxSamples <= MAX_SAMPLES_LIMIT, format("Maximum number of samples must not exceed maximum: %s %s", maxSamples, MAX_SAMPLES_LIMIT)); this.samples = new double[maxSamples]; }
Source:
public void getMrrtReportTemplateByTitle_shouldGetListOfTemplatesThatMatchGivenTitle() throws Exception { List<MrrtReportTemplate> templates = mrrtReportTemplateService.getMrrtReportTemplateByTitle(EXISTING_TEMPLATE_TITLE); assertNotNull(templates); assertThat(templates.size(), is(1)); }

Target:
public void getMrrtReportTemplateByTitle_shouldGetListOfTemplatesThatMatchGivenTitle() throws Exception { List<MrrtReportTemplate> templates = mrrtReportTemplateService.getMrrtReportTemplateByTitle(EXISTING_TEMPLATE_TITLE); assertNotNull(templates); assertThat(templates.size(), is(1)); for (MrrtReportTemplate template : templates) { assertThat(template.getDcTermsTitle() .contains(EXISTING_TEMPLATE_TITLE), is(true)); } }
Source:
private static long computeFileChecksum(final File sourceFile) { try ( CheckedInputStream stream = new CheckedInputStream( new BufferedInputStream(Files.newInputStream(sourceFile.toPath())), new Adler32()); ) { IOUtils.skipFully(stream, sourceFile.length()); return stream.getChecksum().getValue(); } catch (final IOException ignored) { } return System.currentTimeMillis(); }

Target:
private static long computeFileChecksum(final File sourceFile) { try ( CheckedInputStream stream = new CheckedInputStream( new BufferedInputStream(Files.newInputStream(sourceFile.toPath())), new Adler32()); ) { IOUtils.skipFully(stream, sourceFile.length()); return stream.getChecksum().getValue(); } catch (final IOException ignored) { } return 0; }
Source:
void activateOwnedEntityAsClient(EntityRef usedOwnedEntity) { if (!usedOwnedEntity.exists()) { return; } activateTargetOrOwnedEntity(usedOwnedEntity); }

Target:
public void activateOwnedEntityAsClient(EntityRef usedOwnedEntity) { if (!usedOwnedEntity.exists()) { return; } activateTargetOrOwnedEntity(usedOwnedEntity); }
Source:
public QueryPlan implement(PhoenixRelImplementor implementor) { QueryPlan plan = implementor.visitInput(0, (PhoenixQueryRel) getInput()); int fetchValue = RexLiteral.intValue(fetch); int offsetValue = 0; if (offset != null){ offsetValue = RexLiteral.intValue(offset); } if (plan.getLimit() == null) { return plan.limit(fetchValue, offsetValue); } return new ClientScanPlan(plan.getContext(), plan.getStatement(), implementor.getTableMapping().getTableRef(), RowProjector.EMPTY_PROJECTOR, fetchValue, offsetValue, null, OrderBy.EMPTY_ORDER_BY, plan); }

Target:
public QueryPlan implement(PhoenixRelImplementor implementor) { QueryPlan plan = implementor.visitInput(0, (PhoenixQueryRel) getInput()); Integer fetch = this.fetch == null ? null : RexLiteral.intValue(this.fetch); Integer offset = this.offset == null ? null : RexLiteral.intValue(this.offset); if (plan.getLimit() == null && plan.getOffset() == null) { return plan.limit(fetch, offset); } return new ClientScanPlan(plan.getContext(), plan.getStatement(), implementor.getTableMapping().getTableRef(), RowProjector.EMPTY_PROJECTOR, fetch, offset, null, OrderBy.EMPTY_ORDER_BY, plan); }
Source:
public Response getThreads(@PathParam("nodeId") String nodeId) { Set<Node> nodes = nodeManager.getNodes(NodeState.ACTIVE); Node node = nodes.stream() .filter(n -> n.getNodeIdentifier().equals(nodeId)) .findFirst() .orElse(null); if (node == null) { return Response.status(Response.Status.NOT_FOUND).build(); } Request request = prepareGet() .setUri(uriBuilder() .scheme("http") .hostAndPort(fromParts(node.getHostAndPort().getHostText(), node.getHostAndPort().getPort())) .appendPath("v1") .appendPath("thread") .build()) .build(); InputStream responseStream = httpClient.execute(request, new StreamingJsonResponseHandler()); return Response.ok(responseStream, APPLICATION_JSON_TYPE).build(); }

Target:
public Response getThreads(@PathParam("nodeId") String nodeId) { return proxyJsonResponse(nodeId, "v1/thread"); }
Source:
public static void registerClientDriver(String metadataBackendScheme, Class<? extends MetadataClientDriver> driver, boolean allowOverride) { if (!initialized) { initialize(); } String scheme = metadataBackendScheme.toLowerCase(); MetadataClientDriverInfo oldDriverInfo = clientDrivers.get(scheme); if (null != oldDriverInfo && !allowOverride) { return; } MetadataClientDriverInfo newDriverInfo = new MetadataClientDriverInfo(driver); if (allowOverride) { oldDriverInfo = clientDrivers.put(scheme, newDriverInfo); } else { oldDriverInfo = clientDrivers.putIfAbsent(scheme, newDriverInfo); } if (null != oldDriverInfo) { log.debug("Metadata client driver for is already there.", scheme); } }

Target:
public static void registerClientDriver(String metadataBackendScheme, Class<? extends MetadataClientDriver> driver, boolean allowOverride) { if (!initialized) { initialize(); } String scheme = metadataBackendScheme.toLowerCase(); MetadataClientDriverInfo oldDriverInfo = clientDrivers.get(scheme); if (null != oldDriverInfo && !allowOverride) { return; } MetadataClientDriverInfo newDriverInfo = new MetadataClientDriverInfo(driver); oldDriverInfo = clientDrivers.putIfAbsent(scheme, newDriverInfo); if (null != oldDriverInfo) { log.debug("Metadata client driver for is already there.", scheme); if (allowOverride) { log.debug("Overriding client driver for {}", scheme); clientDrivers.put(scheme, newDriverInfo); } } }
Source:
public Iterator<Entry<KeyType>> iterator(final boolean sorted) { final List<Integer> wrappedOffsets = new AbstractList<Integer>() { @Override public Integer get(int index) { return buffer.getInt(tableArenaSize + index * Ints.BYTES); } @Override public Integer set(int index, Integer element) { final Integer oldValue = get(index); buffer.putInt(tableArenaSize + index * Ints.BYTES, element); return oldValue; } @Override public int size() { return size; } }; if (sorted) { final KeyComparator comparator = keySerde.comparator(); Collections.sort( wrappedOffsets, new Comparator<Integer>() { @Override public int compare(Integer lhs, Integer rhs) { return comparator.compare( tableBuffer, tableBuffer, lhs + HASH_SIZE, rhs + HASH_SIZE ); } } ); return new Iterator<Entry<KeyType>>() { int curr = 0; @Override public boolean hasNext() { return curr < size; } @Override public Entry<KeyType> next() { return bucketEntryForOffset(wrappedOffsets.get(curr++)); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } else { return new Iterator<Entry<KeyType>>() { int curr = 0; @Override public boolean hasNext() { return curr < size; } @Override public Entry<KeyType> next() { final int offset = buffer.getInt(tableArenaSize + curr * Ints.BYTES); final Entry<KeyType> entry = bucketEntryForOffset(offset); curr++; return entry; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }

Target:
public Iterator<Entry<KeyType>> iterator(final boolean sorted) { if (sorted) { final List<Integer> wrappedOffsets = new AbstractList<Integer>() { @Override public Integer get(int index) { return buffer.getInt(tableArenaSize + index * Ints.BYTES); } @Override public Integer set(int index, Integer element) { final Integer oldValue = get(index); buffer.putInt(tableArenaSize + index * Ints.BYTES, element); return oldValue; } @Override public int size() { return size; } }; final KeyComparator comparator = keySerde.comparator(); Collections.sort( wrappedOffsets, new Comparator<Integer>() { @Override public int compare(Integer lhs, Integer rhs) { return comparator.compare( tableBuffer, tableBuffer, lhs + HASH_SIZE, rhs + HASH_SIZE ); } } ); return new Iterator<Entry<KeyType>>() { int curr = 0; @Override public boolean hasNext() { return curr < size; } @Override public Entry<KeyType> next() { return bucketEntryForOffset(wrappedOffsets.get(curr++)); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } else { return new Iterator<Entry<KeyType>>() { int curr = 0; @Override public boolean hasNext() { return curr < size; } @Override public Entry<KeyType> next() { final int offset = buffer.getInt(tableArenaSize + curr * Ints.BYTES); final Entry<KeyType> entry = bucketEntryForOffset(offset); curr++; return entry; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
Source:
public Release populateRelease(CollectionReader reader, CollectionWriter collectionWriter, Iterable<ContentDetail> collectionContent) throws IOException, ZebedeeException { if (StringUtils.isEmpty(this.getDescription().getReleaseUri())) { throw new BadRequestException("This collection is not associated with a release."); } String uri = this.getDescription().getReleaseUri() + "/data.json"; try ( Resource resource = reader.getResource(uri); InputStream dataStream = resource.getData() ) { Release release = (Release) ContentUtil.deserialiseContent(dataStream); info().data("collectionId", this).data("title", release.getDescription().getTitle()) .log("Release identified for collection"); if (release == null) { throw new BadRequestException("This collection is not associated with a release."); } release = ReleasePopulator.populate(release, collectionContent); collectionWriter.getReviewed().writeObject(release, uri); return release; } }

Target:
public Release populateRelease(CollectionReader reader, CollectionWriter collectionWriter, Iterable<ContentDetail> collectionContent) throws IOException, ZebedeeException { if (StringUtils.isEmpty(this.getDescription().getReleaseUri())) { throw new BadRequestException("This collection is not associated with a release."); } String uri = this.getDescription().getReleaseUri() + "/data.json"; try ( Resource resource = reader.getResource(uri); InputStream dataStream = resource.getData() ) { Release release = (Release) ContentUtil.deserialiseContent(dataStream); info().data("collectionId", this.getDescription().getId()).data("title", release.getDescription().getTitle()) .log("Release identified for collection"); if (release == null) { throw new BadRequestException("This collection is not associated with a release."); } release = ReleasePopulator.populate(release, collectionContent); collectionWriter.getReviewed().writeObject(release, uri); return release; } }
Source:
public static <T> Predicate<Location> displayNameEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return Objects.equal(input.getDisplayName(), val); } }; }

Target:
public static <T> Predicate<Location> displayNameEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getDisplayName(), val); } }; }
Source:
private String createMultipleSpecsMessage(Fixture fixture, SpecificationType type1, SpecificationType type2) { return SimpleFormatter.format("Found multiple matching specifications: '%s.%s' and '%1$s.%s'", fixture.getFixturePathWithoutSuffix(), type1.getTypeSuffix(), type2.getTypeSuffix()); }

Target:
private String createMultipleSpecsMessage(Fixture fixture, SpecificationType type1, SpecificationType type2) { String fixturePathWithoutSuffix = fixture.getFixturePathWithoutSuffix(); return SimpleFormatter.format("Found multiple matching specifications: '%s.%s' and '%s.%s'", fixturePathWithoutSuffix, type1.getTypeSuffix(), fixturePathWithoutSuffix, type2.getTypeSuffix()); }
Source:
public static University findUniversity(HttpServletRequest request) throws ServiceException { univid = Integer.parseInt(request.getParameter("uid")); return SQLSource.interact(new SQLInteractionInterface<University>() { @Override public University run(Connection connection) throws ServiceException, SQLException { return University.lookup(connection, univid); } }); }

Target:
public static University findUniversity(HttpServletRequest request) throws ServiceException { String idStr = request.getParameter("uid"); if (idStr == null) { throw new ServiceException(ServiceStatus.MALFORMED_REQUEST); } final int univid = Integer.parseInt(idStr); return SQLSource.interact(new SQLInteractionInterface<University>() { @Override public University run(Connection connection) throws ServiceException, SQLException { return University.lookup(connection, univid); } }); }
Source:
public Optional<VM> getVmUsingMac(Guid macPoolId, String mac) { Map<Guid, VM> vmsById = getAllVmsInSystem(getIdsOfAllClustersHavingMacPool(macPoolId)).filter(vm -> !vm.isStateless()) .collect(Collectors.toMap(VM::getId, Function.identity())); Optional<Guid> vmUsingMacId = getVmIdUsingMac(vmsById.keySet() .stream() .flatMap(vmId -> getVmInterfaces(vmId).stream()), mac); return vmUsingMacId.map(vmsById::get); }

Target:
public Optional<VM> getVmUsingMac(Guid macPoolId, String mac) { Map<Guid, VM> vmsById = getAllVmsInSystem(getIdsOfAllClustersHavingMacPool(macPoolId)) .collect(Collectors.toMap(VM::getId, Function.identity())); Optional<Guid> vmUsingMacId = getVmIdUsingMac(vmsById.keySet() .stream() .flatMap(vmId -> getVmInterfaces(vmId).stream()), mac); return vmUsingMacId.map(vmsById::get); }
Source:
public void filter(final ContainerRequestContext requestContext) throws IOException { if (permitAll.contains(resourceInfo.getResourceMethod())) { return; } if (denyAll.contains(resourceInfo.getResourceMethod())) { forbidden(requestContext); return; } final Set<String> roles = rolesAllowed.get(resourceInfo.getResourceMethod()); if (roles != null && !roles.isEmpty()) { final SecurityContext securityContext = requestContext.getSecurityContext(); Boolean hasAtLeasOneValidRole = false; for (String role : roles) { if (securityContext.isUserInRole(role)) { hasAtLeasOneValidRole = true; break; } } if (!hasAtLeasOneValidRole) { forbidden(requestContext); } } }

Target:
public void filter(final ContainerRequestContext requestContext) throws IOException { if (permitAll.contains(resourceInfo.getResourceMethod())) { return; } if (denyAll.contains(resourceInfo.getResourceMethod())) { forbidden(requestContext); return; } final Set<String> roles = rolesAllowed.get(resourceInfo.getResourceMethod()); if (roles != null && !roles.isEmpty()) { final SecurityContext securityContext = requestContext.getSecurityContext(); boolean hasAtLeasOneValidRole = false; for (String role : roles) { if (securityContext.isUserInRole(role)) { hasAtLeasOneValidRole = true; break; } } if (!hasAtLeasOneValidRole) { forbidden(requestContext); } } }