auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testSourceClasspath() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final SpoonModelBuilder.ClasspathOptions options = new SpoonModelBuilder.ClasspathOptions().classpath(systemClasspath); Assert.assertEquals("-cp " + TEST_CLASSPATH, String.join(" ", options.build())); }

Target:
then update doc and command line?
Source:
public void setParams(Collection<?> set) { if (set != null) { this.set = set; elements = set.toArray(); this.hasS = true; prob = set.isEmpty() ? 1 : 1.0 / set.size(); logprob = set.isEmpty() ? 0 : (-Math.log(set.size())); finiteSupport = elements.clone(); } }

Target:
why clone?
Source:
public Object[] getFiniteSupport() { checkHasParams(); return null; }

Target:
remove?
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("UniformChoice("); for (Object item : s) { buffer.append(item.toString() + ", "); } buffer.replace(buffer.length() - 2, buffer.length(), ""); buffer.append(")"); return buffer.toString(); }

Target:
@chrisgioia64 Pls use `StringBuilder`, which is faster!
Source:
public static double beta(double a, double b) { return ((Gamma.gamma(a) * Gamma.gamma(b)) / Gamma.gamma(a + b)); }

Target:
this should be private static function.
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FunctionSignature other = (FunctionSignature) obj; return Arrays.equals(argTypes, other.argTypes) && name.equals(other.name); }

Target:
I think you can swap the order of the conjuncts because `name.equals(other.name)` is less expensive.
Source:
public void addPackages(List<String> pkgs) { for (String pkg: pkgs) { packages.add(pkg); } }

Target:
could use ``` java packages.addAll(pkgs); ```
Source:
public static int parseInt(String s, Dimension dimension) throws NumberFormatException { switch (dimension) { case NOT: case SIZE: return parseInt(s); case DURATION: try { long durationInMillis = TimeUtil.toMillis(s); if ((int) durationInMillis == durationInMillis) { return (int) durationInMillis; } throw new ArithmeticException("integer overflow"); } catch (NumberFormatException e) { return parseInt(s); } } throw new AssertionError("Unknown dimension " + dimension); }

Target:
shouldn’t the NumberFormatException be caught where the method is used — and for example lead to ignoring he new value?
Source:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); if (validator.test(value)) { throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }

Target:
A validator should return `true`if the given value is valid, something needs to be the other way around here. :)
Source:
public synchronized int getFirst() { if (data.isEmpty()) { return -1; } return data.get(0); }

Target:
`return data.isEmpty() ? -1 : data.get(0);`?
Source:
public synchronized int getLast() { if (data.isEmpty()) { return -1; } return data.get(data.size() - 1); }

Target:
Here I would also prefer a one-liner with a ternary operator.
Source:
private void assertSorted(int[] input) { if (input.length < 2) { return; } for (int i = 1; i < input.length; i++) { if (input[i-1] > input[i]) { throw new IllegalStateException("Input must be sorted"); } } }

Target:
`<= 1` seems to be clearer than `< 2`…
Source:
public void writeFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams, FilterCallback cb) throws DataFilterException, IOException { output.write(input.read()); return; }

Target:
What exact purpose does this `return` have here?
Source:
public int queuedJobsUniqueTimes() { synchronized(timedJobsByTime) { return timedJobsByTime.size(); } }

Target:
I don't think this should be part of the public API. Do we need this outside of unit tests? If not, please make it package-private.
Source:
public boolean showSearchBox() { // Only show it if Library is loaded. if (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")) { return true; } else { return false; } }

Target:
if (a) then return true else return false? Are you kidding me? :)
Source:
public boolean hasIV(){ if(ivSize != null){ return true; } return false; }

Target:
Is there a reason not to replace this method body with ``` return ivSize != null; ```
Source:
private CryptByteBufferType(int bitmask, KeyType keyType, int blockSize){ this.bitmask = bitmask; this.ivSize = -1; this.keyType = keyType; this.cipherName = keyType.alg; this.blockSize = blockSize; algName = name(); }

Target:
Should this be set to `null` now?
Source:
public static PublicKey getPublicKey(KeyPairType type, byte[] pub) throws UnsupportedTypeException{ if(type.equals(KeyPairType.DSA)){ throw new UnsupportedTypeException(type); } try { KeyFactory kf = KeyFactory.getInstance(type.alg); X509EncodedKeySpec xks = new X509EncodedKeySpec(pub); return kf.generatePublic(xks); } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; }

Target:
Mind the whitespace, please.
Source:
public static KeyPair genKeyPair(KeyPairType type) throws UnsupportedTypeException{ if(type.equals(KeyPairType.DSA)){ throw new UnsupportedTypeException(type); } try { KeyPairGenerator kg = KeyPairGenerator.getInstance(type.alg); kg.initialize(type.spec); return kg.generateKeyPair(); } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; }

Target:
Any reason for not using the plain old `IllegalArgumentException`? I think the types in `KeyPairType` (except for DSA) should always be present on a Freenet installation, so forcing the user to wrap his code with `try(…) catch(…)` would unnecessarily increase the number of lines in the consuming code.
Source:
public final static boolean verify(HashResult hash1, HashResult hash2){ if(hash1.compareTo(hash2) == 0){ return true; } return false; }

Target:
`HashResult.compareTo(…)` only compares `HashResult.type`, not `HashResult.result` (yes, **that** is wrong, but has not been fixed AFAIK). Also, please compare hashes in a way that is insensitive to timing attacks, `Comparable.compareTo(…)` does not guarantee any such property.
Source:
public int hashCode(){ int hash = 1; hash = hash * 31 + type.hashCode(); hash = hash * 31 + result.hashCode(); return hash; }

Target:
Where did 31 come from? Why not use `*=`?
Source:
public void testVerifyByteArrayByteArray() { for(int i = 0; i < types.length; i++){ Hash hash = new Hash(types[i]); boolean verified = hash.verify(Hex.decode(trueHashes[i]), helloWorld); assertTrue("HashType: "+types[i].name(), verified); } }

Target:
Some places have this separate boolean to assert on and others put the entire condition in the assert statement. It seems preferable to use one consistently. Which one?
Source:
private void closeRAF() { if(!(closed || lockLevel == 0)) throw new IllegalStateException(); if(raf == null) return; try { raf.close(); } catch (IOException e) { Logger.error(this, "Error closing "+this+" : "+e, e); } raf = null; OPEN_FDS--; }

Target:
Writing this as `if(!closed && lockLevel != 0)` instead of the negated disjunction allows for easier recognition of exactly when this condition actually holds.
Source:
public boolean isDefaultValue() { if(this.equals(FRIEND_TRUST.NORMAL)) return true; else return false; }

Target:
Can this be reduced to `return equals(FRIEND_TRUST.NORMAL)`?
Source:
public int hashCode() { // see #equals return element.hashCode(); }

Target:
What I'm missing here is the check if the element is null. I know that the probability is very low, but still...
Source:
public Tool getExecutable() { for (Tool t : Tool.EMULATORS) { if (t.getExecutable(true).equals(executable)) { return t; } } return Tool.EMULATOR; }

Target:
I imagine this should be `!Functions.isWindows()`, rather than being hardcoded to `true`.
Source:
protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); if ( !parameterTaint.isSafe() || (parameterTaint.getConstantValue() != null && parameterTaint.getConstantValue().toLowerCase().equals(VULNERABLE_CONTENT_TYPE)) ) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY; }

Target:
of simply : `if(!parameterTaint.isSafe() || VULNERABLE_CONTENT_TYPE.equalsIgnoreCase(parameterTaint.getConstantValue())) {`
Source:
public Long getCount() { return countResults; }

Target:
Field and constructor parameters may be renamed as well.
Source:
public final void loginThrowSInvalidPasswordException() throws SPlatformLoginException, SInvalidUserException, SInvalidPasswordException, SInvalidPlatformCredentialsException { final String userName = "userName"; final String password = "pwd"; doThrow(new SInvalidPasswordException("")).when(authenticationService).checkUserCredentials(userName, password); platformLoginServiceImpl.login(userName, password); }

Target:
tests method could only throws Exception, since you already expect which one will bo throwned
Source:
public Actor() { users = new HashSet<String>(); groups = new HashSet<String>(); roles = new HashSet<String>(); memberships = new HashSet<BEntry<String, String>>(); }

Target:
This should be done with field declaration example: ``` java private Set<String> users = new HashSet<>() ```
Source:
public APISession login(final String userName, final String password) throws LoginException { try { return loginInternal(userName, password, null); } catch (final UnknownUserException e) { throw e; } catch (final LoginException e) { throw e; } catch (final Exception e) { throw new LoginException(e); } }

Target:
you shouldn't need it as UnknownUserException extends LoginException
Source:
long flush(final long now) { try { final FlushResult flushResult = this.timeTracker.flush(); return flushResult.getFlushTime(); } catch (Exception e) { if (this.logger.isLoggable(getClass(), TechnicalLogSeverity.WARNING)) { this.logger.log(getClass(), TechnicalLogSeverity.WARNING, "Exception caught while flushing: " + e.getMessage(), e); } } return now; }

Target:
it's strange to delegate to the flush result what is the last flush timestamp, should the flush result return the time to flush and let the thread determine when was it's last flush timestamp
Source:
public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException { try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (SProcessDefinitionReadException | IOException | XMLParseException e) { throw new SProcessDefinitionNotFoundException(e, processDefinitionId); } }

Target:
Leave **SProcessDefinitionReadException** pass, add them in method signature. Convert IOException and XMLParseException into **SProcessDefinitionReadException**
Source:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); if (expression == null) { return expression; } } return null; }

Target:
!= null
Source:
protected Expression getExpressionFromContainer(Container container, long expressionDefinitionId) { if (container != null) { final Expression expression = container.accept(this, expressionDefinitionId); if (expression != null) { return expression; } } return null; }

Target:
same thing ``` java return container != null ? container.accept(this, expressionDefinitionId) : null; ```
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()) { deleteRecordedExchange(exchange); } } } } }

Target:
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 :)
Source:
public RpcClient(Channel channel, String exchange, String routingKey, int timeout) throws IOException { this(channel, exchange, routingKey, "amq.rabbitmq.reply-to", timeout) }

Target:
This does not compile.
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; } else if (teamText.hasFocus() == true) { playerPositionSpinner.requestFocus(); return true; } } return super.onKeyUp(keyCode, event); }

Target:
Should be ``` } else if (teamText.hasFocus()) { ```
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pocketpaint_more_options, menu); presenter.removeMoreOptionsItems(); return true; }

Target:
Please move menu into arguments
Source:
public void removeStandaloneMenuItems(Menu menu) { removeItem(R.id.pocketpaint_nav_save_image); removeItem(R.id.pocketpaint_nav_save_duplicate); removeItem(R.id.pocketpaint_nav_new_image); }

Target:
you are calling `removeItem()`. You should call `menu.removeItem()`. The idea is to not have the menu as a member variable.
Source:
public void restoreFragmentListeners() { FragmentManager fragmentManager = mainActivity.getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentByTag(Constants.COLOR_PICKER_DIALOG_TAG); if (fragment != null) { setupColorPickerDialogListeners((ColorPickerDialog) fragment); } }

Target:
please revert all changes to this file
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)); textSizeSpinner.setSelection(sizes.indexOf(localeNumberFormat.format(textSize))); }

Target:
Does this work? You never add anything to `sizes`
Source:
public GeometricFillTool(Context context, ToolType toolType) { super(context, toolType); setRotationEnabled(ROTATION_ENABLED); setRespectImageBounds(RESPECT_IMAGE_BOUNDS); if (baseShape == null) { baseShape = BaseShape.RECTANGLE; } if (shapeOutlineWidth == 0) { shapeOutlineWidth = 25; } shapeDrawType = ShapeDrawType.FILL; createOverlayBitmap(); createAndSetBitmap(); }

Target:
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.
Source:
public static void init(MainActivity mainActivity, Bitmap first_layer) { instance = new LayersDialog(mainActivity, first_layer); }

Target:
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
Source:
void onPrev(ClickEvent event) { GQuery.console.info("prev"); prev(); }

Target:
Do you want to remove the debug?
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()); rb.last(); Assert.assertEquals(x, rb.last()); } }

Target:
Is this call mandatory ? You are not storing the last value and computing it again on the next line.
Source:
public static Container full() { return new RunContainer(1, new short[]{0, -1, 0, 0, 0, 0, 0, 0}); }

Target:
What's the point of the 6 trailing zeros ?
Source:
public void reportsRequestResult() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("", ""); final Talk talk = ReportsTest.example(repo, issue); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); }

Target:
@xupyprmv inline this one as well
Source:
public String author() { try { return new JdkRequest(URI.create(this.url)) .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); } }

Target:
No need to do this, just `this.url` is enough
Source:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); font(env, "http://img.rultor.com/rultor.ttf"); // @checkstyle LineLength (1 line) font(env, "http://img.rultor.com/helveticaneue.ttf"); }

Target:
Should be `this.font()`, and the same on the next line
Source:
public final void authenticateURN() { final AuthKeys authKeys = new AuthKeys(); final String user = "urn:git:rultor"; final String password = "test"; MatcherAssert.assertThat( authKeys.authenticate(user, password) .name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); }

Target:
What happened here with indentation? Why `Matchers.equalTo()` is indented by 8 chars instead of 4?
Source:
public DataSource get() { final BoneCPDataSource src = new BoneCPDataSource(); src.setDriverClass("org.postgresql.Driver"); src.setJdbcUrl(this.jdbc); if (this.user != null) { 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; }

Target:
Why not set it to `postgres` in ctor?
Source:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); env.close(); MatcherAssert.assertThat( env.toString(), Matchers .containsString( "EC2 `instance` instance accessed with Mock for EC2Client" ) ); }

Target:
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)
Source:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { for (String inode : contentTypesSet) { structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }

Target:
set to final
Source:
public SaveContentAsDraftActionlet( final ContentletAPI contentletAPI, final CategoryAPI categoryAPI, final PermissionAPI permissionAPI ) { this.contentletAPI = contentletAPI; this.categoryAPI = categoryAPI; this.permissionAPI = permissionAPI; }

Target:
I think this constructor doesn't need to be public
Source:
public ContentType getContentType() { final ContentType contentType; try { contentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(contentTypeId); return contentType; } catch (final DotSecurityException e) { 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; }

Target:
better: ```suggestion } catch (final DotSecurityException | DotDataException e) { ... ```
Source:
private boolean areFileassetFieldsPresent(final GraphQLObjectType objectType) { 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()))); }

Target:
![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)
Source:
public 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); }

Target:
The constructor signature changed here too
Source:
private void addCustomMapping(final String indexName) { final RelationshipAPI relationshipAPI = APILocator.getRelationshipAPI(); final Set<String> mappedRelationships = addCustomMappingFromFieldVariables(indexName, relationshipAPI); addCustomMappingForRelationships(indexName, relationshipAPI, mappedRelationships); }

Target:
why passing `relationshipAPI` as attribute?
Source:
public Optional<char[]> getValue(final String variableKey) { char[] fromCache = getFromCache(variableKey, () -> loadValueFromStore(variableKey)); return Arrays.equals(fromCache, CACHE_404) ? Optional.empty() : Optional.ofNullable(decrypt(fromCache)); }

Target:
Don't we need to use `.toLowerCase()`?, I thought the keys where saved lowercase in the keystore.
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 { throw new NotFoundInDbException("The bundle id: " + bundleId + " does not exists"); } }

Target:
Please log the bundle ID here.
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) { Logger.error(PublishAuditAPIImpl.class, e.getMessage(), e); throw new DotPublisherException( "Unable to remove element in publish queue audit table:" + "with the following bundle_id "+bundleId+" "+ e.getMessage(), e); } }

Target:
Please log Bundle ID data here.
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; this.expectedValue = expectedValue; }

Target:
Put these two assignments in order so it's clearer
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) { throw se; } catch (final Exception e) { throw new com.liferay.portal.SystemException(e); } }

Target:
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); } ```
Source:
public void removePageMultiTrees(final String pageIdentifier) { for (final String group : getGroups()) { removePageMultiTrees(pageIdentifier, group); } }

Target:
this could be in a simple expression, like: `getGroups().forEach(group -> removePageMultiTrees(pageIdentifier, group));`
Source:
public void clearCache() { DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); for (final String group : getGroups()) { cache.flushGroup(group); } }

Target:
this can be replaced by `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); 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; }

Target:
always use curly brackets even if it is just one line
Source:
private List<Map<String,String>> findAllLangContentlets(final String contentletIdentifier){ return conAPI.findAllLangContentlets(contentletIdentifier).stream().map(contentlet -> { final Map <String,String> map = new HashMap<>(); map.put("inode",contentlet.getInode()); map.put("languageId",contentlet.getLanguageId()+""); return map; }).collect(CollectionsUtils.toImmutableList()); }

Target:
you can use ``` return CollectionUtils.map("inode",contentlet.getInode(),"languageId",contentlet.getLanguageId()+""); ```
Source:
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); } }

Target:
Shouldn't the test fail under this scenario? I will pass according to code @erickgonzalez
Source:
private static String removeQueryPrefix(final String luceneQuery){ final String cleanedUpQuery; if(luceneQuery.startsWith("query_")){ cleanedUpQuery = luceneQuery.replace( "query_", StringPool.BLANK); } else { cleanedUpQuery = luceneQuery; } return cleanedUpQuery; }

Target:
you can use return (luceneQuery.startsWith("query_"))?luceneQuery.replace( "query_", StringPool.BLANK): luceneQuery; it is just a style, up to you
Source:
public boolean isInodeIndexedArchived(String inode){ if (!UtilMethods.isSet(inode)) { Logger.warn(this, "Requested Inode is not indexed because Inode is not set"); } return isInodeIndexedWithQuery("+inode:" + inode + String.format(" +deleted:%s",true)); }

Target:
I think the existing `isInodeIndexedWithQuery` could call the new `isInodeIndexedArchived` you made.
Source:
private void sendDeleteEvent (final Contentlet contentlet) throws DotHibernateException { HibernateUtil.addAsyncCommitListener( () -> { this.isInodeIndexed(contentlet.getInode()); this.contentletSystemEventUtil.pushDeleteEvent(contentlet); }, 1000); }

Target:
If this event is fired after a delete operation what is the **isInodeIndexed** method validating?
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){ throw new DoesNotExistException(e); } }

Target:
probably need to log it
Source:
private boolean hasAnyRolePermission(final WorkflowAction wa,final Iterable<Role> roles) throws DotDataException{ for(Role role:roles){ if (permissionAPI.doesRoleHavePermission(wa, PermissionAPI.PERMISSION_USE, role)) { return true; } } return false; }

Target:
set to final
Source:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { return HTMLPageAssetRenderedBuilder.get() .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }

Target:
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()
Source:
User getUser() { User user = null; HttpSession session = request.getSession(false); if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }

Target:
set to final
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 { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.warn(this, e.getMessage(), e); } } }

Target:
shouldn't be removed this one HibernateUtil.closeSession(); too?
Source:
private static String toLuceneDateTime(Date date) { try { SimpleDateFormat df = new SimpleDateFormat(LUCENE_DATE_TIME_FORMAT); String returnValue = df.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }

Target:
Can this be a constant?
Source:
public boolean isNextStepCurrentStep() { return null == this.getNextStep() || CURRENT_STEP.equalsIgnoreCase(this.getNextStep()); }

Target:
do you need the null check here? I don't think so.
Source:
public final static 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); } }

Target:
![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)
Source:
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); }

Target:
![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)
Source:
abstract void serve() throws Exception; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (Exception e) { throw new DotRuntimeException(e); } return out.toString(); }

Target:
![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)
Source:
public MultiTreeTransformer(List<Map<String, Object>> initList){ List<MultiTree> newList = new ArrayList<>(); if (initList != null){ for(Map<String, Object> map : initList){ newList.add(transform(map)); } } this.list = newList; }

Target:
Consider to use an ImmutableList here
Source:
public String draw () throws Exception { 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(); }

Target:
it looks like logic in a Value object, the concern should be separated
Source:
public String getPath(){ if(getAssetName().equals("system folder") && getParentPath().equals("/System folder")) return "/"; else { String x = getParentPath() + getAssetName(); if("folder".equals(assetType)){ if(! x.endsWith("/")){ x= x + "/"; } } return x; } }

Target:
you might want to use constants and the constant in the left side, such as SYSTEM_FOLDER.equals(getAssetName())
Source:
public Date getLastHeartBeat() { return lastHeartBeat; }

Target:
return defensive copy "new Date(lastHeartBeat.getTime())" to make it immutable
Source:
public String getContentTypeFieldLabelKey(){ String legacyName = LegacyFieldTypes.getLegacyName(this.getClass()); String key = legacyName.substring(0, 1).toUpperCase() + legacyName.substring(1); return key; }

Target:
![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)
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) -> unsubscribed.set( unsubscribed.get() | this.unsubscribe(eventType, eventSubscriber.getId()) )); } return unsubscribed.get(); }

Target:
![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)
Source:
protected List<String> getTablesToDropConstraints() { // TODO Auto-generated method stub return null; }

Target:
![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)
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(); return hostLang.get(0).get("language_id").toString(); }

Target:
![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)
Source:
public void initializeVanityUrlCache(String hostId, long languageId) { List<VanityUrl> activeVanityUrls = APILocator.getVanityUrlAPI() .getActiveVanityUrlsByHostAndLanguage(hostId, languageId, APILocator.systemUser()); activeVanityUrls.stream().forEach((VanityUrl vanity) -> updateCache(vanity)); }

Target:
![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)
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); Host host = null; if (hostId != null) { host = hostAPI.find(hostId, user, false); } return host; } catch (DotDataException|DotSecurityException e) { throw new DotRuntimeException(e); } }

Target:
you can reduce it to (null != hostId)?hostAPI.find(hostId, user, false):null;
Source:
public void testGetFolderContentWithInvalidIdentifier() throws Exception { // 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 ); } }

Target:
" throws Exception " can be removed
Source:
public String getActionUrl(final ContentType contentType, final User user) { final HttpServletRequest request = httpServletRequestThreadLocal.getRequest(); String actionUrl = request != null? getActionUrl(request, contentType, user):null; return actionUrl; }

Target:
you could change this to 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 { Logger.debug(this, "Bundle Context is null, WorkflowAPIOsgiService has been not registered"); } } }

Target:
@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.
Source:
private List<Class<?>> getVersionableWhitelist() { List<Class<?>> whitelist = new ArrayList<>(); whitelist.add(Container.class); whitelist.add(Template.class); whitelist.add(File.class); whitelist.add(HTMLPage.class); return whitelist; }

Target:
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.
Source:
private boolean validPayload(final SessionWrapper session, final Payload payload) { //Get the verifier associated to this Payload final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); if ( null != verifier ) { //Check if we have the "visibility" rights to use this payload return verifier.verified(payload, session); } return true; }

Target:
I would change this for a 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{ snapshot.delete(); } }

Target:
delete if !=null
Source:
public void updateOwnerReferences ( String userId, String replacementUserId ) throws DotDataException { if(!UtilMethods.isSet(userId) || !UtilMethods.isSet(replacementUserId)) { return; } DotConnect dc = new DotConnect(); dc.setSQL(UPDATE_BUNDLE_OWNER_REFERENCES); dc.addParam(replacementUserId); dc.addParam(userId); dc.loadResult(); }

Target:
shouldn't report an exception or something?
Source:
public SystemEvent process(SystemEvent event, Session session) { Payload payload = event.getPayload(); ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = (ContentTypePayloadDataWrapper) payload.getRawData(); Structure structure = contentTypePayloadDataWrapper.getStructure(); ContentTypeView contentTypeView = ContentTypeView.getInstance(structure, contentTypePayloadDataWrapper.getActionUrl()); return new SystemEvent(event.getId(), event.getEventType(), new Payload(contentTypeView, payload.getVisibility(), payload.getVisibilityId()), event.getCreationDate()); }

Target:
The ContentTypeView should be a class attribute instead of getting the instance static.
Source:
private RestRule getRuleInternal(String ruleId, User user) { Rule input = getRule(ruleId, user); RestRule restRule = ruleTransform.appToRest(input, user); if(restRule == null) { throw new NotFoundException("Rule not found: '%s'", ruleId); } return restRule; }

Target:
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.
Source:
private int readStreamToStrBuffer(int length) throws IOException { if (length > strBuffer.length - strBufferIndex) { expandStrBuffer(length); } int bytesRead = inputStream.read(strBuffer, strBufferIndex, Math.min(length, strBuffer.length - strBufferIndex)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } strBufferIndex += bytesRead; System.out.println(bytesRead); return bytesRead; }

Target:
rm the println
Source:
private void readAmount(int numChars) throws IOException { int bytesRead = is.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { // EOF throw new IOException(String.format("Reached end of stream.")); } end = end + bytesRead; }

Target:
just use a raw string here no need for String.format
Source:
public void createNewComponent () { Engine engine = new Engine(); ComponentD componentD = engine.createComponent(ComponentD.class); assertNotEquals(componentD, null); }

Target:
I think there is `assertNotNull()`, could you please do that?
Source:
public Span buildAndStartSpan(String name, SpanContext spanContext) { if(getTracer() == null) { m_tracer = GlobalTracer.get(); } if (spanContext == null) { return getTracer().buildSpan("Provisiond-" + name).start(); } else { return getTracer().buildSpan("Provisiond-" + name).asChildOf(spanContext).start(); } }

Target:
Seems odd to mix calls to `getTracer()` and direct access to `m_tracer` in this same method.
Source:
public void onUnbind(GraphContainerProvider graphContainerProvider, Map<String, String> props) { if(graphContainerProvider != null) { graphContainerProviders.remove(graphContainerProvider); final ServiceRegistration<GraphContainerProviderRegistration> serviceRegistration = serviceRegistrationMap.remove(graphContainerProvider); if (serviceRegistration != null) { serviceRegistration.unregister(); } } }

Target:
Could be simplified by returning immediately if null - would save having to indent the whole block.
Source:
protected JaxbListWrapper<OnmsIpInterface> createListWrapper(Collection<OnmsIpInterface> list) { return new OnmsIpInterfaceList(list); }

Target:
Should be final.
Source:
public boolean getHasIngressFlows() { if (m_lastIngressFlow == null) { return false; } return (new Date().getTime() - m_lastIngressFlow.getTime()) / 1000 < OnmsSnmpInterface.MAX_FLOW_AGE; }

Target:
`new Date().getTime()` can be replaced by `System.currentTimeMillis()`
Source:
public void addResult(Resource resource, Collection<String> metrics) { this.m_results.add(new Result(resource, metrics)); }

Target:
Even if this was copied, we should fix the `this.m_` references here :)
Source:
public Extended80211Payload(final ByteBuf buffer) throws InvalidPacketException { this.ciphersuite = new CipherSuite(buffer); this.data = new Opaque(buffer, Optional.empty(), buffer1 -> Opaque.parseBytes(buffer1)); }

Target:
Revert this.
Source:
public Optional<String> getRoutingKey(final TelemetryProtos.TelemetryMessageLog message) { if (message.getUseRoutingKey()) { return Optional.of(String.format("%s@%s:%d", message.getLocation(), message.getSourceAddress(), message.getSourcePort())); } else { return null; } }

Target:
This is an `Optional` value and thus should not return `null`. Use `Optional.of()` and `Optional.empty()` instead.
Source:
public synchronized static VertexHopCriteria createCriteria(String namespace, String nodeId, String nodeLabel) { VertexHopCriteria criterion = new LinkdHopCriteria(namespace,nodeId, nodeLabel); return criterion; }

Target:
`synchronized` can be safely removed from this method since it is stateless. ```suggestion public static VertexHopCriteria createCriteria(String namespace, String nodeId, String nodeLabel) { ```
Source:
public MetricRegistry getMetrics() { return metrics != null ? metrics : new MetricRegistry(); }

Target:
Shouldn't we store the result of ` new MetricRegistry()` instead of returning a new one on get?
Source:
public CollectionSet build(CollectionAgent agent, Object message, Long timestamp) throws ScriptException { final CollectionSetBuilder builder = new CollectionSetBuilder(agent); if (timestamp != null) { builder.withTimestamp(new Date(timestamp)); } final SimpleBindings globals = new SimpleBindings(); globals.put("agent", agent); globals.put("builder", builder); globals.put("msg", message); compiledScript.eval(globals); return builder.build(); }

Target:
For Nxos, JTI should we check if it is not zero since that would be default value.
Source:
public Collection<E> get() { return container; }

Target:
We should make this immutable to allow manipulation only via the `CaffeineCache` class.
Source:
DefaultExtendedDnsCacheEntry(String hostname, InetAddress address) { this.hostname = hostname; this.address = address; cause = null; hostnameFromPtrRecord = null; }

Target:
Nit: `this` consistency.
Source:
public CompletableFuture<S> writeMessage(S message) throws WriteFailedException { final CompletableFuture<S> future = new CompletableFuture<>(); byte[] bytes = sinkModule.marshalSingleMessage(message); String uuid = UUID.randomUUID().toString(); Long key = offHeapQueue.writeMessage(sinkModule.getId(), bytes); offHeapFutureMap.put(key, future); firstWrite.countDown(); return future; }

Target:
This is unused now.
Source:
public Response saveRule(RuleDTO ruleDTO) { final Rule rule = convert(ruleDTO); rule.setId(null); rule.setPosition(0); // new rules get the lowest position (lowest priority) final int ruleId = classificationService.saveRule(rule); final UriBuilder builder = UriBuilder.fromResource(ClassificationRestService.class); final URI uri = builder.path(ClassificationRestService.class, "getRule").build(ruleId); return Response.created(uri).build(); }

Target:
Shouldn't this mean `new rules get the lowest position (highest priority)`?
Source:
public String getUnmodifiedInstance() { return null; //For node type resources, use the default instance }

Target:
```suggestion return getInstance(); ```
Source:
public void setUp() throws Exception { System.setProperty("org.apache.logging.log4j.simplelog.StatusLogger.level", "INFO"); MockLogAppender.setupLogging(); TemporaryDatabasePostgreSQL temp = new TemporaryDatabasePostgreSQL(); }

Target:
AFAICT this does nothing, or are you doing it just for initialization? If so you don't need the variable.
Source:
public void setDstAddrHostname(String dstAddrHostname) { addHost(dstAddrHostname); this.dstAddrHostname = dstAddrHostname; }

Target:
Could you update the `addHost()` method so that it includes an `Objects.requireNonNull()` check on the host. Looks like I missed that originally.
Source:
public Conversation build() { return new Conversation(this.location, this.protocol, this.lowerIp, this.upperIp, this.lowerHostname, this.upperHostname, this.application); }

Target:
If we switch to the single-arg constructor, we can just pass an instance of the builder `return new Conversation(this)`
Source:
public void setTTL(Long ttl) { this.m_ttl = m_ttl; }

Target:
`this` and `m_`
Source:
public void testNodesWithFlows() { this.m_driver.get(this.getBaseUrl() + "opennms/element/nodeList.htm?flows=true"); assertThat(Iterables.transform(m_driver.findElements(By.xpath("//div[@class='NLnode']//a")), WebElement::getText), containsInAnyOrder("TestMachine loc1node2", "TestMachine loc2node2")); }

Target:
The usage of `this` and `m_` is weird, I'd omit the `this` here.
Source:
private Tracer getTracer() { return tracerRegistry.getTracer(minionIdentity.getId()+"@"+minionIdentity.getLocation()); }

Target:
Can we flip the location and id here so that the all of the systems at the same location a "grouped" together in the Jaeger UI?