auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void sampleTest() throws IOException { InputStream sampleInputStream = getClass().getClassLoader().getResourceAsStream( "analysis/haskell/sample.hs"); ByteArrayOutputStream sampleOutputStream = new ByteArrayOutputStream(); Definitions defs = new Definitions(); defs.addTag(6, "x'y'", "functions", "x'y' = let f' = 1; g'h = 2 in f' + g'h", 0, 0); int actLOC; try { actLOC = writeHaskellXref(sampleInputStream, new PrintStream(sampleOutputStream), defs); } finally { sampleInputStream.close(); sampleOutputStream.close(); } InputStream expectedInputStream = getClass().getClassLoader().getResourceAsStream( "analysis/haskell/sampleXrefExpected.html"); ByteArrayOutputStream expectedOutputSteam = new ByteArrayOutputStream(); try { byte buffer[] = new byte[8192]; int numBytesRead; do { numBytesRead = expectedInputStream.read(buffer, 0, buffer.length); if (numBytesRead > 0) { expectedOutputSteam.write(buffer, 0, numBytesRead); } } while (numBytesRead >= 0); } finally { expectedInputStream.close(); expectedOutputSteam.close(); } <START> String actual[] = new String(sampleOutputStream.toByteArray(), "UTF-8"). <END> replaceAll("\\r", "").split("\n"); String expected[] = new String(expectedOutputSteam.toByteArray(), "UTF-8"). replaceAll("\\r", "").split("\n"); assertLinesEqual("Haskell sampleTest()", expected, actual); assertEquals("Haskell LOC", 3, actLOC); }</code><technical_language>split("\\r?\\n") suggested in <<LINK_0>></technical_language>

Target:
public void sampleTest() throws IOException { InputStream sampleInputStream = getClass().getClassLoader().getResourceAsStream( "analysis/haskell/sample.hs"); ByteArrayOutputStream sampleOutputStream = new ByteArrayOutputStream(); Definitions defs = new Definitions(); defs.addTag(6, "x'y'", "functions", "x'y' = let f' = 1; g'h = 2 in f' + g'h", 0, 0); int actLOC; try { actLOC = writeHaskellXref(sampleInputStream, new PrintStream(sampleOutputStream), defs); } finally { sampleInputStream.close(); sampleOutputStream.close(); } InputStream expectedInputStream = getClass().getClassLoader().getResourceAsStream( "analysis/haskell/sampleXrefExpected.html"); ByteArrayOutputStream expectedOutputSteam = new ByteArrayOutputStream(); try { byte buffer[] = new byte[8192]; int numBytesRead; do { numBytesRead = expectedInputStream.read(buffer, 0, buffer.length); if (numBytesRead > 0) { expectedOutputSteam.write(buffer, 0, numBytesRead); } } while (numBytesRead >= 0); } finally { expectedInputStream.close(); expectedOutputSteam.close(); } String actual[] = new String(sampleOutputStream.toByteArray(), "UTF-8").split("\\r?\\n"); String expected[] = new String(expectedOutputSteam.toByteArray(), "UTF-8").split("\\r?\\n"); assertLinesEqual("Haskell sampleTest()", expected, actual); assertEquals("Haskell LOC", 3, actLOC); }
Source:
<code>public void onEvent(RuntimeStatusEvent event) { if (event.isFailed()) { RuntimeState state = runtimes.remove(event.getIdentity().getWorkspaceId()); if (state != null) { <START> String workspaceId = state.runtime.getContext().getIdentity().getWorkspaceId(); <END> publishWorkspaceStatusEvent( workspaceId, STOPPED, RUNNING, "Error occurs on workspace runtime stop. Error: " + event.getError()); setAbnormalStopAttributes(workspaceId, event.getError()); } } }</code><technical_language>2 lines workspace ID is fetched too. move this assignment higher reuse result</technical_language>

Target:
public void onEvent(RuntimeStatusEvent event) { if (event.isFailed()) { String workspaceId = event.getIdentity().getWorkspaceId(); RuntimeState state = runtimes.remove(workspaceId); if (state != null) { publishWorkspaceStatusEvent( workspaceId, STOPPED, RUNNING, "Error occurs on workspace runtime stop. Error: " + event.getError()); setAbnormalStopAttributes(workspaceId, event.getError()); } } }
Source:
<code>private void writeToChannelVersionOne(WritableByteChannel channel) throws IOException { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); <START> return; <END> } }</code><technical_language>This addition is pointless</technical_language>

Target:
private void writeToChannelVersionOne(WritableByteChannel channel) throws IOException { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); } }
Source:
<code>public boolean equals(Object o) { boolean equals = false; if (ObjectUtils.isNotNull(o) && o instanceof CloudCheckrWrapper) { CloudCheckrWrapper otherWrapper = (CloudCheckrWrapper) o; <START> equals = total.equals(otherWrapper.total) && maximum.equals(otherWrapper.getMaximum()) <END> && minimum.equals(otherWrapper.getMinimum()) && average.equals(otherWrapper.getAverage()) && CollectionUtils.isEqualCollection(groupLevels, otherWrapper.getCostsByAccounts()) && CollectionUtils.isEqualCollection(groupingByTimes, otherWrapper.getGroupingByTimes()); } return equals; }</code><technical_language>this code check for null total, maximum, minimum, average Objects.equals for comparison fields</technical_language>

Target:
public boolean equals(Object o) { boolean equals = false; if (ObjectUtils.isNotNull(o) && o instanceof CloudCheckrWrapper) { CloudCheckrWrapper otherWrapper = (CloudCheckrWrapper) o; equals = CollectionUtils.isEqualCollection(costsByGroup, otherWrapper.getCostsByGroup()) && CollectionUtils.isEqualCollection(costsByTime, otherWrapper.getCostsByTime()) && Objects.equals(total, otherWrapper.getTotal()) && Objects.equals(maximum, otherWrapper.getMaximum()) && Objects.equals(minimum, otherWrapper.getMinimum()) && Objects.equals(average, otherWrapper.getAverage()); } return equals; }
Source:
<code><START> public static void setEnv(Map<String, String> newenv) throws Exception { <END> Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } }</code><technical_language>this method private, need static</technical_language>

Target:
private void setEnv(Map<String, String> newenv) throws Exception { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } }
Source:
<code>private List<FileInfo> listProfiles() { List<FileInfo> files = new ArrayList<>(); File[] profiles = profileDir.listFiles(); <START> if(profiles != null) { <END> for (File file : profileDir.listFiles()) { files.add(new FileInfo(file)); } Collections.sort(files, new Comparator<FileInfo>() { public int compare(FileInfo a, FileInfo b) { return -a.modified.compareTo(b.modified); } }); } return files; }</code><technical_language>Space if (</technical_language>

Target:
private List<FileInfo> listProfiles() { List<FileInfo> files = new ArrayList<>(); File[] profiles = profileDir.listFiles(); if (profiles != null) { for (File file : profiles) { files.add(new FileInfo(file)); } Collections.sort(files, new Comparator<FileInfo>() { public int compare(FileInfo a, FileInfo b) { return -a.modified.compareTo(b.modified); } }); } return files; }
Source:
<code>public List<SentMessage> getSentMessages(User user) throws DAOException { <START> List<SentMessage> sentMessages = sessionFactory.getCurrentSession().createCriteria(SentMessage.class).list(); <END> List<SentMessage> usersMessages = new ArrayList<>(); for (SentMessage sentMessage : sentMessages) { if (sentMessage.getSenderId().equals(user.getUserId())) usersMessages.add(sentMessage); } if (usersMessages.size() == 0) return null; return usersMessages; }</code><technical_language>do a criteria filters userId instead of fetching filter in code</technical_language>

Target:
public List<SentMessage> getSentMessages(User user) throws DAOException { return null; }
Source:
<code>private void assertRowKeysWithRegex(Table table, String[] rowRegEx, String rowPrefix, String[] rowKeys, int[] expected) throws IOException { FilterList filtersList = new FilterList(FilterList.Operator.MUST_PASS_ONE); for (String con : rowRegEx) { <START> filtersList.addFilter(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(con))); <END> } Scan scan = new Scan(); scan.setFilter(filtersList); try (ResultScanner scanner = table.getScanner(scan)) { Result[] results = scanner.next(10); for (int i = 0; i < results.length; i++) { Assert.assertArrayEquals(results[i].getRow(), Bytes.toBytes(rowPrefix + rowKeys[expected[i]])); } } }</code><technical_language>this new RegexStringComparator(rowPrefix + con)</technical_language>

Target:
private void assertRowKeysWithRegex(Table table, String[] rowRegEx, String rowPrefix, String[] rowKeys, int[] expected) throws IOException { FilterList filtersList = new FilterList(FilterList.Operator.MUST_PASS_ONE); for (String condition : rowRegEx) { filtersList.addFilter(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowPrefix + condition))); } Scan scan = new Scan(); scan.setFilter(filtersList); try (ResultScanner scanner = table.getScanner(scan)) { Result[] results = scanner.next(rowKeys.length); assertEquals(expected.length, results.length); for (int i = 0; i < results.length; i++) { Assert.assertArrayEquals(Bytes.toBytes(rowPrefix + rowKeys[expected[i]]), results[i].getRow()); } Assert.assertNull(scanner.next()); } }
Source:
<code>public ContentProviderClient provideDepictsContentProviderClient(Context context) { <START> return context.getContentResolver().acquireContentProviderClient("fr.free.nrw.commons.beta.depicts.contentprovider"); <END> }</code><technical_language>this based package name ? , getPackageName()+".depicts.contentprovider"</technical_language>

Target:
public ContentProviderClient provideDepictsContentProviderClient(Context context) { return context.getContentResolver().acquireContentProviderClient(BuildConfig.DEPICTION_AUTHORITY); }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { ConsoleHistoryLinesBuffer.HistorySnapShot history = fHistoryBuffer.getHistorySnapShot(); String[] buffLines = history.fHistoryLinesSnapShot; int start = 0; int end = buffLines.length <= HIST_BUFFER_WRITE_SIZE ? buffLines.length : HIST_BUFFER_WRITE_SIZE; StringBuilder sb = new StringBuilder(HIST_BUFFER_WRITE_SIZE); OutputStream terminalOutputStream = fTerminalControl.getRemoteToTerminalOutputStream(); while (start < buffLines.length) { String[] chunk = Arrays.copyOfRange(buffLines, start, end); for (String line : chunk) { sb.append(line); } start = end; int linesLeft = buffLines.length - end; end = start + (linesLeft <= HIST_BUFFER_WRITE_SIZE ? linesLeft : HIST_BUFFER_WRITE_SIZE); if (!(start < buffLines.length)) { sb.append(history.fHistoryRemainderSnapShot); } if (sb.length() > 0) { <START> if (terminalOutputStream != null) { <END> synchronized (terminalOutputStream) { try { terminalOutputStream.write(sb.toString().getBytes(), 0, sb.toString().getBytes().length); } catch (IOException e) { } } } sb.setLength(0); } } return Status.OK_STATUS; }</code><technical_language>check for null soon fetch terminalOutputStream. is need do this copying if write anything</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { OutputStream terminalOutputStream = fTerminalControl.getRemoteToTerminalOutputStream(); if (terminalOutputStream == null) { return Status.OK_STATUS; } ConsoleHistoryLinesBuffer.HistorySnapShot history = fHistoryBuffer.getHistorySnapShot(); String[] buffLines = history.fHistoryLinesSnapShot; int start = 0; int end = buffLines.length <= HIST_BUFFER_WRITE_SIZE ? buffLines.length : HIST_BUFFER_WRITE_SIZE; StringBuilder sb = new StringBuilder(HIST_BUFFER_WRITE_SIZE); while (start < buffLines.length) { String[] chunk = Arrays.copyOfRange(buffLines, start, end); for (String line : chunk) { sb.append(line); } start = end; int linesLeft = buffLines.length - end; end = start + (linesLeft <= HIST_BUFFER_WRITE_SIZE ? linesLeft : HIST_BUFFER_WRITE_SIZE); if (!(start < buffLines.length)) { sb.append(history.fHistoryRemainderSnapShot); } if (sb.length() > 0) { byte[] bytes = sb.toString().getBytes(); try { terminalOutputStream.write(bytes, 0, bytes.length); } catch (IOException e) { } sb.setLength(0); } } return Status.OK_STATUS; }
Source:
<code><START> public static OptimizeTableAnalyzedStatement createStatement(AnalyzedOptimizeTable optimizeTable, <END> CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate( txnCtx, functions, x, parameters, subQueryResults ); var genericProperties = optimizeTable.properties().map(eval); var settings = genericPropertiesToSettings(genericProperties, SUPPORTED_SETTINGS); validateSettings(settings, genericProperties); ArrayList<String> toOptimize = new ArrayList<>(); for (Map.Entry<Table<Symbol>, TableInfo> table : optimizeTable.tables().entrySet()) { var tableInfo = table.getValue(); var tableSymbol = table.getKey(); if (tableInfo instanceof BlobTableInfo) { toOptimize.add(((BlobTableInfo) tableInfo).concreteIndices()[0]); } else { var docTableInfo = (DocTableInfo) tableInfo; if (tableSymbol.partitionProperties().isEmpty()) { toOptimize.addAll(Arrays.asList(docTableInfo.concreteOpenIndices())); } else { var partitionName = toPartitionName( docTableInfo, Lists2.map(tableSymbol.partitionProperties(), x -> x.map(eval))); if (!docTableInfo.partitions().contains(partitionName)) { throw new PartitionUnknownException(partitionName); } toOptimize.add(partitionName.asIndexName()); } } } return new OptimizeTableAnalyzedStatement(toOptimize, settings); }</code><technical_language>I nicer if removed intermediate OptimizeTableAnalyzedStatement instead build request classes. WDYT</technical_language>

Target:
public static BoundedOptimizeTable createStatement(AnalyzedOptimizeTable optimizeTable, CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate( txnCtx, functions, x, parameters, subQueryResults ); var genericProperties = optimizeTable.properties().map(eval); var settings = genericPropertiesToSettings(genericProperties, SUPPORTED_SETTINGS); validateSettings(settings, genericProperties); ArrayList<String> toOptimize = new ArrayList<>(); for (Map.Entry<Table<Symbol>, TableInfo> table : optimizeTable.tables().entrySet()) { var tableInfo = table.getValue(); var tableSymbol = table.getKey(); if (tableInfo instanceof BlobTableInfo) { toOptimize.add(((BlobTableInfo) tableInfo).concreteIndices()[0]); } else { var docTableInfo = (DocTableInfo) tableInfo; if (tableSymbol.partitionProperties().isEmpty()) { toOptimize.addAll(Arrays.asList(docTableInfo.concreteOpenIndices())); } else { var partitionName = toPartitionName( docTableInfo, Lists2.map(tableSymbol.partitionProperties(), x -> x.map(eval))); if (!docTableInfo.partitions().contains(partitionName)) { throw new PartitionUnknownException(partitionName); } toOptimize.add(partitionName.asIndexName()); } } } return new BoundedOptimizeTable(toOptimize, settings); }
Source:
<code>private void fetchNodesLimit() { this.rm.getState(LoginModel.getInstance().getSessionId(), new AsyncCallback<String>() { public void onSuccess(String result) { JSONObject rmState = JSONParser.parseStrict(result).isObject(); <START> JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes"); <END> if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) { model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString())); } } public void onFailure(Throwable caught) { LogModel.getInstance().logMessage("Failed to access node limit through rmState: " + caught.getMessage()); } }); }</code><technical_language>check if rmState json is correct? if (rmState == null){ LogModel.getInstance().logMessage("Failed parse json rmState: " + rmstate); }else{ JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes"); if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) { model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString())); } }</technical_language>

Target:
private void fetchNodesLimit() { this.rm.getState(LoginModel.getInstance().getSessionId(), new AsyncCallback<String>() { public void onSuccess(String result) { JSONObject rmState = JSONParser.parseStrict(result).isObject(); if (rmState == null) { LogModel.getInstance().logMessage("Failed to parse json rmState: " + result); } else { JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes"); if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) { model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString())); } } } public void onFailure(Throwable caught) { LogModel.getInstance().logMessage("Failed to access node limit through rmState: " + caught.getMessage()); } }); }
Source:
<code><START> public void setExternalCard(ExternalCard externalCard) { <END> this.externalCard = externalCard; }</code><technical_language>return instance of Builder</technical_language>

Target:
public Builder setExternalCard(ExternalCard externalCard) { this.externalCard = externalCard; return this; }
Source:
<code>public void updateErrataDetailFormPanel(Erratum erratum) { <START> logger.info("updateErrataDetailFormPanel for " + erratum); END> buildErrataDetailPanel(); errataTitle.setText(erratum.getTitle()); FormBuilder formBuilder = new FormBuilder(errataDetailFormPanel, 1, 10); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.errataId(), new Span(erratum.getId()), 0, 0)); formBuilder.addFormItem(new FormItem(constants.errataDateIssued(), new Span(erratum.getIssued().toString()), 1, 0)); formBuilder.addFormItem(new FormItem(constants.errataType(), new Span(erratum.getType().toString()), 2, 0)); if (erratum.getSeverity() != null) { formBuilder.addFormItem(new FormItem(constants.errataSeverity(), new Span(erratum.getSeverity().toString()), 3, 0)); } formBuilder.addFormItem(new FormItem(constants.description(), new Span(erratum.getDescription().toString()), 4, 0)); formBuilder.addFormItem(new FormItem(constants.solution(), new Span(erratum.getSolution()), 5, 0)); formBuilder.addFormItem(new FormItem(constants.summary(), new Span(erratum.getSummary()), 6, 0)); formBuilder.addFormItem(new FormItem(constants.errataPackages(), new Span(StringUtils.join(erratum.getPackages(), ", ")), 7, 0)); }</code><technical_language>debug/trace/remove</technical_language>

Target:
public void updateErrataDetailFormPanel(Erratum erratum) { buildErrataDetailPanel(); errataTitle.setText(erratum.getTitle()); FormBuilder formBuilder = new FormBuilder(errataDetailFormPanel, 1, 10); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.errataId(), new Span(erratum.getId()), 0, 0)); formBuilder.addFormItem(new FormItem(constants.errataDateIssued(), new Span(erratum.getIssued().toString()), 1, 0)); formBuilder.addFormItem(new FormItem(constants.errataType(), new Span(erratum.getType().toString()), 2, 0)); if (erratum.getSeverity() != null) { formBuilder.addFormItem(new FormItem(constants.errataSeverity(), new Span(erratum.getSeverity().toString()), 3, 0)); } formBuilder.addFormItem(new FormItem(constants.description(), new Span(erratum.getDescription().toString()), 4, 0)); formBuilder.addFormItem(new FormItem(constants.solution(), new Span(erratum.getSolution()), 5, 0)); formBuilder.addFormItem(new FormItem(constants.summary(), new Span(erratum.getSummary()), 6, 0)); formBuilder.addFormItem(new FormItem(constants.errataPackages(), new Span(StringUtils.join(erratum.getPackages(), ", ")), 7, 0)); }
Source:
<code>private static Collection<TmfEventTableColumn> convertFromColumnData( org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData[] columnData) { <START> List<TmfEventTableColumn> list = new LinkedList<>(); <END> for (org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData col : columnData) { String header = col.header; if (header != null) { list.add(new TmfEventTableFieldColumn(header)); } } return list; }</code><technical_language>need for LinkedList</technical_language>

Target:
private static Collection<TmfEventTableColumn> convertFromColumnData( org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData[] columnData) { ImmutableList.Builder<TmfEventTableColumn> builder = new ImmutableList.Builder<>(); for (org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData col : columnData) { String header = col.header; if (header != null) { builder.add(new TmfEventTableFieldColumn(header)); } } return builder.build(); }
Source:
<code><START> public boolean isAtLeastAsRecentAs(final VCFHeaderVersion target) { <END> switch (target) { case VCF4_3: return this == VCF4_3; case VCF4_2: return this == VCF4_2 || this == VCF4_3; case VCF4_1: return this == VCF4_1 || this == VCF4_2 || this == VCF4_3; case VCF4_0: return this != VCF3_2 && this != VCF3_3; case VCF3_3: return this != VCF3_2; case VCF3_2: default: return true; } }</code><technical_language>I dumb, this method replaced a >= sign ordinal value</technical_language>

Target:
public boolean isAtLeastAsRecentAs(final VCFHeaderVersion target) { return this.ordinal() >= target.ordinal(); }
Source:
<code><START> T release() { <END> closeable = null; return closeable; }</code><technical_language>return type void</technical_language>

Target:
void release() { closeable = null; }
Source:
<code>private VaadinService getServiceWithResource(String content) throws ServiceException, IOException { MockDeploymentConfiguration configuration = new MockDeploymentConfiguration(); configuration.setProductionMode(true); VaadinService service = new MockVaadinServletService(configuration); service.init(); VaadinContext context = service.getContext(); Lookup lookup = Mockito.mock(Lookup.class); context.setAttribute(Lookup.class, lookup); ResourceProvider provider = Mockito.mock(ResourceProvider.class); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(provider); if (content != null) { <START> File tmpFile = tmpDir.newFile(); <END> try (FileOutputStream outputStream = new FileOutputStream( tmpFile)) { IOUtils.write(content, outputStream, StandardCharsets.UTF_8); } Mockito.when(provider.getApplicationResource(service, VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT)) .thenReturn(tmpFile.toURI().toURL()); } return service; }</code><technical_language>This mockable need temporary file returning a mock url for openStream() returns stream</technical_language>

Target:
private VaadinService getServiceWithResource(String content) throws ServiceException, IOException { MockDeploymentConfiguration configuration = new MockDeploymentConfiguration(); configuration.setProductionMode(true); VaadinService service = new MockVaadinServletService(configuration); VaadinContext context = service.getContext(); Lookup lookup = Mockito.mock(Lookup.class); context.setAttribute(Lookup.class, lookup); ResourceProvider provider = Mockito.mock(ResourceProvider.class); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(provider); if (content != null) { File tmpFile = tmpDir.newFile(); try (FileOutputStream outputStream = new FileOutputStream( tmpFile)) { IOUtils.write(content, outputStream, StandardCharsets.UTF_8); } Mockito.when(provider.getApplicationResource(service, VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT)) .thenReturn(tmpFile.toURI().toURL()); } return service; }
Source:
<code>protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result; try { <START> ReflectionUtil.getField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ); END> result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); } catch( NoSuchFieldException nfe ) { String objectId = FootprintsManager.getInstance().getObjectId( entity ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), objectId } ); } FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }</code><technical_language>code more elegant compact if ReflectionUtil a method "hasField" returns boolean. Throwing exception a direct logic for similar block of code (see "catch" blog) clean</technical_language>

Target:
protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result; if( ReflectionUtil.hasField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ) ) { result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); } else { String objectId = FootprintsManager.getInstance().getObjectId( entity ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), objectId } ); } FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }
Source:
<code>public void testDifferenceExport() { Collection<Mutation> mutations; mutations = new DiffExport(null, "a").toMutations("k1", 1); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k1", "a", 1))); mutations = new DiffExport("b", "b").toMutations("k2", 2); Assert.assertEquals(0, mutations.size()); mutations = new DiffExport("c", "d").toMutations("k3", 3); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k3", "d", 3))); mutations = new DiffExport("e", null).toMutations("k", 4); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makeDel("k", "e"))); <START> } <END></code><technical_language>need test case generates a put a delete</technical_language>

Target:
public void testDifferenceExport() { Collection<Mutation> mutations; mutations = new DiffExport(Optional.empty(), Optional.of("a")).toMutations("k1", 1); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k1", "a", 1))); mutations = new DiffExport(Optional.of("ab"), Optional.of("ab")).toMutations("k2", 2); Assert.assertEquals(0, mutations.size()); mutations = new DiffExport(Optional.of("b"), Optional.of("ab")).toMutations("k2", 2); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k2", "a", 2))); mutations = new DiffExport(Optional.of("c"), Optional.of("d")).toMutations("k3", 3); Assert.assertEquals(1, mutations.size()); Mutation m = makeDel("k3", "c", 3); addPut(m, "k3", "d", 3); Assert.assertTrue(mutations.contains(m)); mutations = new DiffExport(Optional.of("e"), Optional.empty()).toMutations("k4", 4); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makeDel("k4", "e", 4))); mutations = new DiffExport(Optional.of("ef"), Optional.of("fg")).toMutations("k5", 5); Assert.assertEquals(1, mutations.size()); m = makeDel("k5", "e", 5); addPut(m, "k5", "g", 5); Assert.assertTrue(mutations.contains(m)); }
Source:
<code>protected void checkNewDefaultBrowser(Object browser) { TableItem[] children = tableViewer.getTable().getItems(); for (TableItem element : children) { <START> TableItem item = element; <END> if (!(item.getData().equals(browser))) item.setChecked(false); } }</code><technical_language>unnecessary</technical_language>

Target:
protected void checkNewDefaultBrowser(Object browser) { for (TableItem item : tableViewer.getTable().getItems()) { if (!(item.getData().equals(browser))) item.setChecked(false); } }
Source:
<code>private void throwAmbiguousMethodsException(List<ScoreMethodAndExtractPathVars> methods) { WebRequest request = getCurrentWebRequest(); String methodsNames = ""; for (ScoreMethodAndExtractPathVars method : methods) { if (!methodsNames.isEmpty()) methodsNames += ", "; MethodMappingInfo urlMappingInfo = method.getMethodInfo(); <START> methodsNames += urlMappingInfo.getMethod().getReturnType().getSimpleName() + " " + <END> urlMappingInfo.getMethod().getDeclaringClass().getSimpleName() + "." + urlMappingInfo.getMethod().getName(); } throw new WicketRuntimeException("Ambiguous methods mapped for the current request: URL '" + request.getClientUrl() + "', HTTP method " + HttpUtils.getHttpMethod(request) + ". " + "Mapped methods: " + methodsNames); }</code><technical_language>worth StringBuilder in this method</technical_language>

Target:
private void throwAmbiguousMethodsException(List<ScoreMethodAndExtractPathVars> methods) { WebRequest request = getCurrentWebRequest(); StringBuilder methodsNames = new StringBuilder(); for (ScoreMethodAndExtractPathVars method : methods) { if (methodsNames.length() != 0) methodsNames.append(", "); MethodMappingInfo urlMappingInfo = method.getMethodInfo(); methodsNames.append(urlMappingInfo.getMethod().getReturnType().getSimpleName()); methodsNames.append(" "); methodsNames.append(urlMappingInfo.getMethod().getDeclaringClass().getSimpleName()); methodsNames.append("."); methodsNames.append(urlMappingInfo.getMethod().getName()); } throw new WicketRuntimeException("Ambiguous methods mapped for the current request: URL '" + request.getClientUrl() + "', HTTP method " + HttpUtils.getHttpMethod(request) + ". " + "Mapped methods: " + methodsNames); }
Source:
<code><START> public void setBuildDiscarder(BuildDiscarder bd) throws IOException { <END> BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } }</code><technical_language>new method implementation synchronized</technical_language>

Target:
public synchronized void setBuildDiscarder(BuildDiscarder bd) throws IOException { BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } }
Source:
<code>public void onUpdateWeatherReturn(CallbackInfo ci) { Weather weather = getWeather(); <START> if (this.prevWeather != weather) { <END> int duration = (int) getRemainingDuration(); ChangeWorldWeatherEvent event = SpongeEventFactory.createChangeWorldWeatherEvent(Sponge.getGame(), Cause.of((World) this), duration, duration, weather, weather, this.prevWeather, this); Sponge.getGame().getEventManager().post(event); if (event.isCancelled()) { this.forecast(this.prevWeather); } else { this.forecast(event.getWeather(), event.getDuration()); this.prevWeather = event.getWeather(); } } }</code><technical_language>prevWeather null here- necessary update API initialWeather anOptional</technical_language>

Target:
public void onUpdateWeatherReturn(CallbackInfo ci) { Weather weather = getWeather(); int duration = (int) getRemainingDuration(); if (this.prevWeather != weather && duration > 0) { ChangeWorldWeatherEvent event = SpongeEventFactory.createChangeWorldWeatherEvent(Cause.of(NamedCause.source(this)), duration, duration, weather, weather, this.prevWeather, this); SpongeImpl.postEvent(event); if (event.isCancelled()) { this.forecast(this.prevWeather); } else { this.forecast(event.getWeather(), event.getDuration()); this.prevWeather = event.getWeather(); this.weatherStartTime = this.worldInfo.getWorldTotalTime(); } } }
Source:
<code><START> public void setWriteDelays(Integer minWriteDelay, Integer maxWriteDelay) { <END> minWriteDelay = minWriteDelay != null ? minWriteDelay : 0; maxWriteDelay = maxWriteDelay != null ? maxWriteDelay : 1; if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less then 0."); } if (maxWriteDelay < 1) { throw new IllegalArgumentException("Maximum write delay seconds cannot be less then 1."); } if (maxWriteDelay < minWriteDelay) { throw new IllegalArgumentException( format("Maximum write delay (%d seconds) must be equal or greater than minimum write delay (%d seconds)", maxWriteDelay, minWriteDelay)); } this.minWriteDelay = minWriteDelay; this.maxWriteDelay = maxWriteDelay; }</code><technical_language>Eliminating default get rid of nasty null contract too</technical_language>

Target:
public void setWriteDelays(Integer minWriteDelay, Integer maxWriteDelay) { minWriteDelay = minWriteDelay != null ? minWriteDelay : 0; maxWriteDelay = maxWriteDelay != null ? maxWriteDelay : 1; if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less than 0."); } if (maxWriteDelay < 1) { throw new IllegalArgumentException("Maximum write delay seconds cannot be less than 1."); } if (maxWriteDelay < minWriteDelay) { throw new IllegalArgumentException( format("Maximum write delay (%d seconds) must be equal or greater than minimum write delay (%d seconds)", maxWriteDelay, minWriteDelay)); } this.minWriteDelay = minWriteDelay; this.maxWriteDelay = maxWriteDelay; }
Source:
<code>public static <K, V> Predicate<EventJournalCacheEvent<K, V>> cachePutEvents() { <START> return new CachePutEventsPredicate<>(); <END> }</code><technical_language>Missing types</technical_language>

Target:
public static <K, V> Predicate<EventJournalCacheEvent<K, V>> cachePutEvents() { return new CachePutEventsPredicate<K, V>(); }
Source:
<code>public TagPropertySource(Repository repo, Ref ref) { this.ref = ref; <START> RevWalk refWalk = new RevWalk(repo); try { <END> RevObject any = refWalk.parseAny(repo.resolve(ref.getName())); if (any instanceof RevTag) { tag = (RevTag) any; } } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } finally { refWalk.close(); } }</code><technical_language>try-with-resource, RevWalk is AutoCloseable</technical_language>

Target:
public TagPropertySource(Repository repo, Ref ref) { this.ref = ref; try (RevWalk refWalk = new RevWalk(repo)) { ObjectId objectId = repo.resolve(ref.getName()); RevObject any = refWalk.parseAny(objectId); RevObject peeledObject = refWalk.peel(any); if (any instanceof RevTag) { tag = (RevTag) any; } if (peeledObject instanceof RevCommit) { commit = (RevCommit) peeledObject; } } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } }
Source:
<code>private PrintWriter getWriter(OutputStream os) { if (os instanceof WrapperOutputStream) { OutputStream out = ((WrapperOutputStream) os).getRecursivelyUnderlyingStream(); if (out instanceof FilteredOutputStream) { <START> FilteredOutputStream filteredStream = (FilteredOutputStream) out; <END> return new PrintWriter(new IgnoreCloseWriter(filteredStream.asWriter())); } } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))); }</code><technical_language>This is broken again. a new OutputStreamSelector is created for Content, this method is called OutputStreamSelector#getUnderlyingStream returns null bytes. want force text stream in this case, cleanest approach be</technical_language>

Target:
private PrintWriter getWriter(OutputStream os) throws IOException { if (os instanceof WrapperOutputStream) { OutputStream out = ((WrapperOutputStream) os).unwrapRecursively(); if (out instanceof FilteredOutputStream) { FilteredOutputStream filteredStream = (FilteredOutputStream) out; return new PrintWriter(new IgnoreCloseWriter(filteredStream.asWriter())); } } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))); }
Source:
<code>Task<Void> saveAsync(final String sessionToken, final Task<Void> toAwait) { return super.saveAsync(sessionToken, toAwait).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { if(task.getError() != null && task.getError() instanceof ParseException && ((ParseException) task.getError()).getCode() == ParseException.OBJECT_NOT_FOUND) { synchronized (mutex) { setObjectId(null); markAllFieldsDirty(); <START> return ParseInstallation.super.saveAsync(sessionToken, toAwait); <END> } } return task; } }); }</code><technical_language>is easy null out objectId() a failure multiple install id's app</technical_language>

Target:
Task<Void> saveAsync(final String sessionToken, final Task<Void> toAwait) { return super.saveAsync(sessionToken, toAwait).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { if (task.getError() != null && task.getError() instanceof ParseException) { int errCode = ((ParseException) task.getError()).getCode(); if (errCode == ParseException.OBJECT_NOT_FOUND || (errCode == ParseException.MISSING_REQUIRED_FIELD_ERROR && getObjectId() == null)) { synchronized (mutex) { setState(new State.Builder(getState()).objectId(null).build()); markAllFieldsDirty(); return ParseInstallation.super.saveAsync(sessionToken, toAwait); } } } return task; } }); }
Source:
<code>public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); <START> final MethodReference currentMethod = methodReferences.peek(); <END> if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }</code><technical_language>remove final modifier</technical_language>

Target:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); MethodReference currentMethod = methodReferences.peek(); if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }
Source:
<code>public void run() { Set<UUID> onlineIds = new HashSet<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } <START> this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); <END> }</code><technical_language>build immutable set if copy anyways</technical_language>

Target:
public void run() { List<UUID> onlineIds = new ArrayList<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); }
Source:
<code>public TmfModelResponse<OutputStyleModel> fetchStyle(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { for (P dataProvider : getProviders()) { if (dataProvider instanceof IOutputStyleProvider) { TmfModelResponse<OutputStyleModel> response = ((IOutputStyleProvider) dataProvider).fetchStyle(fetchParameters, monitor); OutputStyleModel model = response.getModel(); <START> if (model != null) { return response; } <END> } } return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }</code><technical_language>returning style model data provider provides styles. combine styles data provider styles</technical_language>

Target:
public TmfModelResponse<OutputStyleModel> fetchStyle(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { Map<String, OutputElementStyle> styles = new HashMap<>(); for (P dataProvider : getProviders()) { if (dataProvider instanceof IOutputStyleProvider) { TmfModelResponse<OutputStyleModel> response = ((IOutputStyleProvider) dataProvider).fetchStyle(fetchParameters, monitor); OutputStyleModel model = response.getModel(); if (model != null) { styles.putAll(model.getStyles()); } } } if (styles.isEmpty()) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } return new TmfModelResponse<>(new OutputStyleModel(styles), ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
<code>private synchronized static DataPublisher initDataPublisher(){ <START> if (publisher == null){ <END> try { loadConfigs(); publisher = new DataPublisher(null,receiverUrl, authUrl, username, password); if (log.isDebugEnabled()) { log.debug("Connected to analytics sever with the following details, " + " ReceiverURL:" + receiverUrl + ", AuthURL:" + authUrl + ", Username:" + username); } } catch (DataEndpointAgentConfigurationException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointConfigurationException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointAuthenticationException e) { log.error("Error while creating databridge publisher", e); } catch (TransportException e) { log.error("Error while creating databridge publisher", e); } } return publisher; }</code><technical_language>some formatting issues prior '{' correct in places</technical_language>

Target:
private synchronized static void initDataPublisher() { if (publisher == null) { try { loadConfigs(); publisher = new DataPublisher(null, receiverUrl, authUrl, username, password); if (log.isDebugEnabled()) { log.debug("Connected to analytics sever with the following details, " + " ReceiverURL:" + receiverUrl + ", AuthURL:" + authUrl + ", Username:" + username); } } catch (DataEndpointAgentConfigurationException | DataEndpointConfigurationException | DataEndpointException | DataEndpointAuthenticationException | TransportException e) { log.error("Error while creating databridge publisher", e); } } }
Source:
<code>public void process(JSONRequestContext requestContext) { StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO(); PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO(); <START> Long personId = NumberUtils.createLong(requestContext.getRequest().getParameter("personId")); <END> Person person = personDAO.findById(personId); String personOid = requestContext.getString("personOid"); personVariableDAO.setPersonVariable(person, KoskiConsts.VariableNames.KOSKI_HENKILO_OID, StringUtils.trim(personOid)); Integer personVariableCount = requestContext.getInteger("studentKoskiIDsTable.rowCount"); if (personVariableCount != null) { for (int i = 0; i < personVariableCount; i++) { String colPrefix = "studentKoskiIDsTable." + i; String linkedOid = requestContext.getString(colPrefix + ".linkedOid"); Long studentId = requestContext.getLong(colPrefix + ".studentId"); Student student = studentDAO.findById(studentId); if (person.getId().equals(student.getPerson().getId())) { userVariableDAO.setUserVariable(student, KoskiConsts.VariableNames.KOSKI_LINKED_STUDYPERMISSION_ID, StringUtils.trim(linkedOid)); } } } }</code><technical_language>requestContext.getLong("personId") do trick</technical_language>

Target:
public void process(JSONRequestContext requestContext) { StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO(); PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO(); Long personId = requestContext.getLong("personId"); Person person = personDAO.findById(personId); String personOid = requestContext.getString("personOid"); personVariableDAO.setPersonVariable(person, KoskiConsts.VariableNames.KOSKI_HENKILO_OID, StringUtils.trim(personOid)); Integer personVariableCount = requestContext.getInteger("studentKoskiIDsTable.rowCount"); if (personVariableCount != null) { for (int i = 0; i < personVariableCount; i++) { String colPrefix = "studentKoskiIDsTable." + i; String linkedOid = requestContext.getString(colPrefix + ".linkedOid"); Long studentId = requestContext.getLong(colPrefix + ".studentId"); Student student = studentDAO.findById(studentId); if (person.getId().equals(student.getPerson().getId())) { userVariableDAO.setUserVariable(student, KoskiConsts.VariableNames.KOSKI_LINKED_STUDYPERMISSION_ID, StringUtils.trim(linkedOid)); } } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); <START> sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); <END> }</code><technical_language>Inline occurrences</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); }
Source:
<code><START> public void accept(String json, Context context) { <END> logger.info("Function triggered by event: " + json); }</code><technical_language>nit: show user parse JSON</technical_language>

Target:
public void accept(String json, Context context) { JsonObject body = gsonParser.fromJson(json, JsonObject.class); LOGGER.info("Function triggered by event: " + json); }
Source:
<code>void groupElementWithItsParent(final List<DataTypeListItem> groupedElements, final List<DataTypeListItem> allElements, final DataTypeListItem item) { if (groupedElements.contains(item)) { return; } final String parentElementId = item.getDragAndDropElement().getAttribute(PARENT_UUID_ATTR); if (!StringUtils.isEmpty(parentElementId)) { final Optional<DataTypeListItem> parentElement = allElements.stream() .filter(element -> Objects.equals(element.getDragAndDropElement().getAttribute(UUID_ATTR), parentElementId)) .findFirst(); if (!isParentElementOnList(groupedElements, parentElementId)) { parentElement.ifPresent(p -> groupElementWithItsParent(groupedElements, allElements, p)); groupedElements.add(item); } else { <START> int index = getIndexOfParentOrLastElementInGroup(groupedElements, parentElement.get()); <END> groupedElements.add(index, item); } } else { groupedElements.add(item); } }</code><technical_language>Sonar a good point this block. consider:- parentElement.isPresent(p -> { int index = getIndexOfParentOrLastElementInGroup(groupedElements, p); groupedElements.add(index, item); }</technical_language>

Target:
void groupElementWithItsParent(final List<DataTypeListItem> groupedElements, final List<DataTypeListItem> allElements, final DataTypeListItem item) { if (groupedElements.contains(item)) { return; } final String parentElementId = item.getDragAndDropElement().getAttribute(PARENT_UUID_ATTR); if (!StringUtils.isEmpty(parentElementId)) { final Optional<DataTypeListItem> parentElement = allElements.stream() .filter(element -> Objects.equals(element.getDragAndDropElement().getAttribute(UUID_ATTR), parentElementId)) .findFirst(); parentElement.ifPresent(parent -> { if (!isParentElementOnList(groupedElements, parentElementId)) { groupElementWithItsParent(groupedElements, allElements, parent); groupedElements.add(item); } else { final int index = getIndexOfParentOrLastElementInGroup(groupedElements, parent) + 1; if (index == groupedElements.size()) { groupedElements.add(item); } else { groupedElements.add(index, item); } } }); } else { groupedElements.add(item); } }