auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String getKind(String uniqueId) { if (StringUtils.isEmpty(uniqueId)) { return null; } String[] comps = uniqueId.split(String.valueOf(UNIQUE_ID_PROJECT_NAME_DELIMITER)); if (comps.length == 2) { return ResourceKind.SERVICE; } else { START return comps[1]; END } } this should only be performed once we checked that there are actually >= 2 elements in comps. We otherwise potentially run into an ArrayIndexOutOfBoundsException.

Target:
public static String getKind(String uniqueId) { if (StringUtils.isEmpty(uniqueId)) { return null; } String[] comps = uniqueId.split(String.valueOf(UNIQUE_ID_PROJECT_NAME_DELIMITER)); if (comps.length == 2) { return ResourceKind.SERVICE; } else if (comps.length == 3) { return comps[1]; } else { return null; } }
Source:
private void stopWatchSafe(IProject project, IOpenShiftConnection connection, String... kinds) { START for (String kind : KINDS) { END AtomicReference<IWatcher> watcherRef = watches.remove(new WatchKey(connection, project, kind)); if((watcherRef != null) && (watcherRef.get() != null)) { watcherRef.get().stop(); } } } Should not 'kinds' be used here instead of 'KINDS' as in startWatchSafe(), or it is left intentionally to make sure that all watches are removed?

Target:
private void stopWatchSafe(IProject project, IOpenShiftConnection connection, String... kinds) { for (String kind : kinds) { AtomicReference<IWatcher> watcherRef = watches.remove(new WatchKey(connection, project, kind)); if((watcherRef != null) && (watcherRef.get() != null)) { watcherRef.get().stop(); } } }
Source:
public OpenShiftExplorerContentProvider() { listener = new IElementListener() { @Override START public void elementChanged(IOpenshiftUIElement<?, ?> element) { END if (element instanceof OpenshiftUIModel) { refreshViewer(ConnectionsRegistrySingleton.getInstance()); } else { refreshViewer(element); } if (element.getWrapped() instanceof IRoute) { viewer.update(element.getParent(), null); } } }; model.addListener(listener); } keeping that constructor makes it more testable as you could inject a mock OpenshiftUIModel

Target:
public OpenShiftExplorerContentProvider() { this(OpenshiftUIModel.getInstance()); }
Source:
private String getLabel(String mode) { String label = OpenShiftCoreMessages.RunOnOpenshift; START if (ILaunchManager.PROFILE_MODE.equals(mode)) { END label = OpenShiftCoreMessages.ProfileOnOpenshift; } else if (ILaunchManager.DEBUG_MODE.equals(mode)) { label = OpenShiftCoreMessages.DebugOnOpenshift; } return label; } just a niggle: i think `switch-case` with "RunOnOpenshift" as the default would be more readable here

Target:
private String getLabel(String mode) { String label; switch (mode) { case ILaunchManager.DEBUG_MODE: label = OpenShiftCoreMessages.DebugOnOpenshift; break; case ILaunchManager.PROFILE_MODE: label = OpenShiftCoreMessages.ProfileOnOpenshift; break; default: label = OpenShiftCoreMessages.RunOnOpenshift; break; } return label; }
Source:
START public static com.openshift.restclient.model.IProject getProject(IResource resource) { END IProject project = null; if (resource instanceof IProject) { project = (IProject) resource; } else if (resource != null) { project = resource.getProject(); } return project; } just a niggle : what's the point of using full class name (including package)?

Target:
public static IProject getProject(IResource resource) { IProject project = null; if (resource instanceof IProject) { project = (IProject) resource; } else if (resource != null) { project = resource.getProject(); } return project; }
Source:
public IConnection update(IConnection conn) { Assert.isLegal(conn instanceof Connection); final Connection connection = (Connection) conn; // might be called from job, switch to display thread to access observables Display.getDefault().syncExec(new Runnable() { @Override public void run() { connection.setAuthScheme(IAuthorizationContext.AUTHSCHEME_OAUTH); connection.setToken((String) tokenObservable.getValue()); START connection.setRememberToken((boolean) rememberTokenObservable.getValue()); END } }); return connection; } Since definition of rememberTokenObservable and tokenObservable now has type parameter, the casting may be not needed at all.

Target:
public IConnection update(IConnection conn) { Assert.isLegal(conn instanceof Connection); final Connection connection = (Connection) conn; // might be called from job, switch to display thread to access observables Display.getDefault().syncExec(new Runnable() { @Override public void run() { connection.setAuthScheme(IAuthorizationContext.AUTHSCHEME_OAUTH); connection.setToken(tokenObservable.getValue()); connection.setRememberToken(rememberTokenObservable.getValue()); } }); return connection; }
Source:
private LoadingStub makeStub(Object parentElement) { LoadingStub stub = stubs.get(parentElement); if (stub == null) { stub= new LoadingStub(); START stubs.put(parentElement, stub); END } return stub; } Any chance of a race condition here where concurrent threads try to add entries and one ends up replacing the other?

Target:
private LoadingStub makeStub(Object parentElement) { synchronized (stubs) { LoadingStub stub = stubs.get(parentElement); if (stub == null) { stub = new LoadingStub(); stubs.put(parentElement, stub); } return stub; } }
Source:
Job createJob(final String name, final JobCounter jc) { START return new Job("Job 1") { END @Override protected IStatus run(IProgressMonitor monitor) { jc.jobDone(getName()); return Status.OK_STATUS; } }; } return new Job(name)

Target:
Job createJob(final String name, final JobCounter jc) { return new Job(name) { @Override protected IStatus run(IProgressMonitor monitor) { jc.jobDone(getName()); return Status.OK_STATUS; } }; }
Source:
private IConnectionWrapper createConnection(IServer server) throws MalformedURLException { ConnectorProviderRegistry connectorProviders = OpenShiftCoreActivator.getDefault().getConnectorProviders(); VersionKey version = new VersionDetector(server).guess(); if (version != null) { JMXConnectorProvider provider = connectorProviders.getProvider(version); START return new OpenshiftConnectionWrapper(this, server, provider); END } return null; } what if provider == null?

Target:
private IConnectionWrapper createConnection(IServer server) throws MalformedURLException { ConnectorProviderRegistry connectorProviders = OpenShiftCoreActivator.getDefault().getConnectorProviders(); VersionKey version = new VersionDetector(server).guess(); if (version != null) { JMXConnectorProvider provider = connectorProviders.getProvider(version); if (provider != null) { return new OpenshiftConnectionWrapper(this, server, provider); } } return null; }
Source:
public void dispose() { super.dispose(); DockerConnectionManager.getInstance().removeConnectionManagerListener(this); ((EnvironmentVariablesPageModel)envModel).dispose(); connection = null; project = null; dockerConnection = null; projects.clear(); volumes.clear(); portSpecs.clear(); if(imagePorts != null) { imagePorts.clear(); START } END } set the reference to imagePorts to null (to be consistent)? `imagePorts = null`

Target:
public void dispose() { super.dispose(); DockerConnectionManager.getInstance().removeConnectionManagerListener(this); ((EnvironmentVariablesPageModel)envModel).dispose(); connection = null; project = null; dockerConnection = null; projects.clear(); volumes.clear(); portSpecs.clear(); if(imagePorts != null) { imagePorts.clear(); imagePorts = null; } }
Source:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); START } END ``` @Override public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); } ```

Target:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); }
Source:
protected boolean isEapProfile() { // quick and dirty String profile = ServerProfileModel.getProfile(getServer()); if( "openshift3.eap".equals(profile)) { START return false; END } return true; } nope, return true

Target:
protected boolean isEapProfile() { // quick and dirty String profile = ServerProfileModel.getProfile(getServer()); if( "openshift3.eap".equals(profile)) { return true; } return false; }
Source:
START default public boolean isRememberChoice() { END return false; } I have no issues correcting the other method signatures either. It would be obvious from the diff what is happening and that no code is being changed.

Target:
default boolean isRememberChoice() { return false; }
Source:
public void startWatch(final IProject project) { ConcurrentMap<String, IWatcher> kindMap = new ConcurrentHashMap<>(); if(watches.putIfAbsent(project, kindMap) == null){ START final Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); END for (String kind: KINDS) { WatchListener listener = new WatchListener(project, conn, kind, 0, 0); startWatch(project, 0, 0, listener); } } } can't conn be null at that point?

Target:
public void startWatch(final IProject project) { ConcurrentMap<String, IWatcher> kindMap = new ConcurrentHashMap<>(); if(watches.putIfAbsent(project, kindMap) == null){ final Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); if(conn == null) return; for (String kind: KINDS) { WatchListener listener = new WatchListener(project, conn, kind, 0, 0); startWatch(project, 0, 0, listener); } } }
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(); } START viewer.setExpandedTreePaths(treePaths); END } } }); } This line causes an endless load on linux when a node has zero children.

Target:
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(); } // This line causes an endless load on linux when a node has zero children. (JCantrill) //viewer.setExpandedTreePaths(treePaths); } } }); }
Source:
private ADBInfo createADB(String host, String port) throws URISyntaxException { START HashMap<String,String> env = new HashMap<String,String>(); END 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); } new HashMap<>()

Target:
private ADBInfo createADB(String host, String port) throws URISyntaxException { HashMap<String,String> env = new HashMap<>(); 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); }
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(); } START if (DOCKER_IMAGE_KIND.equals(kind)) { END return build.getOutputTo().getNameAndTag().toString(); } return ""; } seems like both if statements could be merged

Target:
public static String imageRef(IBuild build) { if(build != null) { switch(build.getOutputKind()) { case ResourceKind.IMAGE_STREAM_TAG: case IMAGE_STREAM_IMAGE_KIND: case DOCKER_IMAGE_KIND: return build.getOutputTo().getNameAndTag(); } } return ""; }
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... START new RefreshResourceHandler().execute(event); END } catch (ConnectionNotFoundException e) { return new Status(Status.ERROR, OpenShiftUIActivator.PLUGIN_ID, "Unable to find the connection", e); } return Status.OK_STATUS; } how is that related to the autopublish issue?

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { try { WizardUtils.openWizardDialog(new NewApplicationWizard(), HandlerUtil.getActiveShell(event)); } catch (ConnectionNotFoundException e) { return new Status(Status.ERROR, OpenShiftUIActivator.PLUGIN_ID, "Unable to find the connection", e); } return Status.OK_STATUS; }
Source:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; START String dockerHost = env.get("DOCKER_HOST"); END URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; } possible NPE afterwards. Might as well add an assertion on required "DOCKER_HOST"

Target:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; String dockerHost = env.get("DOCKER_HOST"); if( dockerHost != null ) { URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; } }
Source:
public void selectionChanged(IStructuredSelection sel) { START if( sel.size() == 0 || sel.size() > 1 ) { END setEnabled(false); return; } setEnabled(true); synchronized(this) { switchListener(previousSelection, sel); previousSelection = sel; } super.selectionChanged(sel); } if( sel.size() != 1 )

Target:
public void selectionChanged(IStructuredSelection sel) { if( sel.size() != 1 ) { setEnabled(false); return; } setEnabled(true); synchronized(this) { switchListener(previousSelection, sel); previousSelection = sel; } super.selectionChanged(sel); }
Source:
public OpenShiftProjectUIModel(IProject project) { super(); resourceModel = new OpenShiftResourceUIModel(project); START System.out.println(this.hashCode()); END } yuck

Target:
public OpenShiftProjectUIModel(IProject project) { super(); resourceModel = new OpenShiftResourceUIModel(project); }
Source:
START public String[] getLines() { END return (String[]) lines.toArray(new String[lines.size()]); } Why an array? List<String> is just as fine

Target:
public synchronized List<String> getLines() { return new ArrayList<>(lines); }
Source:
public void run() { while (inScanner.hasNextLine() && !isCanceled()) { String line = inScanner.nextLine(); START lines.add(line); END } } 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().

Target:
public void run() { while (inScanner.hasNextLine() && !isCanceled()) { synchronized(this) { if( !isCanceled()) { lines.add(inScanner.nextLine()); } } } }
Source:
START private void mapBuildsToDeploymentConfigs(Collection<IBuild> builds) { END for (IBuild build : builds) { mapBuildToDeploymentConfig(build); } } or builds.forEach(b -> mapBuildToDeploymentConfig(b)), if you hate brackets

Target:
private void mapBuildsToDeploymentConfigs(Collection<IBuild> builds) { builds.forEach(build->mapBuildToDeploymentConfig(build)); }
Source:
private void mapBuildToDeploymentConfig(IBuild build) { String imageRef = imageRef(build, project); Collection<IDeploymentConfig> deploymentConfigs = imageRefToDeployConfigs.get(imageRef); START if(imageRefToDeployConfigs.containsKey(imageRef) && deploymentConfigs != null) { END for (IDeploymentConfig dc : deploymentConfigs) { createRelation(build, dc); } } } imageRefToDeployConfigs.containsKey(imageRef) is redundant here

Target:
private void mapBuildToDeploymentConfig(IBuild build) { String imageRef = imageRef(build, project); Collection<IDeploymentConfig> deploymentConfigs = imageRefToDeployConfigs.get(imageRef); if(deploymentConfigs != null) { deploymentConfigs.forEach(dc->createRelation(build, dc)); } }
Source:
START default Collation asc() { END return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); } 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).

Target:
default Ordering asc() { return Collation.of(Matchers.extract(this).path(), Ordering.Direction.ASCENDING); }
Source:
START public boolean useBindVariables() { END return true; } Can visibility remain `package-private` ?

Target:
boolean useBindVariables() { return true; }
Source:
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) { START if((state.getBlock() instanceof CropsBlock && ((CropsBlock) state.getBlock()).isMaxAge(state)) || state.getBlock() instanceof PumpkinBlock) END { CropsBlock.spawnDrops(state,worldIn,pos); } return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving); } So does this mean that pumpkins are easily duplicated?

Target:
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) { if((state.getBlock() instanceof CropsBlock && ((CropsBlock) state.getBlock()).isMaxAge(state))) { CropsBlock.spawnDrops(state,worldIn,pos); } return super.onBlockDestroyed(stack, worldIn, state, pos, entityLiving); }
Source:
START public ItemStack onItemUseFinish(ItemStack stack, World worldIn, LivingEntity entityLiving) { END 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); } 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?

Target:
public ItemStack onItemUseFinish(ItemStack stack, World worldIn, LivingEntity entityLiving) { if(entityLiving instanceof PlayerEntity && !entityLiving.world.isRemote) { Random rand = new Random(); int num = rand.nextInt(10); ItemStack crumbs = new ItemStack(MSItems.BREADCRUMBS, num); PlayerEntity entityplayer = (PlayerEntity)entityLiving; entityplayer.addItemStackToInventory(crumbs); } return super.onItemUseFinish(stack, worldIn, entityLiving); }
Source:
START public static void removeFile(String sourceFile) throws IOException { END 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."); } } nitpick: this class should have only one public method: upgradeStorageConfig

Target:
private 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."); } }
Source:
protected void setOrdinal(int ordinal, boolean forced) { START if (forced) { END this.ordinal = ordinal; } } 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?

Target:
protected void setOrdinal(int ordinal, boolean forced) { if (forced) { this.ordinal = ordinal; } else { setOrdinal(ordinal); } }
Source:
START public String placeLimitOrder(LimitOrder limitOrder) { END LgoPlaceOrder lgoOrder = LgoAdapters.adaptLimitOrder(limitOrder); return placeOrder(lgoOrder); } all generic method implementations should have error adaptation everything in this method should be surrounded by ``` try { // ... } catch (LgoException e) { throw LgoErrorAdapter.adapt(e); } ```

Target:
public String placeLimitOrder(LimitOrder limitOrder) throws IOException { LgoPlaceOrder lgoOrder = LgoAdapters.adaptLimitOrder(limitOrder); return placeOrder(lgoOrder); }
Source:
public static String adaptInstrumentName(CurrencyPair pair, Object[] args) { START String instrumentPostfix; END 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; } replace the try catch with: ``` if (args == null || args.length == 0) { throw new throw new ExchangeException("..."); } ```

Target:
public static String adaptInstrumentName(CurrencyPair pair, Object[] args) { if (args == null || args.length == 0) { throw new ExchangeException( "You need to provide a postfix for the instrument name in the first parameter of the array, ie: PERPETUAL, 28JUN19..."); } String instrumentPostfix = args[0].toString(); return pair.base.getSymbol() + "-" + instrumentPostfix; }
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; START } catch (BitfinexException e) { END throw BitfinexErrorAdapter.adapt(e); } } 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

Target:
public List<CurrencyPair> getExchangeSymbols() throws IOException { List<CurrencyPair> currencyPairs = new ArrayList<>(); for (String symbol : bitfinex.getSymbols()) { currencyPairs.add(BitfinexAdapters.adaptCurrencyPair(symbol)); } return currencyPairs; }
Source:
public void remoteInit() throws IOException, ExchangeException { try { exchangeMetaData = ((CoinbeneMarketDataService) marketDataService).getMetadata(); } catch (IOException e) { START throw new IOException("Retrieving MetaData for Coinbene failed", e); END } } remoteInit() throws IOException, so you don't have to catch it and rethrow it. Just take the try catch away completely.

Target:
public void remoteInit() throws IOException, ExchangeException { exchangeMetaData = ((CoinbeneMarketDataService) marketDataService).getMetadata(); }
Source:
public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { String result; START try { END result = withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); return result; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } } you still didn't apply my hint to all the other methods that use this try / catch

Target:
public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { try { return withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
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 { START order = cancelCoingiOrder(request); END } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } return order != null; } the try / catch CoingiException hit not applied

Target:
public boolean cancelOrder(String orderId) throws IOException { try { // if it doesn't return an error and CoingiOrder is returned, then the cancellation is // successful CoingiCancelOrderRequest request = new CoingiCancelOrderRequest(); request.setOrderId(orderId); return cancelCoingiOrder(request) != null; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
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; START getResult().setTs(ts); END } this is odd, these DTO object should represent the exchanges response and should not do any premature mapping nor have data coping logic

Target:
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); }
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(); START return LimitOrder.Builder.from(marketOrder).limitPrice(limitPrice).timestamp(new Date()).build(); END } `timestamp` should be null if there is none given by the server. This has been the standard convention in XChange since day one.

Target:
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).build(); }
Source:
public void testFindAllIDs() throws DataException { List<Integer> allIDs = ServiceManager.getProcessService().findAllIDs(); START System.out.println(allIDs); END 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))); } ```suggestion ```

Target:
public void testFindAllIDs() throws DataException { List<Integer> allIDs = ServiceManager.getProcessService().findAllIDs(); 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))); }
Source:
public List<Integer> findAllIDs() throws DataException { START List<Map<String, Object>> allDocuments = findAllDocuments(); List<Integer> allIds = new ArrayList<>(); for (Map<String, Object> document : allDocuments) { END allIds.add(Integer.parseInt((String) document.get("id"))); } return allIds; } ```suggestion List<Integer> allIds = new ArrayList<>(); for (Map<String, Object> document : findAllDocuments()) { ```

Target:
public List<Integer> findAllIDs() throws DataException { List<Integer> allIds = new ArrayList<>(); for (Map<String, Object> document : findAllDocuments()) { allIds.add(Integer.parseInt((String) document.get("id"))); } return allIds; }
Source:
START public void delete(ProcessDTO processDTO){ END try { ProcessForm processForm = new ProcessForm(); processForm.setProcess(ServiceManager.getProcessService().getById(processDTO.getId())); processForm.delete(); } catch (DAOException e) { Helper.setErrorMessage("errorOnSearch", searchQuery); } filteredList.remove(processDTO); } Missing white space between `)` and `{`.

Target:
public void delete(ProcessDTO processDTO) { try { ProcessForm processForm = new ProcessForm(); processForm.setProcess(ServiceManager.getProcessService().getById(processDTO.getId())); processForm.delete(); filteredList.remove(processDTO); } catch (DAOException e) { Helper.setErrorMessage("errorOnSearch", searchQuery); } }
Source:
public void setTaskStatusDown(Task task) { START setTaskStatusDown(Arrays.asList()); END } The parameter `task` is never used. Should it be passed to `setTaskStatusDown` here? ```suggestion setTaskStatusDown(Arrays.asList(task)); ```

Target:
public void setTaskStatusDown(Task task) { setTaskStatusDown(Arrays.asList(task)); }
Source:
public static List<BatchDTO> getNewspaperBatches() throws DataException, DAOException, IOException { START final BatchService batchService = ServiceManager.getBatchService(); END 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; } you have the batch service already as a class attribute

Target:
public static List<BatchDTO> getNewspaperBatches() throws DataException, DAOException, IOException { List<BatchDTO> newspaperBatches = new ArrayList<>(); for (BatchDTO batchTransfer : batchService.findAll()) { if (isNewspaperBatch(batchTransfer)) { newspaperBatches.add(batchTransfer); } } return newspaperBatches; }
Source:
public String convertTasksToWorkflow(String tasks) { currentTasks = tasks; PrimeFaces.current().executeScript("PF('confirmWorkflowPopup').show();"); START return this.stayOnCurrentPage; END } Since you always return `null` here, I would suggest to change to function to return type `void` and remove the return statement entirely.

Target:
public void convertTasksToWorkflow(String tasks) { currentTasks = tasks; PrimeFaces.current().executeScript("PF('confirmWorkflowPopup').show();"); }
Source:
public int getMultipleAssignmentsIndex(StructureTreeNode treeNode) { START if (Objects.nonNull(treeNode.getDataObject()) && treeNode.getDataObject() instanceof View END && Objects.nonNull(((View) treeNode.getDataObject()).getMediaUnit())) { return severalAssignments.indexOf(((View) treeNode.getDataObject()).getMediaUnit()); } return -1; } ```suggestion if (treeNode.getDataObject() instanceof View ``` instanceof already checks against null

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

Target:
public boolean isAssignedSeveralTimes() { if (Objects.nonNull(selectedLogicalNode) && selectedLogicalNode.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) selectedLogicalNode.getData(); if (structureTreeNode.getDataObject() instanceof View) { View view = (View) structureTreeNode.getDataObject(); return view.getMediaUnit().getIncludedStructuralElements().size() > 1; } } return false; }
Source:
public boolean isConcurrentTaskInWork() { START return this.currentTask.getId() < 0 || !getConcurrentTasksInWork().isEmpty(); END } Can id be smaller than 0?

Target:
public boolean isConcurrentTaskInWork() { return !getConcurrentTasksInWork().isEmpty(); }
Source:
public Date getDate() { if (Objects.isNull(date) && Objects.nonNull(getValue())) { try { date = new SimpleDateFormat("yyyy-mm-dd").parse(getValue()); } catch (ParseException e) { START logger.error(e.getLocalizedMessage()); END } } return date; } For error logger stack trace is already quiet wanted: ```suggestion logger.error(e.getLocalizedMessage(), e); ```

Target:
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(), e); } } return date; }
Source:
public List<TaskDTO> loadData(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) throws DataException { START String filter = ""; END try { filter = ServiceManager.getFilterService().parsePrimeFacesFilter(filters); } catch (IllegalArgumentException e) { logger.error(e.getMessage()); } return findByQuery(createUserTaskQuery(filter), getSortBuilder(sortField, sortOrder), first, pageSize, false); } `String filter = ServiceManager.getFilterService().parsePrimeFacesFilter(filters);`

Target:
public List<TaskDTO> loadData(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) throws DataException { String filter = ServiceManager.getFilterService().parsePrimeFacesFilter(filters); return findByQuery(createUserTaskQuery(filter), getSortBuilder(sortField, sortOrder), first, pageSize, false); }
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()); START metsXmlElementAccess.save(openWorkpiece.getWorkpiece(), out); END } } call method write

Target:
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()); write(openWorkpiece.getWorkpiece(), out); } }
Source:
START public CommentService() { END super(new CommentDAO()); } Constructor needs to be private

Target:
private CommentService() { super(new CommentDAO()); }
Source:
public static CommentService getInstance() { if (Objects.equals(instance, null)) { START synchronized (TaskService.class) { END if (Objects.equals(instance, null)) { instance = new CommentService(); } } } return instance; } Wrong class (TaskService?)

Target:
public static CommentService getInstance() { if (Objects.equals(instance, null)) { synchronized (CommentService.class) { if (Objects.equals(instance, null)) { instance = new CommentService(); } } } return instance; }
Source:
private DivType generatePhysicalStructMapRecursive(MediaUnit mediaUnit, Map<URI, FileType> mediaFilesToIDFiles, START Map<MediaUnit, String> mediaUnitIDs, MetsType mets) { END 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; } The generateFileSecRecursive is actually recursive, but where is the recursive part here?

Target:
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(generatePhysicalStructMapRecursive(child, mediaFilesToIDFiles, mediaUnitIDs, mets)); } return div; }
Source:
START public SearchResult search(String catalogId, String field, String term, int rows) { END loadOPACConfiguration(catalogId); HashMap<String, String> searchFields = new HashMap<>(); searchFields.put(field, term); return search(catalogId, searchFields, rows); } Regarding my question above... you just put the search field in a map and call the other method ;)

Target:
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); }
Source:
START public List<String> getAvailableSearchFields(String opac) throws IllegalArgumentException { END 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!"); } } No need to define "throws IllegalArgumentException" in function. It extends RuntimeException. `public List<String> getAvailableSearchFields(String opac) {`

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

Target:
public List<String> getAvailableCatalogs() { try { return OPACConfig.getCatalogs(); } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: no supported OPACs found in configuration file!"); } }
Source:
void initialize(BaseDAO baseDAO, List<? extends BaseBean> list) { if (Objects.nonNull(this.id) && !Hibernate.isInitialized(list)) { try { START Hibernate.initialize(list); END } catch (HibernateException e) { baseDAO.initialize(this, list); } } } use baseDAO.initialize as we discussed it

Target:
void initialize(BaseDAO baseDAO, List<? extends BaseBean> list) { if (Objects.nonNull(this.id) && !Hibernate.isInitialized(list)) { baseDAO.initialize(this, list); } }
Source:
START public FormRow(Optional<MetadataViewInterface> optionalKeyView, Collection<T> values) { END this.optionalKeyView = optionalKeyView; this.values = values; } Public constructor without JavaDoc.

Target:
FormRow(Optional<MetadataViewInterface> optionalKeyView, Collection<T> values) { this.optionalKeyView = optionalKeyView; this.values = values; }
Source:
START public void setYearBegin(MonthDay yearBegin) { END this.yearBegin = yearBegin; } Public method without JavaDoc.

Target:
void setYearBegin(MonthDay yearBegin) { this.yearBegin = yearBegin; }
Source:
public DeniedAccess(Map<URI, Collection<String>> conflicts) { START assert !conflicts.isEmpty() : "the conflict map should not be empty"; END this.conflicts = conflicts; } Don't use assertions.

Target:
public DeniedAccess(Map<URI, Collection<String>> conflicts) { if (conflicts.isEmpty()) { throw new IllegalArgumentException("the conflict map should not be empty"); } this.conflicts = conflicts; }
Source:
private void canClose(Collection<URI> uris) { String exceptionMessagePrefix = "The lock cannot be released because there are still streams flowing for the following URIs: "; START String exceptionMessage = uris.parallelStream().filter(uri -> streamManagement.isKnowingAnOpenStreamTo(uri)) END .map(uri -> uri.toString()).collect(Collectors.joining(", ", exceptionMessagePrefix, "")); if (exceptionMessage.length() > exceptionMessagePrefix.length()) { throw new IllegalStateException(exceptionMessage); } } Lambda can be replaced with method reference.

Target:
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(streamManagement::isKnowingAnOpenStreamTo) .map(uri -> uri.toString()).collect(Collectors.joining(", ", exceptionMessagePrefix, "")); if (exceptionMessage.length() > exceptionMessagePrefix.length()) { throw new IllegalStateException(exceptionMessage); } }
Source:
void close(String user, Map<URI, AbstractLock> locks) { synchronized (this) { canClose(locks.keySet()); START locks.entrySet().parallelStream().map(entry -> entry.getKey()) END .peek(uri -> removePermission(user, locks.get(uri), uri)) .forEach(uri -> immutableReadFileManagement.maybeRemoveReadFile(uri, user)); } } Lambda can be replaced with method reference.

Target:
void close(String user, Map<URI, AbstractLock> locks) { synchronized (this) { canClose(locks.keySet()); locks.entrySet().parallelStream().map(Entry::getKey) .peek(uri -> removePermission(user, locks.get(uri), uri)) .forEach(uri -> immutableReadFileManagement.maybeRemoveReadFile(uri, user)); } }
Source:
public ProcessEditPage editProcess() throws Exception { if (isNotAt()) { goTo(); } START clickButtonAndWaitForRedirect(editProcessLink, Pages.getProjectEditPage().getUrl()); END return Pages.getProcessEditPage(); } Edit process or project? ;-) Here you click the editProcess Link but you wait for redirect to editProject page.

Target:
public ProcessEditPage editProcess() throws Exception { if (isNotAt()) { goTo(); } clickButtonAndWaitForRedirect(editProcessLink, Pages.getProcessEditPage().getUrl()); return Pages.getProcessEditPage(); }
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)); START System.out.println(getCellDataByRow(row, columnIndex)); END } return data; } Please remove this debug helper ;)

Target:
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)); } return data; }
Source:
public List<String> getTemplateDetails() throws Exception { int index = triggerRowToggle(templatesTable, "First template"); START Thread.sleep(5000); END 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<>(); } 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.

Target:
public List<String> getTemplateDetails() { int index = triggerRowToggle(templatesTable, "First template"); WebElement detailsTable = Browser.getDriver() .findElement(By.id(TEMPLATE_TABLE + ":" + index + ":templateDetailTable")); //TODO: find way to read this table without excpetion... //List<String> details = getTableDataByColumn(detailsTable, 1); //details.addAll(getTableDataByColumn(detailsTable, 3)); return new ArrayList<>(); }
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(); START System.out.println(writer.writeSerializedToString(metsKitodoWrapper.getMets())); END Assert.assertEquals("Div elements from getter and directly from mets objects were not the same", rootDiv, rootDivFromMets); } Is this `System.out.println` call really needed? If not remove it or if this call is needed replace it by a logger call.

Target:
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(); Assert.assertEquals("Div elements from getter and directly from mets objects were not the same", rootDiv, rootDivFromMets); }
Source:
for (String regex : regexList) { START if (name.matches(regex)) { END fileOk = true; } } Missing JavaDoc for public method. Or move this code into its own class to get ride out of this inner class usage.

Target:
for (String regex : regexList) { if (name.matches(regex)) { return true; } }
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()); START Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); END return true; } return false; } 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("")) { .... } ```

Target:
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; }
Source:
private void getFlowingFlowNodes(FlowNode node) { Collection<SequenceFlow> sequenceFlow = node.getOutgoing(); START FlowNode flowNode = sequenceFlow.iterator().next().getTarget(); END if (flowNode instanceof Gateway) { getFlowingFlowNodesWithConditions((Gateway) flowNode); } else if (flowNode instanceof Task) { this.followingFlowNodes.add(flowNode); getFlowingFlowNodes(flowNode); } } Could not a NPE happen here if collection is empty / null ?

Target:
private void getFlowingFlowNodes(FlowNode node) { Collection<SequenceFlow> sequenceFlow = node.getOutgoing(); if (sequenceFlow.iterator().hasNext()) { FlowNode flowNode = sequenceFlow.iterator().next().getTarget(); if (flowNode instanceof Gateway) { getFlowingFlowNodesWithConditions((Gateway) flowNode); } else if (flowNode instanceof Task) { this.followingFlowNodes.add(flowNode); getFlowingFlowNodes(flowNode); } } }
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) { START throw new IOException(e.getMessage(), e); END } } Is this change here necessary? It is new IOException, not logger.

Target:
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 (RuntimeException e) { throw new IOException(e.getMessage(), e); } }
Source:
START List<JsonObject> findBySort(boolean closed, boolean active, String sort, Integer offset,Integer size) END throws DataException { BoolQueryBuilder query = new BoolQueryBuilder(); query.must(getQuerySortHelperStatus(closed)); query.must(getQueryProjectActive(active)); return searcher.findDocuments(query.toString(), sort, offset, size); } Missing space between `offset,Integer size`.

Target:
private 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); }