auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean areAllChildrenIgnored() { for (T child : getFilteredChildren()) { START if(isIgnored(child) == false) { END return false; } } return true; } Space after if, please. And change to if (! isIgnored(child))

Target:
private boolean areAllChildrenIgnored() { for (T child : getFilteredChildren()) { if (!isIgnored(child)) { return false; } } return true; }
Source:
static public void assertNotEquals(String message, long unexpected, long actual) { if (unexpected == actual) { START failEquals(message, actual); END } } 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

Target:
static public void assertNotEquals(String message, long unexpected, long actual) { if (unexpected == actual) { failEquals(message, Long.valueOf(actual)); } }
Source:
static public void assertNotEquals(String message, double unexpected, double actual, double delta) { if (!doubleIsDifferent(unexpected, actual, delta)) { START failEquals(message, actual); END } } Similarly here, use `Double.valueOf(actual)`

Target:
static public void assertNotEquals(String message, double unexpected, double actual, double delta) { if (!doubleIsDifferent(unexpected, actual, delta)) { failEquals(message, Double.valueOf(actual)); } }
Source:
private StackTraceElement[] getStackTrace(Thread thread) { StackTraceElement[] threadStack; try { START threadStack = thread.getStackTrace(); END } catch (SecurityException e) { threadStack = new StackTraceElement[0]; } return threadStack; } Let's just use returns rather than a local

Target:
private StackTraceElement[] getStackTrace(Thread thread) { try { return thread.getStackTrace(); } catch (SecurityException e) { return new StackTraceElement[0]; } }
Source:
START private <T> List<T> getAnnotatedMembers(Map<Class<? extends Annotation>, List<T>> map, END 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; } Same issue here. We should keep this as static if at all possible

Target:
private static <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; }
Source:
public Map<Class<? extends Annotation>, List<FrameworkMethod>> getAnnotationToMethods() { START return Collections.unmodifiableMap(fMethodsForAnnotations); END } 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)

Target:
public Map<Class<? extends Annotation>, List<FrameworkMethod>> getAnnotationToMethods() { return fMethodsForAnnotations; }
Source:
public void annotationToMethodsReturnsUnmodifiableMap() { START exception.expect(UnsupportedOperationException.class); END TestClass tc = new TestClass(MethodsAnnotated.class); Map<Class<? extends Annotation>, List<FrameworkMethod>> annotationToMethods = tc.getAnnotationToMethods(); annotationToMethods.put(Ignore.class, null); } Could you put this line right before the call to `annotationToMethods.put(Ignore.class, null)` ?

Target:
public void annotationToMethodsReturnsUnmodifiableMap() { TestClass tc = new TestClass(MethodsAnnotated.class); Map<Class<? extends Annotation>, List<FrameworkMethod>> annotationToMethods = tc.getAnnotationToMethods(); exception.expect(UnsupportedOperationException.class); annotationToMethods.put(Ignore.class, null); }
Source:
public void annotationToFieldsReturnsValuesInTheMapThatAreUnmodifiable() { START exception.expect(UnsupportedOperationException.class); END 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); } Could you put this line right before the call to `fields.add(null)` ?

Target:
public void annotationToFieldsReturnsValuesInTheMapThatAreUnmodifiable() { TestClass tc = new TestClass(FieldAnnotated.class); Map<Class<? extends Annotation>, List<FrameworkField>> annotationToFields = tc.getAnnotationToFields(); List<FrameworkField> fields = annotationToFields.get(Rule.class); exception.expect(UnsupportedOperationException.class); fields.add(null); }
Source:
public void getDescriptionWithAnnotation() { JUnit38ClassRunner runner = new JUnit38ClassRunner(JUnit3ClassWithAnnotatedMethod.class); Description d = runner.getDescription(); START Assert.assertEquals(2, d.testCount()); END for (Description methodDesc : d.getChildren()) { if (methodDesc.getMethodName().equals("testAnnotated")) { assertNotNull(methodDesc.getAnnotation(MyAnnotation.class)); } else { assertNull( methodDesc.getAnnotation(MyAnnotation.class)); } } } nit: please use a static import for assertEquals

Target:
public void getDescriptionWithAnnotation() { JUnit38ClassRunner runner = new JUnit38ClassRunner(JUnit3ClassWithAnnotatedMethod.class); Description d = runner.getDescription(); 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)); } } }
Source:
public boolean testFinished(final Class<?> testClass) { START return finishedTests.contains(testClass.getName()); END } 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`)?

Target:
private boolean testFinished(final Class<?> testClass) { return finishedTests.contains(testClass.getName()); }
Source:
public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { START throw new FilterNotCreatedException(e.getMessage()); END } } Can we pass e, and not just the message?

Target:
public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e); } }
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 { START return createFilter(filterSpec, new FilterFactoryParams()); END } } I think I'd rather explicitly pass in "" here, rather than have a default construction for FilterFactoryParams.

Target:
public static Filter createFilterFromFilterSpec(Description description, String filterSpec) throws FilterFactory.FilterNotCreatedException { String[] tuple; if (filterSpec.contains("=")) { tuple = filterSpec.split("=", 2); } else { tuple = new String[]{ filterSpec, "" }; } return createFilter(tuple[0], new FilterFactoryParams(tuple[1])); }
Source:
public Ray (Vector3 origin, Vector3 direction, boolean normalizeDirection) { START this(origin, normalizeDirection ? direction.nor() : direction); END } 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`.

Target:
public Ray (Vector3 origin, Vector3 direction, boolean normalizeDirection) { this(origin, direction); if (normalizeDirection) this.direction.nor(); }
Source:
public void ended() { START this.onCompletionListener.onCompletion(this); END } listener may be null, i had the issue when i tested music playback.

Target:
public void ended() { if(this.onCompletionListener != null) this.onCompletionListener.onCompletion(this); }
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); } } }); START success = true; // FIXME: should reflect the success of NSDictionary write. END return success; } 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.

Target:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { success[0] = true; } else { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); return success[0]; }
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; START if (step < 0) step *= -1; END this.step = step; this.value = value; } Nitpick: wouldn't `step = -step` be clearer? (and is this check even necessary?)

Target:
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 = -step; this.step = step; this.value = value; }
Source:
public CubemapAttribute (final long type, final Cubemap texture) { this(type); START textureDescription.set(texture, texture.getMinFilter(), texture.getMagFilter(), texture.getUWrap(), texture.getVWrap()); END } This change is not needed (and unwanted), please undo this.

Target:
public CubemapAttribute (final long type, final Cubemap texture) { this(type); textureDescription.texture = texture; }
Source:
public MeshPartBuilder begin () { if (building) throw new GdxRuntimeException("Call end() after calling begin()"); building = true; builder.begin(mesh.getVertexAttributes(), GL20.GL_LINES); START return builder; END } 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()`.

Target:
public MeshPartBuilder begin () { return begin(GL20.GL_LINES); }
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()]; START init(); END } Calling a protected method in the constructor of the base class is not a good idea ;)

Target:
public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; }
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(); START spotCameraIterator.reset(); END dirCameraIterator = dirCameras.iterator(); dirCameraIterator.reset(); pointCameraIterator = pointCameras.iterator(); pointCameraIterator.reset(); currentPointSide = 6; frameBuffers[n].begin(); beginPass(n); } Calling the `iterator` method always resets it, so you only need one of these two methods.

Target:
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(); dirCameraIterator = dirCameras.iterator(); pointCameraIterator = pointCameras.iterator(); currentPointSide = 6; beginPass(n); }
Source:
public BitmapFontCache newFontCache () { for (int i = 0; i < regions.size; i++) { getRegion(i).getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); START } END return new DistanceFieldFontCache(this, integer); } Bit strange to do this every time a font cache is created?

Target:
public BitmapFontCache newFontCache () { return new DistanceFieldFontCache(this, integer); }
Source:
START public EJBReceiver[] getEjbReceivers() { END EJBReceiver[] ejbReceivers = null; synchronized (this.ejbReceiverAssociations) { ejbReceivers = this.ejbReceiverAssociations.keySet().toArray(new EJBReceiver[this.ejbReceiverAssociations.size()]); } return ejbReceivers; } This API change is not allowed.

Target:
private EJBReceiver[] getEjbReceivers() { EJBReceiver[] ejbReceivers = null; synchronized (this.ejbReceiverAssociations) { ejbReceivers = this.ejbReceiverAssociations.keySet().toArray(new EJBReceiver[this.ejbReceiverAssociations.size()]); } return ejbReceivers; }
Source:
START public boolean isDone() { END 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(); } } } Did you intend to make this public?

Target:
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(); } } }
Source:
START public void setActive(boolean isActive) { END if (!isActive) { logger.debug(Thread.currentThread().getStackTrace().toString()); } this.isActive = isActive; } If `isActive()` always returns `true`, `setActive()` should be a noop. (even the *private* property `isActive` should be removed)

Target:
public void setActive(boolean isActive)
Source:
public static boolean isObject(String typeDescriptor) { START if (typeDescriptor.length() == 0) END return false; char first = typeDescriptor.charAt(0); return first == 'L' || first == '['; } es gibt ein isEmpty()

Target:
public static boolean isObject(String typeDescriptor) { if (typeDescriptor.isEmpty()) return false; char first = typeDescriptor.charAt(0); return first == 'L' || first == '['; }
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. START args.remove("--json=false"); END args.add("-s"); return runCommand(workingDirectory, new String[]{"c", "ls", "--json"}, args); } 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.

Target:
public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { // We're adding the -s and --json options to the command, to make sure the command output can be parsed properly. List<String> args = new ArrayList<>(extraArgs); args.add("-s"); args.add("--json"); return runCommand(workingDirectory, new String[]{"c", "ls"}, args); }
Source:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) throws IOException { START this.clientBuilder = clientBuilder; END this.logger = logger; this.path = path; } ^ This method no longer throws IOException

Target:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) { this.clientBuilder = clientBuilder; this.logger = logger; this.path = path; }
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; START this.insecureTls = false; END } Can be set to false on declaration.

Target:
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; }
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); } START List<Module> modules = Lists.newArrayList(moduleBuilder.build()); END Build build = new Build(); build.setModules(modules); return build; } 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).

Target:
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 = Arrays.asList(moduleBuilder.build()); Build build = new Build(); build.setModules(modules); return build; }
Source:
START public ArtifactoryHttpClient(String artifactoryUrl, String username, String password, String accessToken, Log log) { END this.artifactoryUrl = StringUtils.stripEnd(artifactoryUrl, "/"); this.username = username; this.password = password; this.accessToken = accessToken; this.log = log; } 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.

Target:
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; }
Source:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { START this.generalInfo = new GeneralInfo(generalInfo); END this.issues.addAll(issues .stream() .map(Issue::new) .collect(Collectors.toSet())); this.licenses.addAll(licenses .stream() .map(License::new) .collect(Collectors.toSet())); } 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?

Target:
public Artifact(GeneralInfo generalInfo, Set<Issue> issues, Set<License> licenses) { this.generalInfo = generalInfo; this.issues = issues; this.licenses = licenses; }
Source:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { START output = ExceptionUtils.getStackTrace(e); END } } I think it is better letting this method throw the exception.

Target:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new RuntimeException(e); } }
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); START shell.insertInto("source_db", "test_table") END .withColumns(header) .addRowsFrom(dataFile, parser) .commit(); printResult(shell.executeStatement("select * from source_db.test_table")); } 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`.

Target:
public void insertRowsFromTsvFileWithHeader() { File dataFile = new File("src/test/resources/examples/dataWithHeader1.tsv"); TsvFileParser parser = new TsvFileParser().withHeader(); shell.insertInto("source_db", "test_table") .addRowsFrom(dataFile, parser) .commit(); printResult(shell.executeStatement("select * from source_db.test_table")); }
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") START List<String> results = shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); END } Remove the unused variable declaration and the annotation is not needed

Target:
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); shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); }
Source:
public String transformStatement(String statement) { START return filterFullLineComments(statement); END } According to this http://sqlline.sourceforge.net/#sect_command_run any rows starting with '#' should be ignored

Target:
public String transformStatement(String statement) { return statement; }
Source:
START public List<Facility> getAllowedFacilities(PerunSession sess, Member member) throws InternalErrorException { END return getFacilitiesManagerImpl().getAllowedFacilities(sess, member); } You do not have to throw InternalErrorException.

Target:
public List<Facility> getAllowedFacilities(PerunSession sess, Member member) { return getFacilitiesManagerImpl().getAllowedFacilities(sess, member); }
Source:
START public List<Member> findMembers(PerunSession sess, Vo vo, String searchString, boolean onlySponsored) throws InternalErrorException { END return getMembersManagerImpl().findMembers(sess, vo, searchString, onlySponsored); } You don't need to explicitly declare InternalErrorException, because it is RuntimeException.

Target:
public List<Member> findMembers(PerunSession sess, Vo vo, String searchString, boolean onlySponsored) { return getMembersManagerImpl().findMembers(sess, vo, searchString, onlySponsored); }
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); START facilities.removeIf(facility -> AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); END return getFacilitiesManagerBl().getRichFacilities(sess, facilities); } Shouldn't be there a negation?

Target:
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); }
Source:
public String getValue(String value, Attribute attr) { START ObjectMapper mapper = new ObjectMapper(); END try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.warn("Error converting to JSON", value, e); return null; } } ``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)

Target:
public String getValue(String value, Attribute attr) { try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.warn("Error converting to JSON", value, e); return null; } }
Source:
public String toString() { String roles = ""; if (!this.isEmpty()) { for (String role: this.keySet()) { START roles += role.toLowerCase() + this.get(role) + ","; END } } return getClass().getSimpleName() + "[" + roles + "]"; } We can use upperCase format here too.

Target:
public String toString() { String roles = ""; if (!this.isEmpty()) { for (String role: this.keySet()) { roles += role + this.get(role) + ","; } } return getClass().getSimpleName() + "[" + roles + "]"; }
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { START if (attribute.valueAsString() == null) throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "Value can't be null"); END } Nit: It is not necessary to convert the value to String.

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

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

Target:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if(attribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "account expiration time shouldn't be null"); } }
Source:
public void checkAttributeSyntax(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { START Utils.notNull(attribute, "attribute"); END if (unpermittedLogins.contains(attribute.valueAsString())) throw new WrongAttributeValueException(attribute, user, "Login '" + attribute.getValue() + "' is not permitted."); super.checkAttributeSyntax(sess, user, attribute); } Object attribute should never be null. You can just skip this part if value of attribute is null.

Target:
public void checkAttributeSyntax(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException { if (unpermittedLogins.contains(attribute.valueAsString())) throw new WrongAttributeValueException(attribute, user, "Login '" + attribute.getValue() + "' is not permitted."); super.checkAttributeSyntax(sess, user, attribute); }
Source:
START public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { END 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}"); } } You can skip the part with instanceof String.

Target:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if (attribute.getValue() == null) return; if (!attribute.valueAsString().contains("{link}")) { throw new WrongAttributeValueException(attribute, key, "value doesn't contain contain tag {link}"); } }
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."); START } END } I think empty attribute can't be set any way in Perun so this one is probably not needed at all.

Target:
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."); }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Member member, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException { Attribute currentAttribute = getAttributeValue(sess, member, attribute); START if(!attribute.equals(currentAttribute)) throw new WrongReferenceAttributeValueException(attribute, currentAttribute, member, null, "Attribute value is not the highest value from member's UserExtSources Loas."); END } Also there is missing reference attribute holder.

Target:
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, member, null, "Attribute value is not the highest value from member's UserExtSources Loas."); }
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) && START !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) resIterator.remove(); END } return resources; } For PerunObserver you can return all resources immediately.

Target:
private List<Resource> filterNotAuthorizedResource(PerunSession sess, List<Resource> resources) throws InternalErrorException { Iterator<Resource> resIterator = resources.iterator(); if (AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { return resources; } while(resIterator.hasNext()) { Resource resource = resIterator.next(); if(!AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN, resource)) resIterator.remove(); } return resources; }
Source:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.isAuthorized(sess, Role.SELF) START && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); END return getDatabaseManagerBl().getCurrentDatabaseVersion(); } 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.

Target:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.isAuthorized(sess, Role.SELF)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }
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) { START log.debug("GET_USER_BY_USER_EXT_SOURCE"); END throw new UserNotExistsException("userExtSource=" + userExtSource.toString()); } catch (RuntimeException err) { throw new InternalErrorException(err); } } 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.

Target:
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) { throw new UserNotExistsException("userExtSource=" + userExtSource.toString()); } catch (RuntimeException err) { throw new InternalErrorException(err); } }
Source:
public int getAuditerMessagesCount(PerunSession perunSession) throws InternalErrorException, PrivilegeException { if (!AuthzResolver.isAuthorized(perunSession, Role.PERUNADMIN)) { throw new PrivilegeException(perunSession, "getAuditerMessagesCount"); START } END return getAuditMessagesManagerBl().getAuditerMessagesCount(perunSession); } This is probably used by nagios, so with these restrictions the probe can be broken.

Target:
public int getAuditerMessagesCount(PerunSession perunSession) throws InternalErrorException { return getAuditMessagesManagerBl().getAuditerMessagesCount(perunSession); }
Source:
public void updateUserExtSourceLastAccess(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { START getPerunBl().getAuditer().log(sess, new UserExtSourceUpdated(userExtSource)); END getUsersManagerImpl().updateUserExtSourceLastAccess(sess, userExtSource); } You should always generate message after the process is done. You can prevent unexpected issues.

Target:
public void updateUserExtSourceLastAccess(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { getUsersManagerImpl().updateUserExtSourceLastAccess(sess, userExtSource); getPerunBl().getAuditer().log(sess, new UserExtSourceUpdated(userExtSource)); }
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()); START Utils.copyAttributeToVirtualAttributeWithValue(namespaceGIDRangesAttribute, attribute); END return attribute; } I would change this like to `return Utils.copyAttributeToVirtual.......`

Target:
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()); return Utils.copyAttributeToVirtualAttributeWithValue(namespaceGIDRangesAttribute, attribute); }
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()); START Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); END return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } } Same here: `return Utils.copyAttribute.....`

Target:
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 namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); return Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); }
Source:
public void setStartTime(Long startTime) { START this.startTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); END } 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.

Target:
public void setStartTime(Long startTime) { if (startTime != null) { this.startTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); } else { this.startTime = null; } }
Source:
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException{ START if(actualValue.length() > maxLength) throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length()); END } You should cover also the case, when passed value is ``null``, since ``Candidate`` params titleBefore/titleAfter can be null or empty.

Target:
public static void checkMaxLength(String propertyName, String actualValue, int maxLength) throws MaxSizeExceededException { if (actualValue == null) { return; } if (actualValue.length() > maxLength) { throw new MaxSizeExceededException("Length of '" + propertyName + "' is too long! MaxLength=" + maxLength + ", ActualLength=" + actualValue.length()); } }
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); } START log.debug("[{}] TaskResult for destination sent to dispatcher.", taskResult.getTaskId(), END taskResult.getDestinationId()); } Please keep it in info level.

Target:
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.info("[{}] TaskResult for destination sent to dispatcher.", taskResult.getTaskId(), taskResult.getDestinationId()); }
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"); } START String value = attribute.valueAsString(); END } This line of code is useless.

Target:
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"); } }
Source:
public void removeAllExpiredBans() { if(perunBl.isPerunReadOnly()) { START log.debug("This instance is just read only so skip removing expired bans."); END return; } try { getPerun().getResourcesManagerBl().removeAllExpiredBansOnResources(sess); getPerun().getFacilitiesManagerBl().removeAllExpiredBansOnFacilities(sess); } catch (InternalErrorException ex) { log.error("Synchronizer: removeAllExpiredBans, exception {}", ex); } } also should be warning

Target:
public void removeAllExpiredBans() { if(perunBl.isPerunReadOnly()) { log.warn("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); } }
Source:
public AttributeDefinition createAttribute(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException, AttributeDefinitionExistsException { START return createAttribute(sess, attribute, false); END } There should be "true".

Target:
public AttributeDefinition createAttribute(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException, AttributeDefinitionExistsException { return createAttribute(sess, attribute, true); }
Source:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); dependencies.add(A_G_unixGID_namespace + ":*"); START dependencies.add(A_R_unixGID_namespace + ":*"); END return dependencies; } 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 + ":*"); ```

Target:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); //Disallowed because of crosschecks between modules and performance reason //dependencies.add(A_G_unixGID_namespace + ":*"); //dependencies.add(A_R_unixGID_namespace + ":*"); //Disallowed because it does not affect value of dependent attribute //dependencies.add(A_R_unixGroupName_namespace + ":*"); return dependencies; }
Source:
protected static void init(PerunSession sess) throws InternalErrorException { log.trace("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); START refreshAuthz(sess); END log.debug("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); } Please fix ``refreshAuthz(sess)`` implementation, it's not 1:1 replacement of above removed code right now.

Target:
protected static void init(PerunSession sess) throws InternalErrorException { log.trace("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); refreshAuthz(sess); log.trace("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); }
Source:
public void forceGroupSynchronization(PerunSession sess, Group group) throws GroupSynchronizationAlreadyRunningException, InternalErrorException { START Utils.notNull(group, "group"); END //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); } } We usually don't check for null objects in business logic layer. Any particular reason for it here?

Target:
public void forceGroupSynchronization(PerunSession sess, Group group) throws GroupSynchronizationAlreadyRunningException, InternalErrorException { //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); } }
Source:
START public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, GroupResourceMismatchException { END } 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.

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { }
Source:
public OIDC getOIDCManager(){ if(oidcManager == null){ START oidcManager = new OIDC(); END } return oidcManager; } Susceptible to race condition

Target:
public OIDC getOIDCManager(){ return oidcManager; }