auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void parseJsonResults_Timestamp() { <START> initWithJson(CUCUMBER_TIMESTAMPED_JSON); <END> ReportParser reportParser = new ReportParser(configuration); List<Feature> features = reportParser.parseJsonFiles(jsonReports); assertThat(features).hasSize(3); SoftAssertions.assertSoftly(a -> { for (Feature f : features) { for (Element elm : f.getElements()) { if (elm.isScenario()) { a.assertThat(elm.getStartTime()).isNotNull(); } } } }); }</code><technical_language>//</technical_language>

Target:
public void parseJsonResults_Timestamp() { initWithJson(CUCUMBER_TIMESTAMPED_JSON); ReportParser reportParser = new ReportParser(configuration); List<Feature> features = reportParser.parseJsonFiles(jsonReports); assertThat(features).hasSize(2); SoftAssertions.assertSoftly(a -> { for (Feature f : features) { for (Element elm : f.getElements()) { if (elm.isScenario()) { a.assertThat(elm.getStartTime()).isNotNull(); } } } }); }
Source:
<code>public void testasync3() throws Exception { <START> Client client = ResteasyClientBuilder.newClient(); <END> Response response = null; getDispatcher(server).setMaxCacheSize(10); latch = new CountDownLatch(1); Builder builder = client.target("http://localhost:" + TestPortProvider.getPort() + "?asynch=true").request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); response.close(); Thread.sleep(1000); builder = client.target(jobUrl2).request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); Assert.assertEquals("content", response.readEntity(String.class)); builder = client.target(jobUrl2).request(); response = builder.get(); Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus()); response.close(); }</code><technical_language>Close client () :-)</technical_language>

Target:
public void testasync3() throws Exception { Response response = null; getDispatcher(server).setMaxCacheSize(10); latch = new CountDownLatch(1); Builder builder = client.target("http://localhost:" + TestPortProvider.getPort() + "?asynch=true").request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); String jobUrl2 = response.getHeaderString(HttpHeaders.LOCATION); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); response.close(); Thread.sleep(1000); builder = client.target(jobUrl2).request(); response = builder.post(Entity.entity("content", "text/plain")); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus()); Assert.assertEquals("content", response.readEntity(String.class)); builder = client.target(jobUrl2).request(); response = builder.get(); Assert.assertEquals(HttpServletResponse.SC_GONE, response.getStatus()); response.close(); }
Source:
<code>public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + response.getProperties() <START> .getResourceId() <END> + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }</code><technical_language>I parametrized SqlQuerySpec instead of concating strings</technical_language>

Target:
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
Source:
<code>private Object applyModificationsAndThen(TxInvocationContext ctx, PrepareCommand command, WriteCommand[] modifications, int startIndex, InvocationSuccessFunction handler) throws Throwable { for (int i = startIndex; i < modifications.length; i++) { WriteCommand c = modifications[i]; c.setTopologyId(command.getTopologyId()); Object result = c.acceptVisitor(ctx, entryWrappingVisitor); InvocationStage visitorStage = null; boolean done = true; if (result instanceof InvocationStage) { visitorStage = (InvocationStage) result; done = visitorStage.isDone(); if (done) { visitorStage.get(); } } if (done) { if (c.hasAnyFlag(FlagBitSets.PUT_FOR_X_SITE_STATE_TRANSFER)) { <START> ctx.getCacheTransaction().setStateTransferFlag(Flag.PUT_FOR_X_SITE_STATE_TRANSFER); <END> } } else { int nextIndex = i + 1; if (nextIndex >= modifications.length) { return visitorStage.thenApply(ctx, command, handler); } return visitorStage.thenApply(ctx, command, (rCtx, rCommand, rv) -> applyModificationsAndThen(ctx, command, modifications, nextIndex, handler)); } } return handler.apply(ctx, command, null); }</code><technical_language>This if (done), set state transfer flag invoking entry wrapping visitor</technical_language>

Target:
private Object applyModificationsAndThen(TxInvocationContext ctx, PrepareCommand command, WriteCommand[] modifications, int startIndex, InvocationSuccessFunction handler) throws Throwable { for (int i = startIndex; i < modifications.length; i++) { WriteCommand c = modifications[i]; c.setTopologyId(command.getTopologyId()); if (c.hasAnyFlag(FlagBitSets.PUT_FOR_X_SITE_STATE_TRANSFER)) { ctx.getCacheTransaction().setStateTransferFlag(Flag.PUT_FOR_X_SITE_STATE_TRANSFER); } Object result = c.acceptVisitor(ctx, entryWrappingVisitor); if (!isSuccessfullyDone(result)) { int nextIndex = i + 1; if (nextIndex >= modifications.length) { return makeStage(result).thenApply(ctx, command, handler); } return makeStage(result).thenApply(ctx, command, (rCtx, rCommand, rv) -> applyModificationsAndThen(ctx, command, modifications, nextIndex, handler)); } } return handler.apply(ctx, command, null); }
Source:
<code>public void testEventBridge() throws Exception { EventsCollector eventsCollector = new EventsCollector(); sessionRepository.setApplicationEventPublisher(eventsCollector); MapSession sessionToBeDeleted = sessionRepository.createSession(); MapSession sessionToBeExpired = sessionRepository.createSession(); sessionToBeExpired.setMaxInactiveIntervalInSeconds(1); sessionRepository.save(sessionToBeExpired); sessionRepository.save(sessionToBeDeleted); sessionRepository.delete(sessionToBeDeleted.getId()); TimeUnit.SECONDS.sleep(1); callEviction(); assertNull(cache.get(sessionToBeExpired.getId())); assertNull(cache.get(sessionToBeDeleted.getId())); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionCreatedEvent.class, 2, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDeletedEvent.class, 1, 2, TimeUnit.SECONDS); <START> EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionExpiredEvent.class, 1, 2, TimeUnit.SECONDS); <END> }</code><technical_language>~~No need a Supplier here, pass a stream EventsWaiter.assertNumberOfEvents~~</technical_language>

Target:
public void testEventBridge() throws Exception { EventsCollector eventsCollector = new EventsCollector(); sessionRepository.setApplicationEventPublisher(eventsCollector); MapSession sessionToBeDeleted = sessionRepository.createSession(); MapSession sessionToBeExpired = sessionRepository.createSession(); sessionToBeExpired.setMaxInactiveIntervalInSeconds(1); sessionRepository.save(sessionToBeExpired); sessionRepository.save(sessionToBeDeleted); sessionRepository.delete(sessionToBeDeleted.getId()); TimeUnit.SECONDS.sleep(1); callEviction(); assertNull(springCache.get(sessionToBeExpired.getId())); assertNull(springCache.get(sessionToBeDeleted.getId())); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionCreatedEvent.class, 2, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDeletedEvent.class, 1, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionExpiredEvent.class, 1, 2, TimeUnit.SECONDS); }
Source:
<code>public static void validateArtifactoryServerAndRepo(String serverKey, String repositoryKey, ServerConfigManager serverConfigManager, @NotNull ActionParametersMap params, @NotNull ErrorCollection errorCollection) { if (!params.containsKey(serverKey)) { return; } long configuredServerId = getConfiguredServerId(serverKey, params); if (configuredServerId == -1) { return; } <START> validateServerConfigExists(configuredServerId, serverKey, serverConfigManager, errorCollection); <END> validateRepo(repositoryKey, params, errorCollection); }</code><technical_language>code lines (since beginning of this method) duplicated. call *validateArtifactoryServer* method instaed</technical_language>

Target:
public static void validateArtifactoryServerAndRepo(String serverKey, String repositoryKey, ServerConfigManager serverConfigManager, @NotNull ActionParametersMap params, @NotNull ErrorCollection errorCollection) { boolean shouldCheckRepo = validateServer(serverKey, serverConfigManager, params, errorCollection); if (shouldCheckRepo) { validateRepo(repositoryKey, params, errorCollection); } }
Source:
<code>public synchronized Location getLocation(Context context) { if (mLocation != null) { return mLocation; } start(context); if (isPlayServicesConnected()) { try { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLocation != null) { if (isLocationManagerConnected()) { stopLocationUpdatesWithoutPlayServices(); } return mLocation; } } catch (SecurityException e) { Log.e(TAG, "Appium Settings has no access to location permission", e); } } if (isLocationManagerConnected() || mGoogleApiClient != null) { if (mGoogleApiClient != null && !isLocationManagerConnected()) { Object locationManager = context.getSystemService(LOCATION_SERVICE); <START> if (locationManager != null) { <END> mLocationManager = (LocationManager) locationManager; startLocationUpdatesWithoutPlayServices(); } } if (mLocationManager != null && mLocationProvider != null) { try { return mLocationManager.getLastKnownLocation(mLocationProvider); } catch (SecurityException e) { Log.e(TAG, String.format("Appium Settings has no access to %s location permission", mLocationProvider), e); } } } return null; }</code><technical_language>mLocation assigned returned</technical_language>

Target:
public synchronized Location getLocation(Context context) { if (mLocation != null) { return mLocation; } start(context); if (isPlayServicesConnected()) { try { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLocation != null) { if (isLocationManagerConnected()) { stopLocationUpdatesWithoutPlayServices(); } return mLocation; } } catch (SecurityException e) { Log.e(TAG, "Appium Settings has no access to location permission", e); } } if (isLocationManagerConnected() || mGoogleApiClient != null) { if (mGoogleApiClient != null && !isLocationManagerConnected()) { Object locationManager = context.getSystemService(LOCATION_SERVICE); if (locationManager != null) { mLocationManager = (LocationManager) locationManager; startLocationUpdatesWithoutPlayServices(); } } if (mLocationManager != null && mLocationProvider != null) { try { mLocation = mLocationManager.getLastKnownLocation(mLocationProvider); return mLocation; } catch (SecurityException e) { Log.e(TAG, String.format("Appium Settings has no access to %s location permission", mLocationProvider), e); } } } return null; }
Source:
<code>public void isSameAllergen_shouldReturnFalseForDifferentNonCodedAllergen() { <START> Concept concept = Context.getConceptService().getConceptByUuid(otherNonCodedConceptUuid); <END> Assert.assertFalse(new Allergen(null, concept, "OTHER VALUE1").isSameAllergen(new Allergen(null, concept, "OTHER VALUE2"))); }</code><technical_language>for otherNonCodedConceptUuid</technical_language>

Target:
public void isSameAllergen_shouldReturnFalseForDifferentNonCodedAllergen() { Concept concept = Context.getConceptService().getConceptByUuid(Allergen.getOtherNonCodedConceptUuid()); Assert.assertFalse(new Allergen(null, concept, "OTHER VALUE1").isSameAllergen(new Allergen(null, concept, "OTHER VALUE2"))); }
Source:
<code>public boolean isImageAdInCorrectSize(double imageHeight, String slotSelector) throws InterruptedException { long time = System.currentTimeMillis(); long endTime = time+5000; while(time < endTime) { if (imageHeight == getAdSlotHeight(slotSelector)){ return true; } <START> Thread.sleep(200); <END> time = System.currentTimeMillis(); } PageObjectLogging.log("isImageAdInCorrectSize", "Image is not in correct, required size " + imageHeight + " is not equal with actual size " + getAdSlotHeight(slotSelector), false, driver); return false; }</code><technical_language>instead of Thread.sleep TimeUnit.MILISECONDS.sleep. I more descriptive. do think</technical_language>

Target:
public boolean isImageAdInCorrectSize(double imageHeight, String slotSelector) throws InterruptedException { long time = System.currentTimeMillis(); long endTime = time+3000; while(time < endTime) { if (imageHeight == getAdSlotHeight(slotSelector)){ return true; } TimeUnit.MILLISECONDS.sleep(200); time = System.currentTimeMillis(); } PageObjectLogging.log("isImageAdInCorrectSize", "Image is not in correct, required size " + imageHeight + " is not equal with actual size " + getAdSlotHeight(slotSelector), false, driver); return false; }
Source:
<code>public static Map<String, String> loadMountPoints() throws IOException { Map<String, String> mounts = null; String home = System.getProperty("user.home"); <START> File mountFile = new File( home + File.separator + ".knoxshell" + File.separator + KNOXMOUNTPOINTS_JSON); <END> if (mountFile.exists()) { String json = readFileToString(mountFile); mounts = getMapFromJsonString(json); } return mounts; }</code><technical_language>recommend <LINK_0></technical_language>

Target:
public static Map<String, String> loadMountPoints() throws IOException { Map<String, String> mounts = new HashMap<>(); String home = System.getProperty("user.home"); File mountFile = new File( home + File.separator + ".knoxshell" + File.separator + KNOXMOUNTPOINTS_JSON); if (mountFile.exists()) { String json = readFileToString(mountFile); mounts = getMapFromJsonString(json); } return mounts; }
Source:
<code>protected void syncSearch() { super.syncSearch(); <START> Task.Create(this, null).InvokeUIThread(); <END> }</code><technical_language>I "Task.Create(ITaskTarget,Object)" method is in some other places, Task.Run() is delegate "ITaskTarget.run(TaskContext)" method. In this case, Daniel suggested, remove "implements ITaskTarget" for SearchSuggestModel, replace "Task.Create(this,null).InvokeUIThread()" "SearchSuggestModel.run(TaskContext)" method body, remove "SearchSuggestModel.run(TaskContext)" method afterwards. In case of other classes Task.Create(), i.e. DataCenterGuideModel + StorageListModel, remove "implements ITaskTarget" "run()" method, replacing TaskContext argument (containing "state") "state" List<Object> directly. Also, remove "TaskContext context" field model classes, if need altogether</technical_language>

Target:
protected void syncSearch() { super.syncSearch(); updateOptionsAsync(getPrefix() + getSearchString()); }
Source:
<code>private void insertRow() { db.executeInsert( "PROJECT_BRANCHES", "UUID", "dummy_uuid", "PROJECT_UUID", "dummy_project_uuid", "KEE", "dummy_key", "CREATED_AT", 456789, "UPDATED_AT", 456789, <START> "BRANCH_TYPE", ScannerReport.Metadata.BranchType.PULL_REQUEST.name()); <END> }</code><technical_language>minor: reference a ScannerReport class in a db migration test class</technical_language>

Target:
private void insertRow() { db.executeInsert( "PROJECT_BRANCHES", "UUID", "dummy_uuid", "PROJECT_UUID", "dummy_project_uuid", "KEE", "dummy_key", "CREATED_AT", 456789, "UPDATED_AT", 456789, "BRANCH_TYPE", "PULL_REQUEST"); }
Source:
<code>public boolean accept(Path path) { if (!super.accept(path)) { return false; } String filename = path.getName(); Matcher m = HdfsSinkConnectorConstants.COMMITTED_FILENAME_PATTERN.matcher(filename); if (!m.matches()) { throw new AssertionError("match expected because of CommittedFileFilter"); } <START> String topic = m.group(1); <END> return topic.equals(this.topic); }</code><technical_language>re: this magic constant moving HdfsSinkConnectorConstants</technical_language>

Target:
public boolean accept(Path path) { if (!super.accept(path)) { return false; } String filename = path.getName(); Matcher m = HdfsSinkConnectorConstants.COMMITTED_FILENAME_PATTERN.matcher(filename); if (!m.matches()) { throw new AssertionError("match expected because of CommittedFileFilter"); } String topic = m.group(HdfsSinkConnectorConstants.PATTERN_TOPIC_GROUP); return topic.equals(this.topic); }
Source:
<code>private void asyncInstall(Set<String> editionPluginKeys, UpdateCenter updateCenter) { try { <START> editionPluginDownloader.installEdition(pluginsToInstall(editionPluginKeys), updateCenter); <END> for (String pluginKey : pluginsToRemove(editionPluginKeys)) { editionPluginUninstaller.uninstall(pluginKey); } editionManagementState.automaticInstallReady(); } finally { lock.unlock(); } }</code><technical_language>of call pluginsToInstall pluginsToRemove, pluginRepository.getPluginInfosByKeys() pluginRepository.getPluginInfos() called. This is reading FileSystem twice. is necessary, perf impact opens door for inconsistencies (even if unlikely)</technical_language>

Target:
private void asyncInstall(Set<String> editionPluginKeys, UpdateCenter updateCenter) { Map<String, PluginInfo> pluginInfosByKeys = pluginRepository.getPluginInfosByKeys(); Set<String> pluginsToRemove = pluginsToRemove(editionPluginKeys, pluginInfosByKeys.values()); Set<String> pluginsToInstall = pluginsToInstall(editionPluginKeys, pluginInfosByKeys.keySet()); try { editionPluginDownloader.downloadEditionPlugins(pluginsToInstall, updateCenter); for (String pluginKey : pluginsToRemove) { editionPluginUninstaller.uninstall(pluginKey); } editionManagementState.automaticInstallReady(); } finally { lock.unlock(); } }
Source:
<code>public void testCodeSpanEscaped() { builder.beginDocument(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); <START> builder.characters("A single backtick in a code span: "); <END> builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("`"); builder.endSpan(); builder.endBlock(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("A backtick-delimited string in a code span: "); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("`foo`"); builder.endSpan(); builder.endBlock(); builder.endDocument(); assertMarkup("A single backtick in a code span: `` ` ``\n\nA backtick-delimited string in a code span: `` `foo` ``\n\n"); }</code><technical_language>intend nesting code block in a paragraph block? If method name changed this test is about</technical_language>

Target:
public void testCodeSpanEscaped() { builder.beginDocument(); builder.characters("A single backtick in a code span: "); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("`"); builder.endSpan(); builder.lineBreak(); builder.characters("A backtick-delimited string in a code span: "); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("`foo`"); builder.endSpan(); builder.endDocument(); assertMarkup("A single backtick in a code span: `` ` `` \nA backtick-delimited string in a code span: `` `foo` ``\n\n"); }
Source:
<code>private static PrivateKey readPEMRSAPrivateKey(Reader reader) { PEMParser pemParser = new PEMParser(reader); PKCS8EncodedKeySpec privateKey = null; try { PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject(); privateKey = new PKCS8EncodedKeySpec(pemKeyPair.getPrivateKeyInfo().getEncoded()); } catch (IOException ioex) { <START> new IOException("Failed to read PrivateKey").initCause(ioex); <END> } PrivateKey privateKeyOutput = null; try { privateKeyOutput = KeyFactory.getInstance("RSA").generatePrivate(privateKey); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return privateKeyOutput; }</code><technical_language>ignore exception</technical_language>

Target:
private static PrivateKey readPEMRSAPrivateKey(Reader reader) { PEMParser pemParser = new PEMParser(reader); PKCS8EncodedKeySpec privateKey = null; try { PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject(); privateKey = new PKCS8EncodedKeySpec(pemKeyPair.getPrivateKeyInfo().getEncoded()); } catch (IOException ioex) { throw new WinstoneException(ioex.getMessage(), ioex); } PrivateKey privateKeyOutput = null; try { privateKeyOutput = KeyFactory.getInstance("RSA").generatePrivate(privateKey); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new WinstoneException(e.getMessage(), e); } return privateKeyOutput; }
Source:
<code>public void createChain() throws Exception { SigningKeyPair oldUser = SigningKeyPair.random(new SafeRandom.Java(), new Ed25519.Java()); SigningKeyPair newUser = SigningKeyPair.random(new SafeRandom.Java(), new Ed25519.Java()); <START> PublicKeyHash oldHash = ipfs.putSigningKey( <END> oldUser.secretSigningKey.signOnly(oldUser.publicSigningKey.serialize()), ipfs.hashKey(oldUser.publicSigningKey), oldUser.publicSigningKey).get(); PublicKeyHash newHash = ipfs.putSigningKey( newUser.secretSigningKey.signOnly(newUser.publicSigningKey.serialize()), ipfs.hashKey(newUser.publicSigningKey), newUser.publicSigningKey).get(); SigningPrivateKeyAndPublicHash oldSigner = new SigningPrivateKeyAndPublicHash(oldHash, oldUser.secretSigningKey); SigningPrivateKeyAndPublicHash newSigner = new SigningPrivateKeyAndPublicHash(newHash, newUser.secretSigningKey); List<UserPublicKeyLink> links = UserPublicKeyLink.createChain(oldSigner, newSigner, "someuser", LocalDate.now().plusYears(2)); links.forEach(link -> testSerialization(link)); }</code><technical_language>extracting this method? public PublicKeyHash putSingingKey(user User) { return ipfs.putSigningKey( user.secretSigningKey.signOnly(user.publicSigningKey.serialize()), ipfs.hashKey(user.publicSigningKey), user.publicSigningKey).get(); }</technical_language>

Target:
public void createChain() throws Exception { SigningKeyPair oldUser = SigningKeyPair.random(new SafeRandom.Java(), new Ed25519.Java()); SigningKeyPair newUser = SigningKeyPair.random(new SafeRandom.Java(), new Ed25519.Java()); PublicKeyHash oldHash = putPublicSigningKey(oldUser); PublicKeyHash newHash = putPublicSigningKey(newUser); SigningPrivateKeyAndPublicHash oldSigner = new SigningPrivateKeyAndPublicHash(oldHash, oldUser.secretSigningKey); SigningPrivateKeyAndPublicHash newSigner = new SigningPrivateKeyAndPublicHash(newHash, newUser.secretSigningKey); List<UserPublicKeyLink> links = UserPublicKeyLink.createChain(oldSigner, newSigner, "someuser", LocalDate.now().plusYears(2)); links.forEach(link -> testSerialization(link)); }
Source:
<code>public HTTPKasperResponse asHttp(){ <START> if (HTTPKasperResponse.class.isAssignableFrom(this.getClass())) { <END> return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }</code><technical_language>if (TransportMode.HTTP.equals(getTransportMode())</technical_language>

Target:
public HTTPKasperResponse asHttp(){ if (TransportMode.HTTP.equals(getTransportMode())) { return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }
Source:
<code>public void visitIfStatement(IfStatementTree tree) { insideIfStatement = true; <START> <END> if (isThisAResourceNullCheck(tree, NOT_EQUAL)) { updateNullCheckedResources(tree, true); } else if (isThisAResourceNullCheck(tree, EQUAL)) { insideEqualNullCheck = true; } super.visitIfStatement(tree); if (returnOccurredInsideEqualNullCheck) { updateNullCheckedResources(tree, true); } cleanFlagsAfterIfStatement(tree); }</code><technical_language>Empty line needed</technical_language>

Target:
public void visitIfStatement(IfStatementTree tree) { insideIfStatement = true; if (isResourceNullCheckOfType(tree, NOT_EQUAL_TO.name())) { updateNullCheckedResources(tree, true); } else if (isResourceNullCheckOfType(tree, EQUAL_TO.name())) { insideEqualNullCheck = true; } super.visitIfStatement(tree); if (returnOccurredInsideEqualNullCheck) { updateNullCheckedResources(tree, true); } cleanFlagsAfterIfStatement(tree); }
Source:
<code>public void testAutoRefreshWithoutForceRefresh() throws Exception { genericSetUp(SEMANTIC_MODEL_PATH_FOR_NULL_VALUE, MODELER_DESCRIPTION_PATH_FOR_NULL_VALUE, SESSION_PATH_FOR_NULL_VALUE); changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); Iterator<DRepresentation> iterator = getRepresentations("PackageDiag").iterator(); DDiagram firstDiag = (DDiagram) iterator.next(); DiagramEditor diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, firstDiag, new NullProgressMonitor()); DDiagram secondDiag = (DDiagram) iterator.next(); diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, secondDiag, new NullProgressMonitor()); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); try { applyNodeCreationTool("createPackageNotRefresh", secondDiag, secondDiag); assertEquals("Diagram should not be empty", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Diagram should not be empty", 1, firstDiag.getOwnedDiagramElements().size()); <START> } catch (NullPointerException exception) { Assert.fail("No expcetion should have been raised during Node creation. This is a regression."); } <END> }</code><technical_language>idem, remove</technical_language>

Target:
public void testAutoRefreshWithoutForceRefresh() throws Exception { changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); applyNodeCreationTool("createPackageNotRefresh", secondDiag, secondDiag); assertEquals("Force refresh diagram has not been refreshed", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Non 'Force refresh' diagram has not been refreshed.", 1, firstDiag.getOwnedDiagramElements().size()); }
Source:
<code>public UpdateRequest processPreUpdate( UpdateRequest input, Map<String, Metacard> existingMetacards) throws StopProcessingException { Function<ShareableMetacardImpl, ShareableMetacardImpl> previous = (update) -> ShareableMetacardImpl.from(existingMetacards.get(update.getId())); Set<String> notOwners = input .getUpdates() .stream() .map(Map.Entry::getValue) .filter(ShareableMetacardImpl::canShare) <START> .map(ShareableMetacardImpl::from) <END> .filter(update -> isSharingUpdated(previous.apply(update), update)) .map(previous) .map(ShareableMetacardImpl::getOwner) .filter(this::isNotOwner) .collect(Collectors.toSet()); if (!notOwners.isEmpty()) { throw new StopProcessingException( "Cannot update metacard. Subject cannot change sharing permissions because they are not the owner."); } return input; }</code><technical_language>If decided throw exception in this path execute expected, filtering is done shareability check</technical_language>

Target:
public UpdateRequest processPreUpdate( UpdateRequest input, Map<String, Metacard> existingMetacards) throws StopProcessingException { Function<ShareableMetacardImpl, ShareableMetacardImpl> oldVersionOfMetacard = (update) -> ShareableMetacardImpl.create(existingMetacards.get(update.getId())).orElse(null); Set<String> notOwners = input .getUpdates() .stream() .map(Map.Entry::getValue) .filter(ShareableMetacardImpl::canShare) .map(ShareableMetacardImpl::createOrThrow) .filter(update -> isSharingUpdated(oldVersionOfMetacard.apply(update), update)) .map(oldVersionOfMetacard) .filter(Objects::nonNull) .map(ShareableMetacardImpl::getOwner) .filter(this::isNotOwner) .collect(Collectors.toSet()); if (!notOwners.isEmpty()) { throw new StopProcessingException( "Cannot update metacard. Subject cannot change sharing permissions because they are not the owner."); } return input; }
Source:
<code>public void testServerIssueTracking() { VirtualFile file = mock(VirtualFile.class); ServerIssue serverIssue = mock(ServerIssue.class); when(file.getPath()).thenReturn(""); ConnectedSonarLintEngine engine = mock(ConnectedSonarLintEngine.class); when(bindingManager.getConnectedEngine()).thenReturn(engine); SonarQubeServer server = mock(SonarQubeServer.class); <START> when(server.getHostUrl()).thenReturn("http://localhost:9000"); <END> when(bindingManager.getSonarQubeServer()).thenReturn(server); when(engine.downloadServerIssues(any(ServerConfiguration.class), anyString(), anyString())) .thenReturn(Collections.singleton(serverIssue).iterator()); settings.setBindingEnabled(true); updater.initComponent(); updater.fetchAndMatchServerIssues(Collections.singletonList(file)); verify(issueManager, timeout(1000).times(1)).matchWithServerIssues(eq(file), argThat(new CustomMatcher<Collection<Trackable>>("one trackable") { @Override public boolean matches(Object o) { Collection<Trackable> issues = (Collection<Trackable>) o; return issues.size() == 1; } })); verify(bindingManager).getConnectedEngine(); verify(console, never()).error(anyString()); verify(console, never()).error(anyString(), any(Throwable.class)); }</code><technical_language>"dummyserver" is misleading</technical_language>

Target:
public void testServerIssueTracking() { VirtualFile file = mock(VirtualFile.class); ServerIssue serverIssue = mock(ServerIssue.class); when(file.getPath()).thenReturn(""); ConnectedSonarLintEngine engine = mock(ConnectedSonarLintEngine.class); when(bindingManager.getConnectedEngine()).thenReturn(engine); SonarQubeServer server = mock(SonarQubeServer.class); when(server.getHostUrl()).thenReturn("http://dummyserver:9000"); when(bindingManager.getSonarQubeServer()).thenReturn(server); when(engine.downloadServerIssues(any(ServerConfiguration.class), anyString(), anyString())) .thenReturn(Collections.singleton(serverIssue).iterator()); settings.setBindingEnabled(true); updater.initComponent(); updater.fetchAndMatchServerIssues(Collections.singletonList(file)); verify(issueManager, timeout(1000).times(1)).matchWithServerIssues(eq(file), argThat(new CustomMatcher<Collection<Trackable>>("one trackable") { @Override public boolean matches(Object o) { Collection<Trackable> issues = (Collection<Trackable>) o; return issues.size() == 1; } })); verify(bindingManager).getConnectedEngine(); verify(console, never()).error(anyString()); verify(console, never()).error(anyString(), any(Throwable.class)); }
Source:
<code>private void verifyIfCkptSet(Map<String, String> props, String dumpDir) { assertTrue(props.containsKey(ReplUtils.REPL_CHECKPOINT_KEY)); <START> assertTrue(props.get(ReplUtils.REPL_CHECKPOINT_KEY).equalsIgnoreCase(dumpDir)); <END> }</code><technical_language>for some file systems path is case sensitive</technical_language>

Target:
private void verifyIfCkptSet(Map<String, String> props, String dumpDir) { assertTrue(props.containsKey(ReplUtils.REPL_CHECKPOINT_KEY)); assertTrue(props.get(ReplUtils.REPL_CHECKPOINT_KEY).equals(dumpDir)); }
Source:
<code>public String rerunFailedJobs(Request req, Response res) throws IOException { String pipelineName = req.params("pipeline_name"); String pipelineCounter = req.params("pipeline_counter"); String stageName = req.params("stage_name"); HttpOperationResult result = new HttpOperationResult(); <START> scheduleService.rerunFailedJobs(pipelineName, pipelineCounter, stageName, result); <END> return renderHTTPOperationResult(result, req, res); }</code><technical_language>passing stage counter part of this request. Consider a stage is re-run multiple times time a set of jobs failed. user choose re-run failed jobs a stage</technical_language>

Target:
public String rerunFailedJobs(Request req, Response res) throws IOException { HttpOperationResult result = new HttpOperationResult(); Optional<Stage> optionalStage = getStageFromRequestParam(req, result); optionalStage.ifPresent(stage -> scheduleService.rerunFailedJobs(stage, result)); return renderHTTPOperationResult(result, req, res); }
Source:
<code>public void update(final VDS host) { Collection<String> packages = getPackagesForCheckUpdate(host.getVdsType(), host.getClusterCompatibilityVersion()); try (final VdsDeploy hostPackagesManager = createPackagesManager(host, true)) { hostPackagesManager.addUnit(new VdsDeployPackagesUnit(packages, false)); hostPackagesManager.execute(); } catch (final Exception e) { log.error("Failed to update host '{}' packages '{}'.", host.getName(), StringUtils.join(packages, ", ")); log.error("Exception", e.getMessage()); <START> log.debug("Exception", e); <END> throw new RuntimeException(e); } }</code><technical_language>Please minimize logging invocations: log.error("Failed update host '{}' packages '{}': {}", host.getName(), StringUtils.join(packages, ", "), e.getMessage()); log.debug("Exception", e);</technical_language>

Target:
public void update(final VDS host) { Collection<String> packages = getPackagesForCheckUpdate(host.getVdsType(), host.getClusterCompatibilityVersion()); try (final VdsDeploy hostPackagesManager = createPackagesManager(host, true)) { hostPackagesManager.addUnit(new VdsDeployPackagesUnit(packages, false)); hostPackagesManager.execute(); } catch (final Exception e) { log.error("Failed to update host '{}' packages '{}': {}", host.getName(), StringUtils.join(packages, ", "), e.getMessage()); log.debug("Exception", e); throw new RuntimeException(e); } }
Source:
<code><START> private SystemProducer createAndInitializeSystemProducer() { <END> SystemFactory samzaFactory = ReflectionUtils.createInstance(_factoryClassName); if (samzaFactory == null) { String msg = "Unable to instantiate the factory class " + _factoryClassName; LOG.error(msg); throw new DatastreamRuntimeException(msg); } SystemProducer systemProducer = samzaFactory.getProducer(_systemName, _samzaConfig, new NoOpMetricsRegistry()); systemProducer.register(_source); systemProducer.start(); return systemProducer; }</code><technical_language>nit: this createAndStartSystemProducer</technical_language>

Target:
private SystemProducer createAndInitializeSystemProducer() { SystemFactory samzaFactory = ReflectionUtils.createInstance(_factoryClassName); if (samzaFactory == null) { String msg = "Unable to instantiate the factory class " + _factoryClassName; LOG.error(msg); throw new DatastreamRuntimeException(msg); } SystemProducer systemProducer = samzaFactory.getProducer(_systemName, _samzaConfig, new NoOpMetricsRegistry()); systemProducer.register(_destination); systemProducer.start(); return systemProducer; }
Source:
<code>private void validate(final List<BatchItem> batch, final EventType eventType) throws EventValidationException, EventSizeValidationException, InternalNakadiException { for (final BatchItem item : batch) { item.setStep(EventPublishingStep.VALIDATING); try { validateSchema(item.getEvent(), eventType); validateEventSize(item); } catch (final EventValidationException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, e.getMessage()); throw e; } catch (final EventSizeValidationException e) { <START> item.updateStatusAndDetail(EventPublishingStatus.ABORTED, e.getMessage()); <END> throw e; } } }</code><technical_language>I FAILED in a case a schema validation problem. this is item failed</technical_language>

Target:
private void validate(final List<BatchItem> batch, final EventType eventType) throws EventValidationException, InternalNakadiException, NoSuchEventTypeException { for (final BatchItem item : batch) { item.setStep(EventPublishingStep.VALIDATING); try { validateSchema(item.getEvent(), eventType); validateEventSize(item); } catch (final EventValidationException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, e.getMessage()); throw e; } } }
Source:
<code>public Collection<ConfiguredBundle<AirpalConfiguration>> getConfiguredBundles() { <START> Collection<ConfiguredBundle<AirpalConfiguration>> bundles = super.getConfiguredBundles(); <END> bundles.add(new ShiroBundle<AirpalConfiguration>() { @Override protected ShiroConfiguration narrow(AirpalConfiguration configuration) { return configuration.getShiro(); } }); return bundles; }</code><technical_language>ImmutableList.Builder construct a new collection</technical_language>

Target:
public Iterable<ConfiguredBundle<AirpalConfiguration>> getConfiguredBundles() { Iterable<ConfiguredBundle<AirpalConfiguration>> bundles = super.getConfiguredBundles(); ImmutableList.Builder<ConfiguredBundle<AirpalConfiguration>> builder = ImmutableList.builder(); for (ConfiguredBundle<AirpalConfiguration> bundle : bundles) { builder.add(bundle); } builder.add(new ShiroBundle<AirpalConfiguration>() { @Override protected ShiroConfiguration narrow(AirpalConfiguration configuration) { return configuration.getShiro(); } }); return builder.build(); }
Source:
<code>public void testFailedContainerRegistration() throws ApiException { ApiClient client = getWebClient(); ContainersApi containersApi = new ContainersApi(client); List<DockstoreTool> containers = containersApi.allPublishedContainers(null, null, null, null, null); assertEquals(1, containers.size()); UsersApi usersApi = new UsersApi(client); User user = usersApi.getUser(); containers = usersApi.userContainers(user.getId()); assertEquals(5, containers.size()); List<DockstoreTool> pagedToolsLowercase = containersApi.allPublishedContainers("0", 1, "test", "stars", "desc"); assertEquals(1, pagedToolsLowercase.size()); List<DockstoreTool> pagedToolsUppercase = containersApi.allPublishedContainers("0", 1, "TEST", "stars", "desc"); <START> assertEquals(1, pagedToolsUppercase.size()); <END> DockstoreTool container = containersApi.getContainerByToolPath("quay.io/test_org/test2"); assertFalse(container.isIsPublished()); long containerId = container.getId(); PublishRequest pub = SwaggerUtility.createPublishRequest(true); thrown.expect(ApiException.class); containersApi.publish(containerId, pub); }</code><technical_language>check result is in fact tool</technical_language>

Target:
public void testFailedContainerRegistration() throws ApiException { ApiClient client = getWebClient(); ContainersApi containersApi = new ContainersApi(client); List<DockstoreTool> containers = containersApi.allPublishedContainers(null, null, null, null, null); assertEquals(1, containers.size()); UsersApi usersApi = new UsersApi(client); User user = usersApi.getUser(); containers = usersApi.userContainers(user.getId()); assertEquals(5, containers.size()); List<DockstoreTool> pagedToolsLowercase = containersApi.allPublishedContainers("0", 1, "test", "stars", "desc"); assertEquals(1, pagedToolsLowercase.size()); List<DockstoreTool> pagedToolsUppercase = containersApi.allPublishedContainers("0", 1, "TEST", "stars", "desc"); assertEquals(1, pagedToolsUppercase.size()); assertEquals(pagedToolsLowercase, pagedToolsUppercase); DockstoreTool container = containersApi.getContainerByToolPath("quay.io/test_org/test2"); assertFalse(container.isIsPublished()); long containerId = container.getId(); PublishRequest pub = SwaggerUtility.createPublishRequest(true); thrown.expect(ApiException.class); containersApi.publish(containerId, pub); }
Source:
<code>public FunctionHandle resolveFunction(Session session, QualifiedName name, List<TypeSignatureProvider> parameterTypes) { for (SqlPathElement element : session.getPath().getParsedPath()) { FunctionNamespace namespace = functionNamespaces.get(fetchCatalog(element, session)); if (namespace != null) { try { Signature signature = namespace.resolveFunction(name, parameterTypes); return new FunctionHandle(signature, fetchCatalog(element, session), TEMP_DEFAULT_SCHEMA); } catch (PrestoException e) { <START> if (e.getErrorCode().getCode() != FUNCTION_NOT_FOUND.toErrorCode().getCode()) { <END> throw e; } } } } throw new PrestoException(FUNCTION_NOT_FOUND, format("Function %s not found in path: %s", name, session.getPath())); }</code><technical_language>e.getErrorCode().equals(FUNCTION_NOT_FOUND.toErrorCode())</technical_language>

Target:
public FunctionHandle resolveFunction(Session session, QualifiedName name, List<TypeSignatureProvider> parameterTypes) { try { Signature operatorSignature = operatorNamespace.resolveFunction(name, parameterTypes); return createOperatorHandle(operatorSignature); } catch (Exception e) { } for (SqlPathElement element : session.getPath().getParsedPath()) { FunctionNamespace namespace = functionNamespaces.get(getCatalog(element, session)); if (namespace != null) { try { Signature signature = namespace.resolveFunction(name, parameterTypes); return new FunctionHandle(signature, getCatalog(element, session), TEMP_DEFAULT_SCHEMA); } catch (PrestoException e) { if (!e.getErrorCode().equals(FUNCTION_NOT_FOUND.toErrorCode())) { throw e; } } } } throw new PrestoException(FUNCTION_NOT_FOUND, format("Function %s not found in path: %s", name, session.getPath())); }
Source:
<code>public synchronized boolean seek(CtfLocationInfo ctfLocationData) { boolean ret = false; if (ctfLocationData.equals(CtfLocation.INVALID_LOCATION)) { fCurLocation = NULL_LOCATION; return false; } if (fCurLocation.getLocationInfo().equals(ctfLocationData)) { return super.hasMoreEvents(); } fCurLocation = new CtfLocation(ctfLocationData); final long seekToTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = this.getCtfTmfTrace().timestampNanoToCycles(seekToTimestamp); try { if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } } catch (CTFException e) { Activator.getDefault().logError(e.getMessage(), e); return false; } long index = 0; ITmfEvent currentEvent = getCurrentEvent(); ret &= (currentEvent != null); ITmfEvent previousEvent = currentEvent; <START> for (long i = 0; ret && i < ctfLocationData.getIndex(); i++) { <END> if (seekToTimestamp >= Objects.requireNonNull(currentEvent).getTimestamp().getValue()) { index++; } else { index = 0; break; } ret = advance(); previousEvent = currentEvent; currentEvent = getCurrentEvent(); } if (ret) { fCurLocation = new CtfLocation(new CtfLocationInfo(Objects.requireNonNull(previousEvent).getTimestamp().getValue(), index)); } else { fCurLocation = NULL_LOCATION; } return ret; }</code><technical_language>If seek index more number of events seek timestamp, resulting location next timestamp, index 0. break out of loop index condition, a chance reset index 0</technical_language>

Target:
public synchronized boolean seek(CtfLocationInfo ctfLocationData) { boolean ret = false; if (ctfLocationData.equals(CtfLocation.INVALID_LOCATION)) { fCurLocation = NULL_LOCATION; return false; } if (fCurLocation.getLocationInfo().equals(ctfLocationData)) { return super.hasMoreEvents(); } fCurLocation = new CtfLocation(ctfLocationData); final long seekToTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = this.getCtfTmfTrace().timestampNanoToCycles(seekToTimestamp); try { if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } } catch (CTFException e) { Activator.getDefault().logError(e.getMessage(), e); return false; } long index = 0; ITmfEvent currentEvent = getCurrentEvent(); ret &= (currentEvent != null); long offset = ctfLocationData.getIndex(); while (currentEvent != null && index < offset) { if (seekToTimestamp >= Objects.requireNonNull(currentEvent).getTimestamp().getValue()) { index++; } else { index = 0; break; } ret = advance(); currentEvent = getCurrentEvent(); } if (ret) { long time = Objects.requireNonNull(currentEvent).getTimestamp().getValue(); fCurLocation = new CtfLocation(new CtfLocationInfo(time, time != seekToTimestamp ? 0 : index)); } else { fCurLocation = NULL_LOCATION; } return ret; }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); if (vds.getStatus() != VDSStatus.Up) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_HOST_NOT_UP, String.format("$%1$s %2$s", "hostName", vds.getName())); <START> } <END> if (!checkStorageDomain()) { return false; } boolean localFs = isLocalFs(dom); if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }</code><technical_language>based jenkins, move this part of condition in line 146</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } StorageDomain dom = getStorageDomain(); if (dom == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } VDS vds = getVds(); StorageDomainToPoolRelationValidator domainPoolValidator = createDomainToPoolValidator(dom); boolean localFs = isLocalFs(dom); if (vds == null) { if (localFs) { if (!initializeVds()) { return false; } } else { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_INVALID_HOST_ID); } } if (vds.getStatus() != VDSStatus.Up) { return failValidation(EngineMessage.CANNOT_REMOVE_STORAGE_DOMAIN_HOST_NOT_UP, String.format("$%1$s %2$s", "hostName", vds.getName())); } if (!checkStorageDomain()) { return false; } if (!localFs && !validate(domainPoolValidator.isStorageDomainNotInAnyPool())) { return false; } if (localFs && isDomainAttached(dom) && !canDetachDomain(getParameters().getDestroyingPool(), false)) { return false; } if (getParameters().getDoFormat() && !localFs && isStorageDomainAttached(dom)) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FORMAT_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } if (dom.getStorageType().isOpenStackDomain()) { return failValidation(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); } return true; }
Source:
<code>private String getProperty(String key, String defaultValue) { String value = getProperty(key); <START> return value != null && !value.equals("") ? value : defaultValue; <END> }</code><technical_language>if is " " ? trim</technical_language>

Target:
private String getProperty(String key, String defaultValue) { String value = getProperty(key); return value != null && !value.trim().equals("") ? value : defaultValue; }