auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); // last binding where this exchange is the source is gone, remove recorded exchange // if it is auto-deleted. See bug 26364. if((x != null) && x.isAutoDelete()) { START deleteRecordedExchange(exchange); END } } } } } This isn't directly related to the issue you fix here. Could you address this one in a separate PR? It's better for versioning, changelog, etc. Thanks :)

Target:
void maybeDeleteRecordedAutoDeleteExchange(String exchange) { synchronized (this.consumers) { synchronized (this.recordedExchanges) { if(!hasMoreDestinationsBoundToExchange(Utility.copy(this.recordedBindings), exchange)) { RecordedExchange x = this.recordedExchanges.get(exchange); // last binding where this exchange is the source is gone, remove recorded exchange // if it is auto-deleted. See bug 26364. if((x != null) && x.isAutoDelete()) { this.recordedExchanges.remove(exchange); } } } } }
Source:
public RpcClient(Channel channel, String exchange, String routingKey, int timeout) throws IOException { START this(channel, exchange, routingKey, "amq.rabbitmq.reply-to", timeout) END } This does not compile.

Target:
public RpcClient(Channel channel, String exchange, String routingKey, int timeout) throws IOException { this(channel, exchange, routingKey, "amq.rabbitmq.reply-to", timeout); }
Source:
public boolean onKeyUp(int keyCode, KeyEvent event) { //If the key entered is 'Enter'('next' or 'done'), then move the focus // to the next view. if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; START } else if (teamText.hasFocus() == true) { END playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); } Should be ``` } else if (teamText.hasFocus()) { ```

Target:
public boolean onKeyUp(int keyCode, KeyEvent event) { //If the key entered is 'Enter'('next' or 'done'), then move the focus // to the next view. if (keyCode == KeyEvent.KEYCODE_ENTER) { if (brandText.hasFocus()) { yearText.requestFocus(); return true; } else if (playerNameText.hasFocus()) { teamText.requestFocus(); return true; } else if (teamText.hasFocus()) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pocketpaint_more_options, menu); START presenter.removeMoreOptionsItems(); END return true; } Please move menu into arguments

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pocketpaint_more_options, menu); presenter.removeMoreOptionsItems(menu); return true; }
Source:
public void removeStandaloneMenuItems(Menu menu) { START removeItem(R.id.pocketpaint_nav_save_image); END removeItem(R.id.pocketpaint_nav_save_duplicate); removeItem(R.id.pocketpaint_nav_new_image); } you are calling `removeItem()`. You should call `menu.removeItem()`. The idea is to not have the menu as a member variable.

Target:
public void removeStandaloneMenuItems(Menu menu) { menu.removeItem(R.id.pocketpaint_nav_save_image); menu.removeItem(R.id.pocketpaint_nav_save_duplicate); menu.removeItem(R.id.pocketpaint_nav_new_image); }
Source:
public void restoreFragmentListeners() { START FragmentManager fragmentManager = mainActivity.getSupportFragmentManager(); END Fragment fragment = fragmentManager.findFragmentByTag(Constants.COLOR_PICKER_DIALOG_TAG); if (fragment != null) { setupColorPickerDialogListeners((ColorPickerDialog) fragment); } } please revert all changes to this file

Target:
public void restoreFragmentListeners() { Fragment fragment = findFragmentByTag(Constants.COLOR_PICKER_DIALOG_TAG); if (fragment != null) { setupColorPickerDialogListeners((ColorPickerDialog) fragment); } }
Source:
public void setState(boolean bold, boolean italic, boolean underlined, String text, int textSize, String font) { boldToggleButton.setChecked(bold); italicToggleButton.setChecked(italic); underlinedToggleButton.setChecked(underlined); textEditText.setText(text); fontSpinner.setSelection(fonts.indexOf(font)); START textSizeSpinner.setSelection(sizes.indexOf(localeNumberFormat.format(textSize))); END } Does this work? You never add anything to `sizes`

Target:
public void setState(boolean bold, boolean italic, boolean underlined, String text, int textSize, String font) { boldToggleButton.setChecked(bold); italicToggleButton.setChecked(italic); underlinedToggleButton.setChecked(underlined); textEditText.setText(text); fontSpinner.setSelection(fonts.indexOf(font)); }
Source:
public GeometricFillTool(Context context, ToolType toolType) { super(context, toolType); setRotationEnabled(ROTATION_ENABLED); setRespectImageBounds(RESPECT_IMAGE_BOUNDS); if (baseShape == null) { baseShape = BaseShape.RECTANGLE; } START if (shapeOutlineWidth == 0) { END shapeOutlineWidth = 25; } shapeDrawType = ShapeDrawType.FILL; createOverlayBitmap(); createAndSetBitmap(); } Why do you check for 0? (I mean why a specific value, should this be `<=0`? Since you are in the constructor, you could just set the `shapeOutlineWidth` to 25 there. Even better: don't hardcode magic numbers, use a `DEFAULT_SHAPE_OUTLINE_WIDTH` constant to define the value 25.

Target:
public GeometricFillTool(Context context, ToolType toolType) { super(context, toolType); setRotationEnabled(ROTATION_ENABLED); setRespectImageBounds(RESPECT_IMAGE_BOUNDS); if (baseShape == null) { baseShape = BaseShape.RECTANGLE; } shapeDrawType = ShapeDrawType.FILL; createOverlayBitmap(); createAndSetBitmap(); }
Source:
START public static void init(MainActivity mainActivity, Bitmap first_layer) { END instance = new LayersDialog(mainActivity, first_layer); } I would add a check if instance is != null, because with this, everyone can overwrite the current instance if its not null. Or only create a new instance in the getInstance methode, if instance == null

Target:
public static void init(MainActivity mainActivity, Bitmap first_layer) { if (instance == null) instance = new LayersDialog(mainActivity, first_layer); }
Source:
void onPrev(ClickEvent event) { START GQuery.console.info("prev"); END prev(); } Do you want to remove the debug?

Target:
void onPrev(ClickEvent event) { prev(); }
Source:
public void testFirstLast_CreateSparseContainersAfterRun() { RoaringBitmap rb = new RoaringBitmap(); rb.add(1L, 1 << 14); for(int i = 18; i < 31; ++i) { int x = 1 << i; rb.add(x); Assert.assertEquals(1, rb.first()); START rb.last(); END Assert.assertEquals(x, rb.last()); } } Is this call mandatory ? You are not storing the last value and computing it again on the next line.

Target:
public void testFirstLast_CreateSparseContainersAfterRun() { RoaringBitmap rb = new RoaringBitmap(); rb.add(1L, 1 << 14); for(int i = 18; i < 31; ++i) { int x = 1 << i; rb.add(x); Assert.assertEquals(1, rb.first()); Assert.assertEquals(x, rb.last()); } }
Source:
public static Container full() { START return new RunContainer(1, new short[]{0, -1, 0, 0, 0, 0, 0, 0}); END } What's the point of the 6 trailing zeros ?

Target:
public static Container full() { return new RunContainer(1, new short[]{0, -1}); }
Source:
public void reportsRequestResult() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("", ""); START final Talk talk = ReportsTest.example(repo, issue); END final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); } @xupyprmv inline this one as well

Target:
public void reportsRequestResult() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Talk talk = ReportsTest.example( repo, repo.issues().create("", "") ); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); }
Source:
public String author() { try { START return new JdkRequest(URI.create(this.url)) END .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) .method(Request.GET).fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json() .readObject() .getJsonObject("author") .getString("name"); } catch (IOException ex) { throw new IllegalStateException(ex); } } No need to do this, just `this.url` is enough

Target:
public String author() { try { return new JdkRequest(this.url) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json() .readObject() .getJsonObject("author") .getString("name"); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); START font(env, "http://img.rultor.com/rultor.ttf"); END // @checkstyle LineLength (1 line) font(env, "http://img.rultor.com/helveticaneue.ttf"); } Should be `this.font()`, and the same on the next line

Target:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); this.font(env, "http://img.rultor.com/rultor.ttf"); this.font(env, "http://img.rultor.com/helveticaneue.ttf"); }
Source:
public final void authenticateURN() { final AuthKeys authKeys = new AuthKeys(); final String user = "urn:git:rultor"; final String password = "test"; MatcherAssert.assertThat( START authKeys.authenticate(user, password) END .name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); } What happened here with indentation? Why `Matchers.equalTo()` is indented by 8 chars instead of 4?

Target:
public final void authenticateURN() throws Exception { final AuthKeys authKeys = new AuthKeys(); MatcherAssert.assertThat( authKeys.authenticate("urn:git:rultor", "test").name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); }
Source:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); START if (this.user != null) { END src.setUser("postgres"); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; } Why not set it to `postgres` in ctor?

Target:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); if (this.user != null) { src.setUser(this.user); } src.setPassword(this.password); src.setPartitionCount(Tv.THREE); src.setMaxConnectionsPerPartition(1); src.setMinConnectionsPerPartition(1); src.setAcquireIncrement(1); src.setDisableConnectionTracking(true); return src; }
Source:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); START env.close(); END MatcherAssert.assertThat( env.toString(), Matchers .containsString( "EC2 `instance` instance accessed with Mock for EC2Client" ) ); } You're testing two completely separate features of the class: 1) closing of environment, 2) converting environment to string. There should be two separate test methods. This anti-pattern is sometimes called "Test it all" (http://stackoverflow.com/questions/333682/tdd-anti-patterns-catalogue)

Target:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); env.close(); }
Source:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { START for (String inode : contentTypesSet) { END structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } } set to final

Target:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { for (final String inode : contentTypesSet) { structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }
Source:
START public SaveContentAsDraftActionlet( END final ContentletAPI contentletAPI, final CategoryAPI categoryAPI, final PermissionAPI permissionAPI ) { this.contentletAPI = contentletAPI; this.categoryAPI = categoryAPI; this.permissionAPI = permissionAPI; } I think this constructor doesn't need to be public

Target:
SaveContentAsDraftActionlet( final ContentletAPI contentletAPI, final CategoryAPI categoryAPI, final PermissionAPI permissionAPI ) { super(); this.contentletAPI = contentletAPI; this.categoryAPI = categoryAPI; this.permissionAPI = permissionAPI; }
Source:
public ContentType getContentType() { final ContentType contentType; try { contentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(contentTypeId); return contentType; START } catch (final DotSecurityException e) { END Logger.error(this, String.format("An error occurred when returning the Content Type associated to " + "Contentlet '%s'", this.getIdentifier())); } catch (final DotDataException e) { Logger.error(this, String.format("An error occurred when returning the Content Type associated to " + "Contentlet '%s'", this.getIdentifier())); } return null; } better: ```suggestion } catch (final DotSecurityException | DotDataException e) { ... ```

Target:
public ContentType getContentType() { final ContentType contentType; try { contentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(contentTypeId); return contentType; } catch (final DotSecurityException | DotDataException e) { Logger.error(this, String.format("An error occurred when returning the Content Type associated to " + "Contentlet '%s'", this.getIdentifier())); } return null; }
Source:
private boolean areFileassetFieldsPresent(final GraphQLObjectType objectType) { START List<String> fileAssetFields = list(FILEASSET_FILE_NAME_FIELD_VAR, END FILEASSET_DESCRIPTION_FIELD_VAR, FILEASSET_FILEASSET_FIELD_VAR, FILEASSET_METADATA_FIELD_VAR, FILEASSET_SHOW_ON_MENU_FIELD_VAR, FILEASSET_SORT_ORDER_FIELD_VAR); return objectType.getFieldDefinitions().stream().allMatch((fieldDefinition -> fileAssetFields.contains(fieldDefinition.getName()))); } ![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Local variable 'fileAssetFields' could be declared final](https://app.codacy.com/manual/dotCMS/core/pullRequest?prid=5028723)

Target:
private boolean areFileassetFieldsPresent(final GraphQLObjectType objectType) { final List<String> fileAssetFields = list(FILEASSET_FILE_NAME_FIELD_VAR, FILEASSET_DESCRIPTION_FIELD_VAR, FILEASSET_FILEASSET_FIELD_VAR, FILEASSET_METADATA_FIELD_VAR, FILEASSET_SHOW_ON_MENU_FIELD_VAR, FILEASSET_SORT_ORDER_FIELD_VAR); return objectType.getFieldDefinitions().stream().allMatch(fieldDefinition -> fileAssetFields.contains(fieldDefinition.getName())); }
Source:
START public VelocityNavigateEditMode( END final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); } The constructor signature changed here too

Target:
protected VelocityNavigateEditMode( final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); }
Source:
private void addCustomMapping(final String indexName) { final RelationshipAPI relationshipAPI = APILocator.getRelationshipAPI(); final Set<String> mappedRelationships = addCustomMappingFromFieldVariables(indexName, relationshipAPI); START END addCustomMappingForRelationships(indexName, relationshipAPI, mappedRelationships); } why passing `relationshipAPI` as attribute?

Target:
private void addCustomMapping(final String indexName) { final Set<String> mappedRelationships = addCustomMappingFromFieldVariables(indexName); addCustomMappingForRelationships(indexName, mappedRelationships); }
Source:
public Optional<char[]> getValue(final String variableKey) { START char[] fromCache = getFromCache(variableKey, END () -> loadValueFromStore(variableKey)); return Arrays.equals(fromCache, CACHE_404) ? Optional.empty() : Optional.ofNullable(decrypt(fromCache)); } Don't we need to use `.toLowerCase()`?, I thought the keys where saved lowercase in the keystore.

Target:
public Optional<char[]> getValue(final String variableKey) { final char[] fromCache = getFromCache(variableKey, () -> loadValueFromStore(variableKey)); return Arrays.equals(fromCache, CACHE_404) ? Optional.empty() : Optional.ofNullable(decrypt(fromCache)); }
Source:
public void deleteBundleAndDependencies(final String bundleId, final User user) throws DotDataException { final Bundle bundle = this.getBundleById(bundleId); if (null != bundle) { this.internalDeleteBundleAndDependencies(bundleId, user); } else { START END throw new NotFoundInDbException("The bundle id: " + bundleId + " does not exists"); } } Please log the bundle ID here.

Target:
public void deleteBundleAndDependencies(final String bundleId, final User user) throws DotDataException { final Bundle bundle = this.getBundleById(bundleId); if (null != bundle) { this.internalDeleteBundleAndDependencies(bundleId, user); } else { Logger.error(this,"The bundle id: " + bundleId + " does not exists"); throw new NotFoundInDbException("The bundle id: " + bundleId + " does not exists"); } }
Source:
public void deletePublishAuditStatus(final String bundleId) throws DotPublisherException { try { Logger.info(this, "Deleting the bundle: " + bundleId); new DotConnect() .setSQL(DELETE_BY_BUNDLEID) .addParam(bundleId) .loadResult(); } catch(Exception e) { START Logger.error(PublishAuditAPIImpl.class, e.getMessage(), e); END throw new DotPublisherException( "Unable to remove element in publish queue audit table:" + "with the following bundle_id "+bundleId+" "+ e.getMessage(), e); } } Please log Bundle ID data here.

Target:
public void deletePublishAuditStatus(final String bundleId) throws DotPublisherException { try { Logger.info(this, "Deleting the bundle: " + bundleId); new DotConnect() .setSQL(DELETE_BY_BUNDLEID) .addParam(bundleId) .loadResult(); } catch(Exception e) { Logger.error(PublishAuditAPIImpl.class, "Unable to remove element in publish queue audit table:" + "with the following bundle_id "+bundleId, e); throw new DotPublisherException( "Unable to remove element in publish queue audit table:" + "with the following bundle_id "+bundleId+" "+ e.getMessage(), e); } }
Source:
public TestCase(final String name, final Object fieldValue, final String values, final Object expectedValue, final Class fieldType) { this.name = name; this.fieldValue = fieldValue; this.values = values; this.fieldType = fieldType; START this.expectedValue = expectedValue; END } Put these two assignments in order so it's clearer

Target:
public TestCase(final String name, final Object fieldValue, final String values, final Object expectedValue, final Class fieldType) { this.name = name; this.fieldValue = fieldValue; this.values = values; this.expectedValue = expectedValue; this.fieldType = fieldType; }
Source:
public static java.util.Collection<Portlet> getPortlets(final java.lang.String companyId) throws com.liferay.portal.SystemException { try { final PortletFactory portletFactory = PortletManagerFactory.getManager(); return portletFactory.getPortlets(); } catch (final com.liferay.portal.SystemException se) { START throw se; END } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } } I think this catch is not necessary because on the next lines we have ``` } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } ```

Target:
public static java.util.Collection<Portlet> getPortlets(final java.lang.String companyId) throws com.liferay.portal.SystemException { try { final PortletFactory portletFactory = PortletManagerFactory.getManager(); return portletFactory.getPortlets(); } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } }
Source:
public void removePageMultiTrees(final String pageIdentifier) { for (final String group : getGroups()) { START removePageMultiTrees(pageIdentifier, group); END } } this could be in a simple expression, like: `getGroups().forEach(group -> removePageMultiTrees(pageIdentifier, group));`

Target:
public void removePageMultiTrees(final String pageIdentifier) { Arrays.asList(getGroups()).forEach(group -> removePageMultiTrees(pageIdentifier, group)); }
Source:
public void clearCache() { DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); START for (final String group : getGroups()) { END cache.flushGroup(group); } } this can be replaced by `getGroups().forEach(group -> cache.flushGroup(group));`

Target:
public void clearCache() { Arrays.asList(getGroups()).forEach(group -> cache.flushGroup(group)); }
Source:
public Category findByVariable(final String variable, final User user, final boolean respectFrontendRoles) throws DotDataException, DotSecurityException { final Category category = categoryFactory.findByVar(variable); START if(!InodeUtils.isSet(category.getCategoryId())) END return null; if(!permissionAPI.doesUserHavePermission(category, PermissionAPI.PERMISSION_USE, user, respectFrontendRoles)) throw new DotSecurityException("User doesn't have permission to use this category = " + category.getInode()); return category; } always use curly brackets even if it is just one line

Target:
public Category findByVariable(final String variable, final User user, final boolean respectFrontendRoles) throws DotDataException, DotSecurityException { final Category category = categoryFactory.findByVar(variable); if(!InodeUtils.isSet(category.getCategoryId())) { return null; } if(!permissionAPI.doesUserHavePermission(category, PermissionAPI.PERMISSION_USE, user, respectFrontendRoles)) { throw new DotSecurityException("User doesn't have permission to use this category = " + category.getInode()); } return category; }
Source:
private List<Map<String,String>> findAllLangContentlets(final String contentletIdentifier){ return conAPI.findAllLangContentlets(contentletIdentifier).stream().map(contentlet -> { START final Map <String,String> map = new HashMap<>(); END map.put("inode",contentlet.getInode()); map.put("languageId",contentlet.getLanguageId()+""); return map; }).collect(CollectionsUtils.toImmutableList()); } you can use ``` return CollectionUtils.map("inode",contentlet.getInode(),"languageId",contentlet.getLanguageId()+""); ```

Target:
private List<Map<String,String>> findAllLangContentlets(final String contentletIdentifier){ return conAPI.findAllLangContentlets(contentletIdentifier).stream().map(contentlet -> { return map("inode",contentlet.getInode(), "languageId",contentlet.getLanguageId()+""); }).collect(toImmutableList()); }
Source:
public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { final Template template = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); assertNull(template); } catch(NullPointerException e) { START Logger.error(this, "getting non-existant template should not throw an NPE", e); END } } Shouldn't the test fail under this scenario? I will pass according to code @erickgonzalez

Target:
public void testFindWorkingTemplateNoNPE() throws DotDataException, DotSecurityException { try { final Template template = templateAPI.findWorkingTemplate("NO_TEMPLATE", APILocator.getUserAPI().getSystemUser(), false); assertNull(template); } catch(NullPointerException e) { Logger.error(this, "getting non-existant template should not throw an NPE", e); assertTrue("getting non-existant template should not throw an NPE", false); } }
Source:
private static String removeQueryPrefix(final String luceneQuery){ START final String cleanedUpQuery; END if(luceneQuery.startsWith("query_")){ cleanedUpQuery = luceneQuery.replace( "query_", StringPool.BLANK); } else { cleanedUpQuery = luceneQuery; } return cleanedUpQuery; } you can use return (luceneQuery.startsWith("query_"))?luceneQuery.replace( "query_", StringPool.BLANK): luceneQuery; it is just a style, up to you

Target:
private static String removeQueryPrefix(final String luceneQuery) { return (luceneQuery.startsWith("query_") ? luceneQuery.replace("query_", StringPool.BLANK) : luceneQuery ); }
Source:
public boolean isInodeIndexedArchived(String inode){ if (!UtilMethods.isSet(inode)) { Logger.warn(this, "Requested Inode is not indexed because Inode is not set"); } START return isInodeIndexedWithQuery("+inode:" + inode + String.format(" +deleted:%s",true)); END } I think the existing `isInodeIndexedWithQuery` could call the new `isInodeIndexedArchived` you made.

Target:
public boolean isInodeIndexedArchived(String inode){ return isInodeIndexedArchived(inode, -1); }
Source:
private void sendDeleteEvent (final Contentlet contentlet) throws DotHibernateException { HibernateUtil.addAsyncCommitListener( () -> { START this.isInodeIndexed(contentlet.getInode()); END this.contentletSystemEventUtil.pushDeleteEvent(contentlet); }, 1000); } If this event is fired after a delete operation what is the **isInodeIndexed** method validating?

Target:
private void sendDeleteEvent (final Contentlet contentlet) throws DotHibernateException { HibernateUtil.addAsyncCommitListener( () -> { this.contentletSystemEventUtil.pushDeleteEvent(contentlet); }, 1000); }
Source:
public List<ContentType> findContentTypesForScheme(final WorkflowScheme workflowScheme) { if (!SYSTEM_WORKFLOW_ID.equals(workflowScheme.getId())) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new InvalidLicenseException("Workflow-Schemes-License-required"); } } try { return workFlowFactory.findContentTypesByScheme(workflowScheme); }catch(Exception e){ START throw new DoesNotExistException(e); END } } probably need to log it

Target:
public List<ContentType> findContentTypesForScheme(final WorkflowScheme workflowScheme) { if (!SYSTEM_WORKFLOW_ID.equals(workflowScheme.getId())) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new InvalidLicenseException("Workflow-Schemes-License-required"); } } try { return workFlowFactory.findContentTypesByScheme(workflowScheme); }catch(Exception e){ Logger.debug(this,e.getMessage(),e); throw new DoesNotExistException(e); } }
Source:
private boolean hasAnyRolePermission(final WorkflowAction wa,final Iterable<Role> roles) throws DotDataException{ START for(Role role:roles){ END if (permissionAPI.doesRoleHavePermission(wa, PermissionAPI.PERMISSION_USE, role)) { return true; } } return false; } set to final

Target:
private boolean hasAnyRolePermission(final WorkflowAction wa,final Iterable<Role> roles) throws DotDataException{ for(final Role role:roles){ if (permissionAPI.doesRoleHavePermission(wa, PermissionAPI.PERMISSION_USE, role)) { return true; } } return false; }
Source:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { START return HTMLPageAssetRenderedBuilder.get() END .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); } this is not the right way to do the builder, it should be a separated class such as new HTMLPageAssetRenderedBuilder().htmlPageAsset(page).user(user).request(request).....build()

Target:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { return new HTMLPageAssetRenderedBuilder() .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }
Source:
User getUser() { User user = null; START HttpSession session = request.getSession(false); END if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; } set to final

Target:
User getUser() { User user = null; final HttpSession session = request.getSession(false); if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }
Source:
public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } finally { // The main reason for this abstraction is to ensure that the // database connection is released and closed after executing this try { START HibernateUtil.closeSession(); END } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } } shouldn't be removed this one HibernateUtil.closeSession(); too?

Target:
public void execute(JobDelegateDataBean data) { try { executeDelegate(data); } catch (Exception e) { Logger.error(this, "An error occurred when running the Job Delegate: " + this.getClass(), e); } }
Source:
private static String toLuceneDateTime(Date date) { try { START SimpleDateFormat df = new SimpleDateFormat(LUCENE_DATE_TIME_FORMAT); END String returnValue = df.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } } Can this be a constant?

Target:
private static String toLuceneDateTime(Date date) { try { String returnValue = LUCENE_DATE_TIME_FORMAT.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }
Source:
public boolean isNextStepCurrentStep() { START return null == this.getNextStep() || END CURRENT_STEP.equalsIgnoreCase(this.getNextStep()); } do you need the null check here? I don't think so.

Target:
public boolean isNextStepCurrentStep() { return CURRENT_STEP.equalsIgnoreCase(this.getNextStep()); }
Source:
START public final static VelocityModeHandler modeHandler(PageMode mode, HttpServletRequest request, HttpServletResponse response) { END switch (mode) { case PREVIEW_MODE: return new VelocityPreviewMode(request, response); case EDIT_MODE: return new VelocityEditMode(request, response); default: return new VelocityLiveMode(request, response); } } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Reorder the modifiers to comply with the Java Language Specification. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AModifiersOrderCheck)

Target:
public static final VelocityModeHandler modeHandler(PageMode mode, HttpServletRequest request, HttpServletResponse response) { switch (mode) { case PREVIEW_MODE: return new VelocityPreviewMode(request, response); case EDIT_MODE: return new VelocityEditMode(request, response); default: return new VelocityLiveMode(request, response); } }
Source:
public ContentType find(final String inodeOrVar) throws DotSecurityException, DotDataException { START if(!UtilMethods.isSet(inodeOrVar))return null; END final ContentType type = this.contentTypeFactory.find(inodeOrVar); if (perms.doesUserHavePermission(type, PermissionAPI.PERMISSION_READ, user)) { return type; } throw new DotSecurityException("User " + user + " does not have READ permissions on ContentType " + type); } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Missing curly brace. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS00121) ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') At most one statement is allowed per line, but 2 statements were found on this line. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS00122)

Target:
public ContentType find(final String inodeOrVar) throws DotSecurityException, DotDataException { if(!UtilMethods.isSet(inodeOrVar)) { return null; } final ContentType type = this.contentTypeFactory.find(inodeOrVar); if (perms.doesUserHavePermission(type, PermissionAPI.PERMISSION_READ, user)) { return type; } throw new DotSecurityException("User " + user + " does not have READ permissions on ContentType " + type); }
Source:
abstract void serve() throws Exception; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { START StringWriter out = new StringWriter(4096); END try { serve(out); } catch (Exception e) { throw new DotRuntimeException(e); } return out.toString(); } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Assign this magic number 4096 to a well-named constant, and use the constant instead. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS109)

Target:
abstract void serve() throws DotDataException, IOException, DotSecurityException; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (DotDataException | IOException | DotSecurityException e) { throw new DotRuntimeException(e); } return out.toString(); }
Source:
public MultiTreeTransformer(List<Map<String, Object>> initList){ START List<MultiTree> newList = new ArrayList<>(); END if (initList != null){ for(Map<String, Object> map : initList){ newList.add(transform(map)); } } this.list = newList; } Consider to use an ImmutableList here

Target:
public MultiTreeTransformer(List<Map<String, Object>> initList){ if (initList != null){ for(Map<String, Object> map : initList){ this.list.add(transform(map)); } } }
Source:
START public String draw () throws Exception { END StringBuffer sb = new StringBuffer(); if ( this.containers != null ) { for ( String container: this.containers ) { if ( this.preview ) { sb.append( PreviewTemplateUtil.getMockBodyContent() ); } else { sb.append( "#parseContainer('" ).append( container ).append( "')" ); } } } return sb.toString(); } it looks like logic in a Value object, the concern should be separated

Target:
public String draw () throws Exception { final StringBuilder sb = new StringBuilder(); if ( this.containers != null ) { for ( final String container: this.containers ) { if ( this.preview ) { sb.append( PreviewTemplateUtil.getMockBodyContent() ); } else { sb.append( "#parseContainer('" ).append( container ).append( "')" ); } } } return sb.toString(); }
Source:
public String getPath(){ START if(getAssetName().equals("system folder") && getParentPath().equals("/System folder")) END return "/"; else { String x = getParentPath() + getAssetName(); if("folder".equals(assetType)){ if(! x.endsWith("/")){ x= x + "/"; } } return x; } } you might want to use constants and the constant in the left side, such as SYSTEM_FOLDER.equals(getAssetName())

Target:
public String getPath(){ if(("system folder").equals(getAssetName()) && ("/System folder").equals(getParentPath())){ return "/"; } else { String x = getParentPath() + getAssetName(); if("folder".equals(assetType)){ if(! x.endsWith("/")){ x= x + "/"; } } return x; } }
Source:
public Date getLastHeartBeat() { START return lastHeartBeat; END } return defensive copy "new Date(lastHeartBeat.getTime())" to make it immutable

Target:
public Date getLastHeartBeat() { return new Date(lastHeartBeat); }
Source:
public String getContentTypeFieldLabelKey(){ String legacyName = LegacyFieldTypes.getLegacyName(this.getClass()); START String key = legacyName.substring(0, 1).toUpperCase() + legacyName.substring(1); END return key; } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Immediately return this expression instead of assigning it to the temporary variable "key". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1488)

Target:
public String getContentTypeFieldLabelKey(){ String legacyName = LegacyFieldTypes.getLegacyName(this.getClass()); return legacyName.substring(0, 1).toUpperCase() + legacyName.substring(1); }
Source:
public boolean unsubscribe(final Object subscriber) { final AtomicBoolean unsubscribed = new AtomicBoolean(false); final Map<Class<?>, EventSubscriber> subscriberMap = this.eventSubscriberFinder.findSubscribers(subscriber); if (null != subscriberMap && !subscriberMap.isEmpty()) { subscriberMap.forEach((eventType, eventSubscriber) -> START unsubscribed.set( unsubscribed.get() | this.unsubscribe(eventType, eventSubscriber.getId()) )); END } return unsubscribed.get(); } ![BLOCKER](https://sonarsource.github.io/sonar-github/severity-blocker.png 'Severity: BLOCKER') Correct this "|" to "||". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS2178)

Target:
public boolean unsubscribe(final Object subscriber) { final AtomicBoolean unsubscribed = new AtomicBoolean(false); final Map<Class<?>, EventSubscriber> subscriberMap = this.eventSubscriberFinder.findSubscribers(subscriber); if (null != subscriberMap && !subscriberMap.isEmpty()) { subscriberMap.forEach((eventType, eventSubscriber) -> unsubscribed.set( unsubscribed.get() || this.unsubscribe(eventType, eventSubscriber.getId()) )); } return unsubscribed.get(); }
Source:
protected List<String> getTablesToDropConstraints() { // TODO Auto-generated method stub START return null; END } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Return an empty collection instead of null. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1168)

Target:
protected List<String> getTablesToDropConstraints() { return new ArrayList<>(); }
Source:
private String findHostLang(String hostId) throws DotDataException{ DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTLANG_BY_ID_QUERY); dc.addParam(hostId); List<Map<String,String>> hostLang = dc.loadResults(); START return hostLang.get(0).get("language_id").toString(); END } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') "get" returns a string, there's no need to call "toString()". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1858)

Target:
private String findHostLang(String hostId) throws DotDataException { DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTLANG_BY_ID_QUERY); dc.addParam(hostId); List<Map<String, String>> hostLang = dc.loadResults(); return hostLang.get(0).get("language_id"); }
Source:
public void initializeVanityUrlCache(String hostId, long languageId) { List<VanityUrl> activeVanityUrls = APILocator.getVanityUrlAPI() .getActiveVanityUrlsByHostAndLanguage(hostId, languageId, APILocator.systemUser()); START activeVanityUrls.stream().forEach((VanityUrl vanity) -> updateCache(vanity)); END } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.) [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1612)

Target:
public void initializeVanityUrlCache(String hostId, long languageId) { List<VanityUrl> activeVanityUrls = APILocator.getVanityUrlAPI() .getActiveVanityUrlsByHostAndLanguage(hostId, languageId, APILocator.systemUser()); activeVanityUrls.forEach(this::updateCache); }
Source:
public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); START Host host = null; END if (hostId != null) { host = hostAPI.find(hostId, user, false); } return host; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } } you can reduce it to (null != hostId)?hostAPI.find(hostId, user, false):null;

Target:
public Host getCurrentSite(final HttpServletRequest req, final User user) { try { final HttpSession session = req.getSession(); String hostId = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); return (null != hostId) ? hostAPI.find(hostId, user, false) : null; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }
Source:
START public void testGetFolderContentWithInvalidIdentifier() throws Exception { // https://github.com/dotCMS/core/issues/11829 END final String NOT_EXISTING_ID = "01234567-1234-1234-1234-123456789012"; try { browserAPI.getFolderContent( APILocator.systemUser(), NOT_EXISTING_ID, 0, -1, "", null, null, true, false, false, false, "", false, false, 1 ); } catch ( Exception e ){ Assert.assertTrue( e instanceof NotFoundInDbException ); } } " throws Exception " can be removed

Target:
public void testGetFolderContentWithInvalidIdentifier() { // https://github.com/dotCMS/core/issues/11829 final String NOT_EXISTING_ID = "01234567-1234-1234-1234-123456789012"; try { browserAPI.getFolderContent( APILocator.systemUser(), NOT_EXISTING_ID, 0, -1, "", null, null, true, false, false, false, "", false, false, 1 ); } catch ( Exception e ){ Assert.assertTrue( e instanceof NotFoundInDbException ); } }
Source:
public String getActionUrl(final ContentType contentType, final User user) { final HttpServletRequest request = httpServletRequestThreadLocal.getRequest(); START String actionUrl = request != null? getActionUrl(request, contentType, user):null; END return actionUrl; } you could change this to return request != null? getActionUrl(request, contentType, user):null;

Target:
public String getActionUrl(final ContentType contentType, final User user) { final HttpServletRequest request = httpServletRequestThreadLocal.getRequest(); return request != null ? getActionUrl(request, contentType, user):null; }
Source:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ // Register main service BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { START Logger.debug(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); END } } } @jdotcms please instead of a debug let's change it to error, if we are trying to register something with OSGI and we can not do it we want to be noisy about it and know the reason.

Target:
public void registerBundleService () { if(System.getProperty(WebKeys.OSGI_ENABLED)!=null){ // Register main service BundleContext context = HostActivator.instance().getBundleContext(); if (null != context) { Hashtable<String, String> props = new Hashtable<String, String>(); context.registerService(WorkflowAPIOsgiService.class.getName(), this, props); } else { Logger.error(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }
Source:
private List<Class<?>> getVersionableWhitelist() { START List<Class<?>> whitelist = new ArrayList<>(); END whitelist.add(Container.class); whitelist.add(Template.class); whitelist.add(File.class); whitelist.add(HTMLPage.class); return whitelist; } if you want you can use CollectionsUtils, such as list(Container.class, Template.class....); Also it could be a java.util.Set, the contains will be faster than a java.util.List.

Target:
private Set<Class<?>> getVersionableWhitelist() { return set(Container.class, Template.class, File.class, HTMLPage.class); }
Source:
private boolean validPayload(final SessionWrapper session, final Payload payload) { //Get the verifier associated to this Payload final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); START if ( null != verifier ) { END //Check if we have the "visibility" rights to use this payload return verifier.verified(payload, session); } return true; } I would change this for a return (null != verifier)? verifier.verified(payload, session): true;

Target:
private boolean validPayload(final SessionWrapper session, final Payload payload) { //Get the verifier associated to this Payload final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); //Check if we have the "visibility" rights to use this payload return (null != verifier) ? verifier.verified(payload, session) : true; }
Source:
public void createSnapshotTest(){ String indexName = getLiveIndex(); File snapshot = null; try { snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); assertNotNull(snapshot); } catch (DotStateException | IllegalArgumentException | IOException e) { e.printStackTrace(); }finally{ START snapshot.delete(); END } } delete if !=null

Target:
public void createSnapshotTest() throws IOException{ String indexName = getLiveIndex(); File snapshot = null; snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); assertNotNull(snapshot); snapshot.delete(); }
Source:
public void updateOwnerReferences ( String userId, String replacementUserId ) throws DotDataException { if(!UtilMethods.isSet(userId) || !UtilMethods.isSet(replacementUserId)) { START return; END } DotConnect dc = new DotConnect(); dc.setSQL(UPDATE_BUNDLE_OWNER_REFERENCES); dc.addParam(replacementUserId); dc.addParam(userId); dc.loadResult(); } shouldn't report an exception or something?

Target:
public void updateOwnerReferences ( String userId, String replacementUserId ) throws DotDataException { DotConnect dc = new DotConnect(); dc.setSQL(UPDATE_BUNDLE_OWNER_REFERENCES); dc.addParam(replacementUserId); dc.addParam(userId); dc.loadResult(); }
Source:
public SystemEvent process(SystemEvent event, Session session) { Payload payload = event.getPayload(); ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = (ContentTypePayloadDataWrapper) payload.getRawData(); Structure structure = contentTypePayloadDataWrapper.getStructure(); START ContentTypeView contentTypeView = ContentTypeView.getInstance(structure, contentTypePayloadDataWrapper.getActionUrl()); END return new SystemEvent(event.getId(), event.getEventType(), new Payload(contentTypeView, payload.getVisibility(), payload.getVisibilityId()), event.getCreationDate()); } The ContentTypeView should be a class attribute instead of getting the instance static.

Target:
public SystemEvent process(SystemEvent event, Session session) { Payload payload = event.getPayload(); ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = (ContentTypePayloadDataWrapper) payload.getRawData(); Structure structure = contentTypePayloadDataWrapper.getStructure(); ContentTypeView contentTypeView = new ContentTypeView(structure, contentTypePayloadDataWrapper.getActionUrl()); return new SystemEvent(event.getId(), event.getEventType(), new Payload(contentTypeView, payload.getVisibility(), payload.getVisibilityId()), event.getCreationDate()); }
Source:
private RestRule getRuleInternal(String ruleId, User user) { Rule input = getRule(ruleId, user); RestRule restRule = ruleTransform.appToRest(input, user); START if(restRule == null) { END throw new NotFoundException("Rule not found: '%s'", ruleId); } return restRule; } the transform should never ever return null. if something changed we need to unchange it. #getRule(...) should throw a NotFoundException if the ruleId isn't present in the database. The transform.appToRest should throw any errors that prevent the method from returning a valid rule.

Target:
private RestRule getRuleInternal(String ruleId, User user) { Rule input = getRule(ruleId, user); RestRule restRule = ruleTransform.appToRest(input, user); return restRule; }