auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void executeQueueTest() { try { startResource(); QueueCapability queueCapability = (QueueCapability) networkResource.getCapability(getOSPFInformation(CAPABILIY_TYPE)); queueCapability.execute(); stopResource(); } catch (ResourceException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } catch (ProtocolException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }

Target:
You don't need to catch, print and fail these exception. Simply declare them as part of the method signature and JUnit will fail the test for you if the exceptions should be thrown.
Source:
public ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }

Target:
This constructor should have package visibility instead of public
Source:
public Map<String, CacheEntry> getLayerBuildMap() { return _layerBuilds.getMap(); }

Target:
Restore visibility of fields and methods in this class to package level when unit tests are moved to jaggr-core
Source:
public List<IModule> getModules() { List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }

Target:
Restore visibility of methods in this class to package level when unit tests are moved to jaggr-core
Source:
public static InstallationChecker getInstance() throws ProvisionException { if (INSTANCE == null) { INSTANCE = new InstallationChecker(); } return INSTANCE; }

Target:
prefer the Initialization on Demand Holder pattern to cope with singletons http://blog.crazybob.org/2007/01/lazy-loading-singletons.html
Source:
public void testVertexCentricQuery() { int noVertices = 10000; }

Target:
is this what you wanted to do here? this is different from the previous PR that called `testVertexCentricQuery(10000)`
Source:
protected void setParentNode(GoloElement parent) { if (!(parent instanceof Union) || parent == null) { throw new IllegalArgumentException("UnionValue can only be defined in a Union"); } super.setParentNode(parent); }

Target:
Findbugs says "redundant nullcheck", indeed `parent instanceof Union` is `false` if `parent` is `null`.
Source:
public Tuple destruct() { LinkedList<T> vals = new LinkedList<>(); for (T v : this) { vals.add(v); } return Tuple.fromArray(vals.toArray()); }

Target:
Why not making an array right from the start, and avoid a `LinkedList`?
Source:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation instanceof FunctionInvocation && ((FunctionInvocation) invocation).usesNamedArguments()) { NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }

Target:
Can't we use named arguments on method invocation?
Source:
public MethodHandle find() { try { return resolve().asType(type); } catch (NoSuchMethodException | IllegalAccessException e) { throw new Error(e); } }

Target:
Is `Error` the right exception type? /cc @yloiseau
Source:
public boolean hasMethod(String method) { Object obj = properties.get(method); if(obj != null) { return (obj instanceof MethodHandle); } else { return false; } }

Target:
`if` `space` `(` (...)
Source:
public GoloFunction(String name, Visibility visibility, Scope scope) { this.name = name; this.visibility = visibility; this.scope = scope; this.main = this.name.equals("main"); }

Target:
It would be better to also check that the function is unary.
Source:
public static void addCodedObs(Patient p, String conceptName, String conceptAnswer, String date) { Obs o = new Obs(); o.setPerson(p); o.setConcept(MohCacheUtils.getConcept(conceptName)); o.setValueCoded(MohCacheUtils.getConcept(conceptAnswer)); o.setObsDatetime(MohTestUtils.makeDate(date)); Obs obs = Context.getObsService().saveObs(o, null); }

Target:
Why was this change necessary? I don't see a reason for it if we do not use `obs` later.
Source:
private String sourceName(Token t) { CharStream input = t.getInputStream(); String srcName = null; if ( input!=null ) { srcName = input.getSourceName(); if ( srcName!=null ) srcName = Misc.getFileName(srcName); } return srcName; }

Target:
Overall I like the refactoring, especially the deduplication! However, I suggest using early return as well as braces for all if statements: ```suggestion CharStream input = t.getInputStream(); if ( input==null ) { return null; } String srcName = input.getSourceName(); if ( srcName!=null ) { srcName = Misc.getFileName(srcName); } return srcName; ```
Source:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } //noinspection unchecked return renderers.get(attributeType); }

Target:
The attribute type needs to be exact here. ```suggestion public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<T> attributeType) { ```
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); String str = f.toString(); f.close(); return str; }

Target:
:bulb: This code should be in a try/finally for exception-safe closing of the `Formatter` instance.
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = null; String str = ""; try { f = new Formatter(locale); f.format(formatString, o); str = f.toString(); } finally { if (f != null) f.close(); } return str; }

Target:
:bulb: Slight simplification ``` java Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } ```
Source:
protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); // Set up the progress bar final View vProgressEmpty = (View) findViewById(R.id.vProgressEmpty); vProgressEmpty.post(new Runnable() { @Override public void run() { mProgressWidth = vProgressEmpty.getMeasuredWidth(); updateProgress(); } }); }

Target:
Why is there a runnable needed here? Are you sure this will work on all devices? (the runnable does UI work)
Source:
public FongoDBCollection(FongoDB db, String name) { super(db, name); this.fongoDb = db; this.nonIdCollection = name.startsWith("system"); this.expressionParser = new ExpressionParser(); this.updateEngine = new UpdateEngine(); this.objectComparator = expressionParser.buildObjectComparator(true); this._idIndex = new Index("_id", new BasicDBObject("_id", 1), true); this.indexes.put(Collections.singleton("_id"), _idIndex); }

Target:
You probably don't want this if this is a nonIdCollection
Source:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { // If the jam has just ended or the score is now official, write out a file. if ((inJam && !bool(state.get("ScoreBoard.InJam"))) || (bool(state.get("ScoreBoard.OfficialScore")) && !bool(state.get("ScoreBoard.StatsLocked")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }

Target:
A simpler way to do this would be to make this just `bool(state.get("ScoreBoard.OfficialScore")` without the state. We can then filter out the Clock changes if we want to.
Source:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { set(Value.CURRENT_JAM, s.getCurrentJam()); getLast(NChild.JAM).unlink(); } } }

Target:
The jam should be moved, not deleted. Deleting will remove all the lineups etc that have been entered for the jam.
Source:
String getPath(ScoreBoardEventProvider p) { String path = ""; if (p.getParent() != null) { path = getPath(p.getParent()) + "."; } path = path + p.getProviderName(); if (!"".equals(p.getProviderId()) && p.getProviderId() != null) { path = path + "(" + p.getProviderId() + ")"; } return path; }

Target:
This is a bit odd. p.getProviderId() != null && !p.getProviderId().isEmpty() I think there may also be cases where an empty value is valid
Source:
public static ScoreBoardClock getInstance() { if (instance == null) { instance = new ScoreBoardClock(); } return instance; }

Target:
If you're doing this you need locking. A static initialiser might be simpler.
Source:
public void registerClient(ScoreBoardClockClient client) { clients.add(client); }

Target:
This should be synchronized
Source:
public void timeout() { synchronized (runLock) { createSnapshot(ACTION_TIMEOUT); requestBatchStart(); _startTimeout(); requestBatchEnd(); ScoreBoardManager.gameSnapshot(); } }

Target:
You use a batch here for a single call that also starts a batch, but not in stopJamTO which does similar.
Source:
public void ensureAtLeastNPeriods(int n) { synchronized (this) { while (periods.size() < n) { PeriodStatsModel psm = new DefaultPeriodStatsModel(periods.size() + 1); psm.addScoreBoardListener(this); periods.add(psm); } } }

Target:
Is there a reason to go with `synchronized (this)` in this file instead of just adding the `synchronized` keyword to the method signature?
Source:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) addMediaElement(typeDir.getName(), files.next()); // Ensure we have an entry, even if dir is empty. synchronized (updateLock) { update(createTypeElement(typeDir.getName())); } }

Target:
There should be brackets on the preceding while in order to make clear that the new code is intended to not be part of the loop.
Source:
public HCatClient getHCatClient() throws InterruptedException { HCatClient hcatClient = null; int retryCount = 0; while (hcatClient == null && retryCount < numOfRetries) { hcatClient = hcatUtil.getHCatClient(); retryCount++; } return hcatClient; }

Target:
don't retry here as for getting hcatclient blocking queue with timeout is being used
Source:
private ForkliftConsumerI getGroupedTopic(GroupedTopicSource source) throws ConnectorException { if (!source.groupSpecified()) throw new ConnectorException("No consumer group specified"); // Sanitize the group and topic names so that group and topic names don't accidentally // mess up ActiveMQ's pattern matching final String groupName = source.getGroup().replaceAll("\\.", "_"); final String topicName = source.getName().replaceAll("\\.", "_"); return getConsumerForSource(new QueueSource("Consumer." + groupName + ".VirtualTopic." + topicName)); }

Target:
should this be `new GroupedTopicSource`?
Source:
public synchronized void stop() throws ConnectorException { try { if (controller != null) { this.controller.stop(2000, TimeUnit.MILLISECONDS); this.controller = null; } } catch (InterruptedException e) { log.error("KafkaConnector interrupted while stopping"); } if (kafkaProducer != null) { this.kafkaProducer.close(); this.kafkaProducer = null; } }

Target:
Minor nit: there are a lot of redundant `this` references lying around.
Source:
private OffsetAndMetadata greaterOffset(OffsetAndMetadata a, OffsetAndMetadata b) { if (a == null) { return b; } else if (b == null) { return a; } return a.offset() > b.offset() ? a : b; }

Target:
You shouldn't _need_ to check for null here, since the merge function will only be called if there is an existing value (which should always be non-null).
Source:
public KafkaForkliftProducer(String topic, KafkaProducer<?, ?> kafkaProducer) { this.kafkaProducer = kafkaProducer; this.topic = topic; Schema.Parser parser = new Schema.Parser(); this.forkliftSchema = parser.parse( "{\"type\":\"record\",\"name\":\"ForkliftMessage\"," + " \"doc\":\"Non-Avro messages sent through forklift use this schema.\",\"fields\":" + "[{\"name\":\"forkliftValue\",\"type\":\"string\",\"default\":\"\", \"doc\":\"The forklift message. " + "3 formats are supported. 1: string value, 2: Json object," + "3: Map represented by key,value entries delimited with newline\"}," + "{\"name\":\"forkliftProperties\",\"type\":\"string\",\"default\":\"\"," + "\"doc\":\"Properties added to support forklift interfaces. Format is key,value entries delimited with new lines\"}]}"); }

Target:
Isn't this constant and shared across all producers? Then can't it be static?
Source:
public String getString (String name, String def) { String value = (String)_data.get(name); return StringUtil.isBlank(value) ? def : value; }

Target:
This is another behavioral change that I don't want to see in an unrelated PR.
Source:
public ShellSpout(String... command) { _command = command; _process = new ShellProcess(new JsonSerializer(), _command); }

Target:
hardcoded `JsonSerializer` should not be here, we might have a `default serializer` specified in `defaults.yaml`
Source:
private void handleError(Map action) { String msg = (String) action.get("msg"); if (msg != null) { _collector.reportError(new Exception("Shell Process Exception: " + msg)); } }

Target:
Why do you have to check for null here?
Source:
@Nullable public LatLng parseLatLng(String value) { if (value == null) { return null; } String[] components = value.split(","); if (components.length != 2) { return null; } try { return new LatLng(Double.valueOf(components[0]), Double.valueOf(components[1])); } catch (NumberFormatException e) { return null; } }

Target:
Shouldn't it be `static`?
Source:
protected byte[] searchRaw(Query query) throws AlgoliaException { String paramsString = query.getQueryString(); if (paramsString.length() > 0) return client.getRequestRaw("/1/indexes/" + encodedIndexName + "?" + paramsString, true); else return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); }

Target:
brackets :wink:
Source:
public void run() { countDown--; if (countDown == 0) { System.out.println("## interrupt"); Thread.currentThread().interrupt(); } }

Target:
I don't think we need to keep this println.
Source:
public void blockingStreamShouldNotPreventDiagnosis() throws Exception { FastPipedInputStream in = new FastPipedInputStream(); try (FastPipedOutputStream out = new FastPipedOutputStream(in)) { out.write(payload); } ClassicCommandTransport ct = (ClassicCommandTransport) new ChannelBuilder("dummy",null) .withMode(Mode.BINARY) .withBaseLoader(getClass().getClassLoader()) .negotiate(in, new NullOutputStream()); verify(ct); }

Target:
Shouldn't both the stream opening statements be inside the try with resources? ```suggestion try (FastPipedInputStream in = new FastPipedInputStream(); FastPipedOutputStream out = new FastPipedOutputStream(in)) { ```
Source:
private FastPipedInputStream sink() throws IOException { FastPipedInputStream s = sink.get(); if (s==null) throw (IOException) new IOException("Reader side has already been abandoned", allocatedAt); return s; }

Target:
```suggestion if (s==null) throw new IOException("Reader side has already been abandoned", allocatedAt); ```
Source:
public void testDeadWriterNotification() throws Exception { final OutputStream os = new RemoteOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { System.gc(); throw (IOException) new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); } }); channel.call(new DeadWriterCallable(os)); }

Target:
```suggestion throw new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); ```
Source:
protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. if(channel!=null) { channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }

Target:
`&& oid != -1`
Source:
public FileSystemJarCache(@Nonnull File rootDir, boolean touch) { this.rootDir = rootDir; this.touch = touch; if (rootDir==null) throw new IllegalArgumentException("Root directory is null"); try { Util.mkdirs(rootDir); } catch (IOException ex) { throw new IllegalArgumentException("Root directory not writable: " + rootDir); } }

Target:
Can we append cause so admins has a chance to identify the cause and fix?
Source:
public synchronized Object getProperty(Object key) { return properties.get(key); }

Target:
Hmmm are we sure we want to depend on the `Channel` monitor... for property access it may be preferential to use `properties` as the monitor object
Source:
/*package*/ static ClassFilter createDefaultInstance() { List<Pattern> patternOverride = loadPatternOverride(); try { if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { // when being used by something like XStream the actual cause gets swallowed LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); throw e; } }

Target:
I'm not a big fan of this construct, because it may hide the original OOM if a new one happens within Logger listeners. But good for other error types
Source:
public void putWithAuthentication(String url, String username, String password, int id, Model model, AsyncHttpResponseHandler response) throws UnsupportedEncodingException { Header[] headers = { createBasicAuthenticationHeader(username, password) }; String body = model.getData().toString().substring(0); put(url, id, new ArrayList<Header>(Arrays.asList(headers)), body, response); }

Target:
Why the `.substring(0)`?
Source:
public Variable getVariableInstance(){ if(v_inst == null){ v_inst = new Variable(getVariableIdentifierInstance(), getTypeExpression()); } return v_inst; }

Target:
Why do you need to lazily create the variable instance? I think our convention so far has been that the `get*Instance()` methods always create a new instance and tests that require the same instance multiple times just hold a local copy.
Source:
private NamespaceIdentifier getNamespaceIdentifierInstance() { if (namespaceIdentifierInstance == null) { ArrayList<String> name = new ArrayList<String>(1); name.add("whdl"); namespaceIdentifierInstance = new NamespaceIdentifier(name); } return namespaceIdentifierInstance; }

Target:
Same feedback as above
Source:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException{ // FIXME this does not handle namespaces correctly Variable v = symbolTable.get(identifier); if(v == null){ // no such variable in this scope; check parent scope if(parentScope == null){ throw new VariableNotDefinedException(identifier); } return parentScope.getVariable(identifier); }else{ return v; } }

Target:
Throw this in an `else` clause
Source:
public static boolean validQuestionGroups(final Survey survey){ return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable().booleanValue()).collect(Collectors.toList()).size() == 0; }

Target:
Why do we need an explicit `boolean` primitive? .... using `i.getRepeatable()` does the trick
Source:
private Entity event(Entity entity) { String kind = entity.getKey().getKind(); final EventTypes eventTypes = EventUtils .getEventAndActionType(kind); if (eventTypes != null) { Map<String, Object> event = updateOrCreateEvent(entity, eventTypes); try { return EventUtils.createEventLogEntity(event, new Date()); } catch (IOException e) { throw new RuntimeException(e); } } return entity; }

Target:
Does this mean if no event type is found then the entity would get stored as is in the event queue?
Source:
void testValidSheets() throws IOException { DataImporter dimp = new RawDataSpreadsheetImporter(); //Check that a canonical file passes File file1 = createValidTestSpreadsheet("/tmp/valid1.xlsx"); Map<Integer,String> errors = dimp.validate(file1); for (Integer i: errors.keySet()) { System.out.printf("Unexpected error, row %d: %s", i, errors.get(i)); } assertEquals(0, errors.size()); }

Target:
In this case rather than print out the errors, since it’s supposed to be a valid test sheet, you should assert that errors is empty and that should be enough. If it isn’t empty I believe it prints out the error map
Source:
public void setGeoLocation(String geoLocationString) { String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) return; this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }

Target:
Just in case: is it possible that geoLocationString is null?
Source:
private SurveyAssignment marshallToDomain(SurveyAssignmentDto dto) { //String[] handsOff = {"keyId", "key"}; final SurveyAssignment sa = new SurveyAssignment(); BeanUtils.copyProperties(dto, sa); sa.setKey(KeyFactory.createKey("SurveyAssignment", dto.getKeyId())); sa.setDeviceIds(dto.getDevices()); sa.setSurveyIds(dto.getSurveys()); return sa; }

Target:
Perhaps only set the key when `keyId != null`.
Source:
protected List<QuestionDto> parseQuestions(String response) throws Exception { final ObjectMapper JSON_RESPONSE_PARSER = new ObjectMapper(); List<QuestionDto> dtoList = new ArrayList<QuestionDto>(); final JsonNode questionListNode = JSON_RESPONSE_PARSER.readTree(response).get("dtoList"); final List<QuestionDto> qList = JSON_RESPONSE_PARSER.readValue( questionListNode, new TypeReference<List<QuestionDto>>() { }); dtoList.addAll(qList); //Why? return dtoList; }

Target:
Returning `qList`here should be enough, unless `qList` is null
Source:
public static Map<String, Object> parseCaddisflyResponseValue(String caddisflyValue) { Map<String, Object> caddisflyResponseMap = new HashMap<String, Object>(); try { caddisflyResponseMap = JSON_OBJECT_MAPPER.readValue(caddisflyValue, Map.class); } catch (IOException e) { log.error("Failed to parse the caddisfly response"); } if (caddisflyResponseMap != null) { return caddisflyResponseMap; } else { return Collections.emptyMap(); } }

Target:
new HashMap<>(), explicit type is no longer necessary
Source:
private boolean areLeafNodes(CascadeNodeDao dao, Long cascadeResourceId, List<CascadeNode> nodes) { if (nodes.size() == 0) { return true; } else { CascadeNode firstNode = nodes.get(0); List<CascadeNode> childNodes = dao.listCascadeNodesByResourceAndParentId( cascadeResourceId, firstNode.getKey().getId()); return childNodes.size() == 0; } }

Target:
Perhaps you can move the `nodes.size() == 0` branch to just before the `if(!areLeafNodes())`. This way the meaning of the `areLeafNodes()` function is not mixed with checking if the list of nodes is empty.
Source:
public List<SurveyGroup> listByProjectFolderId(Long parentId) { parentId = parentId < 0 ? null : parentId; return super.listByProperty("parentId", parentId, "Long"); }

Target:
It's not a good practice to override a parameter, create a local variable to default `parentId` to `null`
Source:
private String[] parseCredentials(String credentialsString) { if (credentialsString == null) throw new BadCredentialsException("Authorization required"); String[] credentials = credentialsString.split(":"); if (credentials.length != 2) throw new BadCredentialsException("Authorization required"); return credentials; }

Target:
Do we want to `.trim()` the 2 parts to avoid possible problems if an `Authorization` header comes like `<key> : <signature>` ?
Source:
public void existsByExampleShouldReturnNonExistingWithoutThrowException() { Example<ReactivePerson> example = Example.of(new ReactivePerson("foo", "bar", -1)); StepVerifier.create(repository.findOne(example)).expectNextCount(0).verifyComplete(); }

Target:
`.expectNextCount(0)` can be omitted and simplified to `StepVerifier.create(repository.findOne(example)).verifyComplete();`
Source:
public DBObject fetch(DBRef dbRef) { return ReflectiveDBRefResolver.fetch(MongoClientVersion.isMongo3Driver() ? mongoDbFactory.getDb() : null, dbRef); }

Target:
Wouldn't the test case become much simple if we just handed the factory into the fetch method? `ReflectiveDbRefResolver` does an `isMongo3Driver()` anyway, so why not just lookup the `DB` within that guard? That would be a simple unit test for `ReflectiveDbRefResolver.fetch(MongoDbFactory, DBRef)` then, wouldn't i?
Source:
public void updateFirstShouldDoNothingWhenCalledForEntitiesThatDoNotExist() { Query q = query(where("id").is(Long.MIN_VALUE)); assumeThat(template.findOne(q, VersionedPerson.class), nullValue()); template.updateFirst(q, Update.update("lastname", "supercalifragilisticexpialidocious"), VersionedPerson.class); assertThat(template.findOne(q, VersionedPerson.class), nullValue()); }

Target:
Do we need that `assumeThat(…)` here? I'm not a big fan of them as they essentially express: "we expect the precondition to fail but don't want the test to fail then" which is not really what we're doing here, right?
Source:
public String getServerVersion() { if (getStorageState() != State.UPDATED) { return NEED_UPDATE; } String version = updateStatus.getServerVersion(); return version == null ? "Unknown" : version; }

Target:
I made this change because the `GlobalStorageStatus.getServerVersion()` method is annotated with `@CheckForNull` and I got an issue, that's why I added the check. So we can just ignore the issue ?
Source:
public UserRole[] getAllowedRoles() { return new UserRole[] { UserRole.MANAGER, UserRole.ADMINISTRATOR }; }

Target:
Probably smarter that way yes
Source:
private SourceSystemId parseSource(String lahdeJarjestelmaId) { if (StringUtils.isNotBlank(lahdeJarjestelmaId) && lahdeJarjestelmaId.contains(":")) { KoskiStudyProgrammeHandler handler = KoskiStudyProgrammeHandler.valueOf(StringUtils.substringBefore(lahdeJarjestelmaId, ":")); Long studentId = Long.valueOf(StringUtils.substringAfter(lahdeJarjestelmaId, ":")); return new SourceSystemId(handler, studentId); } return null; }

Target:
No biggie but StringUtils.contains(lahdeJarjestelmaId, ":") should work just the same.
Source:
private Enum reverseLookup(Class enumClass, String enumValue) { try { Method reverseLookupMethod = enumClass.getMethod("reverseLookup", String.class); if (reverseLookupMethod != null) { Enum e = (Enum) reverseLookupMethod.invoke(null, enumValue); return e; } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) { } return null; }

Target:
I suppose null check is irrelevant, as getMethod would have thrown an exception about a missing method already?
Source:
protected String getDiaarinumero(Student student) { Long studyProgrammeId = student.getStudyProgramme() != null ? student.getStudyProgramme().getId() : null; Long curriculumId = student.getCurriculum() != null ? student.getCurriculum().getId() : null; if ((studyProgrammeId != null) && (curriculumId != null)) return settings.getDiaariNumero(studyProgrammeId, curriculumId); else return null; }

Target:
Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html
Source:
protected boolean isPakollinenOppiaine(Student student, KoskiOppiaineetYleissivistava oppiaine) { Set<KoskiOppiaineetYleissivistava> pakollisetOppiaineet = settings.getPakollisetOppiaineet(student.getStudyProgramme().getId()); if (pakollisetOppiaineet != null) return pakollisetOppiaineet.contains(oppiaine); // TODO Vapautetut aineet return false; }

Target:
Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html
Source:
public static ArviointiasteikkoYleissivistava bestGrade(Collection<ArviointiasteikkoYleissivistava> collection) { ArviointiasteikkoYleissivistavaComparator comparator = new ArviointiasteikkoYleissivistavaComparator(); ArviointiasteikkoYleissivistava bestGrade = null; for (ArviointiasteikkoYleissivistava grade : collection) { if (bestGrade == null || comparator.compare(grade, bestGrade) > 0) bestGrade = grade; } return bestGrade; }

Target:
Braces
Source:
public UserRole[] getAllowedRoles() { return new UserRole[] { UserRole.MANAGER, UserRole.STUDY_PROGRAMME_LEADER, UserRole.ADMINISTRATOR }; }

Target:
Should be limited to just UserRole.ADMINISTRATOR, just in case.
Source:
private void execute(IExecution<DB> execution, boolean asTransaction) { query( db -> { execution.execute(db); return Optional.empty(); }, asTransaction ); }

Target:
```suggestion return null; ``` Nitpick: returning `null` also works, and is slightly simpler.
Source:
public DbMetricsImpl(int maxTotalConnections, int minIdleConnections, long maxWaitMillis, long keepAliveMillis) { startTime = System.currentTimeMillis(); this.maxTotalConnections = maxTotalConnections; this.minIdleConnections = minIdleConnections; this.maxWaitMillis = maxWaitMillis; this.keepAliveMillis = keepAliveMillis; }

Target:
Since all the other parameters here are referred to with `this.`, let's keep the same style for `startTime`.
Source:
public T get() { if (persistence == null) { synchronized (this) { this.persistence = build(conn, databases); } } if (disableCaching) { persistence.disableCaching(); } return persistence; }

Target:
is the synchronization around trying to prevent people from simultaneously using the database connection? if so, I think there's a case where you call get() on two persistences simultaneously and it'll use it at the same time. if that's the goal then synchronizing on conn seems safer.
Source:
public DatabasesImpl() { this(new DatabaseConnection("database1")); }

Target:
I don't think this will do what we want though, because new DatabaseConnection("database1") will try to load the db's properties from the yaml. We need that connection to be lazily instantiated.
Source:
private boolean hasContextMultipleReferences(Context context) { int counter = 0; Iterator<Context> iterator = context.getHost().getContexts().iterator(); while (counter <= 1) { if (!iterator.hasNext()) break; if (context.getPath().equals(iterator.next().getPath())) { ++counter; } } return counter > 1; }

Target:
This can be moved to the while condition to avoid unnecessary break.
Source:
public void should_throw_error_if_consumer_array_is_null() { // GIVEN Consumer<String>[] consumers = null; Object o = null; String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }

Target:
Object ```o``` is never used. ```suggestion ```
Source:
public AbstractStringAssert<?> asHexString() { objects.assertNotNull(info, actual); return Assertions.assertThat(Hexadecimals.toHexString(actual)); }

Target:
static imports
Source:
private short toShort(int value) { return (short) value; }

Target:
minor: make it static
Source:
public final boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Tuple)) return false; Tuple other = (Tuple) obj; return Arrays.deepEquals(values.toArray(), other.values.toArray()); }

Target:
I'm ok with that, we might even put the class as final, I don't see why people would subclass `Tuple` it's really an immutable data class.
Source:
public void assertHasSuperclass(AssertionInfo info, Class<?> actual, Class<?> superclass) { assertNotNull(info, actual); Class<?> actualSuperclass = actual.getSuperclass(); if (actualSuperclass == null && superclass != null || actualSuperclass != null && !actualSuperclass.equals(superclass)) { throw failures.failure(info, shouldHaveSuperclass(actual, superclass)); } }

Target:
add `()` to group && conditions for clarity
Source:
private ShouldHaveMessage(Throwable actual, String expectedMessage) { super("%n" + "Expecting message to be:%n" + " <%s>%n" + "but was:%n" + " <%s>%n" + "%n" + "Throwable that failed the check:%n" + "%n" + Strings.escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting expectedMessage, actual.getMessage()); }

Target:
style: prefer static import
Source:
private boolean hasCharacteristic(int characteristics, int characteristic) { return (characteristics & characteristic) == characteristic; }

Target:
can be static
Source:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { if (parameterContext.getParameter().getType() == SoftAssertions.class) { return getStore(extensionContext).getOrComputeIfAbsent(SoftAssertions.class); } return getStore(extensionContext).getOrComputeIfAbsent(BDDSoftAssertions.class); }

Target:
Done in latest commit: 21f5677
Source:
public SELF isBefore(LocalDateTime other) { Objects.instance().assertNotNull(info, actual); assertLocalDateTimeParameterIsNotNull(other); comparables.assertIsBefore(info, actual, other); return myself; }

Target:
Mentioning and explaining the breaking change should be done for all changed assertions, I know that's a bit of work but I think it is necessary.
Source:
public <T extends Comparable<? super T>> void assertLessThan(AssertionInfo info, T actual, T other) { this.assertLessThan(info, actual, other, ShouldBeLess::shouldBeLess); }

Target:
minor: remove `this.`
Source:
public void check(ThrowingRunnable assertion) { try { assertion.run(); } catch (AssertionError error) { proxies.collectError(error); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
it would be nice to catch runtime and rethrow them as is instead wrapping in them in another runtime.
Source:
public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), null, Arrays.asList("name"))) .withMessage(actualIsNull()); }

Target:
replace all `Arrays.asList` by `org.assertj.core.util.Lists.list` and static import it for readability.
Source:
private AssertionError assertionFailedError(String message) { try { Object o = constructorInvoker.newInstance("org.opentest4j.AssertionFailedError", MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR, message, actual, expected); if (o instanceof AssertionError) { AssertionError assertionError = (AssertionError) o; Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); return assertionError; } return null; } catch (Throwable e) { return null; } }

Target:
the code was correct as per https://github.com/ota4j-team/opentest4j/blob/master/src/main/java/org/opentest4j/AssertionFailedError.java#L65 where expected comes before actual.
Source:
protected void verify_internal_effects() { verify(iterables).assertHasOnlyOneElementSatisfying(info(), newArrayList(internalArray()), consumer); }

Target:
use `list` in place of `newArrayList`, it does the same thing but is a bit lighter to read.
Source:
public void should_initialise_actual() { Iterator<String> names = asList("Luke", "Leia").iterator(); Iterable<String> actual = (Iterable<String>) assertThat(names).toIterable().actual; assertThat(actual).containsOnly("Leia", "Luke"); }

Target:
this test class should only deal with `Iterator`, `actual` should be an `Iterator` and not an `Iterable`
Source:
public SELF isEqualTo(ZonedDateTime expected) { Objects.instance().assertNotNull(info, actual); assertDateTimeParameterIsNotNull(expected); return super.isEqualTo(sameInstantInActualTimeZone(expected)); }

Target:
To be consistent with `AbstractAssert.isEqualTo`, this assertion should pass when both actual and expected are null. a possible implementation would be to make `sameInstantInActualTimeZone` return null when given null.
Source:
public void should_fail_when_asserting_no_exception_raised_but_exception_occurs() { // Given Exception exception = new Exception("boom"); ThrowingCallable boom = raisingException(exception); // Expect thrown.expectAssertionError(ShouldNotHaveThrown.shouldNotHaveThrown(exception)); // When assertThatCode(boom).doesNotThrowAnyException(); }

Target:
`startsWith` and `contains` String assertions should do the job.
Source:
public void catchThrowableOfType_should_succeed_and_return_actual_instance_with_correct_class() { final Exception expected = new RuntimeException("boom!!"); Exception actual = null; try { actual = catchThrowableOfType(raisingException(expected), Exception.class); } catch (AssertionError a) { Fail.fail("catchThrowableOfType should not have asserted", a); } assertThat(actual).isSameAs(expected); }

Target:
static import `fail`
Source:
private boolean notNullSeqContainsOnlyWhitespaces(CharSequence actual) { for (int i = 0; i < actual.length(); i++) { if (!Character.isWhitespace(actual.charAt(i))) return false; } return true; }

Target:
minor static import `isWhitespace` for readability
Source:
private boolean isNullOrEmpty(CharSequence actual) { return (actual == null || actual.length() == 0); }

Target:
remove unnecessary parenthesis
Source:
private static List<Object> flattenNonRecursive(Collection<? extends Object> list) { List<Object> result = new ArrayList<>(); LinkedList<Object> stack = new LinkedList<>(list); while (!stack.isEmpty()) { Object e = stack.pop(); if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else result.add(e); } return result; }

Target:
format as: ```java if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else result.add(e); ```
Source:
protected String defaultErrorMessage(Description description, Representation representation) { if (actualAndExpectedHaveSameStringRepresentation()) { return defaultDetailedErrorMessage(description, representation); } return comparisonStrategy.isStandard() ? messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE, actual, expected) : messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE_USING_COMPARATOR, actual, expected, comparisonStrategy); }

Target:
why has this changed to `protected` ?
Source:
public void should_create_AssertionError_if_created_ComparisonFailure_and_AssertionFailedError_is_null() throws Exception { when(constructorInvoker.newInstance(any(String.class), any(Class[].class), anyVararg())).thenReturn(null); AssertionError error = factory.newAssertionError(description, new StandardRepresentation()); check(error); }

Target:
`anyVararg` is deprecated, is that possible to use something else here ?
Source:
public void assertHasDeclaredMethods(AssertionInfo info, Class<?> actual, String... methods) { assertNotNull(info, actual); doAssertHasMethods(info, actual, actual.getDeclaredMethods(), methods); }

Target:
how do you now in `doAssertHasMethods` that the error message is about declared methods and not methods ?
Source:
public void should_pass_if_actual_contains_given_values_exactly_with_null_elements() { iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia")); actual.add(null); iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia", null)); }

Target:
I would just shuffle the order
Source:
public void should_pass_if_difference_is_less_than_given_percentage() { bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(valueOf(1))); bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(valueOf(50))); }

Target:
If I'm not wrong, the difference = 1 and the allowed margin is 2*50%=1, so the difference == allowed margin and not < margin. you need to move this to `should_pass_if_difference_is_equal_to_given_percentage`
Source:
public void should_pass_if_actual_contains_only_expected_entries() throws Exception { maps.assertContainsOnlyKeys(someInfo(), actual, "name", "color"); }

Target:
add `maps.assertContainsOnlyKeys(someInfo(), actual, "color", "name");` to check that order does not matter
Source:
public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(autoScalingGroups); this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } }

Target:
autoScalingGroups should be soloInstances
Source:
protected MavenModuleSet getProject() { MavenModuleSet project = createJob(); copyFilesToWorkspace(project, "checkstyle-qualitygate.xml"); copyToWorkspace(project, "pom.xml"); return project; }

Target:
s. Baseclass Kommentar
Source:
protected FileAnnotation getErrorNumber( final int number) throws IOException { Collection<FileAnnotation> warnings = new SdccParser().parse(openFile("sdcc_Output.txt")); Iterator<FileAnnotation> iterator = warnings.iterator(); FileAnnotation annotation = iterator.next(); for(int i = 1; i < number; i++) { annotation = iterator.next(); } return annotation; }

Target:
Use a list to access at index
Source:
public ClangTidyParser() { super(Messages._Warnings_ClangTidy_ParserName(), Messages._Warnings_ClangTidy_LinkName(), Messages._Warnings_ClangTidy_TrendName(), CLANG_TIDY_WARNING_PATTERN, false); }

Target:
false is default
Source:
public DrMemoryParser() { super(Messages._Warnings_DrMemory_ParserName(), Messages._Warnings_DrMemory_LinkName(), Messages._Warnings_DrMemory_TrendName(), DR_MEMORY_WARNING_PATTERN, true); }

Target:
If the last parameter is true, then you need to override isLineInteresting. Otherwise remove true.
Source:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); request.setServletPath("/destination"); request.setQueryString("param1=a&param2=b&param3=1122"); return request; }

Target:
We should not have to set the servlet path for this test to pass.
Source:
private Set<SignatureAlgorithm> fetchSignatureAlgorithms() { if (StringUtils.isEmpty(jwkSetUri)) { return Collections.emptySet(); } try { return parseAlgorithms(JWKSet.load(toURL(jwkSetUri), 5000, 5000, 0)); } catch (Exception ex) { log.error("Failed to load Signature Algorithms from remote JWK source."); return Collections.emptySet(); } }

Target:
Let's please use the `JWKSource` to retrieve JWKs. That will allow you to use a `JWKMatcher` that removes some of the validation you are doing in `parseAlgorithms`.
Source:
public NimbusJwtDecoder build() { ConfigurableJWTProcessor<SecurityContext> processor = processor(); jwtProcessorCustomizer.accept(processor); return new NimbusJwtDecoder(processor); }

Target:
It seems like the delta would be less if you had `processor()` use the `jwtProcessorCustomizer` instead. Any reason that it needs to be inside the `build()` method?
Source:
JWTProcessor<SecurityContext> processor() { ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations); JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource)); // Spring Security validates the claim set independent from Nimbus jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); jwtProcessorCustomizer.accept(jwtProcessor); return jwtProcessor; }

Target:
For consistency with the rest of the code here, will you please prefix member variable references with `this.`?
Source:
public SwitchUserWebFilter(ReactiveUserDetailsService userDetailsService, String successTargetUrl, @Nullable String failureTargetUrl) { Assert.notNull(userDetailsService, "userDetailsService must be specified"); Assert.notNull(successTargetUrl, "successTargetUrl must be specified"); this.userDetailsService = userDetailsService; this.successHandler = new RedirectServerAuthenticationSuccessHandler(successTargetUrl); this.failureHandler = Optional.ofNullable(failureTargetUrl). map(RedirectServerAuthenticationFailureHandler::new).orElse(null); this.securityContextRepository = new WebSessionServerSecurityContextRepository(); this.userDetailsChecker = new AccountStatusUserDetailsChecker(); }

Target:
In order to reduce the overhead of creating additional objects, we prefer to use null checks instead of `Optional.ofNullable`. For more information see gh-7155.
Source:
protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { final ServerWebExchange exchange = webFilterExchange.getExchange(); final SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return securityContextRepository.save(exchange, securityContext) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); }

Target:
I believe this method should be private. If a user wishes to override this behavior they can supply a custom successHandler. Similar for `onAuthenticationFailure`.
Source:
protected Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }

Target:
Could you explain why `switchUser` and `attemptSwitchUser` are split up this way? Would it make sense to combine them into a single method? Similar question for `exitSwitchUser` and `attemptExitUser`.
Source:
default Map<String, Object> getAttributes() { return Collections.emptyMap(); }

Target:
Since a SAML Attribute map can have multiple values, the type here should be `Map<String, List<Object>>`.
Source:
default <A> A getAttribute(String name) { return (A) getAttributes().get(name); }

Target:
I agree that to get the underlying list you can call `getAttributes().get("tenant")`. Since there is the possibility of adding both somewhere down the road, I'm leaning more heavily now towards renaming this method to `getFirstAttribute`. I believe this aligns nicely with `MultiValueMap` which is similar in concept and also has a method called `getFirst()`.
Source:
@Override public boolean isMergeEnabled() { return true; }

Target:
Can you please put `@Override` on its own line to be consistent with Spring Security code conventions? ```suggestion @Override public boolean isMergeEnabled() { ```
Source:
@Override public Object merge( Object parent ) { if (parent == null) { return this; } if (parent instanceof MockHttpServletRequestBuilder) { this.mergeable = (Mergeable) parent; return this.mergeable; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } }

Target:
I think we can just check if it is an instance of `Mergeable` since that is what we are casting it to. The check for what we pass in is a `MockHttpServletRequestBuilder` will be done when we invoke `MockHttpServletRequestBuilder.merge`
Source:
private void configure(B builder) { OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = createAuthorizationRequestRedirectFilter(builder); builder.addFilter(postProcess(authorizationRequestRedirectFilter)); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = createAuthorizationCodeGrantFilter(builder); RequestCache requestCache = builder.getSharedObject(RequestCache.class); if (requestCache != null) { authorizationCodeGrantFilter.setRequestCache(requestCache); } builder.addFilter(postProcess(authorizationCodeGrantFilter)); }

Target:
Can you move this logic to `createAuthorizationCodeGrantFilter()`
Source:
public void setAuthenticationManager(AuthenticationManager authenticationManager) { Assert.notNull(authenticationManager, "authenticationManager cannot be null"); this.authenticationManager = authenticationManager; }

Target:
This is not really making any guarantees since the value is possibly null before, so we don't do an assertion here.
Source:
public Resource retrieveResource(URL url) { String jwkSet = cache.get(url.toString(), () -> resourceRetriever.retrieveResource(url).getContent()); return new Resource(jwkSet, "UTF-8"); }

Target:
I think we may want to wrap any exception in an `IOException`, like `RestOperationsResourceRetriever` does. The reason for that is so that Nimbus's `RemoteJWKSet` can react appropriately and throw its `RemoteKeySourceException`. My concern is that adding this cache will change the exception callers see from a `RemoteKeySourceException` to a `ValueRetreivalException`.
Source:
public void setPostLogoutRedirectUri(URI postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be empty"); this.postLogoutRedirectUriTemplate = postLogoutRedirectUri.toASCIIString(); }

Target:
This needs to be `@Deprecated` as well