auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean validate() { if (getParameters().isImportEntity()) { return true; } List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); DiskValidator diskValidator = new DiskValidator(getDiskImage()); if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup == true) { return false; } } Guid imageGroupId = Guid.isNullOrEmpty(getParameters().getImageGroupID()) ? getImageGroupId() : getParameters().getImageGroupID(); Disk disk = diskDao.get(imageGroupId); if (disk != null) { DiskValidator diskValidator = new DiskValidator(disk); return validate(diskValidator.validateUnsupportedDiskStorageType( DiskStorageType.LUN, DiskStorageType.CINDER)); } return true; }

Target:
protected boolean validate() { if (getParameters().isImportEntity()) { return true; } List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup() == true) { return false; } } Guid imageGroupId = Guid.isNullOrEmpty(getParameters().getImageGroupID()) ? getImageGroupId() : getParameters().getImageGroupID(); Disk disk = diskDao.get(imageGroupId); if (disk != null) { DiskValidator diskValidator = new DiskValidator(disk); return validate(diskValidator.validateUnsupportedDiskStorageType( DiskStorageType.LUN, DiskStorageType.CINDER)); } return true; }
Source:
public void setFormattedOriginalResponseData(String originalResponseData) throws Exception { if(originalResponseData!=null && !originalResponseData.equals("") && originalResponseContentType!= null && originalResponseContentType.toLowerCase().indexOf("application/json")!=-1){ ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.defaultPrettyPrintingWriter(); Object json = objectMapper.readValue(originalResponseData, Object.class); this.formattedOriginalResponseData = writer.withView(ViewFilters.Default.class).writeValueAsString(json); } else{ this.formattedOriginalResponseData = originalResponseData; } }

Target:
public void setFormattedOriginalResponseData(String originalResponseData) throws Exception { this.formattedOriginalResponseData = originalResponseData; if(originalResponseData!=null && !originalResponseData.equals("") && originalResponseContentType != null && originalResponseContentType.toLowerCase().indexOf("application/json") != -1){ try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.defaultPrettyPrintingWriter(); Object json = objectMapper.readValue(originalResponseData, Object.class); this.formattedOriginalResponseData = writer.withView(ViewFilters.Default.class).writeValueAsString(json); } catch (JsonParseException jpe) { } } }
Source:
private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Bulk export starting generation for batch export job: {}", jobEntity); IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao(myResourceType); ourLog.info("Bulk export assembling export of type for job {}", myResourceType, myJobUUID); RuntimeResourceDefinition def = myContext.getResourceDefinition(myResourceType); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); ISearchBuilder sb = mySearchBuilderFactory.newSearchBuilder(dao, myResourceType, nextTypeClass); SearchParameterMap map = new SearchParameterMap(); Map<String, String[]> requestUrl = UrlUtil.parseQueryStrings(jobEntity.getRequest()); String[] typeFilters = requestUrl.get(JpaConstants.PARAM_EXPORT_TYPE_FILTER); if (typeFilters != null) { Optional<String> filter = Arrays.stream(typeFilters).filter(t -> t.startsWith(myResourceType + "?")).findFirst(); if (filter.isPresent()) { String matchUrl = filter.get(); map = myMatchUrlService.translateMatchUrl(matchUrl, def); } } if (jobEntity.getSince() != null) { map.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } map.setLoadSynchronous(true); IResultIterator myResultIterator = sb.createQuery(map, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions()); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (myResultIterator.hasNext()) { myReadPids.add(myResultIterator.next()); } myPidIterator = myReadPids.iterator(); }

Target:
private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Bulk export starting generation for batch export job: {}", jobEntity); IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao(myResourceType); ourLog.info("Bulk export assembling export of type for job {}", myResourceType, myJobUUID); RuntimeResourceDefinition def = myContext.getResourceDefinition(myResourceType); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); ISearchBuilder sb = mySearchBuilderFactory.newSearchBuilder(dao, myResourceType, nextTypeClass); SearchParameterMap map = createSearchParameterMapFromTypeFilter(jobEntity, def); if (jobEntity.getSince() != null) { map.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } map.setLoadSynchronous(true); IResultIterator myResultIterator = sb.createQuery(map, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions()); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (myResultIterator.hasNext()) { myReadPids.add(myResultIterator.next()); } myPidIterator = myReadPids.iterator(); }
Source:
private void addRefSetFilesForValidating() throws IOException { for (final URL url : configuration.getRefSetUrls()) { addRefSetFile(url); } if (!Iterables.any(releaseFileValidators, Predicates.instanceOf(SnomedLanguageRefSetValidator.class))) { Collection<File> languageRefSetFiles = configuration.getLanguageRefSetFiles(); for (File langFile : languageRefSetFiles) { if (isValidReleaseFile(langFile)) { releaseFileValidators.add(new SnomedLanguageRefSetValidator(configuration, configuration.toURL(langFile), this)); } } } }

Target:
private void addRefSetFilesForValidating() throws IOException { for (final URL url : configuration.getRefSetUrls()) { addRefSetFile(url); } }
Source:
private static Map<String, Object> applyEventStyleProperties(Map<String, Object> styleMap, ITimeEvent event) { Map<String, Object> updatedStyles = new HashMap<>(styleMap); if (event.isPropertyActive(IFilterProperty.DIMMED)) { Integer colorInt = (Integer) updatedStyles.getOrDefault(ITimeEventStyleStrings.fillColor(), 255); RGBAColor oldRgbaColor = new RGBAColor(colorInt); RGBAColor rgbaColor = new RGBAColor(oldRgbaColor.getRed(), oldRgbaColor.getGreen(), oldRgbaColor.getBlue(), Integer.divideUnsigned(oldRgbaColor.getAlpha(), DIMMED_ALPHA_COEFFICIENT)); updatedStyles.put(ITimeEventStyleStrings.fillColor(), rgbaColor.toInt()); updatedStyles.put(ITimeEventStyleStrings.annotated(), true); } if (event.isPropertyActive(IFilterProperty.BOUND)) { updatedStyles.put(ITimeEventStyleStrings.borderColor(), 0xff3300ff); updatedStyles.put(ITimeEventStyleStrings.annotated(), false); } return updatedStyles; }

Target:
private static Map<String, Object> applyEventStyleProperties(Map<String, Object> styleMap, ITimeEvent event) { Map<String, Object> updatedStyles = new HashMap<>(styleMap); if (event.isPropertyActive(IFilterProperty.DIMMED)) { Integer colorInt = (Integer) updatedStyles.getOrDefault(ITimeEventStyleStrings.fillColor(), 255); RGBAColor oldRgbaColor = new RGBAColor(colorInt); RGBAColor rgbaColor = new RGBAColor(oldRgbaColor.getRed(), oldRgbaColor.getGreen(), oldRgbaColor.getBlue(), Integer.divideUnsigned(oldRgbaColor.getAlpha(), DIMMED_ALPHA_COEFFICIENT)); updatedStyles.put(ITimeEventStyleStrings.fillColor(), rgbaColor.toInt()); updatedStyles.put(ITimeEventStyleStrings.annotated(), true); } if (event.isPropertyActive(IFilterProperty.BOUND)) { updatedStyles.put(ITimeEventStyleStrings.borderColor(), HIGHLIGHTED_BOUND_COLOR); updatedStyles.put(ITimeEventStyleStrings.annotated(), false); } return updatedStyles; }
Source:
public <T> T getField(final String name, final TypeReference<T> typeReference) { return Optional.ofNullable(fields.get(name)) .map(jsonNode -> SphereJsonUtils.readObject(jsonNode, typeReference)) .orElse(null); }

Target:
public <T> T getField(final String name, final TypeReference<T> typeReference) { return Optional.ofNullable(getField(name)) .map(jsonNode -> SphereJsonUtils.readObject(jsonNode, typeReference)) .orElse(null); }
Source:
public void addUmiObservationN() { observedUmiWithN++; }

Target:
public void addUmiObservationN() { observedUmiWithNs++; }
Source:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); IModule[] modules = appModule.getModule(); return appServer != null && appServer.getModuleState(appModule.getModule()) == IServer.STATE_STARTED && WSTUtils.isServerStarted(appServer) && WSTUtils.getModuleURL(appServer, modules[modules.length - 1]) != null; }

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); IModule[] modules = appModule.getModule(); return appServer != null && isModuleStartedOrUnknown(appServer, modules) && WSTUtils.isServerStarted(appServer) && WSTUtils.getModuleURL(appServer, modules[modules.length - 1]) != null; }
Source:
public void process() { PerformanceMonitor.startActivity("rendering/finalpostprocessing"); ocUndistorted = frameBuffersManager.getFBO("ocUndistorted"); sceneFinal = frameBuffersManager.getFBO("sceneFinal"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); fullScale = sceneOpaque.dimensions(); if (!renderingDebugConfig.isEnabled()) { finalPost.enable(); } else { debug.enable(); } if (!renderingConfig.isOculusVrSupport()) { renderFinalMonoImage(); } else { renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); } PerformanceMonitor.endActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/finalPostProcessing"); ocUndistorted = frameBuffersManager.getFBO("ocUndistorted"); sceneFinal = frameBuffersManager.getFBO("sceneFinal"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); fullScale = sceneOpaque.dimensions(); if (!renderingDebugConfig.isEnabled()) { finalPost.enable(); } else { debug.enable(); } if (!renderingConfig.isOculusVrSupport()) { renderFinalMonoImage(); } else { renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); } PerformanceMonitor.endActivity(); }
Source:
public MicrometerMetricsReporterProvider() { micrometerMetricsReporter = MicrometerMetricsReporter.newMetricsReporter() .withName(TRACING_METRIC_NAME) .withTagLabel(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) .withTagLabel(Tags.HTTP_STATUS.getKey(), "null") .build(); }

Target:
public MicrometerMetricsReporterProvider() { micrometerMetricsReporter = MicrometerMetricsReporter.newMetricsReporter() .withName(TRACING_METRIC_NAME) .withTagLabel(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) .withTagLabel(Tags.HTTP_STATUS.getKey(), "undefined") .build(); }
Source:
public boolean executeWithAgent(final JobRequest jobRequest, final HttpServletRequest httpServletRequest) { for (final Pair<String, CheckRequestFunction> nameFunctionCheckPair : this.checks) { final String checkName = nameFunctionCheckPair.getKey(); final CheckRequestFunction checkFunction = nameFunctionCheckPair.getValue(); final Optional<Boolean> checkOptionalOutcome = checkFunction.check(jobRequest, httpServletRequest); if (checkOptionalOutcome.isPresent()) { final boolean executeWithAgent = checkOptionalOutcome.get(); this.publishMetric(executeWithAgent, checkName); return executeWithAgent; } } final boolean executeWithAgent = this.environment.getProperty( DEFAULT_EXECUTION_PROPERTY, Boolean.class, DEFAULT_EXECUTE_WITH_AGENT ); this.publishMetric(executeWithAgent, "default"); return executeWithAgent; }

Target:
public boolean executeWithAgent(final JobRequest jobRequest, final HttpServletRequest httpServletRequest) { for (final Pair<String, CheckRequestFunction> nameFunctionCheckPair : this.checks) { final String checkName = nameFunctionCheckPair.getKey(); final CheckRequestFunction checkFunction = nameFunctionCheckPair.getValue(); final Optional<Boolean> checkOptionalOutcome = checkFunction.check(jobRequest, httpServletRequest); if (checkOptionalOutcome.isPresent()) { final boolean executeWithAgent = checkOptionalOutcome.get(); this.publishMetric(executeWithAgent, checkName); return executeWithAgent; } } final boolean executeWithAgent = this.environment.getProperty( DEFAULT_EXECUTE_WITH_AGENT_PROPERTY, Boolean.class, DEFAULT_EXECUTE_WITH_AGENT ); this.publishMetric(executeWithAgent, DEFAULT); return executeWithAgent; }
Source:
public void error() { if (callback != null) { callback.onError(); } }

Target:
@Override void error() { if (callback != null) { callback.onError(); } }
Source:
private void syntaxCheck(String data) { if (!(data.contains("${") && data.contains(":") && data.contains("#") && data.contains("}"))) { throw new IllegalArgumentException("Invalid syntax for lang lookup"); } }

Target:
private void syntaxCheck(String data) { Matcher matcher = pattern.matcher(data); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid syntax for lang lookup"); } }
Source:
public void setVersion(String version) { mVersion = version; System.out.println("Version is now "+version); }

Target:
public void setVersion(String version) { mVersion = version; }
Source:
private Integer parseIoThreadId(XmlNode node) { XmlNode addressNode = node.selectSingleNode("driver"); if (addressNode == null) { return null; } XmlAttribute val = addressNode.attributes.get("iothread"); return val != null ? Integer.valueOf(val.getValue()) : null; }

Target:
private Integer parseIoThreadId(XmlNode node) { XmlNode driverNode = node.selectSingleNode("driver"); if (driverNode == null) { return null; } XmlAttribute val = driverNode.attributes.get("iothread"); return val != null ? Integer.valueOf(val.getValue()) : null; }
Source:
public int getChildCount( Name name ) { int appendedChildren = appended != null ? appended.getChildCount(name) : 0; int persistedChildrenCount = persisted.getChildCount(name); int removedChildren = 0; int renamedChildren = 0; int appendedThenReorderedChildren = 0; if (changedChildren != null) { appendedThenReorderedChildren = changedChildren.insertionCount(name); for (int i = 0; i < persisted.getChildCount(name); i++) { ChildReference persistedChild = persisted.getChild(name, i + 1); if (changedChildren.isRemoved(persistedChild)) { removedChildren--; break; } if (changedChildren.isRenamed(persistedChild)) { renamedChildren--; } } if (changedChildren.isRenamed(name)) { renamedChildren++; } } return persistedChildrenCount + appendedChildren + appendedThenReorderedChildren + removedChildren + renamedChildren; }

Target:
public int getChildCount( Name name ) { int appendedChildren = appended != null ? appended.getChildCount(name) : 0; int persistedChildrenCount = persisted.getChildCount(name); int removedChildren = 0; int renamedChildren = 0; int appendedThenReorderedChildren = 0; if (changedChildren != null) { appendedThenReorderedChildren = changedChildren.insertionCount(name); for (Iterator<ChildReference> childReferenceIterator = persisted.iterator(name); childReferenceIterator.hasNext(); ) { ChildReference persistedChild = childReferenceIterator.next(); if (changedChildren.isRemoved(persistedChild)) { --removedChildren; continue; } if (changedChildren.isRenamed(persistedChild)) { --renamedChildren; } } if (changedChildren.isRenamed(name)) { ++renamedChildren; } } return persistedChildrenCount + appendedChildren + appendedThenReorderedChildren + removedChildren + renamedChildren; }
Source:
public static AnnotationSpec get(AnnotationMirror annotation) { AnnotationSpec.Builder builder = AnnotationSpec.builder( ClassName.get((TypeElement) annotation.getAnnotationType().asElement())); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) { String name = entry.getKey().getSimpleName().toString(); builder.addMember(name, CodeBlock.builder().add(entry.getValue().toString()).build()); } return builder.build(); }

Target:
public static AnnotationSpec get(AnnotationMirror annotation) { TypeElement element = (TypeElement) annotation.getAnnotationType().asElement(); AnnotationSpec.Builder builder = AnnotationSpec.builder(ClassName.get(element)); Visitor visitor = new Visitor(builder); for (ExecutableElement executableElement : annotation.getElementValues().keySet()) { String name = executableElement.getSimpleName().toString(); AnnotationValue value = annotation.getElementValues().get(executableElement); value.accept(visitor, new Entry(name, value)); } return builder.build(); }
Source:
public void savePerson() { try { PersonInterface per = UghImplementation.INSTANCE .createPerson(this.myPrefs.getMetadataTypeByName(this.tempPersonRolle)); per.setFirstName(this.tempPersonVorname); per.setLastName(this.tempPersonNachname); per.setRole(this.tempPersonRolle); String[] authorityFile = parseAuthorityFileArgs(tempPersonRecord); per.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); this.docStruct.addPerson(per); this.modeAddPerson = false; saveMetadataAsBean(this.docStruct); } catch (IncompletePersonObjectException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung("Incomplete data for person", ""); } catch (MetadataTypeNotAllowedException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung("Person is for this structure not allowed", ""); } }

Target:
public void savePerson() { try { PersonInterface per = UghImplementation.INSTANCE .createPerson(this.myPrefs.getMetadataTypeByName(this.tempPersonRolle)); per.setFirstName(this.tempPersonVorname); per.setLastName(this.tempPersonNachname); per.setRole(this.tempPersonRolle); String[] authorityFile = parseAuthorityFileArgs(tempPersonRecord); per.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); this.docStruct.addPerson(per); this.modeAddPerson = false; saveMetadataAsBean(this.docStruct); } catch (IncompletePersonObjectException e) { Helper.setErrorMessage("Incomplete data for person", logger, e); } catch (MetadataTypeNotAllowedException e) { Helper.setErrorMessage("Person is for this structure not allowed", logger, e); } }
Source:
public synchronized void reset() { this.min = 0; this.max = 0; this.count = 0; this.times.clear(); t0 = System.nanoTime() / this.factor; }

Target:
public synchronized void reset() { this.min = Double.MAX_VALUE; this.max = 0; this.count = 0; this.times.clear(); t0 = System.nanoTime() / this.factor; }
Source:
public void testCompareToCornerCases3() { final ITmfTimestamp ts0a = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE - 1); final ITmfTimestamp ts0b = TmfTimestamp.create(0, Integer.MAX_VALUE); final ITmfTimestamp ts0c = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE); assertTrue("compareTo", ts0a.compareTo(ts0b) < 0); assertTrue("compareTo", ts0a.compareTo(ts0c) > 0); assertEquals("compareTo", 1, ts0b.compareTo(ts0a)); assertEquals("compareTo", 1, ts0b.compareTo(ts0c)); assertEquals("compareTo", -1, ts0c.compareTo(ts0a)); assertEquals("compareTo", -1, ts0c.compareTo(ts0b)); }

Target:
public void testCompareToCornerCases3() { final ITmfTimestamp ts0a = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE - 1); final ITmfTimestamp ts0b = TmfTimestamp.create(0, Integer.MAX_VALUE); final ITmfTimestamp ts0c = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE); assertTrue("compareTo", ts0a.compareTo(ts0b) < 0); assertTrue("compareTo", ts0a.compareTo(ts0c) > 0); assertTrue("compareTo", ts0b.compareTo(ts0a) > 0); assertTrue("compareTo", ts0b.compareTo(ts0c) > 0); assertTrue("compareTo", ts0c.compareTo(ts0a) < 0); assertTrue("compareTo", ts0c.compareTo(ts0b) < 0); }
Source:
public boolean hasNext() { if (saveNext != null) { return true; } try { saveNext = internalNext(); return true; } catch (NoSuchElementException e) { return false; } }

Target:
public boolean hasNext() { if (saveNext != null) { return true; } saveNext = internalNext(); return (saveNext != null); }
Source:
public void handleNewSession() throws Exception { LOG.info("Got new session created event for processor=" + processorId); zkUtils.incGeneration(); if (coordinatorListener != null) { coordinatorListener.onJobModelExpired(); } zkUtils.unregister(); if (zkController != null) { LOG.info("register zk controller for the new session"); zkController.register(); } }

Target:
public void handleNewSession() throws Exception { LOG.info("Got new session created event for processor=" + processorId); LOG.info("register zk controller for the new session"); zkController.register(); }
Source:
public void setStatusCode(int code) { this.code = code; }

Target:
void setStatusCode(int code) { this.code = code; }
Source:
public String toJSON() throws IOException { JsonGenerator g = jsonGeneratorThreadLocal.get(); g.writeStartObject(); g.writeStringField("database", this.database); g.writeStringField("table", this.table); g.writeStringField("type", this.rowType); g.writeNumberField("ts", this.timestamp); if ( this.xid != null ) g.writeNumberField("xid", this.xid); if ( this.txCommit ) g.writeBooleanField("commit", true); if ( this.excludeColumns != null ) { Set<String> keys = new HashSet<String>(); keys.addAll(this.data.keySet()); keys.addAll(this.oldData.keySet()); for ( Pattern p : this.excludeColumns ) { for ( String key : keys ) { if ( p.matcher(key).matches() ) { this.data.remove(key); this.oldData.remove(key); } } } } writeMapToJSON("data", this.data, !this.omitNulls); if ( !this.oldData.isEmpty() ) { writeMapToJSON("old", this.oldData, true); } g.writeEndObject(); g.flush(); return jsonFromStream(); }

Target:
public String toJSON() throws IOException { return toJSON(new MaxwellOutputConfig()); }
Source:
public synchronized void startRecovery(final Map<String, GroupStats> failedGroups) { if (!isRecoveryOngoing.compareAndSet(false, true)) { throw new IllegalStateException("Internal Error : startRecovery() is called while other recovery process is " + "already running!"); } if (failedGroups.isEmpty()) { lock.lock(); isRecoveryOngoing.set(true); recoveryFinished.signalAll(); lock.unlock(); return; } LOG.log(Level.INFO, "Start distributed recovery on failed groups: {0}", failedGroups.keySet()); recoveryGroups.putAll(failedGroups); final List<MasterToTaskMessage> proxyToRecoveryTaskList = new ArrayList<>(); try { for (final Map.Entry<String, TaskStats> entry: taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() < overloadedTaskThreshold) { proxyToRecoveryTaskList.add(proxyToTaskMap.get(entry.getKey())); } } for (final MasterToTaskMessage proxyToTask : proxyToRecoveryTaskList) { proxyToTask.startTaskSideRecovery(); } } catch (final AvroRemoteException e) { LOG.log(Level.SEVERE, "Start recovery through avro server has failed! " + e.toString()); } }

Target:
public synchronized void startRecovery(final Map<String, GroupStats> failedGroups) { if (failedGroups.isEmpty()) { LOG.log(Level.INFO, "No groups to recover..."); return; } if (!isRecoveryOngoing.compareAndSet(false, true)) { throw new IllegalStateException("Internal Error : startRecovery() is called while other recovery process is " + "already running!"); } LOG.log(Level.INFO, "Start distributed recovery on failed groups: {0}", failedGroups.keySet()); recoveryGroups.putAll(failedGroups); final List<MasterToTaskMessage> proxyToRecoveryTaskList = new ArrayList<>(); try { for (final Map.Entry<String, TaskStats> entry: taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() < overloadedTaskThreshold) { proxyToRecoveryTaskList.add(proxyToTaskMap.get(entry.getKey())); } } for (final MasterToTaskMessage proxyToTask : proxyToRecoveryTaskList) { proxyToTask.startTaskSideRecovery(); } } catch (final AvroRemoteException e) { LOG.log(Level.SEVERE, "Start recovery through avro server has failed! " + e.toString()); } }
Source:
public void testReduceWindowStateReader() throws Exception { String savepointPath = takeSavepoint(numbers, source -> { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.setStateBackend(getStateBackend()); env.setParallelism(4); env .addSource(source) .rebalance() .assignTimestampsAndWatermarks(WatermarkStrategy .<Integer>noWatermarks() .withTimestampAssigner((event, timestamp) -> 0)) .keyBy(id -> id) .timeWindow(Time.milliseconds(10)) .reduce(new ReduceSum()) .uid(uid) .addSink(new DiscardingSink<>()); return env; }); ExecutionEnvironment batchEnv = ExecutionEnvironment.getExecutionEnvironment(); ExistingSavepoint savepoint = Savepoint.load(batchEnv, savepointPath, getStateBackend()); List<Integer> results = savepoint .timeWindow() .reduce(uid, new ReduceSum(), Types.INT, Types.INT) .collect(); Assert.assertThat("Unexpected results from keyed state", results, Matchers.containsInAnyOrder(numbers)); }

Target:
public void testReduceWindowStateReader() throws Exception { String savepointPath = takeSavepoint(numbers, source -> { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.setStateBackend(getStateBackend()); env.setParallelism(4); env .addSource(source) .rebalance() .assignTimestampsAndWatermarks(WatermarkStrategy .<Integer>noWatermarks() .withTimestampAssigner((event, timestamp) -> 0)) .keyBy(id -> id) .window(TumblingEventTimeWindows.of(Time.milliseconds(10))) .reduce(new ReduceSum()) .uid(uid) .addSink(new DiscardingSink<>()); return env; }); ExecutionEnvironment batchEnv = ExecutionEnvironment.getExecutionEnvironment(); ExistingSavepoint savepoint = Savepoint.load(batchEnv, savepointPath, getStateBackend()); List<Integer> results = savepoint .window(TumblingEventTimeWindows.of(Time.milliseconds(10))) .reduce(uid, new ReduceSum(), Types.INT, Types.INT) .collect(); Assert.assertThat("Unexpected results from keyed state", results, Matchers.containsInAnyOrder(numbers)); }
Source:
public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException { return checkProperties().getShortProperty(SimpleString.toSimpleString(key, getPropertyKeysPool())); }

Target:
public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException { return getShortProperty(key(key)); }
Source:
public int getJuteMaxBufferSize() { return Integer.getInteger("jute.maxbuffer", 0xfffff); }

Target:
public int getJuteMaxBufferSize() { return BinaryInputArchive.maxBuffer; }
Source:
protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) { for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { if (_autoPausedSourcePartitions.containsKey(topicPartition)) { _logger.warn("Abort sending as is auto-paused, rewind offset", topicPartition); seekToLastCheckpoint(Collections.singleton(topicPartition)); break; } else { DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); int numBytes = record.serializedKeySize() + record.serializedValueSize(); sendDatastreamProducerRecord(datastreamProducerRecord, topicPartition, numBytes, null); } } catch (Exception e) { _logger.warn("Got exception while sending record {}, exception: ", record, e); rewindAndPausePartitionOnException(topicPartition, e); break; } } } }

Target:
protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) { for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { if (_autoPausedSourcePartitions.containsKey(topicPartition)) { _logger.warn("Abort sending as is auto-paused, rewind offset", topicPartition); seekToLastCheckpoint(Collections.singleton(topicPartition)); break; } else { DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); int numBytes = record.serializedKeySize() + record.serializedValueSize(); sendDatastreamProducerRecord(datastreamProducerRecord, topicPartition, numBytes, null); } } catch (Exception e) { _logger.warn(String.format("Got exception while sending record %s, exception: ", record), e); rewindAndPausePartitionOnException(topicPartition, e); break; } } } }
Source:
public static BiConsumer<ItemStack.Builder, Random> quantity(VariableAmount amount) { checkNotNull(amount, "VariableAmount cannot be null!"); return ((builder, random) -> builder.quantity(amount.getFlooredAmount(random))); }

Target:
public static BiConsumer<ItemStack.Builder, Random> quantity(VariableAmount amount) { checkNotNull(amount, "VariableAmount cannot be null!"); return (builder, random) -> builder.quantity(amount.getFlooredAmount(random)); }
Source:
public void testValidateAttachementsForVlans(){ NetworkAttachment attachement1 = new NetworkAttachment(); attachement1.setNetworkName("network1"); attachement1.setNicName("eth0"); NetworkAttachment attachement2 = new NetworkAttachment(); attachement2.setNetworkName("any2"); attachement2.setNicName("eth1"); List<NetworkAttachment> attachementList = Arrays.asList(attachement1, attachement2); Nic nic = new Nic(); nic.setName("eth0"); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth.100", 100); ValidationResult result = validator.validateAttachements(vlanNic, attachementList); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ATTACHEMENT_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NETWORK, "network1"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); vlanNic.setBaseInterface("eth7"); result = validator.validateAttachements(vlanNic, attachementList); assertTrue(result.isValid()); }

Target:
public void testValidateAttachementsForVlans(){ String unmanagedBaseNicName = "eth0"; NetworkAttachment attachement1 = new NetworkAttachment(); attachement1.setNetworkName("network1"); attachement1.setNicName(unmanagedBaseNicName); NetworkAttachment attachement2 = new NetworkAttachment(); attachement2.setNetworkName("any2"); attachement2.setNicName("eth1"); List<NetworkAttachment> attachementList = Arrays.asList(attachement1, attachement2); Nic nic = createNic(unmanagedBaseNicName); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100, false); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(vlanNic); Set<String> nicsWithUnmanagedNetworks = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, Collections.emptySet()); assertEquals(1, nicsWithUnmanagedNetworks.size()); String filteredNicName = nicsWithUnmanagedNetworks.iterator().next(); assertEquals(filteredNicName, unmanagedBaseNicName); ValidationResult result = validator.validateAttachements(filteredNicName, attachementList); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ATTACHEMENT_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NETWORK, "network1"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); result = validator.validateAttachements("eth7", attachementList); assertTrue(result.isValid()); }
Source:
public String graph( @RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient oAuth2AuthorizedClient ) { logAuthorizedClient(oAuth2AuthorizedClient); return "graph"; }

Target:
public String graph( @RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient oAuth2AuthorizedClient ) throws JsonProcessingException { return toJsonString(oAuth2AuthorizedClient); }
Source:
public void testDuplicateSetupForTransfer() { SessionData login = login(user.getUsername(), userCleartextPassword); given(). filter(sessionFilter). header(login.getCsrfHeader()). when(). content(ticketReceiver.getUsername()).contentType(ContentType.TEXT). post(TRANSFER_ENDPOINT + "/" + ticket.getId()). then(). extract().response(); given() .filter(sessionFilter) .header(login.getCsrfHeader()) .when() .content(ticketReceiver.getUsername()).contentType(ContentType.TEXT) .post(TRANSFER_ENDPOINT + "/" + ticket.getId()) .then() .statusCode(HttpStatus.SC_BAD_REQUEST); }

Target:
public void testDuplicateSetupForTransfer() { addTicketTransfer(user.getUsername(), userCleartextPassword); Response response = addTicketTransfer(user.getUsername(), userCleartextPassword); response.then() .statusCode(HttpStatus.SC_BAD_REQUEST); }
Source:
public void addFailureDescription(final ModelNode operation, final ModelNode failureDescription) { ModelNode error = new ModelNode(); ModelNode failure = new ModelNode(); failure.get(FAILED).set(operation.clone()); if (failureDescription != null) { if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.failedServices())) { failure.get(FAILURES).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.failedServices())); } if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())) { failure.get(MISSING_DEPS).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())); } if(failureDescription.getType() == ModelType.STRING) { failure.get(FAILURES).add(failureDescription.asString()); } } error.get(BOOT_ERROR).set(failure); errors.get(BOOT_ERRORS).add(error); }

Target:
void addFailureDescription(final ModelNode operation, final ModelNode failureDescription) { ModelNode error = new ModelNode(); ModelNode failure = new ModelNode(); ModelNode failed = failure.get(FAILED); failed.get(OP).set(operation.get(OP)); failed.get(OP_ADDR).set(operation.get(OP_ADDR)); if (failureDescription != null) { if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.failedServices())) { failure.get(FAILURES).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.failedServices())); } if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())) { failure.get(MISSING_DEPS).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())); } if (failureDescription.getType() == ModelType.STRING) { failure.get(FAILURES).add(failureDescription.asString()); } } error.get(BOOT_ERROR).set(failure); errors.get(BOOT_ERRORS).add(error); }
Source:
public void testResourceConfigRefresh() throws Exception { Workflow.Builder builder = new Workflow.Builder("TEST"); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); builder.addJob(WorkflowGenerator.JOB_NAME_1, jobBuilder); _driver.start(builder.build()); WorkflowControllerDataProvider cache = new WorkflowControllerDataProvider("CLUSTER_" + TestHelper.getTestClassName()); boolean expectedValuesAchieved = TestHelper.verify(() -> { cache.requireFullRefresh(); cache.refresh(_manager.getHelixDataAccessor()); int configMapSize = cache.getJobConfigMap().size(); int workflowConfigMapSize = cache.getWorkflowConfigMap().size(); int contextsSize = cache.getContexts().size(); return (configMapSize == 1 && workflowConfigMapSize == 1 && contextsSize == 2); }, 30 * 1000); Assert.assertTrue(expectedValuesAchieved); builder = new Workflow.Builder("TEST1"); builder.addParentChildDependency(WorkflowGenerator.JOB_NAME_1, WorkflowGenerator.JOB_NAME_2); builder.addJob(WorkflowGenerator.JOB_NAME_1, jobBuilder); builder.addJob(WorkflowGenerator.JOB_NAME_2, jobBuilder); _driver.start(builder.build()); expectedValuesAchieved = TestHelper.verify(() -> { cache.requireFullRefresh(); cache.refresh(_manager.getHelixDataAccessor()); int configMapSize = cache.getJobConfigMap().size(); int workflowConfigMapSize = cache.getWorkflowConfigMap().size(); int contextsSize = cache.getContexts().size(); return (configMapSize == 3 && workflowConfigMapSize == 2 && contextsSize == 5); }, 30 * 1000); Assert.assertTrue(expectedValuesAchieved); }

Target:
public void testResourceConfigRefresh() throws Exception { Workflow.Builder builder = new Workflow.Builder("TEST"); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); builder.addJob(WorkflowGenerator.JOB_NAME_1, jobBuilder); _driver.start(builder.build()); WorkflowControllerDataProvider cache = new WorkflowControllerDataProvider("CLUSTER_" + TestHelper.getTestClassName()); boolean expectedValuesAchieved = TestHelper.verify(() -> { cache.requireFullRefresh(); cache.refresh(_manager.getHelixDataAccessor()); int configMapSize = cache.getJobConfigMap().size(); int workflowConfigMapSize = cache.getWorkflowConfigMap().size(); int contextsSize = cache.getContexts().size(); return (configMapSize == 1 && workflowConfigMapSize == 1 && contextsSize == 2); }, TestHelper.WAIT_DURATION); Assert.assertTrue(expectedValuesAchieved); builder = new Workflow.Builder("TEST1"); builder.addParentChildDependency(WorkflowGenerator.JOB_NAME_1, WorkflowGenerator.JOB_NAME_2); builder.addJob(WorkflowGenerator.JOB_NAME_1, jobBuilder); builder.addJob(WorkflowGenerator.JOB_NAME_2, jobBuilder); _driver.start(builder.build()); expectedValuesAchieved = TestHelper.verify(() -> { cache.requireFullRefresh(); cache.refresh(_manager.getHelixDataAccessor()); int configMapSize = cache.getJobConfigMap().size(); int workflowConfigMapSize = cache.getWorkflowConfigMap().size(); int contextsSize = cache.getContexts().size(); return (configMapSize == 3 && workflowConfigMapSize == 2 && contextsSize == 5); }, TestHelper.WAIT_DURATION); Assert.assertTrue(expectedValuesAchieved); }
Source:
private Connection retry(Connection connection) { int retryC = 0; while ((connection == null) && ((retryCount == -1) || (retryC < retryCount))) { retryC++; log.info("[" + name + "] Attempting to create connection to RabbitMQ Broker" + " in " + retryInterval + " ms"); try { Thread.sleep(retryInterval); connection = RabbitMQUtils.createConnection(connectionFactory, addresses); log.info("[" + name + "] Successfully connected to RabbitMQ Broker"); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (IOException e1) { log.error("[" + name + "] Error while trying to reconnect to RabbitMQ Broker", e1); } } return connection; }

Target:
private Connection retry(Connection connection) { int retryC = 0; while ((connection == null) && ((retryCount == -1) || (retryC < retryCount))) { retryC++; log.info("[" + name + "] Attempting to create connection to RabbitMQ Broker" + " in " + retryInterval + "ms. Retry attempts: " + retryC); try { Thread.sleep(retryInterval); connection = RabbitMQUtils.createConnection(connectionFactory, addresses); log.info("[" + name + "] Successfully connected to RabbitMQ Broker"); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (IOException e1) { log.error("[" + name + "] Error while trying to reconnect to RabbitMQ Broker", e1); } } return connection; }
Source:
public void run() { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler running..."); } try { if (this.getListener() == null && !this.isSingleUse()) { logger.debug("TcpListener exiting - no listener and not single use"); return; } try { if (dataAvailable()) { Message<?> message = convert(); if (dataAvailable()) { this.executionControl.incrementAndGet(); this.taskExecutor.execute(this); } this.executionControl.decrementAndGet(); if (message != null) { sendToChannel(message); } } else { this.executionControl.decrementAndGet(); } } catch (Exception e) { if (logger.isTraceEnabled()) { logger.error("Read exception " + this.getConnectionId(), e); } else if (!this.isNoReadErrorOnClose()) { logger.error("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } else { logger.debug("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } this.closeConnection(); this.sendExceptionToListener(e); return; } } finally { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler exiting..."); } try { if (this.isOpen() && dataAvailable()) { checkForAssembler(); } } catch (IOException e) { logger.error("Exception when checking for assembler", e); } } }

Target:
public void run() { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler running..."); } try { if (this.getListener() == null && !this.isSingleUse()) { logger.debug("TcpListener exiting - no listener and not single use"); return; } try { if (dataAvailable()) { Message<?> message = convert(); if (dataAvailable()) { this.executionControl.incrementAndGet(); this.taskExecutor.execute(this); } this.executionControl.decrementAndGet(); if (message != null) { sendToChannel(message); } } else { this.executionControl.decrementAndGet(); } } catch (Exception e) { if (logger.isTraceEnabled()) { logger.error("Read exception " + this.getConnectionId(), e); } else if (!this.isNoReadErrorOnClose()) { logger.error("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } else { if (logger.isDebugEnabled()) { logger.debug("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } } this.closeConnection(); this.sendExceptionToListener(e); return; } } finally { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler exiting..."); } try { if (this.isOpen() && dataAvailable()) { checkForAssembler(); } } catch (IOException e) { logger.error("Exception when checking for assembler", e); } } }
Source:
public int size() { return partitions.length; }

Target:
public int size() { return this.partitions.length; }
Source:
private boolean hasMediaPlayerAudioTracks(ExoPlayer mediaPlayer) { if(mediaPlayer.getAudioComponent() == null) { return false; } else { return true; } }

Target:
private boolean hasMediaPlayerAudioTracks(ExoPlayer mediaPlayer) { return mediaPlayer.getAudioComponent() != null; }
Source:
private void updateRESTConfig(String clusterName, RESTConfig restConfig, boolean overwrite) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("fail to update REST config. cluster: " + clusterName + " is NOT setup."); } HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build(); String zkPath = scope.getZkPath(); String parentPath = HelixUtil.getZkParentPath(zkPath); if (!_zkClient.exists(HelixUtil.getZkParentPath(zkPath))) { ZKUtil.createOrMerge(_zkClient, parentPath, new ZNRecord(parentPath), true, true); } if (overwrite) { ZKUtil.createOrReplace(_zkClient, zkPath, restConfig.getRecord(), true); } else { ZKUtil.createOrUpdate(_zkClient, zkPath, restConfig.getRecord(), true, true); } }

Target:
private void updateRESTConfig(String clusterName, RESTConfig restConfig, boolean overwrite) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("Fail to update REST config. cluster: " + clusterName + " is NOT setup."); } HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build(); String zkPath = scope.getZkPath(); String parentPath = HelixUtil.getZkParentPath(zkPath); if (!_zkClient.exists(parentPath)) { ZKUtil.createOrMerge(_zkClient, parentPath, new ZNRecord(parentPath), true, true); } if (overwrite) { ZKUtil.createOrReplace(_zkClient, zkPath, restConfig.getRecord(), true); } else { ZKUtil.createOrUpdate(_zkClient, zkPath, restConfig.getRecord(), true, true); } }
Source:
public void testActivateFilterException() throws InvalidSyntaxException { CloudPublisher cp = new CloudPublisher(); WireHelperService wireHelperServiceMock = mock(WireHelperService.class); cp.bindWireHelperService(wireHelperServiceMock); BundleContext bundleCtxMock = mock(BundleContext.class); Filter filter = mock(Filter.class); when(bundleCtxMock.createFilter(anyString())).thenThrow(new InvalidSyntaxException("test", "filter")); ComponentContext ctxMock = mock(ComponentContext.class); when(ctxMock.getBundleContext()).thenReturn(bundleCtxMock); Map<String, Object> properties = new HashMap<>(); properties.put("cloud.service.pid", "cspid"); properties.put("publish.priority", 1); properties.put("publish.qos", 0); properties.put("publish.retain", true); try { cp.activate(ctxMock, properties); fail("Exception was expected."); } catch (NullPointerException e) { } verify(ctxMock, times(1)).getBundleContext(); verify(bundleCtxMock, times(1)) .createFilter("(&(objectClass=org.eclipse.kura.cloud.CloudService)(kura.service.pid=cspid))"); }

Target:
public void testActivateFilterException() throws InvalidSyntaxException { CloudPublisher cp = new CloudPublisher(); WireHelperService wireHelperServiceMock = mock(WireHelperService.class); cp.bindWireHelperService(wireHelperServiceMock); BundleContext bundleCtxMock = mock(BundleContext.class); when(bundleCtxMock.createFilter(anyString())).thenThrow(new InvalidSyntaxException("test", "filter")); ComponentContext ctxMock = mock(ComponentContext.class); when(ctxMock.getBundleContext()).thenReturn(bundleCtxMock); Map<String, Object> properties = new HashMap<>(); properties.put("cloud.service.pid", "cspid"); properties.put("publish.priority", 1); properties.put("publish.qos", 0); properties.put("publish.retain", true); try { cp.activate(ctxMock, properties); fail("Exception was expected."); } catch (NullPointerException e) { } verify(ctxMock, times(1)).getBundleContext(); verify(bundleCtxMock, times(1)) .createFilter("(&(objectClass=org.eclipse.kura.cloud.CloudService)(kura.service.pid=cspid))"); }
Source:
private void changeExperimentName(TracePackageExperimentElement experimentElement) { String currentName = experimentElement.getImportName(); int nameSuffixIndex = 1; while (experimentExists(experimentElement)) { String newName = currentName + " (" + nameSuffixIndex + ')'; experimentElement.setImportName(newName); nameSuffixIndex++; } }

Target:
private void changeExperimentName(TracePackageExperimentElement experimentElement) { String currentName = experimentElement.getImportName(); int nameSuffixIndex = 2; while (experimentExists(experimentElement)) { String newName = currentName + " (" + nameSuffixIndex + ')'; experimentElement.setImportName(newName); nameSuffixIndex++; } }
Source:
void assertSameContent( List<Long> actual, List<Long> expected ) { actual.sort( Long::compareTo ); expected.sort( Long::compareTo ); assertThat( actual, is( expected ) ); }

Target:
void assertSameContent( List<Long> actual, List<Long> expected ) { assertThat( actual, is( containsInAnyOrder( expected.toArray() ) ) ); }
Source:
public List<SingularityPendingTaskId> getScheduledTaskIds( @Parameter(hidden = true) @Auth SingularityUser user, @Parameter(description = "Use the cached version of this data to limit expensive api calls") @QueryParam("useWebCache") Boolean useWebCache) { List<SingularityPendingTaskId> taskIds = authorizationHelper.filterByAuthorizedRequests(user, taskManager.getPendingTaskIds(useWebCache(useWebCache)), SingularityTransformHelpers.PENDING_TASK_ID_TO_REQUEST_ID, SingularityAuthorizationScope.READ); Collections.sort(taskIds); return taskIds; }

Target:
public List<SingularityPendingTaskId> getScheduledTaskIds( @Parameter(hidden = true) @Auth SingularityUser user, @Parameter(description = "Use the cached version of this data to limit expensive api calls") @QueryParam("useWebCache") Boolean useWebCache) { return authorizationHelper.filterByAuthorizedRequests(user, taskManager.getPendingTaskIds(useWebCache(useWebCache)), SingularityTransformHelpers.PENDING_TASK_ID_TO_REQUEST_ID, SingularityAuthorizationScope.READ) .stream() .sorted() .collect(Collectors.toList()); }