auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static VmPayload map(Payload model, VmPayload template) { VmPayload entity = template != null ? template : new VmPayload(); if (model.getType() != null) { org.ovirt.engine.api.model.VmDeviceType deviceType = org.ovirt.engine.api.model.VmDeviceType.fromValue(model.getType()); if (deviceType!=null) { entity.setType(map(deviceType, null)); } } <START> entity.setVolumeId(model.getVolumeId()); <END> if (model.getFile() != null) { for (PayloadFile file : model.getFile()) { entity.getFiles().put(file.getName(), file.getContent()); } } return entity; }</code><technical_language>check if volume-id is null. This mapping (API-->Engine) invoked in context of update, if user update volume-id, then, this check, find overriding a valid 'null'</technical_language>

Target:
public static VmPayload map(Payload model, VmPayload template) { VmPayload entity = template != null ? template : new VmPayload(); if (model.getType() != null) { org.ovirt.engine.api.model.VmDeviceType deviceType = org.ovirt.engine.api.model.VmDeviceType.fromValue(model.getType()); if (deviceType!=null) { entity.setType(map(deviceType, null)); } } if (model.isSetVolumeId()) { entity.setVolumeId(model.getVolumeId()); } if (model.getFile() != null) { for (PayloadFile file : model.getFile()) { entity.getFiles().put(file.getName(), file.getContent()); } } return entity; }
Source:
<code>private void validateTestEnv(TestEnvironmentEntity testEnv) { String envId = testEnv.getEnvironmentId(); Pattern envIdPattern = Pattern.compile(ENV_ID_PATTERN); Matcher matcher = envIdPattern.matcher(envId); if (!matcher.matches()) throw new TestEnvironmentInvalidIdException(envId, envIdPattern); <START> <END> if (testEnv.getRunningTestSuite() != null && testEnv.getStatus() == RUNNING || testEnv.getRunningTestSuite() == null && testEnv.getStatus() == PENDING) throw new WrongTestEnvironmentStatusException(testEnv.getStatus(), testEnv.getRunningTestSuite()); }</code><technical_language>is logics correct here</technical_language>

Target:
private void validateTestEnv(TestEnvironmentEntity testEnv) { String envId = testEnv.getEnvironmentId(); Pattern envIdPattern = Pattern.compile(ENV_ID_PATTERN); Matcher matcher = envIdPattern.matcher(envId); if (!matcher.matches()) throw new TestEnvironmentInvalidIdException(envId, envIdPattern); if (testEnv.getRunningTestSuite() == null && testEnv.getStatus() == RUNNING || testEnv.getRunningTestSuite() != null && testEnv.getStatus() == PENDING) throw new WrongTestEnvironmentStatusException(testEnv.getStatus(), testEnv.getRunningTestSuite()); }
Source:
<code>public void handleAction(ActionParameters params) throws ActionException { if(params.getUser().isGuest()) { throw new ActionDeniedException("Session expired"); } final long id = ConversionHelper.getLong(params.getHttpParam(PARAM_ID), -1); if(id == -1) { throw new ActionParamsException("Parameter missing or non-numeric: " + PARAM_ID + "=" + params.getHttpParam(PARAM_ID)); } final UserLayerStyle style = userLayerDbService.getUserLayerStyleById(id); <START> if (style != null){ <END> JSONObject response = style.parseUserLayerStyle2JSON(); ResponseHelper.writeResponse(params, response); }else{ throw new ActionException("Unable to get style for id" + id); } }</code><technical_language>is check style belongs current user. check it? If not, I if logged-in requirement is necessary</technical_language>

Target:
public void handleAction(ActionParameters params) throws ActionException { params.requireLoggedInUser(); final long id = params.getRequiredParamLong(PARAM_ID); final UserLayer userLayer = userLayerDbService.getUserLayerById(id); if(userLayer == null) { throw new ActionParamsException("Userlayer's style id didn't match any userlayer: " + id); } if(!userLayer.isOwnedBy(params.getUser().getUuid())) { throw new ActionDeniedException("Userlayer's style belongs to another user"); } final UserLayerStyle style = userLayerDbService.getUserLayerStyleById(id); if (style != null){ JSONObject response = style.parseUserLayerStyle2JSON(); ResponseHelper.writeResponse(params, response); }else{ throw new ActionParamsException("Unable to get style for id" + id); } }
Source:
<code>public void run(final int iteration) { final long epochStartTime = System.currentTimeMillis(); WorkerMetrics workerMetrics; for (int miniBatchIdx = 0; miniBatchIdx < numMiniBatches; miniBatchIdx++) { resetTracers(); final long miniBatchStartTime = System.currentTimeMillis(); pullTracer.startTimer(); final List<Vector> valueList = parameterWorker.pull(keyList); pullTracer.recordTime(valueList.size()); LOG.log(Level.FINE, "Current values associated with keys {0} is {1}", new Object[]{keyList, valueList}); try { computeTracer.startTimer(); Thread.sleep(computeTime); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while sleeping to simulate computation", e); } finally { computeTracer.recordTime(NUM_DATA_ITEMS_TO_PROCESS); } pushTracer.startTimer(); for (final int key : keyList) { parameterWorker.push(key, delta); } pushTracer.recordTime(keyList.size()); final double miniBatchElapsedTime = (System.currentTimeMillis() - miniBatchStartTime) / 1000.0D; workerMetrics = <START> buildMiniBatchMetric(iteration, miniBatchIdx, miniBatchElapsedTime); <END> LOG.log(Level.INFO, "WorkerMetrics {0}", workerMetrics); sendMetrics(workerMetrics); } final double epochElapsedTime = (System.currentTimeMillis() - epochStartTime) / 1000.0D; workerMetrics = buildEpochMetric(iteration, memoryStore.getNumBlocks(), epochElapsedTime); LOG.log(Level.INFO, "WorkerMetrics {0}", workerMetrics); sendMetrics(workerMetrics); }</code><technical_language>nit: line</technical_language>

Target:
public void run(final int iteration) { final long epochStartTime = System.currentTimeMillis(); for (int miniBatchIdx = 0; miniBatchIdx < numMiniBatches; miniBatchIdx++) { resetTracers(); final long miniBatchStartTime = System.currentTimeMillis(); pullTracer.startTimer(); final List<Vector> valueList = parameterWorker.pull(keyList); pullTracer.recordTime(valueList.size()); LOG.log(Level.FINE, "Current values associated with keys {0} is {1}", new Object[]{keyList, valueList}); try { computeTracer.startTimer(); Thread.sleep(computeTime); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while sleeping to simulate computation", e); } finally { computeTracer.recordTime(NUM_DATA_ITEMS_TO_PROCESS); } pushTracer.startTimer(); for (final int key : keyList) { parameterWorker.push(key, delta); } pushTracer.recordTime(keyList.size()); final double miniBatchElapsedTime = (System.currentTimeMillis() - miniBatchStartTime) / 1000.0D; final WorkerMetrics miniBatchMetric = buildMiniBatchMetric(iteration, miniBatchIdx, miniBatchElapsedTime); LOG.log(Level.INFO, "WorkerMetrics {0}", miniBatchMetric); sendMetrics(miniBatchMetric); } final double epochElapsedTime = (System.currentTimeMillis() - epochStartTime) / 1000.0D; final WorkerMetrics epochMetric = buildEpochMetric(iteration, memoryStore.getNumBlocks(), epochElapsedTime); LOG.log(Level.INFO, "WorkerMetrics {0}", epochMetric); sendMetrics(epochMetric); }
Source:
<code>private void updated(Map<String, Object> properties) { StringBuilder sb = new StringBuilder(); for (Entry<String, Object> entry : properties.entrySet()) { sb.append("[").append(entry.getKey()).append("=").append(entry.getValue()).append("], "); } <START> System.out.println("Properties after update: " + sb.toString()); <END> }</code><technical_language>logger here</technical_language>

Target:
private void updated(Map<String, Object> properties) { if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (Entry<String, Object> entry : properties.entrySet()) { sb.append("[").append(entry.getKey()).append("=").append(entry.getValue()).append("], "); } logger.debug("Properties after update: " + sb.toString()); } }
Source:
<code>public Builder setMutateRpcTimeoutMs(int mutateRpcTimeoutMs) { Preconditions.checkArgument( <START> mutateRpcTimeoutMs > 0, "Long Timeout ms has to be greater than 0"); <END> this.mutateRpcTimeoutMs = mutateRpcTimeoutMs; return this; }</code><technical_language>mutateRpcTimeoutMs int a long</technical_language>

Target:
public Builder setMutateRpcTimeoutMs(int mutateRpcTimeoutMs) { Preconditions.checkArgument( mutateRpcTimeoutMs > 0, "Mutate Rows RPC Timeout ms has to be greater than 0"); this.mutateRpcTimeoutMs = mutateRpcTimeoutMs; return this; }
Source:
<code>public <START> Model checkSyntax(InputStream <END> dataset, String baseURI, RDFFormat format) { Model parsed = null; try { parsed = Rio.parse(dataset, baseURI, format); } catch (IOException ioe) { log.error("Couldn't read your dataset: {}", ioe.getMessage()); System.exit(1); } catch (RDFParseException rpe) { log.error("Your dataset is not valid RDF. Please fix it: {}", rpe.getMessage()); System.exit(1); return null; } return parsed; }</code><technical_language>If is meant check syntax, do need return model? return true/false</technical_language>

Target:
public Model checkSyntax(InputStream dataset, String baseURI, RDFFormat format) throws IOException, RDFParseException { return Rio.parse(dataset, baseURI, format); }
Source:
<code>public void setControllerMethod(ControllerMethod controllerMethod) { <START> createValuedParameter(controllerMethod); <END> this.controllerMethod = controllerMethod; }</code><technical_language>I this method called getValuedParameters if use, create valued parameters VRaptor sets ControllerMethod (and create this, parameterNameProvider, etc... is kind of expensive). a simple lazy strategy: Java if (valuedParameters != null) createValuedParameter(controllerMethod);</technical_language>

Target:
public void setControllerMethod(ControllerMethod controllerMethod) { this.controllerMethod = controllerMethod; }
Source:
<code>protected void doHandleUploadRequest(final Request request) { if (isDisabled() || isReadOnly()) { throw new SystemException("File widget cannot be updated."); } if (!"POST".equals(request.getMethod())) { throw new SystemException( "File widget cannot be updated by " + request.getMethod() + "."); } FileItem[] items = request.getFileItems(getId()); if (items.length > 1) { throw new SystemException("More than one file item received on the request."); } String fileId = request.getParameter(FILE_UPLOAD_MULTI_PART_ID_KEY); if (fileId == null) { throw new SystemException("No file id provided for file upload."); } FileItemWrap wrap = new FileItemWrap(items[0]); <START> if (isSetFileTypes()) { <END> if (!FileValidationUtil.validateFileType(wrap, getFileTypes())) { String invalidMessage = String.format(I18nUtilities.format(null, InternalMessages.DEFAULT_VALIDATION_ERROR_FILE_WRONG_TYPE), StringUtils.join(getFileTypes().toArray(new Object[getFileTypes().size()]))); throw new SystemException(invalidMessage); } } if (isSetFileSize()) { if (!FileValidationUtil.validateFileSize(wrap, getMaxFileSize())) { String invalidMessage = String.format(I18nUtilities.format(null, InternalMessages.DEFAULT_VALIDATION_ERROR_FILE_WRONG_SIZE), Util.readableFileSize(wrap.getSize()), Util.readableFileSize(getMaxFileSize())); throw new SystemException(invalidMessage); } } FileWidgetUpload file = new FileWidgetUpload(fileId, wrap); addFile(file); setFileUploadRequestId(fileId); setNewUpload(true); }</code><technical_language>combine if statements (I pinged static analysis this before)</technical_language>

Target:
protected void doHandleUploadRequest(final Request request) { if (isDisabled() || isReadOnly()) { throw new SystemException("File widget cannot be updated."); } if (!"POST".equals(request.getMethod())) { throw new SystemException( "File widget cannot be updated by " + request.getMethod() + "."); } FileItem[] items = request.getFileItems(getId()); if (items.length > 1) { throw new SystemException("More than one file item received on the request."); } String fileId = request.getParameter(FILE_UPLOAD_MULTI_PART_ID_KEY); if (fileId == null) { throw new SystemException("No file id provided for file upload."); } FileItemWrap wrap = new FileItemWrap(items[0]); if (hasFileTypes() && !FileUtil.validateFileType(wrap, getFileTypes())) { String invalidMessage = FileUtil.getInvalidFileTypeMessage(getFileTypes()); throw new SystemException(invalidMessage); } if (hasMaxFileSize() && !FileUtil.validateFileSize(wrap, getMaxFileSize())) { String invalidMessage = FileUtil.getInvalidFileSizeMessage(getMaxFileSize()); throw new SystemException(invalidMessage); } FileWidgetUpload file = new FileWidgetUpload(fileId, wrap); addFile(file); setFileUploadRequestId(fileId); setNewUpload(true); }
Source:
<code>public void testApplicationConfiguredInConfigDropins() throws Exception { File in = new File(CONFIG_DROPINS_XML); FileInputStream input = new FileInputStream(in); DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc=inputBuilder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/server/webApplication"; NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); Assert.assertEquals("Number of <webApplication/> element ==>", 1, nodes.getLength()); Node node = nodes.item(0); Element element = (Element)node; <START> Assert.assertEquals("Value of the 1st <webApplication/> ==>", <END> "test-war.war", element.getAttribute("location")); }</code><technical_language>If import static org.junit.Assert.*; reference static methods Assert class class in field is defined. I for cleaner test code</technical_language>

Target:
public void testApplicationConfiguredInConfigDropins() throws Exception { File in = new File(CONFIG_DROPINS_XML); FileInputStream input = new FileInputStream(in); DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc=inputBuilder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/server/webApplication"; NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET); assertEquals("Number of <webApplication/> element ==>", 1, nodes.getLength()); Node node = nodes.item(0); Element element = (Element)node; assertEquals("Value of the 1st <webApplication/> ==>", "test-war.war", element.getAttribute("location")); }
Source:
<code>public void testListContainersByName() throws IOException { respondWith(CONTAINERS_JSON); List<? extends Container> list = osv3().barbican().containers().list("test-container"); <START> assertEquals(list.size(), 1); <END> }</code><technical_language>assert container right name</technical_language>

Target:
public void testListContainersByName() throws IOException { respondWith(CONTAINERS_JSON); List<? extends Container> list = osv3().barbican().containers().list("test-container"); assertEquals(list.size(), 1); assertEquals(list.get(0).getName(), containerName); }
Source:
<code>protected void activate(ComponentContext ctxt) { try { BundleContext bundleCtx = ctxt.getBundleContext(); TenantManagementListener idPMgtTenantMgtListener = new TenantManagementListener(); ServiceRegistration tenantMgtListenerSR = bundleCtx.registerService( TenantMgtListener.class.getName(), idPMgtTenantMgtListener, null); if (tenantMgtListenerSR != null) { log.debug("Identity Provider Management - TenantMgtListener registered"); } else { log.error("Identity Provider Management - TenantMgtListener could not be registered"); } ServiceRegistration userOperationListenerSR = bundleCtx.registerService( UserOperationEventListener.class.getName(), new UserStoreListener(), null); if (userOperationListenerSR != null) { log.debug("Identity Provider Management - UserOperationEventListener registered"); } else { log.error("Identity Provider Management - UserOperationEventListener could not be registered"); } ServiceRegistration auditLoggerSR = bundleCtx.registerService(IdentityProviderMgtListener.class.getName() , new IDPMgtAuditLogger(), null); if(auditLoggerSR != null) { <START> log.debug("Identity Provider Management - Audit Logger registered"); <END> } else { log.error("Identity Provider Management - Error while registering Audit Logger"); } setIdentityProviderMgtListenerService(new IdPMgtValidationListener()); buildFileBasedIdPList(); cleanUpRemovedIdps(); log.debug("Identity Provider Management bundle is activated"); } catch (Throwable e) { log.error("Error while activating Identity Provider Management bundle", e); } }</code><technical_language>check isDebugEnabled()</technical_language>

Target:
protected void activate(ComponentContext ctxt) { try { BundleContext bundleCtx = ctxt.getBundleContext(); TenantManagementListener idPMgtTenantMgtListener = new TenantManagementListener(); ServiceRegistration tenantMgtListenerSR = bundleCtx.registerService( TenantMgtListener.class.getName(), idPMgtTenantMgtListener, null); if (tenantMgtListenerSR != null) { log.debug("Identity Provider Management - TenantMgtListener registered"); } else { log.error("Identity Provider Management - TenantMgtListener could not be registered"); } ServiceRegistration userOperationListenerSR = bundleCtx.registerService( UserOperationEventListener.class.getName(), new UserStoreListener(), null); if (userOperationListenerSR != null) { log.debug("Identity Provider Management - UserOperationEventListener registered"); } else { log.error("Identity Provider Management - UserOperationEventListener could not be registered"); } setIdentityProviderMgtListenerService(new IdPMgtValidationListener()); buildFileBasedIdPList(); cleanUpRemovedIdps(); log.debug("Identity Provider Management bundle is activated"); } catch (Throwable e) { log.error("Error while activating Identity Provider Management bundle", e); } }
Source:
<code>protected void ensureValuesCapacity(int capacity, boolean includeNulls) { <START> if (values == null) { <END> values = new int[capacity]; } else if (values == null || values.length < capacity) { values = resize(values, capacity); if (valueIsNull != null) { valueIsNull = resize(valueIsNull, capacity); } } if (includeNulls && valueIsNull == null) { valueIsNull = new boolean[values.length]; } }</code><technical_language>this check removed</technical_language>

Target:
protected void ensureValuesCapacity(int capacity, boolean includeNulls) { if (values == null || values.length < capacity) { values = resize(values, capacity); if (valueIsNull != null) { valueIsNull = resize(valueIsNull, capacity); } } if (includeNulls && valueIsNull == null) { valueIsNull = new boolean[values.length]; } }
Source:
<code>public static SSLContext createSslContext(Map<String, PemX509Certificate> trustCertificatesByAlias) { TrustManager[] trustManagers = createTrustManagers(trustCertificatesByAlias); try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[]{}, trustManagers, null); return sslContext; } catch (GeneralSecurityException e) { throw Throwables.propagate(e); <START> } <END> }</code><technical_language>guessing this block of code repeated: private static SSLContext createSslContextFromTrustManagers(TrustManager[] trustManagers)</technical_language>

Target:
public static SSLContext createSslContext(Map<String, PemX509Certificate> trustCertificatesByAlias) { TrustManager[] trustManagers = createTrustManagers(trustCertificatesByAlias); return createSslContext(trustManagers, new KeyManager[]{}); }
Source:
<code>public PollingLookup( long pollPeriodMs, DataFetcher dataFetcher, PollingCacheFactory cacheFactory ) { this.pollPeriodMs = pollPeriodMs; this.dataFetcher = Preconditions.checkNotNull(dataFetcher); this.cacheFactory = cacheFactory == null ? new OnHeapPollingCache.OnHeapPollingCacheProvider() : cacheFactory; refOfCacheKeeper.set(new CacheRefKeeper(this.cacheFactory.makeOf(dataFetcher.fetchAll()))); if (pollPeriodMs > 0) { scheduledExecutorService = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor( Execs.makeThreadFactory("PollingLookup-" + id, Thread.MIN_PRIORITY) )); <START> pollFuture = scheduledExecutorService.scheduleAtFixedRate( <END> pollAndSwap(), pollPeriodMs, pollPeriodMs, TimeUnit.MILLISECONDS ); } else { scheduledExecutorService = null; pollFuture = null; } this.isOpen.set(true); }</code><technical_language>suggest fixed delay fixed rate</technical_language>

Target:
public PollingLookup( long pollPeriodMs, DataFetcher dataFetcher, PollingCacheFactory cacheFactory ) { this.pollPeriodMs = pollPeriodMs; this.dataFetcher = Preconditions.checkNotNull(dataFetcher); this.cacheFactory = cacheFactory == null ? new OnHeapPollingCache.OnHeapPollingCacheProvider() : cacheFactory; refOfCacheKeeper.set(new CacheRefKeeper(this.cacheFactory.makeOf(dataFetcher.fetchAll()))); if (pollPeriodMs > 0) { scheduledExecutorService = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor( Execs.makeThreadFactory("PollingLookup-" + id, Thread.MIN_PRIORITY) )); pollFuture = scheduledExecutorService.scheduleWithFixedDelay( pollAndSwap(), pollPeriodMs, pollPeriodMs, TimeUnit.MILLISECONDS ); } else { scheduledExecutorService = null; pollFuture = null; } this.isOpen.set(true); }
Source:
<code>private void configureRatingControls() { if (!replay.getValidity().equals(Validity.VALID)) { showRatingChangeButton.setVisible(false); notRatedReasonLabel.setVisible(true); <START> notRatedReasonLabel.setText(i18n.get("game.reasonNotValid", replay.getValidity())); <END> } else if (!replayService.replayChangedRating(replay)) { showRatingChangeButton.setVisible(false); notRatedReasonLabel.setVisible(true); notRatedReasonLabel.setText(i18n.get("game.notRatedYet")); } else { showRatingChangeButton.setVisible(true); showRatingChangeButton.setDisable(false); notRatedReasonLabel.setVisible(false); } }</code><technical_language>This translate validity reasons, a proper i18n solution</technical_language>

Target:
private void configureRatingControls() { if (!replay.getValidity().equals(Validity.VALID)) { showRatingChangeButton.setVisible(false); notRatedReasonLabel.setVisible(true); String reasonText; try { reasonText = i18n.get("game.reasonNotValid", i18n.get(replay.getValidity().getI18nKey())); } catch (NoSuchMessageException e) { reasonText = replay.getValidity().toString(); } notRatedReasonLabel.setText(reasonText); } else if (!replayService.replayChangedRating(replay)) { showRatingChangeButton.setVisible(false); notRatedReasonLabel.setVisible(true); notRatedReasonLabel.setText(i18n.get("game.notRatedYet")); } else { showRatingChangeButton.setVisible(true); showRatingChangeButton.setDisable(false); notRatedReasonLabel.setVisible(false); } }
Source:
<code>public List<ControlPoint> addControlPoints(final ControlPoint... controlPoint) { if (validateControlPointShape()) { return Stream.of(controlPoint) .map(cp -> { double x = cp.getLocation().getX(); double y = cp.getLocation().getY(); addControlPoint(x, y, cp.getIndex() + 1); return cp; }).collect(Collectors.toList()); } <START> refrehControlPoints(); <END> return Collections.emptyList(); }</code><technical_language>is this call necessary? is called validateControlPointShape() is **false**</technical_language>

Target:
public List<ControlPoint> addControlPoints(final ControlPoint... controlPoint) { if (validateControlPointShape()) { final List<ControlPoint> result = Stream.of(controlPoint) .map(cp -> { double x = cp.getLocation().getX(); double y = cp.getLocation().getY(); addControlPoint(x, y, cp.getIndex() + 1); return cp; }).collect(Collectors.toList()); refrehControlPoints(); return result; } return Collections.emptyList(); }
Source:
<code>public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain, String username) throws IdentityApplicationManagementException { try { startTenantFlow(tenantDomain, username); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); ApplicationBasicInfo[] applicationBasicInfos = appDAO.getAllApplicationBasicInfo(); ArrayList<ApplicationBasicInfo> appInfo = new ArrayList<>(); for (ApplicationBasicInfo applicationBasicInfo: applicationBasicInfos) { if (ApplicationMgtUtil.isUserAuthorized(applicationBasicInfo.getApplicationName(), username)) { appInfo.add(applicationBasicInfo); if (log.isDebugEnabled()) { log.debug("Application Name:" + applicationBasicInfo.getApplicationName()); } } } <START> return appInfo.toArray(new ApplicationBasicInfo[appInfo.size()]); <END> } catch (Exception e) { String error = "Error occurred while retrieving all the applications"; throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } }</code><technical_language>move this Admin service level, OSGi service level</technical_language>

Target:
public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain, String username) throws IdentityApplicationManagementException { try { startTenantFlow(tenantDomain, username); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); return appDAO.getAllApplicationBasicInfo(); } catch (Exception e) { String error = "Error occurred while retrieving all the applications"; throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } }
Source:
<code>Object getValue(Object obj, String attributePath, Object metadata) throws Exception { if (metadata == null) { return getValue(obj, attributePath); } JsonSchemaNode schemaNode = (JsonSchemaNode) metadata; NavigableJsonInputAdapter adapter = annotate(obj); JsonGetterContext queryContext = contextCache.getContext(attributePath); List<WeightedItem<JsonPattern>> patternsSnapshot = queryContext.getPatternListSnapshot(); JsonPathCursor pathCursor = queryContext.newJsonPathCursor(); JsonPattern knownPattern = null; <START> for (int i = 0; i < patternTryCount && i < patternsSnapshot.size(); i++) { <END> WeightedItem<JsonPattern> patternWeightedItem = patternsSnapshot.get(i); knownPattern = patternWeightedItem.getItem(); JsonValue value = JsonSchemaHelper.findValueWithPattern(adapter, schemaNode, knownPattern, pathCursor); pathCursor.reset(); if (value != null) { queryContext.voteFor(patternWeightedItem); return convertFromJsonValue(value); } } knownPattern = JsonSchemaHelper.createPattern(adapter, schemaNode, pathCursor); pathCursor.reset(); if (knownPattern != null) { if (knownPattern.hasAny()) { return getValue(obj, attributePath); } WeightedItem<JsonPattern> weightedItem = queryContext.addPattern(knownPattern); queryContext.voteFor(weightedItem); return convertFromJsonValue(JsonSchemaHelper.findValueWithPattern(adapter, schemaNode, knownPattern, pathCursor)); } return null; }</code><technical_language>If iterate patternTryCount, queryContext.getPatternListSnapshot() need greater patternTryCount</technical_language>

Target:
Object getValue(Object obj, String attributePath, Object metadata) throws Exception { if (metadata == null) { return getValue(obj, attributePath); } JsonSchemaNode schemaNode = (JsonSchemaNode) metadata; NavigableJsonInputAdapter adapter = annotate(obj); JsonGetterContext queryContext = contextCache.getContext(attributePath); List<WeightedItem<JsonPattern>> patternsSnapshot = queryContext.getPatternListSnapshot(); JsonPathCursor pathCursor = queryContext.newJsonPathCursor(); JsonPattern knownPattern = null; for (int i = 0; i < PATTERN_TRY_COUNT && i < patternsSnapshot.size(); i++) { WeightedItem<JsonPattern> patternWeightedItem = patternsSnapshot.get(i); knownPattern = patternWeightedItem.getItem(); JsonValue value = JsonSchemaHelper.findValueWithPattern(adapter, schemaNode, knownPattern, pathCursor); pathCursor.reset(); if (value != null) { queryContext.voteFor(patternWeightedItem); return convertFromJsonValue(value); } } knownPattern = JsonSchemaHelper.createPattern(adapter, schemaNode, pathCursor); pathCursor.reset(); if (knownPattern != null) { if (knownPattern.hasAny()) { return getValue(obj, attributePath); } queryContext.addOrVoteForPattern(knownPattern); return convertFromJsonValue(JsonSchemaHelper.findValueWithPattern(adapter, schemaNode, knownPattern, pathCursor)); } return null; }
Source:
<code>public void initializeUI(UIBuilder builder) throws Exception { super.initializeUI(builder); idStrategy.setDefaultValue(GenerationType.AUTO); idType.setDefaultValue(EntityIdType.LONG_PROPERTY); <START> idClass.setRequired(new Callable<Boolean>(){ <END> @Override public Boolean call(){ return idType.getValue() == EntityIdType.EMBEDDED_ID; } }); builder.add(idStrategy).add(tableName) .add(idType).add(idClass); }</code><technical_language>a lambda here:idClass.setRequired(() -> idType.getValue() == EntityIdType.EMBEDDED_ID);</technical_language>

Target:
public void initializeUI(UIBuilder builder) throws Exception { super.initializeUI(builder); idStrategy.setDefaultValue(GenerationType.AUTO); idType.setDefaultValue(EntityIdType.LONG_PROPERTY); idClass.setRequired(() -> idType.getValue().isClassRequired()); idClass.setValueConverter(new PackageRootConverter(getProjectFactory(), builder)); builder.add(idStrategy).add(tableName) .add(idType).add(idClass); }
Source:
<code>protected Guid getStoragePoolId() { <START> return getDbFacade().getStoragePoolDao().getAllForStorageDomain(getStorageDomainId()).get(0).getId(); <END> }</code><technical_language>throw IndexOutOfBound if storage domain is attached storage pool</technical_language>

Target:
protected Guid getStoragePoolId() { return getParameters().getStoragePoolId(); }
Source:
<code>public static void restartJobServiceInterval(Context context, long intervalMillis) { JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); <START> if (jobScheduler != null) { <END> JobInfo oldJob = jobScheduler.getPendingJob(JOB_ID_FEED_UPDATE); if (oldJob == null || oldJob.getIntervalMillis() != intervalMillis) { JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setPeriodic(intervalMillis); jobScheduler.cancel(JOB_ID_FEED_UPDATE); if (intervalMillis <= 0) { Log.d(TAG, "Automatic update was deactivated"); return; } jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set at interval " + intervalMillis); } else { Log.d(TAG, "JobScheduler was already set at interval " + intervalMillis + ", ignoring."); } } }</code><technical_language>invert</technical_language>

Target:
private static void restartJobServiceInterval(Context context, long intervalMillis) { JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); if (jobScheduler == null) { Log.d(TAG, "JobScheduler was null."); return; } JobInfo oldJob = jobScheduler.getPendingJob(JOB_ID_FEED_UPDATE); if (oldJob != null && oldJob.getIntervalMillis() == intervalMillis) { Log.d(TAG, "JobScheduler was already set at interval " + intervalMillis + ", ignoring."); return; } JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setPeriodic(intervalMillis); jobScheduler.cancel(JOB_ID_FEED_UPDATE); if (intervalMillis <= 0) { Log.d(TAG, "Automatic update was deactivated"); return; } jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set at interval " + intervalMillis); }
Source:
<code>private boolean isNestedSingleResourceBinaryModule() { <START> if( module.length > 1 && all.length == 1 && all[0] instanceof IModuleFile) { <END> return true; } return false; }</code><technical_language>do write return module.length > 1 && all.length == 1 && all[0] instanceof IModuleFile;</technical_language>

Target:
private boolean isNestedSingleResourceBinaryModule() { return module.length > 1 && all.length == 1 && all[0] instanceof IModuleFile; }
Source:
<code>public static boolean getOptionAsBoolean(Map<String, String> options, String option, boolean defaultValue) { String value = options.get(option); <START> return value == null ? defaultValue : Boolean.valueOf(value); <END> }</code><technical_language>Boolean.parseBoolean</technical_language>

Target:
public static boolean getOptionAsBoolean(Map<String, String> options, String option, boolean defaultValue) { String value = options.get(option); return value == null ? defaultValue : Boolean.parseBoolean(value); }
Source:
<code>public void testValidIsNotHonoredValidateValue() { Validator validator = TestUtil.getValidatorUnderTest(); Customer customer = new Customer(); Order order = new Order(); <START> customer.addOrder( order ); <END> Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue( Customer.class, "orders", Collections.singleton(order) ); assertNumberOfViolations( constraintViolations, 0 ); }</code><technical_language>this is testing validateValue(), customer instance removed altogether</technical_language>

Target:
public void testValidIsNotHonoredValidateValue() { Validator validator = TestUtil.getValidatorUnderTest(); Order order = new Order(); Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue( Customer.class, "orders", Collections.singleton(order) ); assertNumberOfViolations( constraintViolations, 0 ); }
Source:
<code>public int hashCode() { final int prime = 31; <START> int result = 1; <END> final Packet child = fChildPacket; result = child != null ? prime * result + child.hashCode() : prime * result; result = prime * result + fPayload.hashCode(); return result; }</code><technical_language>super efficient initializing result prime avoid else clause in if</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = prime; final Packet child = fChildPacket; if (child != null) { result += child.hashCode(); } result = prime * result + fPayload.hashCode(); return result; }
Source:
<code>public void testCountry() { <START> assertEquals( <END> "country.getCountry().isInEuropeanUnion() does not return false", false, this.country.getCountry().isInEuropeanUnion()); assertEquals("country.getCountry().getCode() does not return US", "US", this.country.getCountry().getIsoCode()); assertEquals("country.getCountry().getGeoNameId() does not return 1", 1, (int) this.country.getCountry().getGeoNameId()); assertEquals("country.getCountry().getConfidence() does not return 56", new Integer(56), this.country.getCountry().getConfidence()); assertEquals( "country.getCountry().getName(\"en\") does not return United States", "United States", this.country.getCountry().getName()); }</code><technical_language>assertFalse for this below</technical_language>

Target:
public void testCountry() { assertFalse( "country.getCountry().isInEuropeanUnion() does not return false", this.country.getCountry().isInEuropeanUnion()); assertEquals("country.getCountry().getCode() does not return US", "US", this.country.getCountry().getIsoCode()); assertEquals("country.getCountry().getGeoNameId() does not return 1", 1, (int) this.country.getCountry().getGeoNameId()); assertEquals("country.getCountry().getConfidence() does not return 56", new Integer(56), this.country.getCountry().getConfidence()); assertEquals( "country.getCountry().getName(\"en\") does not return United States", "United States", this.country.getCountry().getName()); }
Source:
<code>public void setCurrentFont(String fontName) { currentFont = fonts.get(fontName); if (currentFont != null) Timber.i("Font Selected: %s", fontName); else <START> Timber.e("Couldn't select font: %s", fontName); <END> }</code><technical_language>set this warning level instead of error (Timber.w) - avoid non-fatal stuff in error logs</technical_language>

Target:
public void setCurrentFont(String fontName) { currentFont = fonts.get(fontName); if (currentFont != null) Timber.i("Font Selected: %s", fontName); else Timber.w("Couldn't select font: %s", fontName); }
Source:
<code>protected void setVmQuotaPercentage(VirtualMachineTO to, VirtualMachineProfile vmProfile) { if (to.getLimitCpuUse()) { VirtualMachine vm = vmProfile.getVirtualMachine(); HostVO host = _hostDao.findById(vm.getHostId()); if (host == null) { <START> throw new CloudRuntimeException("Host with id: " + vm.getHostId() + " not found"); <END> } s_logger.debug("Limiting CPU usage for VM " + vm.getId() + " on host " + host.getId()); double hostMaxSpeed = getHostCPUSpeed(host); double maxSpeed = getVmSpeed(to); try { BigDecimal percent = new BigDecimal(maxSpeed / hostMaxSpeed); percent = percent.setScale(2, RoundingMode.HALF_DOWN); to.setCpuQuotaPercentage(percent.doubleValue()); s_logger.debug("Host " + host.getId() + " max CPU speed = " + hostMaxSpeed + "MHz, VM " + vm.getId() + "max CPU speed = " + maxSpeed + "MHz. Setting CPU quota percentage as: " + percent.doubleValue()); } catch (NumberFormatException e) { s_logger.error("Error calculating vm quota percentage, it wll not be set: " + e.getMessage()); } } }</code><technical_language>instead of ID, UUID here? operator is UUID ID, internal db ID</technical_language>

Target:
protected void setVmQuotaPercentage(VirtualMachineTO to, VirtualMachineProfile vmProfile) { if (to.getLimitCpuUse()) { VirtualMachine vm = vmProfile.getVirtualMachine(); HostVO host = _hostDao.findById(vm.getHostId()); if (host == null) { throw new CloudRuntimeException("Host with id: " + vm.getHostId() + " not found"); } s_logger.debug("Limiting CPU usage for VM: " + vm.getUuid() + " on host: " + host.getUuid()); double hostMaxSpeed = getHostCPUSpeed(host); double maxSpeed = getVmSpeed(to); try { BigDecimal percent = new BigDecimal(maxSpeed / hostMaxSpeed); percent = percent.setScale(2, RoundingMode.HALF_DOWN); if (percent.compareTo(new BigDecimal(1)) == 1) { s_logger.debug("VM " + vm.getUuid() + " CPU MHz exceeded host " + host.getUuid() + " CPU MHz, limiting VM CPU to the host maximum"); percent = new BigDecimal(1); } to.setCpuQuotaPercentage(percent.doubleValue()); s_logger.debug("Host: " + host.getUuid() + " max CPU speed = " + hostMaxSpeed + "MHz, VM: " + vm.getUuid() + "max CPU speed = " + maxSpeed + "MHz. Setting CPU quota percentage as: " + percent.doubleValue()); } catch (NumberFormatException e) { s_logger.error("Error calculating VM: " + vm.getUuid() + " quota percentage, it wll not be set. Error: " + e.getMessage(), e); } } }
Source:
<code><START> public void testSortNodes_Stage() throws Exception { <END> final Diagram<Graph<DefinitionSet, Node>, Metadata> diagram = mock(Diagram.class); final Graph<DefinitionSet, Node> graph = mock(Graph.class); when(diagram.getGraph()).thenReturn(graph); final List<Node> nodes = new LinkedList<>(); when(graph.nodes()).thenReturn(nodes); final Node root = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage1 = createNode(AdHocSubprocess.class); final Node stage2 = createNode(AdHocSubprocess.class); nodes.add(root); nodes.add(start); nodes.add(end); nodes.add(stage1); nodes.add(stage2); createChildEdge(root, end); createChildEdge(root, start); createChildEdge(root, stage2); createChildEdge(root, stage1); createSequenceFlow(start, stage1); createSequenceFlow(stage1, stage2); createSequenceFlow(stage2, end); tested.sortNodes(diagram); final List<Edge> rEdges = root.getOutEdges(); assertEquals(4, rEdges.size()); assertEquals(start, rEdges.get(0).getTargetNode()); assertEquals(stage1, rEdges.get(1).getTargetNode()); assertEquals(stage2, rEdges.get(2).getTargetNode()); assertEquals(end, rEdges.get(3).getTargetNode()); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testSortNodes_Stage() { final Diagram<Graph<DefinitionSet, Node>, Metadata> diagram = mock(Diagram.class); final Graph<DefinitionSet, Node> graph = mock(Graph.class); when(diagram.getGraph()).thenReturn(graph); final List<Node> nodes = new LinkedList<>(); when(graph.nodes()).thenReturn(nodes); final Node root = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage1 = createNode(AdHocSubprocess.class); final Node stage2 = createNode(AdHocSubprocess.class); nodes.add(root); nodes.add(start); nodes.add(end); nodes.add(stage1); nodes.add(stage2); createChildEdge(root, end); createChildEdge(root, start); createChildEdge(root, stage2); createChildEdge(root, stage1); createSequenceFlow(start, stage1); createSequenceFlow(stage1, stage2); createSequenceFlow(stage2, end); tested.sortNodes(diagram); final List<Edge> rEdges = root.getOutEdges(); assertEquals(4, rEdges.size()); assertEquals(start, rEdges.get(0).getTargetNode()); assertEquals(stage1, rEdges.get(1).getTargetNode()); assertEquals(stage2, rEdges.get(2).getTargetNode()); assertEquals(end, rEdges.get(3).getTargetNode()); }
Source:
<code>public static Object[][] adsVelesErrorTracking() { <START> final String TURN_ON_VELES = "?InstantGlobals.wgAdDriverVelesBidderCountries=[XX]"; <END> return new Object[][]{ { new Page(WIKI_SPECIAL, "SyntheticTests/RTB/Prebid.js/Veles/Both/Leaderboard" + TURN_ON_VELES), ImmutableMap.builder() .put(AdsContent.TOP_LB, "") .put(AdsContent.INCONTENT_PLAYER, "") .build(), ImmutableMap.builder() .put(".*output=vast.*", new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_TIMEOUT)) .build() }, { new Page(WIKI_SPECIAL, "Project43_Wikia" + TURN_ON_VELES), ImmutableMap.builder() .put(AdsContent.TOP_LB, "0.00") .build(), ImmutableMap.builder() .build() } }; }</code><technical_language>![image](<LINK_0></technical_language>

Target:
public static Object[][] adsVelesErrorTracking() { return new Object[][]{ { new Page(WIKI_SPECIAL, "SyntheticTests/RTB/Prebid.js/Veles/Both/Leaderboard?" + AdsVeles.TURN_ON_QUERY_PARAM), ImmutableMap.builder() .put(AdsContent.TOP_LB, "") .put(AdsContent.INCONTENT_PLAYER, "") .build(), ImmutableMap.builder() .put(".*output=vast.*", new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_TIMEOUT)) .build() }, { new Page(WIKI_SPECIAL, "Project43_Wikia?" + AdsVeles.TURN_ON_QUERY_PARAM), ImmutableMap.builder() .put(AdsContent.TOP_LB, "0.00") .build(), ImmutableMap.builder() .build() } }; }
Source:
<code>public void blockingRejectedExecution() throws Exception { Scheduler blockingSchedulerSpy = spy(blocking); RejectingScheduler rejectingSchedulerSpy = new RejectingScheduler(blockingSchedulerSpy); flow = flowBuilder.get().processors(blockingProcessor) .processingStrategyFactory((context, prefix) -> new ProactorStreamEmitterProcessingStrategy(DEFAULT_BUFFER_SIZE, 1, () -> cpuLight, () -> rejectingSchedulerSpy, () -> cpuIntensive, 1, 2, true)) .build(); flow.initialise(); flow.start(); rejectingSchedulerSpy.reset(); processFlow(testEvent()); probe(() -> { <START> assertThat(rejectingSchedulerSpy.getRejections(), is(greaterThanOrEqualTo(10))); <END> return true; }); assertThat(threads, hasSize(1)); assertThat(threads.stream().filter(name -> name.startsWith(IO)).count(), equalTo(1l)); assertThat(threads, not(hasItem(startsWith(CPU_LIGHT)))); assertThat(threads, not(hasItem(startsWith(CPU_INTENSIVE)))); assertThat(threads, not(hasItem(startsWith(CUSTOM)))); }</code><technical_language>extract constant</technical_language>

Target:
public void blockingRejectedExecution() throws Exception { Scheduler blockingSchedulerSpy = spy(blocking); RejectingScheduler rejectingSchedulerSpy = new RejectingScheduler(blockingSchedulerSpy); flow = flowBuilder.get().processors(blockingProcessor) .processingStrategyFactory((context, prefix) -> new ProactorStreamEmitterProcessingStrategy(DEFAULT_BUFFER_SIZE, 1, () -> cpuLight, () -> rejectingSchedulerSpy, () -> cpuIntensive, 1, 2, true)) .build(); flow.initialise(); flow.start(); rejectingSchedulerSpy.reset(); processFlow(testEvent()); verify(blockingSchedulerSpy, times(1)).submit(any(Callable.class)); probe(() -> { assertThat(rejectingSchedulerSpy.getRejections(), is(greaterThanOrEqualTo(REJECTION_COUNT))); return true; }); assertThat(threads, hasSize(1)); assertThat(threads.stream().filter(name -> name.startsWith(IO)).count(), equalTo(1l)); assertThat(threads, not(hasItem(startsWith(CPU_LIGHT)))); assertThat(threads, not(hasItem(startsWith(CPU_INTENSIVE)))); assertThat(threads, not(hasItem(startsWith(CUSTOM)))); }
Source:
<code>public static byte[] digestWithSalt(String password, byte[] salt, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); <START> String temp_password = (password == null ? "" : password); <END> md.update(temp_password.getBytes("UTF-8")); md.update(salt); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(algorithm, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }</code><technical_language>Please rename variable tempPassword (we camel case). Remove parenthesis ternary expression</technical_language>

Target:
public static byte[] digestWithSalt(String password, byte[] salt, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); if (password == null) { password = ""; } md.update(password.getBytes("UTF-8")); md.update(salt); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(algorithm, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
<code>@Test public void unexpectedSignatureFromAdapters() throws Exception { try { Moshi moshi = new Moshi.Builder() .add(new UnexpectedSignatureFromJsonAdapter()).build(); <START> } catch (IllegalArgumentException expected){ <END> assertThat(expected.getMessage()).contains( "<any access modifier> void toJson(JsonWriter writer, T value) throws <any>;", "pointFromJson" ); } }</code><technical_language>needs a fail() call</technical_language>

Target:
@Test public void unexpectedSignatureFromAdapters() throws Exception { Moshi.Builder builder = new Moshi.Builder(); try { builder.add(new UnexpectedSignatureFromJsonAdapter()).build(); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("Unexpected signature for void " + "com.squareup.moshi.AdapterMethodsTest$UnexpectedSignatureFromJsonAdapter.pointFromJson" + "(java.lang.String).\n" + "@FromJson method signatures may have one of the following structures:\n" + " <any access modifier> void fromJson(JsonReader jsonReader) throws <any>;\n" + " <any access modifier> R fromJson(T value) throws <any>;\n"); } }
Source:
<code>public void testDeleteWithDelay() throws Exception { int delay = 200; File[] files = initFiles(10, monitoredDirectory, "file00"); observer.checkAndNotify(); <START> init(); <END> addDelay(delay); Stream.of(files) .forEach( f -> { fileDelete(f); observer.checkAndNotify(); }); runThreads(observer::checkAndNotify, 3); Thread.sleep(delay + delayBuf); verify(fileListener, never()).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, times(files.length)) .onFileDelete(any(File.class), any(Synchronization.class)); }</code><technical_language>Is a chance onFileChange is called in time this sleep finished</technical_language>

Target:
public void testDeleteWithDelay() throws Exception { File[] files = initFiles(10, monitoredDirectory, "file00"); observer.checkAndNotify(); init(); initSemaphore(files.length); delayLatch = new CountDownLatch(1); Stream.of(files) .forEach( f -> { fileDelete(f); observer.checkAndNotify(); }); artificialDelay.release(files.length); delayLatch.await(timeout, TimeUnit.MILLISECONDS); verify(fileListener, never()).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, times(1)).onFileDelete(any(File.class), any(Synchronization.class)); delayLatch = new CountDownLatch(files.length - 1); observer.checkAndNotify(); delayLatch.await(timeout, TimeUnit.MILLISECONDS); verify(fileListener, never()).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, times(files.length)) .onFileDelete(any(File.class), any(Synchronization.class)); assertThat(artificialDelay.getQueueLength(), is(0)); }