auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getPropertyType(String className, String propertyName, XWikiContext context) throws Exception { PropertyClass pc = null; try { pc = (PropertyClass) context.getWiki().getDocument(className, context).getXClass().get(propertyName); } catch (XWikiException e) { LOGGER.error("Failed to get property for document [{}]", propertyName, className, e); } return pc.newProperty().getClass().getName(); }

Target:
This will throw a `NullPointerException` if an `XWikiException` is caught above. You need to choose between - falling back on a default property type in case of an `XWikiException` or - let the `XWikiException` propagate In general, there are two main reasons for which you would catch an exception: - provide a fall back or - throw a more domain-specific exception that wraps the caught exception.
Source:
public void maxSimultaneousCompilations() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4); int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations(); assertTrue(i == 4); }

Target:
Just for the information, you could use: ``` assertEquals(4, i) ```
Source:
public String getHint() { return getBasePropertyClass().getTranslatedHint(context); }

Target:
API methods are supposed to be simple wrappers for the protected classes. As such, it's not quite right that an API method calls a different method (`getHint` doesn't call the equivalent `getHint`, but `getTranslatedHint`).
Source:
List<GermplasmList> retrieveAndValidateIfHasGermplasmList(Integer studyId) throws MiddlewareQueryException, CrossingTemplateExportException { List<GermplasmList> crossesList = this.fieldbookMiddlewareService.getGermplasmListsByProjectId(studyId, GermplasmListType.NURSERY); if (crossesList.isEmpty()) { throw new CrossingTemplateExportException("study.export.crosses.no.germplasm.list.available"); } return crossesList; }

Target:
Remove MiddlewareQueryException
Source:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } for (String key : expressionMap.keySet()) { if (key != null && pattern.matches(key)) { Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); // memoize return expression; } } return null; }

Target:
add final
Source:
public void testGetStartingSequenceNumberWhereCrossSettingStartNumberIsNull() { this.crossSetting.getCrossNameSetting().setStartNumber(null); final CrossNameSetting setting = new CrossNameSetting(); setting.setStartNumber(0); setting.setPrefix("A"); final int startingSequenceNumber = this.crossingService.getStartingSequenceNumber(setting); Assert.assertEquals("The starting sequence number should be " + startingSequenceNumber, CrossingServiceImplTest.NEXT_NUMBER.intValue(), startingSequenceNumber); }

Target:
In this test, the start number is not null but zero. Please create a test also when it is actually null.
Source:
private void validateAndSetNewDesignation(final int desigColumn, final Row xlsRow, final MeasurementRow measurementRow) throws WorkbookParserException { final String newDesig = this.getDesignation(xlsRow, desigColumn); setNewDesignation(measurementRow, newDesig); }

Target:
Please add this.
Source:
public List<Object> configurations() { return Collections.singletonList(new TooManyLinesInFileCheck.Config(maximum)); }

Target:
You can probably remove `TooManyLinesInFileCheck`
Source:
public List<Object> configurations() { return Collections.singletonList(new TooManyLinesInFunctionCheck.Config(max)); }

Target:
same here, remove `TooManyLinesInFunctionCheck`
Source:
private static void saveHighlights(InputFile file, SensorContext context, AnalysisResponseHighlight[] highlights) { NewHighlighting highlighting = context.newHighlighting().onFile(file); for (AnalysisResponseHighlight highlight : highlights) { highlighting.highlight(highlight.startLine, highlight.startCol, highlight.endLine, highlight.endCol, TypeOfText.valueOf(highlight.textType.toUpperCase(Locale.ENGLISH))); } highlighting.save(); }

Target:
we should avoid this conversion by sending uppercase constants in the response directly
Source:
public String[] getFileSuffixes() { String[] suffixes = configuration.getStringArray(FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = StringUtils.split(FILE_SUFFIXES_DEFVALUE, ","); } return suffixes; }

Target:
should we simplify this implementation the same way it's done for TS?
Source:
public void execute(SensorContext context) { if (rules.length == 0) { LOG.info("Skipping execution of eslint-based rules because none of them are activated"); return; } startEslintBridgeServerProcess(); if (process == null) { return; } try { for (InputFile inputFile : getInputFiles(context)) { analyze(inputFile, context); } } finally { clean(); } }

Target:
I think this should be `DEBUG`
Source:
public static int findOpenPort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { return 3000; } }

Target:
I don't think it makes sense to try to recover from this exception, we should just log and fail in the sensor (i.e. skip analysis)
Source:
private List<String> buildCommand(String nodeExecutable, List<String> nodeJsArgs, @Nullable String scriptFilename, List<String> args) { List<String> result = new ArrayList<>(); result.add(nodeExecutable); result.addAll(nodeJsArgs); if (scriptFilename != null) { result.add(scriptFilename); } result.addAll(args); return Collections.unmodifiableList(result); }

Target:
![Code Smell](https://sonarsource.github.io/sonar-github/code_smell.png 'Code Smell') Code Smell: Make "buildCommand" a "static" method. ([squid:S2325](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)) [See it in SonarQube](https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.javascript%3Ajavascript&pullRequest=1065&issues=AWYLrx4p0ts69roINji_&open=AWYLrx4p0ts69roINji_) [ISSUE_KEY]: AWYLrx4p0ts69roINji_
Source:
public static WsClient newWsClient() { return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() .url(orchestrator.getServer().getUrl()) .build()); }

Target:
Also here access can be private
Source:
public boolean isExcluded(InputFile file) { boolean isMinified = new MinificationAssessor().isMinified(file); if (isMinified) { LOG.debug("File [" + file.toString() + "] looks like a minified file and will not be analyzed"); } return isMinified; }

Target:
@vilchik-elena same
Source:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); assertThat(logTester.logs()).contains("Unable to analyse file: " + file.toString()); }

Target:
@vilchik-elena if you follow my suggestion on `file.uri()` you'll have to update here as well
Source:
public void test() throws Exception { assertThat(g.rule(Tree.Kind.FLOW_FUNCTION_TYPE)) .matches("(str: string) => void") .matches("(str: string, number) => void") .matches("() => void") .matches("(string, string,) => void") .matches("(name: string, ...numbers:SomeArrayType) => void") .matches("(name: string, middle?: string) => void") .matches("(string, SomeArrayType) => SomeType") .matches("(await: number) => void") .matches("string => number") .matches("number | string => number") ; }

Target:
@inverno we need more tests, let's have model test for parameter clause at least
Source:
public Iterator<Tree> childrenIterator() { if (parameters != null) { return Iterators.concat(Iterators.singletonIterator(lParenthesis), parameters.elementsAndSeparators(Functions.identity()), Iterators.forArray(restParameter, comma, rParenthesis)); } else { return Iterators.forArray(lParenthesis, restParameter, comma, rParenthesis); } }

Target:
@inverno when you will make `parameters` not nullable, you can simplify this method
Source:
private static boolean insideCondition(SyntaxToken token) { Tree treeWithCondition = CheckUtils.getFirstAncestor(token, Kind.IF_STATEMENT, Kind.WHILE_STATEMENT, Kind.DO_WHILE_STATEMENT, Kind.FOR_STATEMENT, Kind.CONDITIONAL_EXPRESSION); Tree condition = condition(treeWithCondition); return condition != null && ((JavaScriptTree) condition).isAncestorOf((JavaScriptTree) token); }

Target:
I would rather check for a null treeWithCondition here and return false rather than passing it into the `condition` method as a nullable.
Source:
private void checkSuperOnlyInvokedInDerivedClassConstructor(SuperTreeImpl superTree) { if (!isInConstructor(superTree) || isInBaseClass(getEnclosingConstructor(superTree))) { addIssue(superTree, MESSAGE_SUPER_ONLY_IN_DERIVED_CLASS_CONSTRUCTOR); } }

Target:
@ivandalbosco Minor: another possibility would have been to move these tests up to `visitSuper`.
Source:
private static boolean isConstructor(FunctionTree tree) { if (tree.is(Kind.METHOD)) { MethodDeclarationTree constructor = (MethodDeclarationTree) tree; Tree nameTree = constructor.name(); if (nameTree.is(Kind.IDENTIFIER_NAME)) { String name = ((IdentifierTree) nameTree).name(); if ("constructor".equals(name)) { return true; } } } return false; }

Target:
@ivandalbosco Why not `return "constructor".equals(name)`?
Source:
public String contents() throws IOException { return wrapped.contents(); }

Target:
@janos-ss We usually don't want to deal with an `IOException` in our analyzers. Why not simply wrapping it in a subclass of `RuntimeException`? That would simplify a bit this pull request.
Source:
public void technical_error_should_add_error_to_context() { thrown.expect(AnalysisException.class); JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor)check), ImmutableList.of(new CompatibleInputFile(inputFile("file.js"))), progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); }

Target:
@janos-ss We could probably change the `inputFile`method defined in this class to return a `CompatibleInputFile `.
Source:
public synchronized void writeIssues(Iterator<Issue> issues, File file) { while (issues.hasNext()) { Issue issue = issues.next(); IssueEntry entry = IssueEntry.from(issue, file); if (expectedIssues.expects(entry)) { continue; } output.accept(entry.createExcerpt()); } }

Target:
@inverno I don't like this style: I would not use a `continue` here.
Source:
public boolean isAncestorOf(JavaScriptTree tree) { Tree parentTree = tree.getParent(); if (this.equals(parentTree)) { return true; } if (parentTree instanceof JavaScriptTree) { return this.isAncestorOf((JavaScriptTree) parentTree); } return false; }

Target:
@inverno remove this check and make `getParent` return JSTree
Source:
private boolean isInfiniteLoop(IterationStatementTree tree, @Nullable JavaScriptTree condition) { if (isNeverExecutedLoop(condition)) { return false; } ControlFlowGraph flowGraph = CheckUtils.buildControlFlowGraph(tree); Map<Tree, CfgBlock> treesOfFlowGraph = treesToBlocks(flowGraph); if (isBrokenLoop(tree, flowGraph)) { return false; } if (condition != null && conditionIsUpdated(condition, (JavaScriptTree) tree, treesOfFlowGraph)) { return false; } else { return true; } }

Target:
![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Replace this if-then-else statement by a single return statement. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1126)
Source:
private void issueIfLineMismatch(SyntaxToken curlyBrace, SyntaxToken target) { CodeLine curlyBraceLine = new CodeLine(curlyBrace.line()); if (curlyBraceLine.isJustBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of the previous line."))); } if (curlyBraceLine.isFarBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of line " + target.line() + "."))); } }

Target:
@inverno Why don't you use an "else" here? With an "else", without reading the implementation of methods isJust/FarBelow, we know that all cases are covered, that is, that we will always hit one of the 2 cases. Further advantage: either of the two methods isJust/FarBelow can be removed.
Source:
public void beforeBlockElement(ProgramState currentState, Tree element) { if (element.is(Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree memberExpression = (DotMemberExpressionTree) element; if (isArrayPropertyExecuted(currentState) && METHODS_WITH_CALLBACK.contains(memberExpression.property().name())) { checkArgumentToBeFunctionWithReturn(memberExpression, 0); } if (isArrayFromMethod(memberExpression, currentState)) { checkArgumentToBeFunctionWithReturn(memberExpression, 1); } } }

Target:
@vilchik-elena "else if" rather than "if" would be clearer (and a picosecond faster).
Source:
public BuiltInFunctionSymbolicValue(Constraint returnedValueConstraint, IntFunction<Constraint> signature) { this.returnedValueConstraint = returnedValueConstraint; this.signature = signature; this.argumentsConstrainer = null; }

Target:
@vilchik-elena Why not make this constructor call the third one?
Source:
public void startOfExecution(Scope functionScope) { operandsWithIssues.clear(); super.startOfExecution(functionScope); }

Target:
@ivandalbosco we better remove call to `super`, it does nothing
Source:
private void checkPlus(ExpressionTree leftOperand, ExpressionTree rightOperand, Type leftType, Type rightType, Tree operator) { if (leftType != Type.STRING && rightType != Type.STRING) { if (leftType == Type.NUMBER && BOOLEAN_DATE.contains(rightType)) { raiseIssue(rightOperand, leftOperand, operator); } if (rightType == Type.NUMBER && BOOLEAN_DATE.contains(leftType)) { raiseIssue(leftOperand, leftOperand, operator); } } }

Target:
@vilchik-elena copy-paste issue
Source:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { ProgramState newState = state.constrainOwnSV(this, constraint); if (newState == null) { return ImmutableList.of(); } if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return checkRelationsAndConstrain(newState, relationWhenTrue); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return checkRelationsAndConstrain(newState, relationWhenTrue.not()); } return ImmutableList.of(state); }

Target:
Should be `newState`
Source:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return firstOperandValue.constrain(state, secondOperandConstraint); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return firstOperandValue.constrain(state, secondOperandConstraint.not()); } return ImmutableList.of(state); }

Target:
@vilchik-elena Good question: what happens here? Can we reach that code?
Source:
private boolean isNullyComparison(Tree lastElement) { if (lastElement.is(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)) { BinaryExpressionTree comparison = (BinaryExpressionTree) lastElement; return SymbolicValue.get(comparison.leftOperand()).nullability().isNullOrUndefined().equals(State.YES) || SymbolicValue.get(comparison.rightOperand()).nullability().isNullOrUndefined().equals(State.YES); } return false; }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isNullyComparison" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AS2325)
Source:
public Truthiness not() { if (this == TRUTHY) { return FALSY; } else if (this == FALSY) { return TRUTHY; } else { return UNKNOWN; } }

Target:
@pynicolas why not switch?
Source:
public void visitScript(ScriptTree tree) { storageTypes = new HashedMap(); super.visitScript(tree); checkForIssues(); }

Target:
@ganncamp minor: could be instantiate at the field declaration level and here it could be cleared by calling `storage.clear()` WDYT ?
Source:
private static String getObjectName(MemberExpressionTree dme) { if (dme.object() != null) { if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } } return ""; }

Target:
@ganncamp actually this null check should not be required be [MemberExpression#object()](https://github.com/SonarCommunity/sonar-javascript/blob/master/javascript-frontend/src/main/java/org/sonar/plugins/javascript/api/tree/expression/MemberExpressionTree.java#L35) is not nullable and should never be null.
Source:
public void scanFile(AstTreeVisitorContext context) { super.scanFile(context); RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(getContext().getFile(), "r"); if (!endsWithNewline(randomAccessFile)) { getContext().addFileIssue(this, "Add a new line at the end of this file."); } } catch (IOException e) { LOG.error("Unable to execute rule \"MissingNewlineAtEndOfFile\" for file because of error: {}", getContext().getFile().getName(), e); } finally { Closeables.closeQuietly(randomAccessFile); } }

Target:
We are now compatible with java 7 so you should probably use a try with resource.
Source:
public int hashCode() { int result = super.hashCode(); result = 31 * result + center.hashCode(); result = 31 * result + new Double(scale.getResolution()).hashCode(); return result; }

Target:
You could implement hashCode in Scale
Source:
public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(resolution); result = (int) (temp ^ (temp >>> 32)); return result; }

Target:
You should use static Double.hasCode
Source:
public final void cacheResources(final HttpRequestCache httpRequestCache, final MfClientHttpRequestFactory clientHttpRequestFactory, final MapfishMapContext transformer) { final MapfishMapContext layerTransformer = getLayerTransformer(transformer); final double dpi = transformer.getDPI(); final TilePreparationTask task = new TilePreparationTask( clientHttpRequestFactory, dpi, layerTransformer, this.tileCacheInformation, httpRequestCache); this.tilePreparationInfo = this.forkJoinPool.invoke(task); }

Target:
Does it still make sense to use `forkJoinPool`? The tiles are no longer downloaded at this point, so it would add an overhead to run this in parallel.
Source:
public void setFeatureAttributeName(String featureAttributeName) { if (null == featureAttributeName) log.debug("WPS request process error: Feature Attribute Name was null. Can not process without the output column name."); this.featureAttributeName = featureAttributeName; }

Target:
I know Sonar will flag this for not having the around the block. This can be tricky to read the logic coming back at a later date.
Source:
private void initializeBaseDirectory(PropertyUtil propertyUtil) throws IOException { String baseDirectoryPath = propertyUtil.extractString(KEY_DATABASE_PATH, DEFAULT_BASE_DIRECTORY); BASE_DIRECTORY = Paths.get(baseDirectoryPath); LOGGER.info("Using \"{}\" as base directory for results database", baseDirectoryPath); if (!Files.isDirectory(BASE_DIRECTORY)) { Files.createDirectories(BASE_DIRECTORY); } }

Target:
Does there need to be an if check here? From JavaDoc: Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. So if it doesn't already exist, it will create it, otherwise, it will move on.
Source:
public void contextDestroyed(ServletContextEvent sce) { LOGGER.info("(\"*****************************************************WPSJobListener - context destroyed, cancelling request tasks"); for (Runnable runnable : RequestHandler.pool.getQueue()) { ((FutureTask) runnable).cancel(true); LOGGER.info("cancelling task"); } }

Target:
Personally I'd prefer just a couple asterisks if you want this to stick out, this is quite jarring to see in code.
Source:
public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } return queue.offer(msg); }

Target:
I thought you were just changing this offer to put. but that will be a big change. you current change doesn't break any existing behavior. looks good/safe to me. nitpicking: a if-else might be more straightforward.
Source:
public void onViewStateRestored(Bundle savedInstanceState) { if (savedInstanceState != null) { layoutManagerSavedState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE); prevLeftAction = savedInstanceState.getString("prevLeftAction", ""); prevRightAction = savedInstanceState.getString("prevRightAction", ""); } super.onViewStateRestored(savedInstanceState); }

Target:
Do we need this here? I think `onResume()` is called when the activity is restored. Therefore the settings will be reloaded. So I think we can remove the logic from both the `onViewStateRestored()` and `onSaveInstanceState()` right? Or am I missing something here?
Source:
public SSDate resetTime() { this.setHours(0); this.setMinutes(0); this.setSeconds(0); return this; }

Target:
dont think a setter type function should return the "this"
Source:
public FilterDropdownListBox(FilterDropdownResources resources) { super(true); this.setStyleName(""); this.resources = resources; this.resources.filterDropdownStyle().ensureInjected(); mainPanel.setStyleName(this.resources.filterDropdownStyle().dropDown()); this.add(mainPanel); addInfoMessages(); mainPanel.getElement().getStyle().setProperty("maxHeight", "250px"); mainPanel.getElement().getStyle().setProperty("overflow", "auto"); }

Target:
create a setter for this so that the height can be changed from outside
Source:
public Field(InputField inputField, String label, boolean embeded, int layout) { this(inputField, label, embeded, DynamicForm.LAYOUT_VERTICAL, ""); }

Target:
this is wrong
Source:
public void displayHelpWidget() { //display helpWidget //will be implemented at a later stage Window.alert( "Coming soon!" ); }

Target:
spaces inside brackets should be removed
Source:
public float getLeftMargin(Actor actor) { for (Constraints c : constraints) { if (c.actor == actor) { return marginLeft(c); } } return -1; }

Target:
Hmm. This a weird value for the default, which should likely be positive. Maybe this should be 0?
Source:
public Array<Actor> getExtras() { final Array<Actor> actors = new Array<Actor>(false, 2); actors.add(this.paint); actors.add(this.eraser); return actors; }

Target:
Unnecessary final.
Source:
public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(); stage.draw(); Table.drawDebug(stage); }

Target:
How do you control drawing the debug lines? It should be conditioned by a global variable that sets the editor in debug (pass as command line argument).
Source:
private TimedRenderer getCurrentFrame() { // In case the current frame is null, just return an empty timed // renderer as a frame if (frames.get(currentFrame) != null) return frames.get(currentFrame); else { return new TimedRenderer() { @Override public void draw(Batch batch) { } @Override public float getHeight() { return 0; } @Override public float getWidth() { return 0; } @Override public void initialize(Object schemaObject) { } public float surplusTime() { return 0; } }; } }

Target:
Frames shouldn't contain null frames.
Source:
public void initialize(AddAction schemaObject) { Action action = schemaObject.getAction(); for (String tag : schemaObject.getTags()) { SceneActor scene = gameLoop.getSceneView().getCurrentScene(); Array<SceneElementActor> sceneElements = scene.findByTag(tag); if (sceneElements != null) { for (SceneElementActor sceneElement : sceneElements) { sceneElement.addAction(action); } } } }

Target:
We don't check if schemaObject.getTags() or gameLoop.getSceneView().getCurrentScene() are null. I assume this is because those methods will never return null. To be consistent, scene.findByTag(tag) should never return null.
Source:
public void initialize(Scene schemaObject) { for (SceneElement se : schemaObject.getChildren()) { addActor(se); } sceneElementTags.clear(); addChildrenTagsTo(this); }

Target:
why is this needed?
Source:
protected boolean delegate(float delta) { return rendererChanged; }

Target:
You don't really need "rendererChanged". "delegate" is the update method of the action (probably not the best method name) and returns true once the action is done. If the action only needs one update to execute (like in this case), it must return true (all things that should happen, already happened during initialize).
Source:
private Boolean checkMatchpassword(String password, String password2) { if (!password.equals(password2)) { return false; } else { return true; } }

Target:
you can use one single line for this...
Source:
public AuthMePlayer getPlayerInfo(String playerName) { PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } return AuthMePlayerImpl.fromPlayerAuth(auth); }

Target:
Api v4, deprecate api v3
Source:
public void setUnlogged(String user) { String sql = "UPDATE " + tableName + " SET " + col.IS_LOGGED + "=? WHERE LOWER(" + col.NAME + ")=?;"; if (user != null) { try (PreparedStatement pst = con.prepareStatement(sql)) { pst.setInt(1, 0); pst.setString(2, user); pst.executeUpdate(); } catch (SQLException ex) { logSqlException(ex); } } }

Target:
Like in the MySQL class, here I'm missing the initialization of the `hasSession` column
Source:
private String emailMask(String email){ String[] frag = email.split("@"); //Split id and domain int sid = frag[0].length() / 3 + 1; //Define the id view int sdomain = frag[1].length() / 3 + 1; //Define the domain view String id = frag[0].substring(0, sid) + "*****"; //Build the id String domain = "***" + frag[1].substring(sdomain); //Build the domain return id + "@" + domain; }

Target:
I love the `+1` as to guarantee that there will always be a letter visible. Is there a reason for the asterisks in id vs. domain to be of different length? I might find it less confusing if my email `test@example.org` became something like `te***@***le.org` rather than `te*****@***le.org`.
Source:
public void loadState(SonarLintGlobalSettings state) { XmlSerializerUtil.copyBean(state, this); includedRules.forEach(it -> { rules.put(it, new Rule(true)); }); excludedRules.forEach(it -> { rules.put(it, new Rule(false)); }); }

Target:
If you don't clear (or better set to null) the two sets after the migration, it means the next time you'll reopen your IDE, the migration will happen again, and override possible different values added in the meantime by the user in the rules map.
Source:
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { if (!globalSettings.isAutoTrigger()) { return; } Module m = ModuleUtil.findModuleForFile(file, myProject); if (m == null || !SonarLintUtils.shouldAnalyzeAutomatically(file, m)) { return; } analyzer.submitAsync(m, Collections.singleton(file), TriggerType.EDITOR_OPEN); serverIssueUpdater.trackServerIssues(Collections.singleton(file)); }

Target:
To synchronize both tasks at the end (only do server issue tracking after local analysis completes) we could share a CountDownLatch
Source:
@Override public boolean value(VirtualFile virtualFile) { return openedFiles.contains(virtualFile); }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make this line start at column 7. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AIndentationCheck)
Source:
public String getMaxConnections() { return maxConnections == null ? Integer.valueOf(DEFAULT_CONNECTIONS).toString() : maxConnections; }

Target:
``String.valueOf(DEFAULT_CONNECTIONS)`` would be more straightforward.
Source:
private AWSCredentialsProvider getCredentialsProvider() { if (null == awsSecretKey || null == awsAccessKey) { return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(awsAccessKey, awsSecretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); }

Target:
This looks backwards. This would attempt to create BasicAWSCredentials when neither awsSecretKey nor awsAccessKey is provided.
Source:
public Boolean isWmtsCiteCompliant() { return wmtsCiteCompliant; }

Target:
Confused about the change of signature... what about keeping the field as Boolean for XStream, "boolean" for the methods, and then do a null check inside the body?
Source:
public void getFileName_ReturnsFileNameForSVG() { // given Embedding embedding = new Embedding("image/svg+xml", "some data", null); // when String fileName = embedding.getFileName(); // then assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }

Target:
then consider to leave old constructor and add new one below
Source:
public String getRawName() { return name().toLowerCase(Locale.US); }

Target:
My suggestion is to take a look at https://github.com/damianszczepanik/cucumber-reporting/tree/master/src/main/java/net/masterthought/cucumber/json/deserializers and move this change insto single class which is executed then the JSON is created instead of having the same fix in many places which are invoked many times during report creation
Source:
private Properties buildProperties() { Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getCanonicalName()); props.setProperty("runtime.log", new File(configuration.getReportDirectory(), "velocity.log").getPath()); props.setProperty("eventhandler.referenceinsertion.class", "org.apache.velocity.app.event.implement.EscapeHtmlReference"); return props; }

Target:
Also I prefer compile time checking, not runtime checking EscapeHtmlReference.class.getName() should work
Source:
public void generateReport_OnInvalidPath_ThrowsException() { setUpWithJson(SAMPLE_JSON); // given page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { // invalid file path return StringUtils.EMPTY; } }; // when thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }

Target:
why it was not needed and now you copy it over and over again?
Source:
public boolean isSleepingConsumer(){ if(System.currentTimeMillis() < this.consumerSleepEndTime){ return true; } return false; }

Target:
可以简化一下，直接return System.currentTimeMillis() < this.consumerSleepEndTime
Source:
private long getMemoryMb(String key) { long memoryMb = 0L; if (key.equals(Constants.MAP_MEMORY_MB_CONF_KEY)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_MAP_MEMORY_MB); }else if (key.equals(Constants.REDUCE_MEMORY_MB_CONF_KEY)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_REDUCE_MEMORY_MB); } if (memoryMb == 0L) { throw new ProcessingException( "While correcting slot millis, " + key + " was found to be 0 "); } return memoryMb; }

Target:
If key is null and there is no check for nullness of key, this would throw a NullPointerException. A better way to do this could be if (Constants.MAP_MEMORY_MB_CONF_KEY.equals(key)). Similarly for reduce memory mb.
Source:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; }

Target:
Maybe use StringUtils.isEmpty(jobtracker) instead of jobtracker == null.
Source:
private Put getMegaByteMillisPut(Long mbMillis, JobKey jobKey) { JobKeyConverter jobKeyConv = new JobKeyConverter(); Put pMb = new Put(jobKeyConv.toBytes(jobKey)); pMb.add(Constants.INFO_FAM_BYTES, Constants.MEGABYTEMILLIS_BYTES, Bytes.toBytes(mbMillis)); return pMb; }

Target:
minor: it appears that JobKeyConverter could be singleton.
Source:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file " + ioe.getMessage()); LOG.error(ioe.getStackTrace()); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " + ioe.getMessage()); } }

Target:
I think LOG.error("your log message", ioe); would do what these 2 lines are doing.
Source:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " + ioe.getMessage()); } }

Target:
This should use the constructor version: ProcessingException(String, Throwable) Otherwise you lose the stack trace of the underlying IOException
Source:
public Map<String, Serializable> getCachedMetaData( final String key ) { final IPluginCacheManager cacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = cacheManager.getCache(); return cache.getMetaData( key ); }

Target:
THere is no reason to have this method as public, I suppose. No one can call this method from elsewhere.
Source:
public JobManager( final boolean isSupportAsync, final long pollingIntervalMilliseconds, final long dialogThresholdMillisecond ) { if ( !isSupportAsync ) { logger.info( ASYNC_DISABLED ); } this.config = new Config( isSupportAsync, pollingIntervalMilliseconds, dialogThresholdMillisecond, Boolean.FALSE ); }

Target:
Avoid duplicate code (and magically cover more lines in tests) by re-routing this constructor to the one with 4 parameters.
Source:
@Override public PerformanceLoggingStopWatch createStopWatch( String tag, Object message ) { return new LoggingStopWatch( tag, message + this.getMessage() ); }

Target:
Instead of using string + string, pass the "message" object into the "getMessage" method and format everything in one operation. Your format string would then be "%s sessionid[%s] userid[%s] requestid[%s]" You probably dont intend to use a one-space padding, two-space padding and 3 space padding on the format string either.
Source:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { pool = new ThreadLocal<NonBlockingSslBufferPoll>() { @Override protected NonBlockingSslBufferPoll initialValue() { int threadLocalMaxPoolSize = maxPoolSize / DEFAULT_WORKER_THREAD_COUNT; if (threadLocalMaxPoolSize % DEFAULT_WORKER_THREAD_COUNT != 0) { threadLocalMaxPoolSize ++; } return new NonBlockingSslBufferPoll(threadLocalMaxPoolSize, preallocate, allocateDirect); } }; }

Target:
nit: threadLocalMaxPoolSize++
Source:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); // Try to acquire buffer. Unlike SslBufferPool, this should not block and will return another buffer. ByteBuffer buf2 = pool.acquireBuffer(); pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); }

Target:
put these 2 in a finally block. don't know whether acquire can throw an exception like a runtime exception. similarly in other tests as well
Source:
List<String> getAllSeeds() { final ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); return builder.addAll(currentSeeds).addAll(newSeeds).addAll(oldSeeds).build(); }

Target:
You can chain this like ``` java return ImmutableList.<String>builder() .addAll(currentSeeds) .addAll(newSeeds) .addAll(oldSeeds) .build(); ```
Source:
public void modify(Path path, byte[] data, Consumer<Long> progressConsumer) { FileWrapper file = getPath(path); ProgressConsumer<Long> pc = l -> progressConsumer.accept(l); file.overwriteFileJS(AsyncReader.build(data), 0, data.length, userContext.network, userContext.crypto, pc).join(); }

Target:
can just use progressConsumer directly
Source:
public void dosCborObject() throws Throwable { if(true)throw new RuntimeException(); // make a header for a byte[] that is 2^50 long byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }

Target:
yep, will revert once I check it works on github
Source:
public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); if (nativePath.toFile().isDirectory()) { return null; } try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } }

Target:
This would be easier to reason about if it raised an exception. Why return null?
Source:
private CompletableFuture<Boolean> updatedSharedWithCache(FileWrapper file, Set<String> usersToAdd, SharedWithCache.Access access) { return file.getPath(network).thenCompose(path -> { network.sharedWithCache.addSharedWith(access, file.getPointer().capability, usersToAdd); CompletableFuture<Boolean> res = new CompletableFuture<>(); res.complete(true); return res; }); }

Target:
no path required
Source:
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) { try { System.arraycopy(data, index, res, offset, length); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(); } index += length; return CompletableFuture.completedFuture(length); }

Target:
debug artefact?
Source:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; assertTrue(length >= 0); assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }

Target:
In case is this zero?
Source:
private static Object wrapHash(String key, Multihash h) { Map<String, Object> json = new TreeMap<>(); json.put(key, h.toString()); return json; }

Target:
Mind changing the type of this to ``Map<String, Object>``?
Source:
public static int compare(byte[] a, byte[] b) { for (int i=0; i < Math.min(a.length, b.length); i++) if (a[i] != b[i]) return a[i] & 0xff - b[i] & 0xff; return 0; }

Target:
Could you explain the contract here in a docstring? If two arrays are different lengths why are they ``equal`` if they have the same content up to the length of the smaller array?
Source:
public int getQueuePositionForSong(long id) { return mTimeline.getPositionForSong(id); }

Target:
Could we rename the function in SongTimeline to have the same function name? (= getQueuePositionForSong)
Source:
public org.kiji.schema.AsyncKijiBufferedWriter openAsyncBufferedWriter() throws IOException { return AsyncHBaseAsyncKijiBufferedWriter.create(mTable); }

Target:
Full path is no longer needed, right?
Source:
private PagedColumnIterable(final Column columnRequest) { mColumn = columnRequest.getColumnName(); mCloser = Closer.create(); mColumnRequest = columnRequest; mTableName = KijiManagedHBaseTableName .getKijiTableName(mTable.getURI().getInstance(), mTable.getURI().getTable()).toBytes(); }

Target:
charset
Source:
private CachedCuratorFrameworkImpl( final ReferenceCountedCache<K, CuratorFramework> cache, final K key, final CuratorFrameworkImpl delegate ) { super(delegate); mCache = cache; mCacheKey = key; DebugResourceTracker .get() .registerResource(this, ExceptionUtils.getStackTrace(new Exception())); }

Target:
This looks like the result of a bad merge.
Source:
public void close() throws IOException { final State oldState = mState.getAndSet(State.CLOSED); Preconditions.checkState(oldState == State.OPEN, "Cannot close KijiTableWriter instance %s in state %s.", this, oldState); mLayoutConsumerRegistration.close(); try { mHBClient.shutdown().join(); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } mTable.release(); }

Target:
I believe that many AsyncKTR's can share a single HBaseClient, so it should be 'owned' by the Kiji instead of being shut down here. Let me know if this isn't a clear explanation.
Source:
public KijiCell<T> next() { KeyValue kv = mKVs.next(); mNumVersions += 1; try { return new KijiCell<T>(mFamily, mQualifier, kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } catch (IOException ex) { throw new KijiIOException(ex.getMessage()); } }

Target:
Use new KijiIOException(ex), to not lose the stacktrace of the cause
Source:
public boolean equals(Object obj) { return HttpServerModule.class.equals(obj.getClass()); }

Target:
Why not just `getClass().equals(obj.getClass())`? nit: The contract for equals says you should check for obj being null to avoid an NPE.
Source:
private Module getAdditionalBindings() { return new AbstractModule() { @Override protected void configure() { bind(AdminContainerConfig.class).to(AdminConfigImpl.class); bind(AdminResourcesFilter.class); } }; }

Target:
This method enforces AdminConfigImpl binding, while it should be possible to inject custom instance of it. Now injecting custom implementation results in duplicate binding exception.
Source:
public Collection<E> makeConfirmedCollection() { final ArrayList<E> list = new ArrayList<>(); return list; }

Target:
The local var is useless, you can remove it.
Source:
public static <T extends Collection<E>,E> T deepMerge(final Iterable<? extends Iterable<?>> iterableOfIterables, final T collectionToFill) { Iterator<? extends Iterable<?>> iterator = iterableOfIterables.iterator(); if (!iterator.hasNext()) { return collectionToFill; } while (iterator.hasNext()) { deepMergeRecursion(iterator.next(), collectionToFill); } return collectionToFill; }

Target:
This if statement is not necessary as the while loop below would handle the negative case.
Source:
protected Statement withInterruptIsolation(final Statement statement) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { Thread.interrupted(); // clearing thread interrupted status for isolation } } }; }

Target:
I personally would prefer this is be `final`
Source:
public void testAssumptionFailure(Failure failure) { ignoreCount.getAndIncrement(); }

Target:
In #1294 (currently targeted for 4.13) we are proposing updating this class to collect assumption failure counts, so I am not sure we should make this change.
Source:
public void testRemoveElement() { fullList.remove(2); assertFalse(fullList.contains(3)); }

Target:
fullList.remove(Integer.valueOf(3));
Source:
private static boolean hasSuppressed(Throwable exception) { if (getSuppressed != null) { try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } } else { return false; } }

Target:
nit: I personally prefer existing out on error conditions early, to avoid over-intentation: if (getSuppressed == null) { return false; } try { ... } catch (Throwable e) { return false; }
Source:
public static <T> T notNull(T value, String message) { if (value == null) { throw new NullPointerException(String.valueOf(message)); } return value; }

Target:
I conform to @panchenko's suggestion. I normally expect that `someMethod(someValue)` and `someMethod(someValue, null)` behave the same.
Source:
public boolean isAnyExceptionExpected() { return matcherBuilder.expectsThrowable(); }

Target:
Let's make this final
Source:
protected void after() throws Exception { // do nothing }

Target:
Why `Exception` instead of `Throwable` like we did for `before()`?
Source:
public void assumeNotNullSingleNullThrowsException() { try { assumeNotNull(null); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }

Target:
Please add a cast to `Object[]` here.
Source:
public void executeRulesInCorrectOrder() throws Exception { LOG.clear(); testResult(UseRuleChain.class); List<String> expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); }

Target:
Let's put this call in a `@Before` method named `clearLog()`
Source:
public void assumeNotNullThrowsException() { try { Object[] objects = {1, 2, null}; assumeNotNull(objects); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }

Target:
Please put this line outside of the "try" block
Source:
protected void after() throws Throwable { // do nothing }

Target:
We can't change the signature of published methods
Source:
Builder parentFolder(File parentFolder) { this.parentFolder = parentFolder; return this; }

Target:
Shouldn't this be public? Also, if we need the getter methods (and I don't think we do) could we put them right after the setter methods?
Source:
protected boolean tryDelete() { boolean result = true; if (folder != null) { result = recursiveDelete(folder); } return result; }

Target:
This method boils down to ``` java return folder == null || recursiveDelete(folder); ``` or ``` java if (folder == null) return true; return recursiveDelete(folder); ```
Source:
public void testStrictVerificationFailure() { PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); assertThat(result, failureCountIs(1)); assertThat(result.toString(), CoreMatchers.containsString("Unable to clean up temporary folder")); }

Target:
Please add a static import for `containsString`.
Source:
private Builder() { }

Target:
When subclassing the builder one might want to subclass the builder as well. Let's make it `protected`?
Source:
public AssumptionViolatedException(String assumption, boolean valueMatcher, Object value, Matcher<?> matcher) { if (value instanceof Throwable) { initCause((Throwable) value); } this.assumption = assumption; this.value = value; this.matcher = matcher; this.valueMatcher = valueMatcher; }

Target:
Looking closer, I think this should be: ``` if (!valueMatcher && (value instanceof Throwable)) { ``` This will lead to `initCause()` to only be called if you got here via the last constructor. This is a slight change in behavior, but I wouldn't expect the following to throw an `AssumptionViolationException` with a cause: ``` assumeThat(e, hasMessage("woops")); ``` _Edit:_ A much simpler solution would be to only call `initCause()` in `AssumptionViolatedException(String assumption, Throwable e)`. Sorry I didn't see that before; this class is too complicated.
Source:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); if (tempFile != null && tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }

Target:
`tempFile` cannot be `null`
Source:
public File newFolder(String folder) throws IOException, IllegalArgumentException { return newFolder(new String[]{folder}); }

Target:
Please remove `IllegalArgumentException` from the `throws` clause
Source:
public static void assertEquals(String message, CharSequence expected, CharSequence actual) { Assert.assertEquals(message, expected, actual); }

Target:
We have not been making changes to the code under `junit.framework`
Source:
RuleMemberValidator build() { return new RuleMemberValidator(fAnnotation, fMethods, fValidatorStrategies); }

Target:
change to: ``` return new RuleMemberValidator(this); ``` (see Effective Java, 2nd edition)