auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void internalAssertEquals( String message, Object expecteds, Object actuals, ComparisonHelper comparisonHelper) { String messagePrefix = message == null ? "" : message + ": "; if (arraysTriviallyEqual(messagePrefix, expecteds, actuals)) { return; } assertElementsEqual(messagePrefix, comparisonHelper); }

Target:
What do you think about changing this code to ``` if (!arraysTriviallyEqual(messagePrefix, expecteds, actuals)) { assertElementsEqual(messagePrefix, comparisonHelper); } ```
Source:
public void methodNameTest() throws Exception { Description description = Description.createTestDescription("some-class-name", methodName); assertNotNull("Method name should be not null", description.getMethodName()); assertEquals(description.getMethodName(), methodName); }

Target:
Note that we may be moving soon to a builder for Description objects, and the builder should provide a way to specify the test method and test class independently of the "description" (i.e. we wouldn't use a regex to parse it). Having both types of test would allow us to verify this bug doesn't come back. Thanks!
Source:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); assertNotNull(fResult); }

Target:
Useless. This line will not be executed if `fResult` is `null` because a `NullPointerException` will be thrown the line before.
Source:
private String expectedDiff() { return extractDiff(expected); }

Target:
I would personally prefer if the methods that are the "external API" be public. Yes, the outer class can call private methods directly, but most IDEs show public methods differently, let you filter out non-public methods when browsing, etc.
Source:
private String compactPrefix() { if (sharedPrefix.length() > contextLength) { return ELLIPSIS + sharedPrefix.substring(sharedPrefix.length() - contextLength); } return sharedPrefix; }

Target:
This is really a nit, but I would _personally_ prefer inverting this `if` statement: ``` if (sharedPrefix.length() <= contextLength) { return sharedPrefix; } ... ``` That way, 1) the simplest part of the code is taken care of up front and 2) the indented line is the short line, not the long line
Source:
public boolean isComplete() { return unassigned.size() == 0; }

Target:
how about `return unassigned.isEmpty()` ?
Source:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; } catch (Throwable t) { addError(test, t); } }

Target:
IMHO, for things like variable naming, local consistency is arguably more important than global consistency, so naming this `e` is best. If we make a global change, I would prefer to rename variables of type `Throwable` to `e`
Source:
static public void assertEquals(String message, double expected, double actual, double delta) { if (Double.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, Double.valueOf(expected), Double.valueOf(actual)); } }

Target:
This actually isn't an optimization; `Double.valueOf(double d)` just calls 'new Double(d)' Let's just remove this change. Since this class is deprecated, I want to minimize changes to it wherever possible.
Source:
static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, Float.valueOf(expected), Float.valueOf(actual)); } }

Target:
This actually isn't an optimization; Float.valueOf(float f) just calls 'new Float(f)'
Source:
public Runner runnerForClass(Class<?> testClass) throws Exception { for (Class<?> currentTestClass = testClass; currentTestClass != null; currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) { RunWith annotation = currentTestClass.getAnnotation(RunWith.class); if (annotation != null) { return buildRunner(annotation.value(), currentTestClass); } } return null; }

Target:
Are you sure you don't want to pass `testClass` instead of `currentTestClass` here? Passing the outermost class with `@RunWith` doesn't appear to solve #816
Source:
private Throwable createTimeoutException(Thread thread) { List<Throwable> exceptions = new ArrayList<Throwable>(); exceptions.add(createCurrentThreadException(thread)); exceptions.addAll(createAdditionalTimeoutExceptions(thread)); return exceptions.size() == 1 ? exceptions.get(0) : new MultipleFailureException(exceptions); }

Target:
This can be simplified to MultipleFailureException.assertEmpty, for what it's worth.
Source:
private static ParametersRunnerFactory getParametersRunnerFactory( Class<?> klass) throws InstantiationException, IllegalAccessException { UseParametersRunnerFactory annotation = klass .getAnnotation(UseParametersRunnerFactory.class); if (annotation == null) { return DEFAULT_FACTORY; } else { Class<? extends ParametersRunnerFactory> factoryClass = annotation .value(); return factoryClass.newInstance(); } }

Target:
Do we need some error handling here?
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestClass other = (TestClass) obj; if (fClass == null) return other.fClass == null; else return fClass.equals(other.fClass); }

Target:
JUnit style is to always use braces for "if" "do" and "while" statements.
Source:
public String toString() { return fTestClass.getName() + " '" + fName + "' with parameters " + Arrays.toString(fParameters); }

Target:
If `fName` is null, then `toString()` will include `'null'`. Is that intentional? Why do you want to allow this class to have a null `fName` (vs an empty string)?
Source:
public int hashCode() { int prime = 14747; int result = prime + ((fName == null) ? 0 : fName.hashCode()); result = prime * result + fTestClass.hashCode(); return prime * result + fParameters.hashCode(); }

Target:
`fName` can't be null, so this can be simpler
Source:
private boolean areAllChildrenIgnored() { for (T child : getFilteredChildren()) { if(isIgnored(child) == false) { return false; } } return true; }

Target:
Space after if, please. And change to if (! isIgnored(child))
Source:
static public void assertNotEquals(String message, long unexpected, long actual) { if (unexpected == actual) { failEquals(message, actual); } }

Target:
I would strongly prefer: ``` failEquals(message, Long.valueOf(actual)) ``` There are a lot of methods in this class, so it's not clear from reading this line that autoboxing is happening. I think knowing that autoboxing is happening here increases readability. It also makes it more clear why you are doing the `if` check above
Source:
static public void assertNotEquals(String message, double unexpected, double actual, double delta) { if (!doubleIsDifferent(unexpected, actual, delta)) { failEquals(message, actual); } }

Target:
Similarly here, use `Double.valueOf(actual)`
Source:
private StackTraceElement[] getStackTrace(Thread thread) { StackTraceElement[] threadStack; try { threadStack = thread.getStackTrace(); } catch (SecurityException e) { threadStack = new StackTraceElement[0]; } return threadStack; }

Target:
Let's just use returns rather than a local
Source:
private <T> List<T> getAnnotatedMembers(Map<Class<? extends Annotation>, List<T>> map, Class<? extends Annotation> type, boolean fillIfAbsent) { if (!map.containsKey(type) && fillIfAbsent) { map.put(type, new ArrayList<T>()); } List<T> members = map.get(type); return members == null ? Collections.<T>emptyList() : members; }

Target:
Same issue here. We should keep this as static if at all possible
Source:
public Map<Class<? extends Annotation>, List<FrameworkMethod>> getAnnotationToMethods() { return Collections.unmodifiableMap(fMethodsForAnnotations); }

Target:
Although the returned Map is unmodifiable, the values are modifiable lists. Please change to: ``` public List<FrameworkMethod> getAnnotatedMethods(Class<? extends Annotation> annotation) { return Collections.unmodifiableList(fMethodsForAnnotations.get(annotation)); } ``` (though I would prefer that the values for fMethodsForAnnotations to be unmodifiable lists)
Source:
public void annotationToMethodsReturnsUnmodifiableMap() { exception.expect(UnsupportedOperationException.class); TestClass tc = new TestClass(MethodsAnnotated.class); Map<Class<? extends Annotation>, List<FrameworkMethod>> annotationToMethods = tc.getAnnotationToMethods(); annotationToMethods.put(Ignore.class, null); }

Target:
Could you put this line right before the call to `annotationToMethods.put(Ignore.class, null)` ?
Source:
public void annotationToFieldsReturnsValuesInTheMapThatAreUnmodifiable() { exception.expect(UnsupportedOperationException.class); TestClass tc = new TestClass(FieldAnnotated.class); Map<Class<? extends Annotation>, List<FrameworkField>> annotationToFields = tc.getAnnotationToFields(); List<FrameworkField> fields = annotationToFields.get(Rule.class); fields.add(null); }

Target:
Could you put this line right before the call to `fields.add(null)` ?
Source:
public void getDescriptionWithAnnotation() { JUnit38ClassRunner runner = new JUnit38ClassRunner(JUnit3ClassWithAnnotatedMethod.class); Description d = runner.getDescription(); Assert.assertEquals(2, d.testCount()); for (Description methodDesc : d.getChildren()) { if (methodDesc.getMethodName().equals("testAnnotated")) { assertNotNull(methodDesc.getAnnotation(MyAnnotation.class)); } else { assertNull( methodDesc.getAnnotation(MyAnnotation.class)); } } }

Target:
nit: please use a static import for assertEquals
Source:
public boolean testFinished(final Class<?> testClass) { return finishedTests.contains(testClass.getName()); }

Target:
Unless I'm missing something, `testFinished(class)` == `testStarted(class)` (either a test starts and finishes, or it never starts). Can we just have one method (perhaps named `wasRun`)?
Source:
public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e.getMessage()); } }

Target:
Can we pass e, and not just the message?
Source:
public static Filter createFilterFromFilterSpec(Description description, String filterSpec) throws FilterFactory.FilterNotCreatedException { if (filterSpec.contains("=")) { String[] tuple = filterSpec.split("=", 2); return createFilter(tuple[0], new FilterFactoryParams(tuple[1])); } else { return createFilter(filterSpec, new FilterFactoryParams()); } }

Target:
I think I'd rather explicitly pass in "" here, rather than have a default construction for FilterFactoryParams.
Source:
public Ray (Vector3 origin, Vector3 direction, boolean normalizeDirection) { this(origin, normalizeDirection ? direction.nor() : direction); }

Target:
This will change the `direction` vector that was passed in, please don't do that. Simple ```java this(origin, direction); if (normalizeDirection) { this.direction.nor(); } ``` should suffice. Same for `setNormalize`.
Source:
public void ended() { this.onCompletionListener.onCompletion(this); }

Target:
listener may be null, i had the issue when i tested music playback.
Source:
public boolean flush () { boolean success = false; // FIXME: how to hoist the success or failure of write to return it? ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (!nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); success = true; // FIXME: should reflect the success of NSDictionary write. return success; }

Target:
You could change line 188 to `final boolean[] success = {false};`, success set on line 194 with `success[0] = true;` and `return success[0];`. This pattern is often used in similar situations. It leads to an allocation, but if the MOE is smart enough, it could optimize it out. And if not - flush is a slow operation anyway, so it doesn't matter that much.
Source:
public SpinnerNumberModel (int min, int max, int step, int value) { if (max < min) throw new IllegalArgumentException("The maximum cannot be smaller than the minimum"); if (value < min || value > max) throw new IllegalArgumentException("The current value must be between the minimum and the maximum (inclusive)"); this.min = min; this.max = max; if (step < 0) step *= -1; this.step = step; this.value = value; }

Target:
Nitpick: wouldn't `step = -step` be clearer? (and is this check even necessary?)
Source:
public CubemapAttribute (final long type, final Cubemap texture) { this(type); textureDescription.set(texture, texture.getMinFilter(), texture.getMagFilter(), texture.getUWrap(), texture.getVWrap()); }

Target:
This change is not needed (and unwanted), please undo this.
Source:
public MeshPartBuilder begin () { if (building) throw new GdxRuntimeException("Call end() after calling begin()"); building = true; builder.begin(mesh.getVertexAttributes(), GL20.GL_LINES); return builder; }

Target:
Better change this in `builder.begin(attributes);` followed by `builder.part(id, primitive, renderable.meshPart);`. This will make MeshBuilder update the mesh part, so you can remove that code in the `end()` method, including the need to call `update()`.
Source:
public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; frameBuffers = new FrameBuffer[getPassQuantity()]; passShaderProviders = new ShaderProvider[getPassQuantity()]; init(); }

Target:
Calling a protected method in the constructor of the base class is not a good idea ;)
Source:
public void begin (int n) { if (n >= passShaderProviders.length) throw new GdxRuntimeException("Pass " + n + " doesn't exist in " + getClass().getName()); currentPass = n; spotCameraIterator = spotCameras.iterator(); spotCameraIterator.reset(); dirCameraIterator = dirCameras.iterator(); dirCameraIterator.reset(); pointCameraIterator = pointCameras.iterator(); pointCameraIterator.reset(); currentPointSide = 6; frameBuffers[n].begin(); beginPass(n); }

Target:
Calling the `iterator` method always resets it, so you only need one of these two methods.
Source:
public BitmapFontCache newFontCache () { for (int i = 0; i < regions.size; i++) { getRegion(i).getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); } return new DistanceFieldFontCache(this, integer); }

Target:
Bit strange to do this every time a font cache is created?
Source:
public EJBReceiver[] getEjbReceivers() { EJBReceiver[] ejbReceivers = null; synchronized (this.ejbReceiverAssociations) { ejbReceivers = this.ejbReceiverAssociations.keySet().toArray(new EJBReceiver[this.ejbReceiverAssociations.size()]); } return ejbReceivers; }

Target:
This API change is not allowed.
Source:
public boolean isDone() { assert !holdsLock(lock); synchronized (lock) { switch (state) { case WAITING: { return false; } case CANCEL_REQ: case READY: case FAILED: case CANCELLED: case DONE: case CONSUMING: case DISCARDED: { return true; } default: throw new IllegalStateException(); } } }

Target:
Did you intend to make this public?
Source:
public void setActive(boolean isActive) { if (!isActive) { logger.debug(Thread.currentThread().getStackTrace().toString()); } this.isActive = isActive; }

Target:
If `isActive()` always returns `true`, `setActive()` should be a noop. (even the *private* property `isActive` should be removed)
Source:
public static boolean isObject(String typeDescriptor) { if (typeDescriptor.length() == 0) return false; char first = typeDescriptor.charAt(0); return first == 'L' || first == '['; }

Target:
es gibt ein isEmpty()
Source:
public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { // We're adding the -s option to the command, to make sure the command output can be parsed properly. List<String> args = new ArrayList<>(extraArgs); // We will temporarily remove this argument because we do want to get json output for the config list cmd // The required value will be restore later while writing the npmrc file. args.remove("--json=false"); args.add("-s"); return runCommand(workingDirectory, new String[]{"c", "ls", "--json"}, args); }

Target:
Will not work on: ``` --json false --json false ``` etc. I think that `args.add("--json")` and also removing `"--json"` from line 82 will do the work.
Source:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) throws IOException { this.clientBuilder = clientBuilder; this.logger = logger; this.path = path; }

Target:
^ This method no longer throws IOException
Source:
private ArtifactoryHttpClient(String artifactoryUrl, String username, String password, String accessToken, Log log) { this.artifactoryUrl = StringUtils.stripEnd(artifactoryUrl, "/"); this.username = username; this.password = password; this.accessToken = accessToken; this.log = log; this.insecureTls = false; }

Target:
Can be set to false on declaration.
Source:
protected Build createBuild(List<Artifact> artifacts, List<Dependency> dependencies) { ModuleBuilder moduleBuilder = new ModuleBuilder().id(moduleName); if (artifacts != null) { moduleBuilder.artifacts(artifacts); } if (dependencies != null) { moduleBuilder.dependencies(dependencies); } List<Module> modules = Lists.newArrayList(moduleBuilder.build()); Build build = new Build(); build.setModules(modules); return build; }

Target:
Specifically in the build-info project, we should try and avoid using guava as much as possible, due to potential compatibility issues (@RobiNino can probably elaborate more about this).
Source:
public ArtifactoryHttpClient(String artifactoryUrl, String username, String password, String accessToken, Log log) { this.artifactoryUrl = StringUtils.stripEnd(artifactoryUrl, "/"); this.username = username; this.password = password; this.accessToken = accessToken; this.log = log; }

Target:
Any reason why we need a constructor that gets both username/password and an access token? This is reflected also in other constructors in the code.
Source:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { this.generalInfo = new GeneralInfo(generalInfo); this.issues.addAll(issues .stream() .map(Issue::new) .collect(Collectors.toSet())); this.licenses.addAll(licenses .stream() .map(License::new) .collect(Collectors.toSet())); }

Target:
Question - wouldn't a simple assignment be sufficient here? - ```this.generalInfo = generalInfo;``` Do we really need a clone of GeneralInfo here? If so, then the constructor in GeneralInfo which accepts another GeneralInfo may be redundant. The same question goes for *this.issues* and *this.licenses* in the same method - are we actually aggregating issues and licenses (with addAll) or this is a one time assignment?
Source:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { output = ExceptionUtils.getStackTrace(e); } }

Target:
I think it is better letting this method throw the exception.
Source:
public void insertRowsFromTsvFileWithHeader() { File dataFile = new File("src/test/resources/examples/dataWithHeader1.tsv"); TsvFileParser parser = new TsvFileParser().withHeader(true); String[] header = parser.parseHeader(dataFile); shell.insertInto("source_db", "test_table") .withColumns(header) .addRowsFrom(dataFile, parser) .commit(); printResult(shell.executeStatement("select * from source_db.test_table")); }

Target:
I think it would be nicer if the header extraction was implicit, i.e. it magically happens when you call `addRowsFrom ` and you do not need to manually extract the header with a call to `TsvFileParser.parseHeader`. This would make it simpler for users and remove a method from the public API. Yes, it may require a reworking of the `insertInto` implementation, but I find the following sequence a bit clunky and unnecessary: String[] header = parser.parseHeader(dataFile); ... .withColumns(header) The `insertInto` should be able to figure out the `columns` from the `parser`.
Source:
public void executeQueryFromFileZeroStatements() throws IOException { HiveShell shell = createHiveShell(); shell.start(); String hql = ""; File file = new File(tempFolder.getRoot(), "script.hql"); Files.write(hql, file, UTF_8); @SuppressWarnings("unused") List<String> results = shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); }

Target:
Remove the unused variable declaration and the annotation is not needed
Source:
public String transformStatement(String statement) { return filterFullLineComments(statement); }

Target:
According to this http://sqlline.sourceforge.net/#sect_command_run any rows starting with '#' should be ignored
Source:
public List<Facility> getAllowedFacilities(PerunSession sess, Member member) throws InternalErrorException { return getFacilitiesManagerImpl().getAllowedFacilities(sess, member); }

Target:
You do not have to throw InternalErrorException.
Source:
public List<Member> findMembers(PerunSession sess, Vo vo, String searchString, boolean onlySponsored) throws InternalErrorException { return getMembersManagerImpl().findMembers(sess, vo, searchString, onlySponsored); }

Target:
You don't need to explicitly declare InternalErrorException, because it is RuntimeException.
Source:
public List<RichFacility> getRichFacilities(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.authorizedInternal(sess, "getRichFacilities_policy")) { throw new PrivilegeException(sess, "getRichFacilities"); } List<Facility> facilities = getFacilitiesManagerBl().getFacilities(sess); facilities.removeIf(facility -> AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); return getFacilitiesManagerBl().getRichFacilities(sess, facilities); }

Target:
Shouldn't be there a negation?
Source:
public String getValue(String value, Attribute attr) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.warn("Error converting to JSON", value, e); return null; } }

Target:
``ObjectMapper`` is fully thread safe, we can have it as a single static variable inside this transformer class (also because we do not configure it differently per method usage)
Source:
public String toString() { String roles = ""; if (!this.isEmpty()) { for (String role: this.keySet()) { roles += role.toLowerCase() + this.get(role) + ","; } } return getClass().getSimpleName() + "[" + roles + "]"; }

Target:
We can use upperCase format here too.
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.valueAsString() == null) throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "Value can't be null"); }

Target:
Nit: It is not necessary to convert the value to String.
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.valueAsString() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute was not filled, therefore there is nothing to be checked."); }

Target:
Nit: It is not necessary to convert the value to String.
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if(attribute.valueAsInteger() == null) { throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "account expiration time shouldn't be null"); } }

Target:
Nit: It is not necessary to convert the value to String.
Source:
public void checkAttributeSyntax(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { Utils.notNull(attribute, "attribute"); if (unpermittedLogins.contains(attribute.valueAsString())) throw new WrongAttributeValueException(attribute, user, "Login '" + attribute.getValue() + "' is not permitted."); super.checkAttributeSyntax(sess, user, attribute); }

Target:
Object attribute should never be null. You can just skip this part if value of attribute is null.
Source:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if (attribute.getValue() == null) return; if (!(attribute.getValue() instanceof String)) { throw new WrongAttributeValueException(attribute, key, "value must be of type String"); } String value = attribute.valueAsString(); if (!value.contains("{link}")) { throw new WrongAttributeValueException(attribute, key, "value doesn't contain contain tag {link}"); } }

Target:
You can skip the part with instanceof String.
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException { // null attribute if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be null."); if (attribute.valueAsString().isEmpty()) { throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be empty."); } }

Target:
I think empty attribute can't be set any way in Perun so this one is probably not needed at all.
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Member member, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException { Attribute currentAttribute = getAttributeValue(sess, member, attribute); if(!attribute.equals(currentAttribute)) throw new WrongReferenceAttributeValueException(attribute, currentAttribute, member, null, "Attribute value is not the highest value from member's UserExtSources Loas."); }

Target:
Also there is missing reference attribute holder.
Source:
private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) resIterator.remove(); } return resources; }

Target:
For PerunObserver you can return all resources immediately.
Source:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.isAuthorized(sess, Role.SELF) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }

Target:
Currently we don't have PERUNOBSERVER role assignable by config to specific credentials (unlike perun admin). This mean, we will always have User, related to this role. So anywhere, check on SELF (without specifying user or where passed user is only own) will let PERUNOBSERVER pass too. Only if it would filter result, we would have to separate them. What do you think @stavamichal @licehammer @martin-kuba ? Will we need PERUNOBSERVER role for accounts without User in Perun or not ? I suppose not, it is always safer to have account with contact info etc.
Source:
public User getUserByUserExtSource(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException, UserNotExistsException { try { return jdbc.queryForObject("select " + userMappingSelectQuery + " from users, user_ext_sources " + "where users.id=user_ext_sources.user_id and user_ext_sources.login_ext=? and user_ext_sources.ext_sources_id=? ", USER_MAPPER, userExtSource.getLogin(), userExtSource.getExtSource().getId()); } catch (EmptyResultDataAccessException ex) { log.debug("GET_USER_BY_USER_EXT_SOURCE"); throw new UserNotExistsException("userExtSource=" + userExtSource.toString()); } catch (RuntimeException err) { throw new InternalErrorException(err); } }

Target:
Again, this change probably shouldn't be a part of this pull-request, since it seems to be related to ExtSources and purpose is debugging it.
Source:
public int getAuditerMessagesCount(PerunSession perunSession) throws InternalErrorException, PrivilegeException { if (!AuthzResolver.isAuthorized(perunSession, Role.PERUNADMIN)) { throw new PrivilegeException(perunSession, "getAuditerMessagesCount"); } return getAuditMessagesManagerBl().getAuditerMessagesCount(perunSession); }

Target:
This is probably used by nagios, so with these restrictions the probe can be broken.
Source:
public void updateUserExtSourceLastAccess(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { getPerunBl().getAuditer().log(sess, new UserExtSourceUpdated(userExtSource)); getUsersManagerImpl().updateUserExtSourceLastAccess(sess, userExtSource); }

Target:
You should always generate message after the process is done. You can prevent unexpected issues.
Source:
public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceGIDRangesAttribute = getNamespaceGIDRangesAttribute(sess, (String) gidNamespaceAttribute.getValue()); Utils.copyAttributeToVirtualAttributeWithValue(namespaceGIDRangesAttribute, attribute); return attribute; }

Target:
I would change this like to `return Utils.copyAttributeToVirtual.......`
Source:
public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); try { Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } }

Target:
Same here: `return Utils.copyAttribute.....`
Source:
public void setStartTime(Long startTime) { this.startTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); }

Target:
All setters with ``Long`` as param should check on ``null`` since then ``Instant.ofEpochMilli()`` will fail on ``NullPointerException``. We should safely set null to the base object instead.
Source:
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException{ if(actualValue.length() > maxLength) throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length()); }

Target:
You should cover also the case, when passed value is ``null``, since ``Candidate`` params titleBefore/titleAfter can be null or empty.
Source:
public void reportTaskResult(TaskResult taskResult) throws JMSException { TextMessage message = session.createTextMessage("taskresult:" + propertiesBean.getProperty("engine.unique.id") + ":" + taskResult.serializeToString()); synchronized(producer) { producer.send(message, DeliveryMode.PERSISTENT, 2, 0); } log.debug("[{}] TaskResult for destination sent to dispatcher.", taskResult.getTaskId(), taskResult.getDestinationId()); }

Target:
Please keep it in info level.
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, String key, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) return; if(!(attribute.getValue() instanceof String)) { throw new WrongAttributeValueException(attribute, key, "value must be of type String"); } String value = attribute.valueAsString(); }

Target:
This line of code is useless.
Source:
public void removeAllExpiredBans() { if(perunBl.isPerunReadOnly()) { log.debug("This instance is just read only so skip removing expired bans."); return; } try { getPerun().getResourcesManagerBl().removeAllExpiredBansOnResources(sess); getPerun().getFacilitiesManagerBl().removeAllExpiredBansOnFacilities(sess); } catch (InternalErrorException ex) { log.error("Synchronizer: removeAllExpiredBans, exception {}", ex); } }

Target:
also should be warning
Source:
public AttributeDefinition createAttribute(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException, AttributeDefinitionExistsException { return createAttribute(sess, attribute, false); }

Target:
There should be "true".
Source:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); dependencies.add(A_G_unixGID_namespace + ":*"); dependencies.add(A_R_unixGID_namespace + ":*"); return dependencies; }

Target:
Similar to urn_perun_group_attribute_def_def_unixGID_namespace.java The output should contain something like: ``` //Disallowed because of crosschecks between modules and peformance reason //dependencies.add(A_G_unixGID_namespace + ":*"); //dependencies.add(A_R_unixGID_namespace + ":*"); //dependencies.add(A_R_unixGroupName_namespace + ":*"); ```
Source:
protected static void init(PerunSession sess) throws InternalErrorException { log.trace("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); refreshAuthz(sess); log.debug("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); }

Target:
Please fix ``refreshAuthz(sess)`` implementation, it's not 1:1 replacement of above removed code right now.
Source:
public void forceGroupSynchronization(PerunSession sess, Group group) throws GroupSynchronizationAlreadyRunningException, InternalErrorException { Utils.notNull(group, "group"); //Check if the group is not currently in synchronization process if(poolOfGroupsToBeSynchronized.putJobIfAbsent(group, true)) { log.info("Scheduling synchronization for the group by force!", group); } else { throw new GroupSynchronizationAlreadyRunningException(group); } }

Target:
We usually don't check for null objects in business logic layer. Any particular reason for it here?
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, GroupResourceMismatchException { }

Target:
Please remove ``GroupResourceMismatchException`` and ``MemberResourceMismatchException`` from all member-resource and group-resource attribute modules (api, abstract). If passed entities mismatch, it's programmers fault. We want these exceptions mostly to be used in outer api (Api and Entry, sometimes it's in Bl/BlImpl). Then please catch such exceptions in modules implementation and wrap them to ``InternalErrorException``. This should result in lowering exceptions usages in normal methods from ``AttributesManager`` and back in normal managers.
Source:
public OIDC getOIDCManager(){ if(oidcManager == null){ oidcManager = new OIDC(); } return oidcManager; }

Target:
Susceptible to race condition
Source:
public void removeResultGroupRelations(PerunSession sess, Group resultGroup) { jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId()); jdbc.update("DELETE FROM groups_members WHERE group_id = ? AND membership_type != ?", resultGroup.getId(), MembershipType.DIRECT.getCode()); }

Target:
In redmine 2630.
Source:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = null; Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }

Target:
Variable attributeValue always contains null (see line 24), therefore this matcher will never match.
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { //Null is ok, it means use default permissions in script (probably 0700) if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); Pattern pattern = Pattern.compile("^[01234567]?[01234567]{3}$"); Matcher match = pattern.matcher(attrValue); if(!match.matches()) throw new WrongAttributeValueException(attribute, facility, "Bad format of attribute, (expected something like '750' or '0700')."); }

Target:
Pattern should be compiled only once. Please move it outside from method.
Source:
public List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException { List<RichGroup> richGroups = new ArrayList<>(); for(Group group: groups) richGroups.add(new RichGroup(group, this.getPerunBl().getAttributesManagerBl().getAttributes(sess, group))); return richGroups; }

Target:
Even if there is only 1 row in "for cyclus" i prefer using '{' and '}' for better reading.
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { //Null means the same like 0 (not enabled) if(attribute.getValue() == null) return; Integer quotaEnabled = (Integer) attribute.getValue(); if(quotaEnabled > 1 || quotaEnabled < 0) throw new WrongAttributeValueException(attribute, "Attribute has only two possible options for quota: 0 - means not enabled, 1 - means enabled."); }

Target:
Please add attribute holder to the exception parameters.
Source:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { //previous regex ^/[-a-zA-Z0-9_/]*$" Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } if(!shell.startsWith("/")) { throw new WrongAttributeValueException(attribute, "Shell " + shell + " doesnt start with /"); } }

Target:
This is already covered on line 524, isn't it?
Source:
public VehicleLocationRecordBean getVehicleLocationRecordForVehicleId( AgencyAndId vehicleId, long targetTime) { TargetTime target = new TargetTime(targetTime, targetTime); if (_blockLocationService == null) { _log.error("blocklocationservice is null"); return null; } BlockLocation blockLocation = _blockLocationService.getLocationForVehicleAndTime( vehicleId, target); if (blockLocation == null) return null; return getBlockLocationAsVehicleLocationRecord(blockLocation); }

Target:
Now that you've added the setBlockLocationService(...) with @Autowired you can probably remove this null check, since it shouldn't ever be null.
Source:
public OutputStream openOutputStream(String filePath) throws IOException { try { DistributedLogManager dlm = namespace.openLog( filePath); LedgerMetadata metadata = new LedgerMetadata(); metadata.setApplication(Constants.LEDGER_METADATA_APPLICATION_STREAM_STORAGE); metadata.setComponent("checkpoint-store"); AsyncLogWriter writer = Utils.ioResult(dlm.openAsyncLogWriter()); return new BufferedOutputStream( new DLOutputStream(dlm, writer), 128 * 1024); } catch (LogNotFoundException le) { throw new FileNotFoundException(filePath); } }

Target:
this looks like a dead store, you are not using this variable
Source:
public void process(int journalVersion, long offset, ByteBuffer entry) throws IOException { if (!printJournalVersion) { System.out.println("Journal Version : " + journalVersion); printJournalVersion = true; } }

Target:
Use Logger please
Source:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { log.error("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); nonSupportedMessagePrinted = true; } }

Target:
Can we still make this logging statement to `warn`?
Source:
public long getLastStoredEntryId() { Long lastEntry = LedgerHandle.INVALID_ENTRY_ID; for (int bookieIndex : bookieIndexes) { Long lastStoredEntryIdForBookie = getLastStoredEntryId(bookieIndex); if (lastStoredEntryIdForBookie != LedgerHandle.INVALID_ENTRY_ID) { if (lastEntry == LedgerHandle.INVALID_ENTRY_ID) { lastEntry = lastStoredEntryIdForBookie; } else { lastEntry = Math.max(lastEntry, lastStoredEntryIdForBookie); } } } return lastEntry; }

Target:
this can be 'long' instead of 'Long'
Source:
protected void doStart() { try { this.server.start(); } catch (Throwable exc) { LOG.error("Got unexpected exception while starting BookieServer", exc); if (uncaughtExceptionHandler != null) { LOG.error("Calling uncaughtExceptionHandler"); uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exc); } else { throw new RuntimeException("Failed to start bookie server", exc); } } }

Target:
nit: add more details to this log line?
Source:
protected void doStart() { try { this.main.start(); } catch (Throwable exc) { LOG.error("Got unexpected exception while starting AutoRecoveryMain", exc); if (uncaughtExceptionHandler != null) { LOG.error("Calling uncaughtExceptionHandler"); uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exc); } else { throw new RuntimeException("Failed to start AutoRecoveryMain", exc); } } }

Target:
Lets move this to AbstractLifecycle#start() method, since exceptions can happen in any component start.
Source:
public long getTLSCertFilesRefreshDurationSeconds() { return getLong(TLS_CERT_FILES_REFRESH_DURATION_SECONDS, 300); }

Target:
It should be disabled by default
Source:
Future<?> triggerGC(final boolean force, final boolean suspendMajor, final boolean suspendMinor) { return gcExecutor.submit(() -> { try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { LOG.warn("Failed to complete gc {}", e.getMessage(), e); } }); }

Target:
it would be better not to reformat code, as this changes makes the diff harder to review. Can you revert the formatting ? as soon as checkstyle is happy we are okay
Source:
public void safeRun() { boolean force = forceGarbageCollection.get(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { LOG.warn("Failed to complete gc {}", e.getMessage(), e); } if (force) { // only set force to false if it had been true when the garbage // collection cycle started forceGarbageCollection.set(false); } }

Target:
if we are catching "Exception" any time you call runWithFlags.... why don't catch the error inside runWithFlags and leave the previous signature ? catch (Exception) is a code smell, do we really need it ?
Source:
public PlacementResult(T result, boolean adhering) { this.result = result; this.adhering = adhering; }

Target:
I am fine with either approach.
Source:
public long getCtime() { return ctime.orElse(metadataStoreCtime.orElse(-1L)); }

Target:
isn't this a behavior change?
Source:
public void setExceptionHandler(UncaughtExceptionHandler exceptionHandler) { this.uncaughtExceptionHandler = exceptionHandler; this.bookie.setExceptionHandler(exceptionHandler); }

Target:
nit: since bookie is not final, there can be possibility `bookie` is null if these methods are not called in correct order. can we add `final` modifier to `bookie` field?
Source:
public void close() throws IOException { IOUtils.close(log, activeLogChannel); }

Target:
unrelated note. With current method definition ```java public static void close(Logger log, java.io.Closeable... closeables) { ``` java will create new Object[] for single closeable that is passed to the method. We'll benefit from a variant that takes only one parameter. Do we ever use this method with more than one closeable?
Source:
protected synchronized void closeLedgerManagerFactory() { LedgerManagerFactory lmToClose; synchronized (this) { lmToClose = lmFactory; lmFactory = null; } if (null != lmToClose) { try { lmToClose.close(); } catch (IOException e) { log.warn("Failed to close zookeeper based ledger manager", e); } } }

Target:
you already synchronized at line 261, do we still need this?
Source:
static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); LOG.info("AuthProvider used by the Auditor is {}", clientConfiguration.getClientAuthProviderFactoryClass()); try { return BookKeeper.forConfig(clientConfiguration).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } }

Target:
I think this logging doesn't belong to this method. it should be kept at `initialize` method.
Source:
public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) throws IOException, BookieException, InterruptedException { LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); return handle.fenceAndLogInJournal(getJournal(ledgerId)); }

Target:
Same problem here
Source:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(); toReplace.putAll(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); // Original intent of this change is to do a best-effort ensemble change. // But this is not possible until the local metadata is completely immutable. // Until the feature "Make LedgerMetadata Immutable #610" Is complete we will use // handleBookieFailure() to handle delayed writes as regular bookie failures. handleBookieFailure(toReplace); } }

Target:
the existing code to construct the hashmap from `delayedWriteFailedBookies`. it is one line code. any reason why do you split into 2 lines?
Source:
ConcurrentHashMap<Long, LedgerData> getBookieData(BookieSocketAddress addr) { return data.computeIfAbsent(addr, (key) -> new ConcurrentHashMap<>()); }

Target:
"public" or "private" ?
Source:
public void close() throws IOException { Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs(); for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) { IOUtils.close(log, currentLogWithDirInfo.getLogChannel()); } }

Target:
any reason why "IOUtils.close" is called instead of "currentLogWithDirInfo.getLogChannel().close()"
Source:
public synchronized void close() throws IOException { if (writeBuffer != null) { ReferenceCountUtil.safeRelease(writeBuffer); writeBuffer = null; } fileChannel.close(); }

Target:
Thanks @merlimat calling twice is an issue and we should address that. :)
Source:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { checkQueue(); return super.invokeAll(tasks); }

Target:
Shouldn't you pass something like the size of the list? checkQueue assumes you are going to add 1 item. I mean something like checkQueue(tasks.size())
Source:
private TransientLedgerInfo getOrAddLedgerInfo(long ledgerId) { TransientLedgerInfo tli = transientLedgerInfoCache.get(ledgerId); if (tli != null) { return tli; } else { TransientLedgerInfo newTli = new TransientLedgerInfo(ledgerId, ledgerIndex); tli = transientLedgerInfoCache.putIfAbsent(ledgerId, newTli); return tli != null ? tli : newTli; } }

Target:
better to close `newTli`?
Source:
public ClientConfiguration getConf() { return conf; }

Target:
This is not good. Unfortunately this object is mutable. You can you Whitebox in tests
Source:
public long getWaitTimeoutOnBackpressureMillis() { return getLong(WAIT_TIMEOUT_ON_BACKPRESSURE, 500); }

Target:
I think we should make this default value as -1, util we have benchmarks show 500 is in general good for most of applications.