auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void refreshViewer(final Object object) { asyncViewerRefresh(new Runnable() { public void run() { synchronized (viewer) { final TreePath[] treePaths = viewer.getExpandedTreePaths(); if (object != null) { viewer.refresh(object); } else { viewer.refresh(); } viewer.setExpandedTreePaths(treePaths); } } }); }

Target:
This line causes an endless load on linux when a node has zero children.
Source:
private ADBInfo createADB(String host, String port) throws URISyntaxException { HashMap<String,String> env = new HashMap<String,String>(); env.put("DOCKER_HOST","tcp://" + host + ":" + port); env.put("DOCKER_CERT_PATH","/home/rob/Downloads/cdk/github/openshift-vagrant/cdk-v2/.vagrant/machines/cdk/virtualbox/.docker"); env.put("DOCKER_TLS_VERIFY","1"); env.put("DOCKER_MACHINE_NAME","e5d7d0a"); return new ADBInfo(env); }

Target:
new HashMap<>()
Source:
public static String imageRef(IBuild build) { final String kind = build.getOutputKind(); if (ResourceKind.IMAGE_STREAM_TAG.equals(kind) || IMAGE_STREAM_IMAGE_KIND.equals(kind)) { return build.getOutputTo().getNameAndTag(); } if (DOCKER_IMAGE_KIND.equals(kind)) { return build.getOutputTo().getNameAndTag().toString(); } return ""; }

Target:
seems like both if statements could be merged
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { try { WizardUtils.openWizardDialog(new NewApplicationWizard(), HandlerUtil.getActiveShell(event)); // This technically sends the wrong event for the wrong 'command' id, // but the refresh resource handler only looks at the selection... new RefreshResourceHandler().execute(event); } catch (ConnectionNotFoundException e) { return new Status(Status.ERROR, OpenShiftUIActivator.PLUGIN_ID, "Unable to find the connection", e); } return Status.OK_STATUS; }

Target:
how is that related to the autopublish issue?
Source:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; String dockerHost = env.get("DOCKER_HOST"); URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; }

Target:
possible NPE afterwards. Might as well add an assertion on required "DOCKER_HOST"
Source:
public void selectionChanged(IStructuredSelection sel) { if( sel.size() == 0 || sel.size() > 1 ) { setEnabled(false); return; } setEnabled(true); synchronized(this) { switchListener(previousSelection, sel); previousSelection = sel; } super.selectionChanged(sel); }

Target:
if( sel.size() != 1 )
Source:
public OpenShiftProjectUIModel(IProject project) { super(); resourceModel = new OpenShiftResourceUIModel(project); System.out.println(this.hashCode()); }

Target:
yuck
Source:
public String[] getLines() { return (String[]) lines.toArray(new String[lines.size()]); }

Target:
Why an array? List<String> is just as fine
Source:
public void run() { while (inScanner.hasNextLine() && !isCanceled()) { String line = inScanner.nextLine(); lines.add(line); } }

Target:
When cancel() is called, this thread can be right before adding line to lines, and that may cause concurrent exception while the other thread calls getLines() or works with list if getLines() will return list. I suggest wrap it with ``` synchronized (this) { if(!isCanceled()) { lines.add(line); } } ``` and call cancel() as the first command in getLines().
Source:
private void mapBuildsToDeploymentConfigs(Collection<IBuild> builds) { for (IBuild build : builds) { mapBuildToDeploymentConfig(build); } }

Target:
or builds.forEach(b -> mapBuildToDeploymentConfig(b)), if you hate brackets
Source:
private void mapBuildToDeploymentConfig(IBuild build) { String imageRef = imageRef(build, project); Collection<IDeploymentConfig> deploymentConfigs = imageRefToDeployConfigs.get(imageRef); if(imageRefToDeployConfigs.containsKey(imageRef) && deploymentConfigs != null) { for (IDeploymentConfig dc : deploymentConfigs) { createRelation(build, dc); } } }

Target:
imageRefToDeployConfigs.containsKey(imageRef) is redundant here
Source:
default Collation asc() { return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }

Target:
Is it possible to keep return type of `asc()` as is (ie `Collation`) ? While it doesn't add functionality it hides all methods from user during IDE auto-complete (that was the point of empty interface).
Source:
public boolean useBindVariables() { return true; }

Target:
Can visibility remain `package-private` ?
Source:
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) { if((state.getBlock() instanceof CropsBlock && ((CropsBlock) state.getBlock()).isMaxAge(state)) || state.getBlock() instanceof PumpkinBlock) { CropsBlock.spawnDrops(state,worldIn,pos); } return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving); }

Target:
So does this mean that pumpkins are easily duplicated?
Source:
public ItemStack onItemUseFinish(ItemStack stack, World worldIn, LivingEntity entityLiving) { Random rand = new Random(); int num = rand.nextInt(10); ItemStack crumbs = new ItemStack(MSItems.BREADCRUMBS, num); if(entityLiving instanceof PlayerEntity && !entityLiving.world.isRemote) { PlayerEntity entityplayer = (PlayerEntity)entityLiving; entityplayer.addItemStackToInventory(crumbs); } return super.onItemUseFinish(stack, worldIn, entityLiving); }

Target:
In some other cases, this is used for functionality when an item has been eaten or similarily. Is that the case here? And if so, have baguettes been made edible?
Source:
public static void removeFile(String sourceFile) throws IOException { File file = new File(sourceFile); if (file.delete()) { LOGGER.log(Level.INFO, file.getName() + " is deleted!"); } else { LOGGER.log(Level.WARNING, file.getName() + "deletion is failed."); } }

Target:
nitpick: this class should have only one public method: upgradeStorageConfig
Source:
protected void setOrdinal(int ordinal, boolean forced) { if (forced) { this.ordinal = ordinal; } }

Target:
This seems weird. If the caller knows enough to pass forced or not, wouldn't they just be able to not call the method when forced is false?
Source:
public String placeLimitOrder(LimitOrder limitOrder) { LgoPlaceOrder lgoOrder = LgoAdapters.adaptLimitOrder(limitOrder); return placeOrder(lgoOrder); }

Target:
all generic method implementations should have error adaptation everything in this method should be surrounded by ``` try { // ... } catch (LgoException e) { throw LgoErrorAdapter.adapt(e); } ```
Source:
public static String adaptInstrumentName(CurrencyPair pair, Object[] args) { String instrumentPostfix; try { instrumentPostfix = args[0].toString(); } catch (Throwable t) { throw new ExchangeException( "You need to provide a postfix for the instrument name in the first parameter of the array, ie: PERPETUAL, 28JUN19..."); } return pair.base.getSymbol() + "-" + instrumentPostfix; }

Target:
replace the try catch with: ``` if (args == null || args.length == 0) { throw new throw new ExchangeException("..."); } ```
Source:
public List<CurrencyPair> getExchangeSymbols() throws IOException { try { List<CurrencyPair> currencyPairs = new ArrayList<>(); for (String symbol : bitfinex.getSymbols()) { currencyPairs.add(BitfinexAdapters.adaptCurrencyPair(symbol)); } return currencyPairs; } catch (BitfinexException e) { throw BitfinexErrorAdapter.adapt(e); } }

Target:
this try / catch should be done only in generic methods not in *Raw methods https://github.com/knowm/XChange/wiki/New-Implementation-Best-Practices#step-7
Source:
public void remoteInit() throws IOException, ExchangeException { try { exchangeMetaData = ((CoinbeneMarketDataService) marketDataService).getMetadata(); } catch (IOException e) { throw new IOException("Retrieving MetaData for Coinbene failed", e); } }

Target:
remoteInit() throws IOException, so you don't have to catch it and rethrow it. Just take the try catch away completely.
Source:
public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { String result; try { result = withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); return result; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }

Target:
you still didn't apply my hint to all the other methods that use this try / catch
Source:
public boolean cancelOrder(String orderId) throws IOException { // if it doesn't return an error and CoingiOrder is returned, then the cancellation is // successful CoingiCancelOrderRequest request = new CoingiCancelOrderRequest(); request.setOrderId(orderId); CoingiOrder order; try { order = cancelCoingiOrder(request); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } return order != null; }

Target:
the try / catch CoingiException hit not applied
Source:
public HuobiDepthResult( @JsonProperty("status") String status, @JsonProperty("ts") Date ts, @JsonProperty("tick") HuobiDepth tick, @JsonProperty("ch") String ch, @JsonProperty("err-code") String errCode, @JsonProperty("err-msg") String errMsg) { super(status, errCode, errMsg, tick); this.ts = ts; this.ch = ch; getResult().setTs(ts); }

Target:
this is odd, these DTO object should represent the exchanges response and should not do any premature mapping nor have data coping logic
Source:
public static LimitOrder createLimitOrder(MarketOrder marketOrder, DSXExchangeInfo dsxExchangeInfo) { DSXPairInfo dsxPairInfo = dsxExchangeInfo.getPairs().get(getPair(marketOrder.getCurrencyPair())); BigDecimal limitPrice = marketOrder.getType() == OrderType.BID ? dsxPairInfo.getMaxPrice() : dsxPairInfo.getMinPrice(); return LimitOrder.Builder.from(marketOrder).limitPrice(limitPrice).timestamp(new Date()).build(); }

Target:
`timestamp` should be null if there is none given by the server. This has been the standard convention in XChange since day one.
Source:
public void testFindAllIDs() throws DataException { List<Integer> allIDs = ServiceManager.getProcessService().findAllIDs(); System.out.println(allIDs); Assert.assertEquals("Wrong amount of id's in index", 7, allIDs.size()); Assert.assertTrue("id's contain wrong entries", allIDs.containsAll(Arrays.asList(5, 2, 6, 4, 1, 7, 3))); }

Target:
```suggestion ```
Source:
public List<Integer> findAllIDs() throws DataException { List<Map<String, Object>> allDocuments = findAllDocuments(); List<Integer> allIds = new ArrayList<>(); for (Map<String, Object> document : allDocuments) { allIds.add(Integer.parseInt((String) document.get("id"))); } return allIds; }

Target:
```suggestion List<Integer> allIds = new ArrayList<>(); for (Map<String, Object> document : findAllDocuments()) { ```
Source:
public void delete(ProcessDTO processDTO){ try { ProcessForm processForm = new ProcessForm(); processForm.setProcess(ServiceManager.getProcessService().getById(processDTO.getId())); processForm.delete(); } catch (DAOException e) { Helper.setErrorMessage("errorOnSearch", searchQuery); } filteredList.remove(processDTO); }

Target:
Missing white space between `)` and `{`.
Source:
public void setTaskStatusDown(Task task) { setTaskStatusDown(Arrays.asList()); }

Target:
The parameter `task` is never used. Should it be passed to `setTaskStatusDown` here? ```suggestion setTaskStatusDown(Arrays.asList(task)); ```
Source:
public static List<BatchDTO> getNewspaperBatches() throws DataException, DAOException, IOException { final BatchService batchService = ServiceManager.getBatchService(); final ProcessService processService = ServiceManager.getProcessService(); final FileService fileService = ServiceManager.getFileService(); List<BatchDTO> newspaperBatches = new ArrayList<>(); for (BatchDTO batchTransfer : batchService.findAll()) { if (isNewspaperBatch(batchTransfer, processService, fileService)) { newspaperBatches.add(batchTransfer); } } return newspaperBatches; }

Target:
you have the batch service already as a class attribute
Source:
public String convertTasksToWorkflow(String tasks) { currentTasks = tasks; PrimeFaces.current().executeScript("PF('confirmWorkflowPopup').show();"); return this.stayOnCurrentPage; }

Target:
Since you always return `null` here, I would suggest to change to function to return type `void` and remove the return statement entirely.
Source:
public int getMultipleAssignmentsIndex(StructureTreeNode treeNode) { if (Objects.nonNull(treeNode.getDataObject()) && treeNode.getDataObject() instanceof View && Objects.nonNull(((View) treeNode.getDataObject()).getMediaUnit())) { return severalAssignments.indexOf(((View) treeNode.getDataObject()).getMediaUnit()); } return -1; }

Target:
```suggestion if (treeNode.getDataObject() instanceof View ``` instanceof already checks against null
Source:
public boolean isAssignedSeveralTimes() { if (Objects.nonNull(selectedLogicalNode) && selectedLogicalNode.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) selectedLogicalNode.getData(); if (Objects.nonNull(structureTreeNode.getDataObject()) && structureTreeNode.getDataObject() instanceof View) { View view = (View) structureTreeNode.getDataObject(); return view.getMediaUnit().getIncludedStructuralElements().size() > 1; } } return false; }

Target:
```suggestion if (structureTreeNode.getDataObject() instanceof View) { ``` instanceof already checks against null
Source:
public boolean isConcurrentTaskInWork() { return this.currentTask.getId() < 0 || !getConcurrentTasksInWork().isEmpty(); }

Target:
Can id be smaller than 0?
Source:
public Date getDate() { if (Objects.isNull(date) && Objects.nonNull(getValue())) { try { date = new SimpleDateFormat("yyyy-mm-dd").parse(getValue()); } catch (ParseException e) { logger.error(e.getLocalizedMessage()); } } return date; }

Target:
For error logger stack trace is already quiet wanted: ```suggestion logger.error(e.getLocalizedMessage(), e); ```
Source:
public List<TaskDTO> loadData(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) throws DataException { String filter = ""; try { filter = ServiceManager.getFilterService().parsePrimeFacesFilter(filters); } catch (IllegalArgumentException e) { logger.error(e.getMessage()); } return findByQuery(createUserTaskQuery(filter), getSortBuilder(sortField, sortOrder), first, pageSize, false); }

Target:
`String filter = ServiceManager.getFilterService().parsePrimeFacesFilter(filters);`
Source:
public void save(OpenWorkpiece openWorkpiece) throws IOException { URI uri = openWorkpiece.getUri(); try (OutputStream out = ServiceManager.getFileService().write(uri, openWorkpiece.getLockResult())) { logger.info("Saving {}", uri.toString()); metsXmlElementAccess.save(openWorkpiece.getWorkpiece(), out); } }

Target:
call method write
Source:
public CommentService() { super(new CommentDAO()); }

Target:
Constructor needs to be private
Source:
public static CommentService getInstance() { if (Objects.equals(instance, null)) { synchronized (TaskService.class) { if (Objects.equals(instance, null)) { instance = new CommentService(); } } } return instance; }

Target:
Wrong class (TaskService?)
Source:
private DivType generatePhysicalStructMapRecursive(MediaUnit mediaUnit, Map<URI, FileType> mediaFilesToIDFiles, Map<MediaUnit, String> mediaUnitIDs, MetsType mets) { DivType div = new FileXmlElementAccess(mediaUnit).toDiv(mediaFilesToIDFiles, mediaUnitIDs, mets); for (MediaUnit child : mediaUnit.getChildren()) { div.getDiv().add(new FileXmlElementAccess(child).toDiv(mediaFilesToIDFiles, mediaUnitIDs, mets)); } return div; }

Target:
The generateFileSecRecursive is actually recursive, but where is the recursive part here?
Source:
public SearchResult search(String catalogId, String field, String term, int rows) { loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, term); return search(catalogId, searchFields, rows); }

Target:
Regarding my question above... you just put the search field in a map and call the other method ;)
Source:
public List<String> getAvailableSearchFields(String opac) throws IllegalArgumentException { try { HierarchicalConfiguration searchFields = OPACConfig.getSearchFields(opac); List<String> fields = new ArrayList<>(); for (HierarchicalConfiguration searchField : searchFields.configurationsAt("searchField")) { fields.add(searchField.getString("[@label]")); } return fields; } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: OPAC '" + opac + "' is not supported!"); } }

Target:
No need to define "throws IllegalArgumentException" in function. It extends RuntimeException. `public List<String> getAvailableSearchFields(String opac) {`
Source:
public List<String> getAvailableCatalogs() throws IllegalArgumentException { try { return OPACConfig.getCatalogs(); } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: no supported OPACs found in configuration file!"); } }

Target:
No need to define "throws IllegalArgumentException" in function. It extends RuntimeException. `public List<String> getAvailableSearchFields(String opac) {`
Source:
void initialize(BaseDAO baseDAO, List<? extends BaseBean> list) { if (Objects.nonNull(this.id) && !Hibernate.isInitialized(list)) { try { Hibernate.initialize(list); } catch (HibernateException e) { baseDAO.initialize(this, list); } } }

Target:
use baseDAO.initialize as we discussed it
Source:
public FormRow(Optional<MetadataViewInterface> optionalKeyView, Collection<T> values) { this.optionalKeyView = optionalKeyView; this.values = values; }

Target:
Public constructor without JavaDoc.
Source:
public void setYearBegin(MonthDay yearBegin) { this.yearBegin = yearBegin; }

Target:
Public method without JavaDoc.
Source:
public DeniedAccess(Map<URI, Collection<String>> conflicts) { assert !conflicts.isEmpty() : "the conflict map should not be empty"; this.conflicts = conflicts; }

Target:
Don't use assertions.
Source:
private void canClose(Collection<URI> uris) { String exceptionMessagePrefix = "The lock cannot be released because there are still streams flowing for the following URIs: "; String exceptionMessage = uris.parallelStream().filter(uri -> streamManagement.isKnowingAnOpenStreamTo(uri)) .map(uri -> uri.toString()).collect(Collectors.joining(", ", exceptionMessagePrefix, "")); if (exceptionMessage.length() > exceptionMessagePrefix.length()) { throw new IllegalStateException(exceptionMessage); } }

Target:
Lambda can be replaced with method reference.
Source:
void close(String user, Map<URI, AbstractLock> locks) { synchronized (this) { canClose(locks.keySet()); locks.entrySet().parallelStream().map(entry -> entry.getKey()) .peek(uri -> removePermission(user, locks.get(uri), uri)) .forEach(uri -> immutableReadFileManagement.maybeRemoveReadFile(uri, user)); } }

Target:
Lambda can be replaced with method reference.
Source:
public ProcessEditPage editProcess() throws Exception { if (isNotAt()) { goTo(); } clickButtonAndWaitForRedirect(editProcessLink, Pages.getProjectEditPage().getUrl()); return Pages.getProcessEditPage(); }

Target:
Edit process or project? ;-) Here you click the editProcess Link but you wait for redirect to editProject page.
Source:
public static List<String> getTableDataByColumn(WebElement table, int columnIndex) { List<WebElement> rows = getRowsOfTable(table); List<String> data = new ArrayList<>(); for (WebElement row : rows) { data.add(getCellDataByRow(row, columnIndex)); System.out.println(getCellDataByRow(row, columnIndex)); } return data; }

Target:
Please remove this debug helper ;)
Source:
public List<String> getTemplateDetails() throws Exception { int index = triggerRowToggle(templatesTable, "First template"); Thread.sleep(5000); WebElement detailsTable = Browser.getDriver() .findElement(By.id(TEMPLATE_TABLE + ":" + index + ":templateDetailTable")); Thread.sleep(5000); //TODO: find way to read this table without excpetion... //List<String> details = getTableDataByColumn(detailsTable, 1); //details.addAll(getTableDataByColumn(detailsTable, 3)); return new ArrayList<>(); }

Target:
Why did you add this and a few lines below this call and only returning an empty list? I think this and similar line below could be removed.
Source:
public void shouldGetDivOfLogicalStructMapFromExistingFile() throws DatatypeConfigurationException, IOException, JAXBException, TransformerException { MetsKitodoWrapper metsKitodoWrapper = new MetsKitodoWrapper(xmlfile, xsltFile); DivType rootDiv = metsKitodoWrapper.getLogicalStructMap().getDiv(); DivType rootDivFromMets = metsKitodoWrapper.getMets().getStructMap().get(1).getDiv(); MetsKitodoWriter writer = new MetsKitodoWriter(); System.out.println(writer.writeSerializedToString(metsKitodoWrapper.getMets())); Assert.assertEquals("Div elements from getter and directly from mets objects were not the same", rootDiv, rootDivFromMets); }

Target:
Is this `System.out.println` call really needed? If not remove it or if this call is needed replace it by a logger call.
Source:
for (String regex : regexList) { if (name.matches(regex)) { fileOk = true; } }

Target:
Missing JavaDoc for public method. Or move this code into its own class to get ride out of this inner class usage.
Source:
private boolean isPropertyInvalid(Property property, Task task) { if ((property.getValue() == null || property.getValue().equals(""))) { List<String> parameter = new ArrayList<>(); parameter.add(property.getTitle()); parameter.add(task.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); return true; } return false; }

Target:
Braces are correct set as you double encode the expression. It is only moved code but can be fixed to ```java if (property.getValue() == null || property.getValue().equals("")) { .... } ```
Source:
private void getFlowingFlowNodes(FlowNode node) { Collection<SequenceFlow> sequenceFlow = node.getOutgoing(); FlowNode flowNode = sequenceFlow.iterator().next().getTarget(); if (flowNode instanceof Gateway) { getFlowingFlowNodesWithConditions((Gateway) flowNode); } else if (flowNode instanceof Task) { this.followingFlowNodes.add(flowNode); getFlowingFlowNodes(flowNode); } }

Target:
Could not a NPE happen here if collection is empty / null ?
Source:
public void startExport(Process process, OutputStream os, String xslt) throws IOException { try { Document doc = createDocument(process, true); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); outp.output(doc, os); os.close(); } catch (IOException | RuntimeException e) { throw new IOException(e.getMessage(), e); } }

Target:
Is this change here necessary? It is new IOException, not logger.
Source:
List<JsonObject> findBySort(boolean closed, boolean active, String sort, Integer offset,Integer size) throws DataException { BoolQueryBuilder query = new BoolQueryBuilder(); query.must(getQuerySortHelperStatus(closed)); query.must(getQueryProjectActive(active)); return searcher.findDocuments(query.toString(), sort, offset, size); }

Target:
Missing space between `offset,Integer size`.
Source:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getTemplatePage().countListedTemplates(); Thread.sleep(50000); Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }

Target:
Why need this test need such a high timeout value?
Source:
public Long countDocuments(String query) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.countDocuments(overrideNullQuery(query)); if (!response.equals("")) { JsonReader jsonReader = Json.createReader(new StringReader(response)); JsonObject result = jsonReader.readObject(); return result.getJsonNumber("count").longValue(); } else { return 0L; } }

Target:
`JsonReader` is a closeable class but the created object is never closed. Maybe you can use a try-with-resources statement?
Source:
public JsonObject findDocument(Integer id) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.getDocument(id); if (!response.equals("")) { JsonReader jsonReader = Json.createReader(new StringReader(response)); return jsonReader.readObject(); } else { return Json.createObjectBuilder().build(); } }

Target:
Same here. `JsonReader` is closeable so using a try-with-resources statement for closing the object is maybe a good idea.
Source:
public JsonObject aggregateDocuments(String query, String aggregation) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.aggregateDocuments(overrideNullQuery(query), aggregation); if (!response.equals("")) { JsonReader jsonReader = Json.createReader(new StringReader(response)); JsonObject result = jsonReader.readObject(); return result.getJsonObject("aggregations"); } else { return Json.createObjectBuilder().build(); } }

Target:
Same here. `JsonReader` is closeable so using a try-with-resources statement for closing the object is maybe a good idea.
Source:
private void saveTask(String processTitle, Task task) { try { serviceManager.getTaskService().save(task); } catch (DataException e) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving - " + processTitle, e); logger.error(KITODO_SCRIPT_FIELD + "Error while saving - " + processTitle, e); } }

Target:
Please first log the error and then inform the user.
Source:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } Helper.setMeldung(null, "ExportFinished", ""); logger.info(Helper.getTranslation("ExportFinished")); }

Target:
If you add a log message it should be logged before the user get the information. Please move this log call in front of the `Helper.setMeldung()` call.
Source:
protected void initUserList() { try { this.user.addAll(serviceManager.getUserService().getAllActiveUsersSortedByNameAndSurname()); } catch (RuntimeException rte) { Helper.setErrorMessage("errorLoadingMany", new String[] {Helper.getTranslation("aktiveBenutzer") }); logger.warn("RuntimeException caught. List of users could be empty!"); } }

Target:
Same here. Please first log the error message / reason and then display it to the user.
Source:
public ArrayList<Property> getWorkpieceProperties() { if (Objects.isNull(workpieceProperties)) { return new ArrayList<>(); } return workpieceProperties; }

Target:
Why did you not assign this empty list and return it?
Source:
private MetadataInterface findMetadatumIn(DocStructInterface node) { List<? extends MetadataInterface> metadataInterface = node.getAllMetadataByType(selector); for (MetadataInterface metadatum : metadataInterface) { if (selector.getName().equals(metadatum.getMetadataType().getName())) { return metadatum; } } return null; }

Target:
Interface appended to variable name
Source:
public static FileformatInterface parsePicaFormat(Node pica, PrefsInterface prefs) throws ReadException, PreferencesException, TypeNotAllowedForParentException { PicaPlusInterface pp = UghImplementation.INSTANCE.createPicaPlus(prefs); pp.read(pica); DigitalDocumentInterface dd = pp.getDigitalDocument(); FileformatInterface ff = UghImplementation.INSTANCE.createXStream(prefs); ff.setDigitalDocument(dd); /* BoundBook hinzufügen */ DocStructTypeInterface dst = prefs.getDocStrctTypeByName("BoundBook"); DocStructInterface dsBoundBook = dd.createDocStruct(dst); dd.setPhysicalDocStruct(dsBoundBook); return ff; }

Target:
TypeNotAllowedForParentException - not used exception.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Authority authority = (Authority) o; return title != null ? title.equals(authority.title) : authority.title == null; }

Target:
Wrong formatting in whole method. Please fix it.
Source:
private Actuate(String name) { this.name = name; }

Target:
Modifier 'private' is redundant for Enum constructor - needs to be removed.
Source:
private Type(String name) { this.name = name; }

Target:
Modifier 'private' is redundant for Enum constructor - needs to be removed.
Source:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { // This NPE gets thrown - and therefore must be caught - when "RulesetForm" is // used from it's integration test // class "RulesetFormIT", where no "FacesContext" is available! return "/pages/ProjekteBearbeiten" + urlSuffix; } }

Target:
This looks wrong. Why should edit page for projects be returned if we are in ruleset editing?
Source:
public SelectItem[] getAddableDocStructTypes() { switch (positionOfNewDocStrucElement) { case BEFOR_CURRENT_ELEMENT: case AFTER_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, true); case FIRST_CHILD_OF_CURRENT_ELEMENT: case LAST_CHILD_OF_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, false); default: logger.error("Invalid positionOfNewDocStrucElement"); return null; } }

Target:
Returning null should be avoided as it introduce unnecessary null pointer checks. Could not a empty object be returned?
Source:
private ObjectType findNextNode() { while (true) { if ((inner == null) || !inner.hasNext()) { if (outer.hasNext()) { inner = outer.next().getValue().iterator(); } else { return null; } } while (inner.hasNext()) { return inner.next(); } } }

Target:
Return empty object instead of null.
Source:
public static Boolean updateHistoryForProcess(Process inProc) { Boolean updated; try { //TODO: updateHistoryForSteps overwrites result of updateHistory updated = updateHistory(inProc); updated = updateHistoryForSteps(inProc); } catch (Exception ex) { logger.warn("Updating history failed.", ex); logger.error(ex.getStackTrace()); updated = false; } return updated; }

Target:
Is this error log call necessary as in the warning call is the stack trace included.
Source:
public File generateDocket(DocketData docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); try { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.flush(); fileOutputStream.close(); } return file; }

Target:
Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.
Source:
public void testStartExport() throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); File xslFile = new File("src/test/resources/docket.xsl"); try { exportDocket.startExport(docketDataGenerator.createDocketData("processId", "signature", "doctype"), fileOutputStream, xslFile); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.close(); } }

Target:
Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.
Source:
public Long getNumberOfPagesPerIssue() { if (course.countIndividualIssues() != 0) { return numberOfPages != null ? numberOfPages / course.countIndividualIssues() : null; } else { return null; } }

Target:
We would never return `null` as this value cause null pointer exceptions or add a lot of null value checks.
Source:
public boolean isSelected() { return (this.selected); }

Target:
Why did you add the round braces?
Source:
private void manageProcessDependenciesForIndex(Template template) throws CustomResponseException, IOException { Process process = template.getProcess(); if (template.getIndexAction() == IndexAction.DELETE) { if (process != null) { process.getTemplates().remove(template); serviceManager.getProcessService().saveToIndex(process); } } else { if (process != null) { serviceManager.getProcessService().saveToIndex(process); } } }

Target:
A template should never exists without a corresponding process. It could be possible that a process has no template.
Source:
<F extends BaseBean> JSONArray addObjectRelation(List<F> objects) { JSONArray jsonArray = new JSONArray(); if (objects != null && objects.size() > 0) { for (F property : objects) { jsonArray.add(addIdForRelation(property.getId())); } } return jsonArray; }

Target:
Why did you add this empty list check (null check is OK)? I think it is not necessary as an empty list will do nothing in later for statement.
Source:
private boolean isValidProcessProperty() { if (this.processProperty.isValid()) { return true; } else { List<String> param = new ArrayList<String>(); param.add(processProperty.getName()); String value = Helper.getTranslation("propertyNotValid", param); Helper.setFehlerMeldung(value); Helper.setFehlerMeldung("Property " + this.processProperty.getName() + " is not valid"); return false; } }

Target:
What about `String value = Helper.getTranslation("propertyNotValid", Arrays.asList(new String[]{ processProperty.getName() }));`
Source:
public void test() throws Exception { ServiceManager serviceManager = new ServiceManager(); long counted = serviceManager.getProcessService().count("from Process"); Assert.assertNotNull("No Process found", counted); Assert.assertEquals(4, counted); String title = serviceManager.getProcessService().find(1).getTitle(); Assert.assertEquals("DBConnectionTest", title); }

Target:
This test could not work, as you are search for first process but your test data is inserted as 4th.
Source:
public static String getKitodoConfigDirectory() { return ConfigCore.getParameter(CONFIG_DIR); }

Target:
This could be simplified to `return getParameter(CONFIG_DIR);` or did I miss something?
Source:
public int getWorkpiecesSize() { if (this.getWorkpieces() == null) { return 0; } else { return this.getWorkpieces().size(); } }

Target:
Why did you leave changes for this method out? This method looks like the other changed methods.
Source:
public void setTimeout(long timeout) { this.timeout = timeout; }

Target:
missing JavaDoc statement
Source:
public ProcessProperty() { this.container = new Integer(0); this.value = ""; this.possibleValues = new ArrayList<String>(); this.projects = new ArrayList<String>(); this.showStepConditions = new ArrayList<ShowStepCondition>(); this.prozesseigenschaft = new Prozesseigenschaft(); }

Target:
IntelliJ IDEA tolds me to remove this unnecessary boxing.
Source:
public void setDest(final RandomAccessOutputStream stream, final int imageIndex, final SCIFIOConfig config) throws FormatException, IOException { super.setDest(stream, imageIndex, config); if (getStream().length() == 0) { writeHeader(); } }

Target:
This is not ImageJ style. When curly braces are present, the opening brace goes on the same line, the statement(s) go on following line(s), and closing brace on its own line. The Eclipse code style formatter does this.
Source:
public void close() throws IOException { if (getStream() != null) { writeFooter(); } super.close(); }

Target:
Not ImageJ style.
Source:
public void writeEntityToNBT(NBTTagCompound n) { n.setInteger("frogType", (byte)getType().ordinal()); super.writeEntityToNBT(n); }

Target:
setInteger(byte) :thinking:
Source:
public void onRenderTick(RenderWorldLastEvent event) { if(Minecraft.getMinecraft().player != null && !Minecraft.getMinecraft().player.isDead) { if (Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 || Minecraft.getMinecraft().currentScreen != null) { EntityPlayer p = Minecraft.getMinecraft().player; if(!p.isInWater()) updateSwimDataAngles(p); updateSwimRenderAngles(p); } } }

Target:
This is sketchy. Should this encompass both of these? just one?
Source:
public void doRender(EntityTropicraftWaterBase entityliving, double d, double d1, double d2, float f, float f1) { if(refreshModel && entityliving.ticksExisted % 20 == 0) { this.mainModel = new ModelDolphin(); this.dolphin = new ModelDolphin(); refreshModel = false; } //refreshModel = true; this.renderWaterMob((EntityTropicraftWaterBase) entityliving, d, d1, d2, f1); }

Target:
Why do you use mainModel and dolphin, since dolphin is just equal to mainModel?
Source:
public void assignRandomTexture() { if(!world.isRemote) { if(getTexturePool().length > 0) { setTexture(getTexturePool()[rand.nextInt(getTexturePool().length)]); } } }

Target:
Since getTexturePool can return null, you should add a null check here.
Source:
private boolean shouldRedirect(ContainerRequestContext requestContext) { String maybeVehicle = requestContext.getUriInfo().getQueryParameters().getFirst("vehicle"); if (maybeVehicle != null && maybeVehicle.equals("pt")) { return true; } String maybeProfile = requestContext.getUriInfo().getQueryParameters().getFirst("profile"); if (maybeProfile != null && maybeProfile.equals("pt")) { return true; } return false; }

Target:
this could be a bit shorter ;) `return "pt".equals(maybeProfile)` And should we also remove the profile param in the filter method above? (`replaceQueryParam("profile")`)
Source:
public static BBox createBBox(NodeAccess na, EdgeIteratorState edgeState) { return BBox.fromPoints(na.getLatitude(edgeState.getBaseNode()), na.getLongitude(edgeState.getBaseNode()), na.getLatitude(edgeState.getAdjNode()), na.getLongitude(edgeState.getAdjNode())); }

Target:
This would be better to duplicate and keep private
Source:
public CHProfileConfig setProfile(String profile) { validateProfileName(profile); this.profile = profile; return this; }

Target:
Should we better make this method package protected to only allow jackson access to it?
Source:
protected void fillEdgesToUsingFilter(EdgeFilter edgeFilter) { // we temporarily ignore the additionalEdgeFilter EdgeFilter tmpFilter = additionalEdgeFilter; additionalEdgeFilter = edgeFilter; finishedTo = !fillEdgesTo(); additionalEdgeFilter = tmpFilter; }

Target:
What are the use cases for the EdgeFilter for non-CH algos? (For CH there is the CHLevelEdgeFilter, but here?) Is it just regarding the vehicle edge and we can remove this code with #1835 ?
Source:
public OSMMaxAxleLoadParser() { this.maxAxleLoadEncoder = MaxAxleLoad.create(); }

Target:
I would not remove this. I think the additional constructor is a meaningful addition, so that the user could increase or decrease the precision. (same for the other parsers)
Source:
public boolean acceptsTurnRelation(OSMTurnRelation relation) { if (relation.isVehicleTypeConcernedByTurnRestriction(restrictions)) { return true; } return false; }

Target:
just `return relation.isVehicleTypeConcernedByTurnRestriction(restrictions)` (here and in other encoders)
Source:
private JsonNode parseRequestResponse (Response response) throws IOException { response.bufferEntity(); String body = response.readEntity(String.class); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(body); }

Target:
Why is this necessary?
Source:
private Weighting createWeighting(FlagEncoder encoder, double uTurnCosts) { TurnWeighting result = new TurnWeighting(new FastestWeighting(encoder), tcs); if (!Double.isInfinite(uTurnCosts)) { result.setUTurnCost(uTurnCosts); } return result; }

Target:
Can this be moved into the new constructor?
Source:
public static String join(String delimiter, List<String> strings) { StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs : strings) { joiner.add(cs); } return joiner.toString(); }

Target:
That would cause problem on Android compatibility, since [StringJoiner](https://developer.android.com/reference/java/util/StringJoiner) being a Java 8 class, was added in API level 24 (Android 7 Nougat).
Source:
public GraphHopper() { chFactoryDecorator.setEnabled(true); lmFactoryDecorator.setEnabled(false); arFactoryDecorator.setEnabled(true); // order is important to use CH as base algo and set the approximation in the followed lm factory decorator. // AR must be the last factory decorator because it need both other decorators during preparation algoDecorators.add(chFactoryDecorator); algoDecorators.add(lmFactoryDecorator); algoDecorators.add(arFactoryDecorator); }

Target:
I would not enable this by default. Then there is also no need to change the many tests.
Source:
private int distToInt(double distance) { if (distance < 0) throw new IllegalArgumentException("Distance cannot be negative: " + distance); if (distance > MAX_DIST) { distance = MAX_DIST; // throw new IllegalArgumentException("Distance too large leading to overflowed integer (#435): " + distance + " "); } int integ = Math.round((float) (distance * INT_DIST_FACTOR)); assert integ >= 0 : "distance out of range"; return integ; }

Target:
Ok, yes. It looks that we do not have a test for this. So when I remove "if (integ >= Integer.MAX_VALUE) return Integer.MAX_VALUE;" everything is fine, which I would fix before doing the refactoring.
Source:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) { return; } BiFunction<Long, Long, Long> overwriteFunc = (oldFlags, newFlags) -> { return newFlags; }; setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, overwriteFunc); }

Target:
It would be better to avoid creating this function on every method call.
Source:
public ConnectionNotFoundException(List<Path> paths, PointList waypoints) { super(unconnectedListString(paths), unconnectedInfo(paths, waypoints)); }

Target:
Wouldn't it be better to call `this(unconnectedListString(paths), unconnectedInfo(paths, waypoints));` in this case?
Source:
public void readGraph() throws IOException { // TODO why 1000? graphStorage.create(1000); processJunctions(); processRoads(); }

Target:
In very early version we gave a hint how large the graph can get, but this is no longer really necessary. Can be removed in another issue ;)
Source:
protected String removeRelation(String edgeName){ if(edgeName != null && edgeName.contains(", ")){ edgeName = edgeName.substring(0, edgeName.lastIndexOf(',')); } return edgeName; }

Target:
Nice hack :) !
Source:
boolean isPushingSection( OSMWay way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return way.hasTag("highway", pushingSections) || way.hasTag("railway", "platform") || way.hasTag("bicycle", "dismount") || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); }

Target:
here we should use `isPushingSection` instead (?)
Source:
private boolean appendValue(final StringBuilder rval, final Long value, final String key, final boolean nonzeroFragmentVisited) { boolean append = nonzeroFragmentVisited; if (value == null) { return nonzeroFragmentVisited; } if (!nonzeroFragmentVisited && value.longValue() > 0) { append = true; } if (append) { rval.append(value.longValue()).append(key); return true; } return false; }

Target:
Is boolean append necessary? nozeroFragmentVisited || value.longValue() > 0 would be more simple. Please check.
Source:
private boolean loadDataFromSession() { HttpSession session = getHttpSession(); Object data = session.getAttribute(SESSION_KEY); if ((data != null) && (data instanceof ReportSessionData)) { ReportSessionData reportSessionData = (ReportSessionData) data; currentUser = reportSessionData.currentUser; dateFrom = reportSessionData.dateFrom; dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); dateTo = reportSessionData.dateTo; dateToFormated = DateTimeConverterUtil.dateToString(dateTo); return true; } else { return false; } }

Target:
How about this: if (data == null || !(data instanceof ReportSessionData)) { return false }
Source:
private void dateFromDefaultInit() { final Calendar calendarFrom = Calendar.getInstance(); calendarFrom.add(Calendar.WEEK_OF_MONTH, -1); dateFrom = calendarFrom.getTime(); dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); }

Target:
Remove the unnecessary final modifier from the local variables.
Source:
public static String getPluginVersion() { final String pluginVersion = ComponentAccessor.getPluginAccessor() .getPlugin("org.everit.jira.timetracker.plugin") .getPluginInformation().getVersion(); return pluginVersion; }

Target:
Remove all of the unnecessary final modifier from the local variables from all of the modified classes.
Source:
public CookieFilter(CookieSpec cookieSpec) { this.cookieSpec = cookieSpec; this.allowMultipleCookiesWithTheSameName = false; this.cookieStore = new BasicCookieStore(); }

Target:
re-use existing constructors: ``` this(cookieSpec, false); ```
Source:
public StockSaver(final HibernateSessionProvider sessionProviderForLocal) { super(sessionProviderForLocal); this.studyGermplasmListService = new StudyGermplasmListServiceImpl(sessionProviderForLocal); }

Target:
Better to autowire _studyGermplasmListService_ instead
Source:
public FormulaDto save(final FormulaDto formulaDto) { Formula formula = FormulaUtils.convertToFormula(formulaDto); formula = this.daoFactory.getFormulaDAO().save(formula); final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }

Target:
@nahuel-soldevilla does not hibernate set the id to the object once the transaction is committed?
Source:
public MeasurementData(final String label, final String value) { super(); this.label = label; this.value = value; this.changed = false; }

Target:
It's easiest to initiate the field directly, and I'm not sure it's needed, the primitive should be false by default
Source:
private static List<MarkerMetadataSet> buildMarkerMetadataSet(final Dataset dataset, final Map<String, Marker> markerMap) { List<MarkerMetadataSet> markerMetadataSetList = new ArrayList<>(); for (final Marker marker : markerMap.values()) { final MarkerMetadataSet mdb = new MarkerMetadataSet(); mdb.setDataset(dataset); mdb.setMarkerId(marker.getMarkerId()); mdb.setMarkerSampleId(1); markerMetadataSetList.add(mdb); } return markerMetadataSetList; }

Target:
Please add final
Source:
public ProjectProperty(DmsProject project, Integer typeId, String value, Integer rank, Integer variableId, String alias) { this.project = project; this.typeId = typeId; this.value = value; this.rank = rank; this.variableId = variableId; this.alias = alias; this.description = description; }

Target:
We can remove assignment to local variable description
Source:
public void setVariableTypeIfNull(){ if(this.getVariableType() != null) { return; } if(this.getRole() == null){ return; } String propertyName = this.getStandardVariable().getProperty().getName(); this.setVariableType(OntologyDataHelper.mapFromPhenotype(this.getRole(), propertyName)); }

Target:
add final
Source:
public Workbook strictParseWorkbook(final File file, final String programUUID) throws WorkbookParserException { final WorkbookParser parser = new WorkbookParser(this.maxRowLimit); final OntologyDataManagerImpl ontology = new OntologyDataManagerImpl(this.getSessionProvider()); final GermplasmDataManager germplasmDataManager = new GermplasmDataManagerImpl(this.getSessionProvider()); // partially parse the file to parse the description sheet only at first return this.strictParseWorkbook(file, parser, parser.parseFile(file, true), ontology, germplasmDataManager, programUUID); }

Target:
Boy Scout Cleanup: ``` final OntologyDataManagerImpl ontology = new OntologyDataManagerImpl(this.getSessionProvider()); final GermplasmDataManager germplasmDataManager = new GermplasmDataManagerImpl(this.getSessionProvider()); ``` Instead of manual local creation of service dependencies like this, we should follow the standard pattern of having the OntologyDataManager and GermplasmDataManager interface typed class member variables and inject the services via spring auto wiring.
Source:
protected void initTiffParser() { super.initTiffParser(); // older .scn files require color correction // newer files from Versa systems do not if (handler != null) { Image i = handler.imageMap.get(0); tiffParser.setYCbCrCorrection(!"versa".equalsIgnoreCase(i.devModel) && !"leica scn400".equalsIgnoreCase(i.devModel); } }

Target:
```suggestion tiffParser.setYCbCrCorrection(!("versa".equalsIgnoreCase(i.devModel) || "leica scn400".equalsIgnoreCase(i.devModel))); ```