auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String transformResponse(String transformation, String response) { String transformedResponse; try { String[] parts = splitTransformationConfig(transformation); String transformationType = parts[0]; String transformationFunction = parts[1]; if (transformationType == "") { transformedResponse = transformationFunction; } else { TransformationService transformationService = TransformationHelper .getTransformationService(TCPActivator.getContext(), transformationType); if (transformationService != null) { transformedResponse = transformationService.transform(transformationFunction, response); } else { transformedResponse = response; logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationType); } } } catch (Exception te) { logger.error("transformation throws exception [transformation=" + transformation + ", response=" + response + "]", te); transformedResponse = response; } logger.debug("transformed response is '{}'", transformedResponse); return transformedResponse; }

Target:
protected String transformResponse(String transformation, String response) { String transformedResponse; Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation); String transformationServiceName; String transformationServiceParam; if (StringUtils.isEmpty(transformation) || transformation.equalsIgnoreCase("default")) { transformedResponse = response; } else if (matcher.matches()) { matcher.reset(); matcher.find(); transformationServiceName = matcher.group(1); transformationServiceParam = matcher.group(2); try { TransformationService transformationService = TransformationHelper .getTransformationService(TCPActivator.getContext(), transformationServiceName); if (transformationService != null) { transformedResponse = transformationService.transform(transformationServiceParam, response); } else { transformedResponse = response; logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationServiceName); } } catch (Exception te) { logger.error("transformation throws exception [transformation=" + transformation + ", response=" + response + "]", te); transformedResponse = response; } } else { transformedResponse = transformation; } logger.debug("transformed response is '{}'", transformedResponse); return transformedResponse; }
Source:
public boolean canBePreempted() { assert parent != null; if (parent.policy.checkIfUsageOverFairShare( getResourceUsage(), getFairShare())) { return true; } else { for (FSQueue queue: getChildQueues()) { if (queue.canBePreempted()) { return true; } } } return false; }

Target:
public boolean canBePreempted() { if (parent == null || parent.policy.checkIfUsageOverFairShare( getResourceUsage(), getFairShare())) { return true; } else { for (FSQueue queue: getChildQueues()) { if (queue.canBePreempted()) { return true; } } } return false; }
Source:
public static Set<InstanceConfig> getBrokerInstanceConfigsForTenant(List<InstanceConfig> instanceConfigs, String tenant) { return new HashSet<>(HelixHelper.getInstancesConfigsWithTag(instanceConfigs, TagNameUtils.getBrokerTagForTenant(tenant))); }

Target:
public static Set<InstanceConfig> getBrokerInstanceConfigsForTenant(List<InstanceConfig> instanceConfigs, String tenant) { return new HashSet<>(getInstancesConfigsWithTag(instanceConfigs, TagNameUtils.getBrokerTagForTenant(tenant))); }
Source:
public static ErlangFunctionReferenceImpl<ErlangQAtom> createFunctionReference(@NotNull ErlangQAtom atom) { ErlangFunctionCallExpression call = PsiTreeUtil.getParentOfType(atom, ErlangFunctionCallExpression.class); if (call != null) { int position = getPositionInFunctionCall(call, atom); List<ErlangExpression> expressions = call.getArgumentList().getExpressionList(); if (0 < position && position + 1 < expressions.size()) { ErlangMaxExpression module = ObjectUtils.tryCast(expressions.get(position - 1), ErlangMaxExpression.class); ErlangListExpression list = ObjectUtils.tryCast(expressions.get(position + 1), ErlangListExpression.class); ErlangQAtom moduleAtom = module != null ? module.getQAtom() : null; int arity = list != null ? list.getExpressionList().size() : -1; return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, moduleAtom, arity); } } return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, null, -1); }

Target:
public static ErlangFunctionReferenceImpl<ErlangQAtom> createFunctionReference(@NotNull ErlangQAtom atom) { ErlangFunctionCallExpression call = PsiTreeUtil.getParentOfType(atom, ErlangFunctionCallExpression.class); if (call != null) { int position = getPositionInFunctionCall(call, atom); List<ErlangExpression> expressions = call.getArgumentList().getExpressionList(); if (position > 0 && position + 1 < expressions.size()) { ErlangMaxExpression module = ObjectUtils.tryCast(expressions.get(position - 1), ErlangMaxExpression.class); ErlangListExpression list = ObjectUtils.tryCast(expressions.get(position + 1), ErlangListExpression.class); ErlangQAtom moduleAtom = module != null ? module.getQAtom() : null; int arity = list != null ? list.getExpressionList().size() : -1; return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, moduleAtom, arity); } } return new ErlangFunctionReferenceImpl<ErlangQAtom>(atom, null, -1); }
Source:
protected List<String> generateHeaderValues() { List<String> result = new ArrayList<String>(); result.add("Certification Edition"); result.add("CHPL ID"); result.add("Listing Database ID"); result.add("ONC-ACB Certification ID"); result.add("Certification Date"); result.add("Inactive As Of Date"); result.add("Decertified As Of Date"); result.add("Certification Status"); result.add("ACB Name"); result.add("Previous ACB Name"); result.add("Developer Name"); result.add("Developer Database ID"); result.add("Vendor Street Address"); result.add("Vendor City"); result.add("Vendor State"); result.add("Vendor Zip Code"); result.add("Vendor Website"); result.add("Self-developer"); result.add("Vendor Contact Name"); result.add("Vendor Contact Email"); result.add("Vendor Contact Phone"); result.add("Product Name"); result.add("Product Database ID"); result.add("Version"); result.add("Real World Testing Eligibility Year"); result.add("Real World Testing Plan URL"); result.add("Real World Testing Plan Submission Date"); result.add("Real World Testing Results URL"); result.add("Real World Testing Results Submission Date"); result.add("Total Surveillance Activities"); result.add("Total Nonconformities"); result.add("Open Nonconformities"); if (applicableCriteria != null) { for (CertificationCriterionDTO criteria : applicableCriteria) { result.add(criteria.getNumber() + ": " + criteria.getTitle()); } } return result; }

Target:
protected List<String> generateHeaderValues() { List<String> result = new ArrayList<String>(); result.add("Certification Edition"); result.add("CHPL ID"); result.add("Listing Database ID"); result.add("ONC-ACB Certification ID"); result.add("Certification Date"); result.add("Inactive As Of Date"); result.add("Decertified As Of Date"); result.add("Certification Status"); result.add("ACB Name"); result.add("Previous ACB Name"); result.add("Developer Name"); result.add("Developer Database ID"); result.add("Vendor Street Address"); result.add("Vendor City"); result.add("Vendor State"); result.add("Vendor Zip Code"); result.add("Vendor Website"); result.add("Self-developer"); result.add("Vendor Contact Name"); result.add("Vendor Contact Email"); result.add("Vendor Contact Phone"); result.add("Product Name"); result.add("Product Database ID"); result.add("Version"); result.add("Version Database ID"); result.add("Real World Testing Eligibility Year"); result.add("Real World Testing Plans URL"); result.add("Real World Testing Results URL"); result.add("Total Surveillance Activities"); result.add("Total Nonconformities"); result.add("Open Nonconformities"); if (applicableCriteria != null) { for (CertificationCriterionDTO criteria : applicableCriteria) { result.add(criteria.getNumber() + ": " + criteria.getTitle()); } } return result; }
Source:
public List<Timeline> getActiveTimelinesOrdered(final String eventType) throws InternalNakadiException, NoSuchEventTypeException { final List<Timeline> timelines = eventTypeCache.getTimelines(eventType); if (timelines.isEmpty()) { return Collections.singletonList(getFakeTimeline(eventTypeCache.getEventType(eventType))); } else { return timelines.stream().sorted(Comparator.comparing(Timeline::getOrder)).collect(Collectors.toList()); } }

Target:
public List<Timeline> getActiveTimelinesOrdered(final String eventType) throws InternalNakadiException, NoSuchEventTypeException { final List<Timeline> timelines = eventTypeCache.getTimelinesOrdered(eventType); if (timelines.isEmpty()) { return Collections.singletonList(getFakeTimeline(eventTypeCache.getEventType(eventType))); } else { return timelines.stream().filter(t -> t.getSwitchedAt() != null).collect(Collectors.toList()); } }
Source:
public void shouldReturnEncounterForLookupGetEncounterByUuid() { String className = OpenMRSEncounter.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(UUID, "5"); OpenMRSEncounter openMRSEncounter = new OpenMRSEncounter(); openMRSEncounter.setEncounterType("encounterTypeTest"); when(encounterService.getEncounterByUuid("5")).thenReturn(openMRSEncounter); Object object = taskDataProvider.lookup(className, BY_UUID, lookupFields); assertTrue(object instanceof OpenMRSEncounter); assertEquals("encounterTypeTest", ((OpenMRSEncounter) object).getEncounterType()); verify(encounterService).getEncounterByUuid("5"); }

Target:
public void shouldReturnEncounterForLookupGetEncounterByUuid() { String className = OpenMRSEncounter.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(UUID, "5"); OpenMRSEncounter openMRSEncounter = new OpenMRSEncounter(); openMRSEncounter.setEncounterType("encounterTypeTest"); when(encounterService.getEncounterByUuid("5")).thenReturn(openMRSEncounter); Object object = taskDataProvider.lookup(className, BY_UUID, lookupFields); assertEquals(openMRSEncounter, object); verify(encounterService).getEncounterByUuid("5"); }
Source:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); int crsCode = Byte.toUnsignedInt( header[5] ) + (Byte.toUnsignedInt( header[4] ) << 8); return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }

Target:
static GeometryHeader fromArrayHeaderBytes( byte[] header ) { int geometryType = Byte.toUnsignedInt( header[1] ); int dimension = Byte.toUnsignedInt( header[2] ); int crsTableId = Byte.toUnsignedInt( header[3] ); int crsCode = (Byte.toUnsignedInt( header[4] ) << 8) + Byte.toUnsignedInt( header[5] ); return new GeometryHeader( geometryType, dimension, crsTableId, crsCode ); }
Source:
public void synchronizeStart() throws InterruptedException { Executor e = Executor.currentExecutor(); if (e == null) { throw new IllegalStateException("synchronizeStart shall only be called from an Executor"); } WorkUnit wu = e.getCurrentWorkUnit(); if (wu == null) { throw new IllegalStateException("synchronizeStart shall only be called after a WorkUnit has been assigned"); } boolean mainWork = wu.isMainWork(); try { startLatch.synchronize(); if (mainWork) { future.start.set(e.getCurrentExecutable()); } } catch (Error | RuntimeException | InterruptedException problem) { if (mainWork) { future.start.set(problem); } throw problem; } finally { if (mainWork && !future.start.isDone()) { future.start.set(e.getCurrentExecutable()); } } }

Target:
public void synchronizeStart() throws InterruptedException { try { startLatch.synchronize(); } finally { Executor e = Executor.currentExecutor(); WorkUnit wu = e.getCurrentWorkUnit(); if (wu.isMainWork()) { future.start.set(e.getCurrentExecutable()); } } }
Source:
static long storageCapacityInBytes(StatFs statFs) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statFs.getTotalBytes(); } else { return (long) statFs.getBlockCount() * (long) statFs.getBlockSize(); } }

Target:
long storageCapacityInBytes(StatFs statFs) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return statFs.getTotalBytes(); } else { return (long) statFs.getBlockCount() * (long) statFs.getBlockSize(); } }
Source:
public PipelinePlacementPolicy(final NodeManager nodeManager, final Configuration conf) { super(nodeManager, conf); this.nodeManager = nodeManager; this.conf = conf; heavy_node_criteria = conf.getInt(ScmConfigKeys.OZONE_SCM_DATANODE_MAX_PIPELINE_ENGAGEMENT, ScmConfigKeys.OZONE_SCM_DATANODE_MAX_PIPELINE_ENGAGEMENT_DEFAULT); }

Target:
public PipelinePlacementPolicy( final NodeManager nodeManager, final Configuration conf) { super(nodeManager, conf); this.nodeManager = nodeManager; this.conf = conf; heavyNodeCriteria = conf.getInt( ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT_DEFAULT); }
Source:
public synchronized void addOrUpdate(final MessageReceiverBreakpoint bId) { FullSourceCoordinate coord = bId.getCoordinate(); BreakpointEnabling<MessageReceiverBreakpoint> existingBP = receiverBreakpoints.get(coord); if (existingBP == null) { existingBP = new BreakpointEnabling<MessageReceiverBreakpoint>(bId); receiverBreakpoints.put(coord, existingBP); } else { existingBP.setEnabled(bId.isEnabled()); } }

Target:
public synchronized void addOrUpdate(final MessageReceiverBreakpoint bId) { saveBreakpoint(bId, receiverBreakpoints); }
Source:
protected QosDao<?> getQosDao() { QosType qosType = getParameters().getQosType(); if (qosType == null) { return getDbFacade().getQosBaseDao(); } switch (qosType) { case STORAGE: qosDao = getDbFacade().getStorageQosDao(); break; default: break; } return qosDao; }

Target:
protected QosDao<?> getQosDao() { QosType qosType = getParameters().getQosType(); if (qosType == null) { return getDbFacade().getQosBaseDao(); } switch (qosType) { case STORAGE: qosDao = getDbFacade().getStorageQosDao(); break; default: log.debugFormat("Not handled QoS type: {0}", qosType); break; } return qosDao; }
Source:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterHost("192.168.1.12") .setClusterPort(17001) .setClusterManager(clusterManager); return options; }

Target:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterManager(clusterManager); return options; }
Source:
public SuggestLocationsResult suggestLocations(final CharSequence constraint) throws IOException { final String nameCstr = constraint.toString(); final HttpUrl.Builder url = url().addPathSegment("places"); url.addQueryParameter("q", nameCstr); url.addQueryParameter("type[]", "stop_area"); url.addQueryParameter("type[]", "address"); url.addQueryParameter("type[]", "poi"); url.addQueryParameter("type[]", "administrative_region"); url.addQueryParameter("depth", "1"); final CharSequence page = httpClient.get(url.build()); try { final List<SuggestedLocation> locations = new ArrayList<>(); final JSONObject head = new JSONObject(page.toString()); if (head.has("places")) { final JSONArray places = head.getJSONArray("places"); final int priorityBase = places.length(); for (int i = 0; i < places.length(); ++i) { final JSONObject place = places.getJSONObject(i); final int priority = priorityBase - i; final Location location = parseLocation(place); locations.add(new SuggestedLocation(location, priority)); } } final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null); return new SuggestLocationsResult(resultHeader, locations); } catch (final JSONException jsonExc) { throw new ParserException(jsonExc); } }

Target:
public SuggestLocationsResult suggestLocations(final CharSequence constraint) throws IOException { final String nameCstr = constraint.toString(); final HttpUrl.Builder url = url().addPathSegment("places"); url.addQueryParameter("q", nameCstr); url.addQueryParameter("type[]", "stop_area"); url.addQueryParameter("type[]", "address"); url.addQueryParameter("type[]", "poi"); url.addQueryParameter("type[]", "administrative_region"); url.addQueryParameter("depth", "1"); final CharSequence page = httpClient.get(url.build()); try { final List<SuggestedLocation> locations = new ArrayList<>(); final JSONObject head = new JSONObject(page.toString()); if (head.has("places")) { final JSONArray places = head.getJSONArray("places"); final int numPlaces = places.length(); for (int i = 0; i < numPlaces; ++i) { final JSONObject place = places.getJSONObject(i); final int priority = numPlaces - i; final Location location = parseLocation(place); locations.add(new SuggestedLocation(location, priority)); } } final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null); return new SuggestLocationsResult(resultHeader, locations); } catch (final JSONException jsonExc) { throw new ParserException(jsonExc); } }
Source:
public TableSpec getTableSpec() { validate(); Map<String, String> tableSpecConfig = new HashMap<>(); generateTableSpecConfig(tableSpecConfig); tableSpecConfig.put(RemoteTableProvider.READ_FN, serializeObject("read function", readFn)); if (writeFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_FN, serializeObject("write function", writeFn)); } if (this.rateLimiter == null) { Map<String, Integer> tagCreditsMap = new HashMap<>(); if (readRateLimit > 0) { tagCreditsMap.put(RL_READ_TAG, readRateLimit); } if (writeRateLimit > 0) { tagCreditsMap.put(RL_WRITE_TAG, writeRateLimit); } if (!tagCreditsMap.isEmpty()) { rateLimiter = new EmbeddedTaggedRateLimiter(tagCreditsMap); } } if (rateLimiter != null) { tableSpecConfig.put(RemoteTableProvider.RATE_LIMITER, serializeObject("rate limiter", rateLimiter)); } if (readCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.READ_CREDIT_FN, serializeObject( "read credit function", readCreditFn)); } if (writeCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_CREDIT_FN, serializeObject( "write credit function", writeCreditFn)); } return new TableSpec(tableId, serde, RemoteTableProviderFactory.class.getName(), tableSpecConfig); }

Target:
public TableSpec getTableSpec() { validate(); Map<String, String> tableSpecConfig = new HashMap<>(); generateTableSpecConfig(tableSpecConfig); tableSpecConfig.put(RemoteTableProvider.READ_FN, serializeObject("read function", readFn)); if (writeFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_FN, serializeObject("write function", writeFn)); } if (!tagCreditsMap.isEmpty()) { rateLimiter = new EmbeddedTaggedRateLimiter(tagCreditsMap); } if (rateLimiter != null) { tableSpecConfig.put(RemoteTableProvider.RATE_LIMITER, serializeObject("rate limiter", rateLimiter)); } if (readCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.READ_CREDIT_FN, serializeObject( "read credit function", readCreditFn)); } if (writeCreditFn != null) { tableSpecConfig.put(RemoteTableProvider.WRITE_CREDIT_FN, serializeObject( "write credit function", writeCreditFn)); } return new TableSpec(tableId, serde, RemoteTableProviderFactory.class.getName(), tableSpecConfig); }
Source:
public String getRunningFlowIds() { final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get running flow ids.", e); } return allIds.toString(); }

Target:
public List<Integer> getRunningFlowIds() { final List<Integer> allIds = new ArrayList<>(); try { getExecutionIdsHelper(allIds, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { this.logger.error("Failed to get running flow ids.", e); } return allIds; }
Source:
List<EventID> getGIIEvents() { List<EventID> events = new LinkedList<>(); for (long i = positionBeforeGII; i < positionAfterGII + 1; i++) { Map.Entry entry = region.getEntry(i); if (entry != null && entry.getValue() instanceof HAEventWrapper) { HAEventWrapper wrapper = uncheckedCast(entry.getValue()); events.add(wrapper.getEventId()); } } return events; }

Target:
List<EventID> getGIIEvents() { List<EventID> events = new LinkedList<>(); for (long i = positionBeforeGII; i < positionAfterGII + 1; i++) { Map.Entry<?, ?> entry = region.getEntry(i); if (entry != null && entry.getValue() instanceof HAEventWrapper) { HAEventWrapper wrapper = (HAEventWrapper) entry.getValue(); events.add(wrapper.getEventId()); } } return events; }
Source:
private void fetchGitHubRepository(final int repositoryId) { Log.d(TAG, "fetchGitHubRepository(" + repositoryId + ")"); if (isOngoingRequest(repositoryId)) { Log.d(TAG, "Found an ongoing request for repository " + repositoryId); return; } final String uri = getUniqueId(repositoryId); Disposable disposable = createNetworkObservable(repositoryId) .subscribeOn(Schedulers.computation()) .doOnSubscribe(d -> startRequest(uri)) .doOnError(doOnError(uri)) .doOnDispose(() -> completeRequest(uri)) .subscribe(gitHubRepositoryStore::put, e -> Log.e(TAG, "Error fetching GitHub repository " + repositoryId, e)); addRequest(repositoryId, disposable); }

Target:
private void fetchGitHubRepository(final int repositoryId) { Log.d(TAG, "fetchGitHubRepository(" + repositoryId + ")"); if (isOngoingRequest(repositoryId)) { Log.d(TAG, "Found an ongoing request for repository " + repositoryId); return; } final String uri = getUniqueId(repositoryId); Disposable disposable = createNetworkObservable(repositoryId) .subscribeOn(Schedulers.computation()) .doOnSubscribe(__ -> startRequest(uri)) .doOnError(doOnError(uri)) .doOnDispose(() -> completeRequest(uri)) .subscribe(gitHubRepositoryStore::put, e -> Log.e(TAG, "Error fetching GitHub repository " + repositoryId, e)); addRequest(repositoryId, disposable); }
Source:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .addMinutes(-1 * Config.<Integer>getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMTask task : tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogable logable = new AuditLogableImpl(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getActionType().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { task.setZombieTask(true); auditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Stopping async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)); task.stopTask(true); } else { auditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Clearing async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)); task.clearAsyncTask(true); } } } }

Target:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .addMinutes(-1 * Config.<Integer>getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); int asyncZombieTaskLife = Config.<Integer> getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes); for (SPMTask task : tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogable logable = new AuditLogableImpl(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getActionType().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { task.setZombieTask(true); auditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Stopping async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), asyncZombieTaskLife); task.stopTask(true); } else { auditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.info( "Cleaning zombie tasks: Clearing async task '{}' that started at '{}' since it reached a timeout of minutes", task.getParameters().getDbAsyncTask().getActionType(), task.getParameters().getDbAsyncTask().getStartTime(), asyncZombieTaskLife); task.clearAsyncTask(true); } } } }
Source:
public ImmutableSet<ModelWithPayload<Item>> resolveItems(Iterable<ModelWithPayload<Item>> items) throws NitroException { ImmutableList.Builder<String> itemUris = ImmutableList.builder(); for (ModelWithPayload<Item> itemWithPayload : items) { itemUris.add(itemWithPayload.getModel().getCanonicalUri()); } ResolvedContent resolvedItems = resolve(itemUris.build()); ImmutableSet<Item> itemsOnly = ImmutableSet.copyOf(Iterables.filter( resolvedItems.getAllResolvedResults(), Item.class )); ImmutableSet<ModelWithPayload<Item>> wrappedItems = itemsOnly.stream() .map(input -> wrapResolvedContentWithEmptyPayload(input)) .collect(MoreCollectors.toImmutableSet()); return mergeItemsWithExisting(ImmutableSet.copyOf(items), wrappedItems); }

Target:
public ImmutableSet<ModelWithPayload<Item>> resolveItems(Iterable<ModelWithPayload<Item>> items) throws NitroException { ImmutableSet<String> itemUris = StreamSupport .stream(items.spliterator(), false) .map(ModelWithPayload::getModel) .map(Item::getCanonicalUri) .collect(MoreCollectors.toImmutableSet()); ResolvedContent resolvedItems = resolve(itemUris); ImmutableSet<ModelWithPayload<Item>> wrappedItems = resolvedItems.getAllResolvedResults().stream() .filter(Item.class::isInstance) .map(Item.class::cast) .map(this::wrapResolvedContentWithEmptyPayload) .collect(MoreCollectors.toImmutableSet()); return mergeItemsWithExisting(ImmutableSet.copyOf(items), wrappedItems); }
Source:
public void updateEnrollSuccessLines(List<StudentAttributes>[] students) { for (int i = 1; i < StudentUpdateStatus.STATUS_COUNT - 2; i++) { switch (StudentUpdateStatus.enumRepresentation(i)) { case NEW: for (StudentAttributes newStudent : students[i]) { enrollNewStudentsLines.put(newStudent.email, "Student has been added successfully."); } break; case MODIFIED: for (StudentAttributes modifiedStudent : students[i]) { enrollModifiedStudentsLines.put(modifiedStudent.email, "Student has been modified successfully."); } break; case UNMODIFIED: for (StudentAttributes unmodifiedStudent : students[i]) { enrollUnmodifiedStudentsLines.put(unmodifiedStudent.email, "Existing student has been unmodified."); } break; default: log.severe("Unknown Enrollment status " + i); break; } } }

Target:
public void updateEnrollSuccessLines(List<StudentAttributes>[] students) { for (int i = 1; i < StudentUpdateStatus.STATUS_COUNT - 2; i++) { switch (StudentUpdateStatus.enumRepresentation(i)) { case NEW: for (StudentAttributes newStudent : students[i]) { enrollNewStudentsLines.put(newStudent.email, "Student has been added successfully."); } break; case MODIFIED: for (StudentAttributes modifiedStudent : students[i]) { enrollModifiedStudentsLines.put(modifiedStudent.email, "Student has been modified successfully."); } break; case UNMODIFIED: for (StudentAttributes unmodifiedStudent : students[i]) { enrollUnmodifiedStudentsLines.put(unmodifiedStudent.email, "Existing student is unmodified."); } break; default: log.severe("Unknown Enrollment status " + i); break; } } }
Source:
public synchronized void onStart(SourceCallback<String, Object> sourceCallback) throws MuleException { checkArgument(heisenberg != null, "config not injected"); HeisenbergExtension.sourceTimesStarted++; configName = refName; location = componentLocation.getLocation(); if (corePoolSize < 0) { throw new RuntimeException(CORE_POOL_SIZE_ERROR_MESSAGE); } receivedDebtProperties = debtProperties; receivedUsableWeapons = usableWeapons; executor = schedulerService.cpuLightScheduler(); connection = connectionProvider.connect(); scheduledFuture = executor.scheduleAtFixedRate(() -> { final Result<String, Object> result = makeResult(sourceCallback); if (result != null) { SourceCallbackContext context = sourceCallback.createContext(); context.addVariable(BATCH_NUMBER, initialBatchNumber); context.fireOnHandle(NEW_BATCH, TypedValue.of(initialBatchNumber)); context.fireOnHandle(NEXT_BATCH, TypedValue.of(frequency)); sourceCallback.handle(result, context); } }, 0, 4000, MILLISECONDS); }

Target:
public synchronized void onStart(SourceCallback<String, Object> sourceCallback) throws MuleException { checkArgument(heisenberg != null, "config not injected"); HeisenbergExtension.sourceTimesStarted++; configName = refName; location = componentLocation.getLocation(); if (corePoolSize < 0) { throw new RuntimeException(CORE_POOL_SIZE_ERROR_MESSAGE); } receivedDebtProperties = debtProperties; receivedUsableWeapons = usableWeapons; executor = schedulerService.cpuLightScheduler(); connection = connectionProvider.connect(); scheduledFuture = executor.scheduleAtFixedRate(() -> { final Result<String, Object> result = makeResult(sourceCallback); if (result != null) { SourceCallbackContext context = sourceCallback.createContext(); context.addVariable(BATCH_NUMBER, initialBatchNumber); context.fireOnHandle(NEW_BATCH, TypedValue.of(initialBatchNumber)); context.fireOnHandle(NEXT_BATCH, TypedValue.of(frequency)); sourceCallback.handle(result, context); } }, 0, frequency, MILLISECONDS); }
Source:
public Option[] uberJar() { return options( gradleBundle("org.ehcache:dist"), jaxbConfiguration(), gradleBundle("org.ehcache:clustered-dist"), jaxbConfiguration(), baseConfiguration("ClusteredOsgiTest", "uberJar") ); }

Target:
public Option[] uberJar() { return options( gradleBundle("org.ehcache:dist"), jaxbConfiguration(), gradleBundle("org.ehcache:clustered-dist"), baseConfiguration("ClusteredOsgiTest", "uberJar") ); }
Source:
static BalancerSegmentHolder getRandomBalancerSegmentHolder(final List<ServerHolder> serverHolders) { ServerHolder fromServerHolder = getRandomElementFromList(serverHolders); Collection<DataSegment> segments = fromServerHolder.getServer().getSegments(); Spliterator<DataSegment> chosenSpliterator = segments.spliterator(); DataSegment proposalSegment = null; for (int i = 0; i < Math.log(segments.size()); i++) { if (chosenSpliterator.estimateSize() < SPLITERATOR_SIZE_THRESHOLD) { List<DataSegment> finalList = StreamSupport .stream(chosenSpliterator, false) .collect(Collectors.toList()); proposalSegment = getRandomElementFromList(finalList); break; } Spliterator<DataSegment> newSpliterator = chosenSpliterator.trySplit(); if (ThreadLocalRandom.current().nextBoolean()) { chosenSpliterator = newSpliterator; } } if (fromServerHolder != null) { return new BalancerSegmentHolder(fromServerHolder.getServer(), proposalSegment); } else { return null; } }

Target:
static BalancerSegmentHolder getRandomBalancerSegmentHolder(final List<ServerHolder> serverHolders) { ServerHolder fromServerHolder = reservoirSampleServer(serverHolders); if (fromServerHolder == null) { return null; } DataSegment proposalSegment; Collection<DataSegment> segments = fromServerHolder.getServer().getSegments(); if (segments.size() == 1) { proposalSegment = segments.iterator().next(); } else { Spliterator<DataSegment> chosenSpliterator = segments.spliterator(); if (chosenSpliterator == null) { return null; } int randomBits = ThreadLocalRandom.current().nextInt(); while (chosenSpliterator.estimateSize() >= SPLITERATOR_SIZE_THRESHOLD) { Spliterator<DataSegment> newSpliterator = chosenSpliterator.trySplit(); boolean chooseNewSpliterator = ((randomBits >>= 1) & 1) == 0; if (chooseNewSpliterator) { chosenSpliterator = newSpliterator; } } List<DataSegment> finalList = StreamSupport .stream(chosenSpliterator, false) .collect(Collectors.toList()); proposalSegment = getRandomElementFromList(finalList); } return new BalancerSegmentHolder(fromServerHolder.getServer(), proposalSegment); }
Source:
public short calculateBreakDamage(GlowBlock target) { return (short) (target.getType().equals(Material.LEAVES) ? 1 : 0); }

Target:
public short calculateBreakDamage(GlowBlock target) { return (short) (Arrays.asList(new Material[]{Material.LEAVES, Material.LONG_GRASS, Material.WOOL}).contains(target.getType()) ? 1 : 0); }
Source:
public void test_definition() { WebService.Action def = wsTester.getDef(); assertThat(def.key()).isEqualTo("search"); assertThat(def.isInternal()).isFalse(); assertThat(def.isPost()).isFalse(); assertThat(def.since()).isEqualTo("3.6"); assertThat(def.responseExampleAsString()).isNotEmpty(); assertThat(def.params()).extracting("key").containsOnly( "actionPlans", "additionalFields", "asc", "assigned", "assignees", "authors", "componentKeys", "componentRootUuids", "componentRoots", "componentUuids", "components", "createdAfter", "createdAt", "createdBefore", "createdInLast", "directories", "facetMode", "facets", "fileUuids", "issues", "languages", "moduleUuids", "onComponentOnly", "organization", "p", "planned", "projectKeys", "projectUuids", "projects", "ps", "reporters", "resolutions", "resolved", "rules", "s", "severities", "sinceLeakPeriod", "statuses", "tags", "types"); assertThat(def.param("organization")) .matches(p -> p.isInternal()) .matches(p -> p.since().equals("6.4")); }

Target:
public void test_definition() { WebService.Action def = wsTester.getDef(); assertThat(def.key()).isEqualTo("search"); assertThat(def.isInternal()).isFalse(); assertThat(def.isPost()).isFalse(); assertThat(def.since()).isEqualTo("3.6"); assertThat(def.responseExampleAsString()).isNotEmpty(); assertThat(def.params()).extracting("key").containsExactlyInAnyOrder( "actionPlans", "additionalFields", "asc", "assigned", "assignees", "authors", "componentKeys", "componentRootUuids", "componentRoots", "componentUuids", "components", "createdAfter", "createdAt", "createdBefore", "createdInLast", "directories", "facetMode", "facets", "fileUuids", "issues", "languages", "moduleUuids", "onComponentOnly", "organization", "p", "planned", "projectKeys", "projectUuids", "projects", "ps", "reporters", "resolutions", "resolved", "rules", "s", "severities", "sinceLeakPeriod", "statuses", "tags", "types"); assertThat(def.param("organization")) .matches(p -> p.isInternal()) .matches(p -> p.since().equals("6.4")); }
Source:
private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox) throws IOException { Map<Integer, Long> partitionOffsetMap = Maps.newHashMap(); for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue()); } boolean result = taskToolbox.getTaskActionClient() .submit(new ResetDataSourceMetadataAction( getDataSource(), new KafkaDataSourceMetadata(new KafkaPartitions( ioConfig.getStartPartitions() .getTopic(), partitionOffsetMap )) )); if (result) { log.makeAlert( "Successfully sent the reset request for partitions [%s], waiting to be killed", partitionOffsetMap.keySet() ).emit(); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while waiting to be killed"); } } else { log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit(); } }

Target:
private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox) throws IOException { Map<Integer, Long> partitionOffsetMap = Maps.newHashMap(); for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue()); } boolean result = taskToolbox.getTaskActionClient() .submit(new ResetDataSourceMetadataAction( getDataSource(), new KafkaDataSourceMetadata(new KafkaPartitions( ioConfig.getStartPartitions() .getTopic(), partitionOffsetMap )) )); if (result) { log.makeAlert("Resetting Kafka offsets for datasource [%s]", getDataSource()) .addData("partitions", partitionOffsetMap.keySet()) .emit(); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while waiting to be killed"); } } else { log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit(); } }
Source:
public Response create( final WhoisResources resources, @Context final HttpServletRequest request, @PathParam("source") final String sourceParam, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey) { if (resources == null) { return badRequest("WhoisResources is mandatory"); } try { final Origin origin = updatePerformer.createOrigin(request); final UpdateContext updateContext = updatePerformer.initContext(origin, crowdTokenKey); updateContext.setBatchUpdate(); final Credentials credentials = createCredentials(updateContext.getUserSession(), passwords, null); final List<Update> updates = extractUpdates(resources, credentials); final WhoisResources updatedResources = updatePerformer.performUpdates(updateContext, origin, updates, Keyword.NEW, request); validateUpdates(updateContext, updates, updatedResources); return createResponse(request, updatedResources, Response.Status.OK); } catch (WebApplicationException e) { throw specializeWebApplicationException(e, request, resources); } catch (UpdateFailedException e) { return createResponse(request, e.whoisResources, e.status); } catch (Exception e) { updatePerformer.logError(e); LOGGER.error("Unexpected", e); return createResponse(request, resources, Response.Status.INTERNAL_SERVER_ERROR); } finally { updatePerformer.closeContext(); } }

Target:
public Response create( final WhoisResources resources, @Context final HttpServletRequest request, @PathParam("source") final String sourceParam, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey) { if (resources == null || resources.getWhoisObjects().size() == 0) { return badRequest("WhoisResources is mandatory"); } try { final Origin origin = updatePerformer.createOrigin(request); final UpdateContext updateContext = updatePerformer.initContext(origin, crowdTokenKey); updateContext.setBatchUpdate(); final Credentials credentials = createCredentials(updateContext.getUserSession(), passwords); final List<Update> updates = extractUpdates(resources, credentials); final WhoisResources updatedResources = updatePerformer.performUpdates(updateContext, origin, updates, Keyword.NEW, request); validateUpdates(updateContext, updates, updatedResources); return createResponse(request, updatedResources, Response.Status.OK); } catch (WebApplicationException e) { throw specializeWebApplicationException(e, request, resources); } catch (UpdateFailedException e) { return createResponse(request, e.whoisResources, e.status); } catch (Exception e) { updatePerformer.logError(e); LOGGER.error("Unexpected", e); return createResponse(request, resources, Response.Status.INTERNAL_SERVER_ERROR); } finally { updatePerformer.closeContext(); } }
Source:
private boolean advanceLeft(TSource left, TKey leftKey) { lefts.clear(); lefts.add(left); while (getLeftEnumerator().moveNext()) { left = getLeftEnumerator().current(); TKey leftKey2 = outerKeySelector.apply(left); if (leftKey2 == null) { if (joinType != JoinType.LEFT) { break; } } int c = compare(leftKey, leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however '" + leftKey + "' is greater than '" + leftKey2 + "'"); } return true; } lefts.add(left); } return false; }

Target:
private boolean advanceLeft(TSource left, TKey leftKey) { lefts.clear(); lefts.add(left); while (getLeftEnumerator().moveNext()) { left = getLeftEnumerator().current(); TKey leftKey2 = outerKeySelector.apply(left); if (leftKey2 == null && joinType != JoinType.LEFT) { break; } int c = compare(leftKey, leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however '" + leftKey + "' is greater than '" + leftKey2 + "'"); } return true; } lefts.add(left); } return false; }
Source:
public Metadata getMetadata() { return document.getMetadata(); }

Target:
public Metadata getMetadata() { return this.document.getMetadata(); }
Source:
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null && j.isDisableRememberMe()) { cancelCookie(request, response, null); return null; } else { try { String rememberMeValue = findRememberMeCookieValue(request, response); if (rememberMeValue == null) { return null; } return retrieveAuthFromCookie(request, response, rememberMeValue); } catch (Exception e) { cancelCookie(request, response, "Failed to handle remember-me cookie: " + Functions.printThrowable(e)); return null; } } }

Target:
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { Jenkins j = Jenkins.getInstanceOrNull(); if (j == null) { return null; } if (j.isDisableRememberMe()) { cancelCookie(request, response, null); return null; } else { try { String rememberMeValue = findRememberMeCookieValue(request, response); if (rememberMeValue == null) { return null; } return retrieveAuthFromCookie(request, response, rememberMeValue); } catch (Exception e) { cancelCookie(request, response, "Failed to handle remember-me cookie: " + Functions.printThrowable(e)); return null; } } }
Source:
public long getExternalStorageAvailableSpaceInMb() { if (!isExternalStorageMounted()) { Timber.e("External storage is not mounted"); return 0L; } StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); double sdAvailSize = getAvailableSpace(stat); return (long) Math.floor(sdAvailSize / 1048576.0); }

Target:
public long getExternalStorageAvailableSpaceInMb() { if (!isExternalStorageMounted()) { Timber.e("External storage is not mounted"); return 0L; } StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); double sdAvailSize = getAvailableSpace(stat); return (long) Math.floor(sdAvailSize / ONE_MEBIBIT); }
Source:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }

Target:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }
Source:
public void sendBatch(Batch batch) { final Batch filtered = filter(batch); debug.inspectBatch(DEBUG_ID, filtered); int batchSize = batch.getPoints().size(); hyperLog.offer(batch.hashCode()); statistics.reportMetricsCardinality(batch.hashCode()); if (!Arrays.asList(KEYS_NEVER_TO_DROP).contains(batch.getPoints().get(0).getKey())) { if (batchSize > 0 && !rateLimitAllowed(batchSize)) { log.debug("Dropping metrics due to rate limiting", batchSize); statistics.reportMetricsDroppedByRateLimit(batchSize); return; } if (!cardinalityLimitAllowed(hyperLog.cardinality())) { log.debug( "Dropping metrics due to cardinality limiting; cardinality {}", batchSize, hyperLog.cardinality()); statistics.reportMetricsDroppedByCardinalityLimit(batchSize); swapHyperLogLogPlus(); return; } } sinks.stream() .filter(PluginSink::isReady) .forEach(s -> s.sendBatch(filtered)); statistics.reportSentMetrics(batchSize); }

Target:
public void sendBatch(Batch batch) { final Batch filtered = filter(batch); debug.inspectBatch(DEBUG_ID, filtered); int batchSize = batch.getPoints().size(); hyperLog.get().offer(batch.hashCode()); statistics.reportMetricsCardinality(hyperLog.get().cardinality()); if (isDroppable(batchSize, batch.getPoints().get(0).getKey())) { return; } sinks.stream() .filter(PluginSink::isReady) .forEach(s -> s.sendBatch(filtered)); statistics.reportSentMetrics(batchSize); }
Source:
private static Response buildServerError(Exception exception) { log.error("Error in kick job: {}", Throwables.getStackTraceAsString(exception)); String message = exception.getMessage(); if (message == null) { message = exception.toString(); } final String response = "ERROR: " + exception.getClass() + " was thrown <br/>" + "MESSAGE: " + StringEscapeUtils.escapeEcmaScript(message); return Response.serverError().entity(response).build(); }

Target:
private static Response buildServerError(Exception exception) { log.warn("", exception); String message = exception.getMessage(); if (message == null) { message = exception.toString(); } final String response = "{" + "\"error\": \"A java exception was thrown.\", " + "\"message\": \"" + StringEscapeUtils.escapeEcmaScript(message) + "\"" + "}"; return Response.serverError().entity(response).build(); }
Source:
public void testQueryFullProcessImageName() { HANDLE h = Kernel32.INSTANCE.OpenProcess(0, false, Kernel32.INSTANCE.GetCurrentProcessId()); char[] path = new char[1024]; IntByReference lpdwSize = new IntByReference(path.length); boolean b = Kernel32.INSTANCE.QueryFullProcessImageName(h, 0, path, lpdwSize); assertTrue(b); assertTrue(lpdwSize.getValue() > 0); }

Target:
public void testQueryFullProcessImageName() { HANDLE h = Kernel32.INSTANCE.OpenProcess(0, false, Kernel32.INSTANCE.GetCurrentProcessId()); assertNotNull("Failed (" + Kernel32.INSTANCE.GetLastError() + ") to get process handle", h); char[] path = new char[WinDef.MAX_PATH]; IntByReference lpdwSize = new IntByReference(path.length); boolean b = Kernel32.INSTANCE.QueryFullProcessImageName(h, 0, path, lpdwSize); assertTrue("Failed (" + Kernel32.INSTANCE.GetLastError() + ") to query process image name", b); assertTrue("Failed to query process image name, empty path returned", lpdwSize.getValue() > 0); }
Source:
private List<PartitionId> getPartitionsInClass(String partitionClass, boolean minimumReplicaCountRequired) { List<PartitionId> toReturn = new ArrayList<>(); rwLock.readLock().lock(); try { if (partitionClass == null) { toReturn.addAll(allPartitions); } else { SortedMap<Integer, List<PartitionId>> partitionsByReplicaCount = partitionIdsByClassAndLocalReplicaCount.get(partitionClass); if (partitionsByReplicaCount == null) { partitionsByReplicaCount = partitionIdsByClassAndLocalReplicaCount.get(defaultPartitionClass); } if (partitionsByReplicaCount == null) { throw new IllegalArgumentException( "No partitions for default partition class " + partitionClass + " found"); } if (minimumReplicaCountRequired) { for (List<PartitionId> partitionIds : partitionsByReplicaCount.tailMap(minimumLocalReplicaCount).values()) { toReturn.addAll(partitionIds); } } else { for (List<PartitionId> partitionIds : partitionsByReplicaCount.values()) { toReturn.addAll(partitionIds); } } } } finally { rwLock.readLock().unlock(); } return toReturn; }

Target:
private List<PartitionId> getPartitionsInClass(String partitionClass, boolean minimumReplicaCountRequired) { List<PartitionId> toReturn = new ArrayList<>(); rwLock.readLock().lock(); try { if (partitionClass == null) { toReturn.addAll(allPartitions); } else { SortedMap<Integer, List<PartitionId>> partitionsByReplicaCount = partitionIdsByClassAndLocalReplicaCount.get(partitionClass); if (partitionsByReplicaCount == null) { partitionsByReplicaCount = partitionIdsByClassAndLocalReplicaCount.get(defaultPartitionClass); } if (partitionsByReplicaCount == null) { throw new IllegalArgumentException( "No partitions for partition class = '" + partitionClass + "' or default partition class = '" + defaultPartitionClass + "' found"); } if (minimumReplicaCountRequired) { for (List<PartitionId> partitionIds : partitionsByReplicaCount.tailMap(minimumLocalReplicaCount).values()) { toReturn.addAll(partitionIds); } } else { for (List<PartitionId> partitionIds : partitionsByReplicaCount.values()) { toReturn.addAll(partitionIds); } } } } finally { rwLock.readLock().unlock(); } return toReturn; }