auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testUnsupportedFs() throws Exception { FileSystem mockFs = Mockito.mock(FileSystem.class); Mockito.doThrow( new UnsupportedOperationException("Mock unsupported exception.")) .when(mockFs).concat(any(Path.class), any(Path[].class)); Mockito.doAnswer(invocationOnMock -> new URI("mockfs:/ .getUri(); Concat.setTstFs(mockFs); PrintStream oldErr = System.err; final ByteArrayOutputStream err = new ByteArrayOutputStream(); System.setErr(new PrintStream(err)); shellRun(1, "-concat", dstPath.toString(), testRootDir + "/file-*"); System.setErr(oldErr); System.err.print(err.toString()); <START> assertTrue(err.toString() <END> .contains("Dest filesystem 'mockfs' doesn't support concat")); }</code><technical_language>Prefer Assertions.assertThat for new tests, generate a meaningful error message</technical_language>

Target:
public void testUnsupportedFs() throws Exception { FileSystem mockFs = Mockito.mock(FileSystem.class); Mockito.doThrow( new UnsupportedOperationException("Mock unsupported exception.")) .when(mockFs).concat(any(Path.class), any(Path[].class)); Mockito.doAnswer(invocationOnMock -> new URI("mockfs:/ .getUri(); Concat.setTestFs(mockFs); final ByteArrayOutputStream err = new ByteArrayOutputStream(); PrintStream oldErr = System.err; System.setErr(new PrintStream(err)); try { shellRun(1, "-concat", dstPath.toString(), testRootDir + "/file-*"); } finally { System.setErr(oldErr); } System.err.print(err.toString()); String expectedErrMsg = "Dest filesystem 'mockfs' doesn't support concat"; Assertions.assertThat(err.toString().contains(expectedErrMsg)) .withFailMessage("The err message should contain \"" + expectedErrMsg + "\" message.").isTrue(); }
Source:
<code>public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!(sender instanceof GlowPlayer)) { return innerExecute(sender, commandLabel, args); } localeChangeLock.lock(); try { Locale locale = Locale.forLanguageTag(((GlowPlayer) sender).getLocale()); if (locale.equals(lastLoadedLocale)) { return innerExecute(sender, commandLabel, args); } <START> lastLoadedLocale = locale; <END> String oldDescription = getDescription(); String oldUsage = getUsage(); String oldPermissionMessage = getPermissionMessage(); ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_BASE_NAME, locale); description = bundle.getString(getName() + DESCRIPTION_SUFFIX); usageMessage = bundle.getString(getName() + USAGE_SUFFIX); super.setPermissionMessage(bundle.getString(getName() + PERMISSION_SUFFIX)); try { return innerExecute(sender, commandLabel, args); } finally { description = oldDescription; usageMessage = oldUsage; super.setPermissionMessage(oldPermissionMessage); } } finally { localeChangeLock.unlock(); } }</code><technical_language>loaded locale is set sender's locale if equal current locale, command is executed, permission message, description usage is reverted locale, while loaded locale is set sender's locale</technical_language>

Target:
public boolean execute(CommandSender sender, String commandLabel, String[] args) { CommandMessages localizedMessages = null; if (sender instanceof GlowPlayer) { try { localizedMessages = bundleToMessageCache.get( STRING_TO_BUNDLE_CACHE.get(((GlowPlayer) sender).getLocale())); } catch (ExecutionException e) { ConsoleMessages.Warn.Command.L10N_FAILED.log(e, getName(), sender); } } if (localizedMessages == null) { localizedMessages = new CommandMessages(getDescription(), getUsage(), getPermissionMessage()); } return execute(sender, commandLabel, args, localizedMessages); }
Source:
<code>public MatrixBuild getMatrixBuild() <START> { <END> if( parent == null ) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }</code><technical_language>Please, respect surrounding code style (() {)</technical_language>

Target:
public MatrixBuild getMatrixBuild() { if (parent == null && parentId != null) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }
Source:
<code>private void trackNewServerEvent(int succesful) { UsageEventType eventType = JBossServerUIPlugin.getDefault().getNewServerEventType(); <START> UsageReporter.getInstance().trackEvent(eventType.event(newRuntimeWorkingCopy.getId(), succesful)); <END> }</code><technical_language>getId returns runtime user defined label afaik. issues that: 1) servers a runtime 2) users labels give a view server... wtp server id instead + if detected version. @robstryker find</technical_language>

Target:
private void trackNewServerEvent(int succesful) { IServerAttributes server = (IServerAttributes)getTaskModel().getObject(TaskModel.TASK_SERVER); String serverType = server.getServerType().getId(); UsageEventType eventType = JBossServerUIPlugin.getDefault().getNewServerEventType(); UsageReporter.getInstance().trackEvent(eventType.event(serverType, succesful)); }
Source:
<code>public byte[] getImageContent(String location, String name) { org.kie.api.definition.process.Process process = kieContainer.getKieBase(kieBaseName).getProcess(name); if (process != null) { String sourcePath = process.getResource().getSourcePath(); if (sourcePath != null) { String processDirectory = ""; <START> if (sourcePath != null && sourcePath.indexOf("/") != -1) { <END> processDirectory = sourcePath.substring(0, sourcePath.lastIndexOf("/") + 1); } byte[] data = seek(processDirectory, name, kieModule); if (data != null) { return data; } location = processDirectory; } } byte[] data = seek(location, name, kieModule); if (data == null && kieModule.getKieDependencies() != null) { for (InternalKieModule depKieModule : kieModule.getKieDependencies().values()) { data = seek(location, name, depKieModule); if (data != null) { break; } } } return data; }</code><technical_language>need for null check, is done in previous if statement</technical_language>

Target:
public byte[] getImageContent(String location, String name) { org.kie.api.definition.process.Process process = kieContainer.getKieBase(kieBaseName).getProcess(name); if (process != null) { String sourcePath = process.getResource().getSourcePath(); if (sourcePath != null) { String processDirectory = ""; if (sourcePath.indexOf("/") != -1) { processDirectory = sourcePath.substring(0, sourcePath.lastIndexOf("/") + 1); } byte[] data = seek(processDirectory, name, kieModule); if (data != null) { return data; } location = processDirectory; } } byte[] data = seek(location, name, kieModule); if (data == null && kieModule.getKieDependencies() != null) { for (InternalKieModule depKieModule : kieModule.getKieDependencies().values()) { data = seek(location, name, depKieModule); if (data != null) { break; } } } return data; }
Source:
<code><START> private boolean matchId(CsvRow row, String id) { <END> String scheme = row.findValue(ID_SCHEME_HEADER).orElse(DEFAULT_SCHEME); String rowId = row.findValue(ID_HEADER).map(str -> StandardId.of(scheme, str).toString()).orElse(""); return id.equals(rowId); }</code><technical_language>static</technical_language>

Target:
private static boolean matchId(CsvRow row, String id) { String scheme = row.findValue(ID_SCHEME_HEADER).orElse(DEFAULT_SCHEME); String rowId = row.findValue(ID_HEADER).map(str -> StandardId.of(scheme, str).toString()).orElse(""); return id.equals(rowId); }
Source:
<code>protected boolean canDoAction() { String user = getParameters().getLoginName(); if (StringUtils.isEmpty(user)) { ExtMap authRecord = (ExtMap) getParameters().getAuthRecord(); if (authRecord != null) { user = authRecord.get(AuthRecord.PRINCIPAL); } } String profile = getParameters().getProfileName(); if (StringUtils.isEmpty(profile)) { <START> profile = "UNKNOWN"; <END> } setUserName(String.format("%s@%s", user, profile)); boolean result = isUserCanBeAuthenticated(); if (! result) { logAutheticationFailure(); } return result; }</code><technical_language>Hmm, UKNOWN N/A, in other place perform String.format profile is unavailable N/A? please consistent</technical_language>

Target:
protected boolean canDoAction() { String user = getParameters().getLoginName(); if (StringUtils.isEmpty(user)) { ExtMap authRecord = (ExtMap) getParameters().getAuthRecord(); if (authRecord != null) { user = authRecord.get(AuthRecord.PRINCIPAL); } } String profile = getParameters().getProfileName(); if (StringUtils.isEmpty(profile)) { profile = "N/A"; } setUserName(String.format("%s@%s", user, profile)); boolean result = isUserCanBeAuthenticated(); if (! result) { logAutheticationFailure(); } return result; }
Source:
<code>public void setRefreshInterval(final long refreshInterval) { <START> REFRESH_INTERVAL_IN_SECONDS = refreshInterval; <END> }</code><technical_language>if is constant, please convert case</technical_language>

Target:
public void setRefreshInterval(final long refreshInterval) { this.refreshInterval = refreshInterval; }
Source:
<code>public void selectContainer( FormModelCreationContainer container ) { <START> Assert.notNull( "Manager cannot be null", container ); <END> if ( currentManager != null ) { currentManager.hideCreationView(); } currentManager = container; currentManager.showCreationView(); }</code><technical_language>If land of KIE tend PortablePreconditions (in Uberfire) Errai's Assert used. I guess convention standard.. big deal</technical_language>

Target:
public void selectContainer( FormModelCreationContainer container ) { PortablePreconditions.checkNotNull( "container", container ); if ( currentManager != null ) { currentManager.hideCreationView(); } currentManager = container; currentManager.showCreationView(); }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IProject project = null; IEditorPart editorPart = window.getActivePage().getActiveEditor(); if (editorPart != null) { IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput(); IFile file = input.getFile(); project = file.getProject(); } else { if (window != null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { project = ((IAdaptable) first).getAdapter(IProject.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { project = ((IAdaptable) firstElement).getAdapter(IProject.class); } } } } if (project != null) { <START> if (project.getFile("/gulpfile.js").exists()) { <END> return true; } } return false; }</code><technical_language>gulpfile.js is necessarily located in root of project. In order fix tester need call: WorkbenchResourceUtil.findFileRecursively(project, "gulpfile.js"); This work correctly performance overhead. IMHO, simply enable "Run Gulp Task" default project testers. WDYT</technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IContainer container = null; if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IWorkbenchPart part = page.getActivePart(); if (part != null) { IFile activeEditorFile = getEditorFile(part); if (activeEditorFile != null) { if (RunGulpTaskCommand.GULP_FILE_NAME.equals(activeEditorFile.getName())) { return true; } else { container = activeEditorFile.getProject(); } } } if (container == null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; Object element = treeSelection.getFirstElement(); if (element != null) { element.toString(); if (element instanceof IFile && RunGulpTaskCommand.GULP_FILE_NAME.equals(((IFile) element).getName())) { return true; } else if (element instanceof ITask) { return true; } } TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { container = ((IAdaptable) first).getAdapter(IContainer.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { container = ((IAdaptable) firstElement).getAdapter(IContainer.class); } } } } } if (container != null) { try { IFile file = WorkbenchResourceUtil.findFileRecursively(container, RunGulpTaskCommand.GULP_FILE_NAME); return file != null && file.exists(); } catch (CoreException ex) { } } return false; }
Source:
<code>protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("SVN Tab"); <START> toolbar.addLeftWidget(diffButton_ = commands_.vcsDiff().createToolbarButton()); <END> toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsAddFiles().createToolbarButton()); toolbar.addLeftWidget(commands_.vcsRemoveFiles().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsCommit().createToolbarButton()); toolbar.addLeftSeparator(); ToolbarPopupMenu moreMenu = new ToolbarPopupMenu(); moreMenu.addItem(commands_.vcsRevert().createMenuItem(false)); moreMenu.addItem(commands_.vcsIgnore().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsResolve().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsPull().createMenuItem(false)); moreMenu.addItem(commands_.vcsCleanup().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsShowHistory().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.showShellDialog().createMenuItem(false)); toolbar.addLeftWidget(new ToolbarMenuButton( "More", ToolbarButton.NoTitle, new ImageResource2x(StandardIcons.INSTANCE.more_actions2x()), moreMenu)); toolbar.addLeftSeparator(); toolbar.addRightWidget(commands_.vcsRefresh().createToolbarButton()); return toolbar; }</code><technical_language>need added diffButton_ member variable</technical_language>

Target:
protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("SVN Tab"); toolbar.addLeftWidget(commands_.vcsDiff().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsAddFiles().createToolbarButton()); toolbar.addLeftWidget(commands_.vcsRemoveFiles().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsCommit().createToolbarButton()); toolbar.addLeftSeparator(); ToolbarPopupMenu moreMenu = new ToolbarPopupMenu(); moreMenu.addItem(commands_.vcsRevert().createMenuItem(false)); moreMenu.addItem(commands_.vcsIgnore().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsResolve().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsPull().createMenuItem(false)); moreMenu.addItem(commands_.vcsCleanup().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsShowHistory().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.showShellDialog().createMenuItem(false)); toolbar.addLeftWidget(new ToolbarMenuButton( "More", ToolbarButton.NoTitle, new ImageResource2x(StandardIcons.INSTANCE.more_actions2x()), moreMenu)); toolbar.addLeftSeparator(); toolbar.addRightWidget(commands_.vcsRefresh().createToolbarButton()); return toolbar; }
Source:
<code>public void onRemoteOpen(Connection connection) throws Exception { handler.requireHandler(); try { initInternal(); } catch (Exception e) { log.error("Error init connection", e); } if (!validateConnection(connection)) { connection.close(); } else { connection.setContext(AMQPConnectionContext.this); connection.setContainer(containerId); connection.setProperties(connectionProperties); connection.setOfferedCapabilities(getConnectionCapabilitiesOffered()); connection.open(); } initialise(); if (connection.getRemoteProperties() == null || !connection.getRemoteProperties().containsKey(CONNECTION_OPEN_FAILED)) { long nextKeepAliveTime = handler.tick(true); scheduledFutureRef.getAndUpdate(value -> { <START> if (value != null && nextKeepAliveTime != 0 && scheduledPool != null) { <END> return scheduledPool.schedule(new ScheduleRunnable(), (nextKeepAliveTime - TimeUnit.NANOSECONDS.toMillis(System.nanoTime())), TimeUnit.MILLISECONDS); } return value; }); } }</code><technical_language>nextKeepAliveTime != 0 && scheduledPool != null pulled atomic function call. bring in handler.tick(true) it, function instance parent object, currently a new function object is instantiated invocation</technical_language>

Target:
public void onRemoteOpen(Connection connection) throws Exception { handler.requireHandler(); try { initInternal(); } catch (Exception e) { log.error("Error init connection", e); } if (!validateConnection(connection)) { connection.close(); } else { connection.setContext(AMQPConnectionContext.this); connection.setContainer(containerId); connection.setProperties(connectionProperties); connection.setOfferedCapabilities(getConnectionCapabilitiesOffered()); connection.open(); } initialise(); if (connection.getRemoteProperties() == null || !connection.getRemoteProperties().containsKey(CONNECTION_OPEN_FAILED)) { long nextKeepAliveTime = handler.tick(true); if (nextKeepAliveTime != 0 && scheduledPool != null) { scheduleOp.setDelay(nextKeepAliveTime - TimeUnit.NANOSECONDS.toMillis(System.nanoTime())); scheduledFutureRef.getAndUpdate(scheduleOp); } } }
Source:
<code>public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().compressed().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); <START> Assert.assertEquals(data1.length, client.getData().decompressed().forPath(path1).length); <END> Assert.assertNotEquals(data2, client.getData().forPath(path2)); Assert.assertEquals(data2.length, client.getData().decompressed().forPath(path2).length); } finally { CloseableUtils.closeQuietly(client); } }</code><technical_language>is this asserting equal lengths instead of a strong assertion for equal content (after decompression?)</technical_language>

Target:
public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().compressed().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1, client.getData().decompressed().forPath(path1)); Assert.assertNotEquals(data2, client.getData().forPath(path2)); Assert.assertEquals(data2, client.getData().decompressed().forPath(path2)); } finally { CloseableUtils.closeQuietly(client); } }
Source:
<code>long next() { if (!hasNext()) { throw new NoSuchElementException(); } final long ret = currentRecord; try { currentRecord = is.readLong(); } catch (EOFException eof) { isCurrentRecord = false; currentRecord = 0; <START> } catch (IOException e) { <END> throw new RuntimeException(e); } return ret; }</code><technical_language>e final</technical_language>

Target:
long next() { if (!hasNext()) { throw new NoSuchElementException(); } final long ret = currentRecord; try { currentRecord = is.readLong(); } catch (final EOFException eof) { isCurrentRecord = false; currentRecord = 0; } catch (final IOException e) { throw new RuntimeException(e); } return ret; }
Source:
<code>public XMLRecordReader(FileSplit split, Configuration conf) throws IOException { <START> file = split.getPath(); <END> fileName = file.toUri().toString(); fs = file.getFileSystem(conf); XMLInputFactory factory = XMLInputFactory.newInstance(); FSDataInputStream fdDataInputStream = fs.open(file); inputStream = new PublishingInputStream(fdDataInputStream); availableBytes = inputStream.available(); try { reader = factory.createXMLStreamReader(inputStream); } catch (XMLStreamException exception) { throw new RuntimeException("XMLStreamException exception : ", exception); } nodePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_NODE_PATH); if (nodePath.indexOf("/") == 0) { nodePath = nodePath.substring(1, nodePath.length()); } nodes = nodePath.split("/"); totalNodes = nodes.length; actualNodeLevelMap = new HashMap<Integer, String>(); for (int i = 0; i < totalNodes; i++) { actualNodeLevelMap.put(i, nodes[i]); } currentNodeLevelMap = new HashMap<Integer, String>(); tempFilePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_DATA_TEMP_FILE); fileAction = conf.get(XMLInputFormat.XML_INPUTFORMAT_FILE_ACTION); targetFolder = conf.get(XMLInputFormat.XML_INPUTFORMAT_TARGET_FOLDER); }</code><technical_language>indentation 2 spaces</technical_language>

Target:
public XMLRecordReader(FileSplit split, Configuration conf) throws IOException { file = split.getPath(); fileName = file.toUri().toString(); fs = file.getFileSystem(conf); XMLInputFactory factory = XMLInputFactory.newInstance(); FSDataInputStream fdDataInputStream = fs.open(file); inputStream = new TrackingInputStream(fdDataInputStream); availableBytes = inputStream.available(); try { reader = factory.createXMLStreamReader(inputStream); } catch (XMLStreamException exception) { throw new RuntimeException("XMLStreamException exception : ", exception); } String nodePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_NODE_PATH); if (nodePath.indexOf("/") == 0) { nodePath = nodePath.substring(1, nodePath.length()); } nodes = nodePath.split("/"); currentNodeLevelMap = new HashMap<Integer, String>(); tempFilePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_DATA_TEMP_FOLDER); fileAction = conf.get(XMLInputFormat.XML_INPUTFORMAT_FILE_ACTION); targetFolder = conf.get(XMLInputFormat.XML_INPUTFORMAT_TARGET_FOLDER); }
Source:
<code>public MarketplaceProxy() { try { url = new URL(MP_URL); <START> ThreadPoolManager.getScheduledPool("marketplace").scheduleWithFixedDelay(() -> refresh(), 0, <END> refresh_interval, TimeUnit.SECONDS); } catch (MalformedURLException e) { throw new IllegalArgumentException("Something is very wrong - cannot instantiate URL " + MP_URL); } }</code><technical_language>place is pool cleaned again? getScheduledPool(...) creates a new if is put a map. I expect MarketProxy remove ti is is removed system. this a general problem in ThreadPoolManager, it? adds new Pools map cleans up. Miss I something</technical_language>

Target:
public MarketplaceProxy() { try { url = new URL(MP_URL); this.executorService = Executors.newSingleThreadScheduledExecutor(); this.refreshJob = this.executorService.scheduleWithFixedDelay(() -> refresh(), 0, refresh_interval, TimeUnit.SECONDS); } catch (MalformedURLException e) { throw new IllegalArgumentException("Something is very wrong - cannot instantiate URL " + MP_URL); } }
Source:
<code>public void testSingleFileUpdate() throws InterruptedException, IOException { Files.write(file1.toPath(), new byte[]{11}, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); <START> Thread.sleep(150); <END> Assert.assertEquals(poller.getUpdatedFilesSinceLastTime(), ImmutableSet.of(file1)); }</code><technical_language>above... add onTick well</technical_language>

Target:
public void testSingleFileUpdate() throws InterruptedException, IOException { long fileChanges = poller.getStats().getFileChangesDetected(); Files.write(file1.toPath(), new byte[]{11}, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); while (fileChanges == poller.getStats().getFileChangesDetected()) { Thread.sleep(25); } Assert.assertEquals(poller.getUpdatedFilesSinceLastTime(), ImmutableSet.of(file1)); }
Source:
<code>public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) { ensureDataIsValid(); DeliveryAnnotations deliveryAnnotations; <START> if (reference != null && reference.getProtocolData() != null && reference.getProtocolData() instanceof DeliveryAnnotations) { <END> deliveryAnnotations = (DeliveryAnnotations) reference.getProtocolData(); } else { deliveryAnnotations = null; } if (deliveryCount > 1) { return createCopyWithNewDeliveryCount(deliveryCount, deliveryAnnotations); } else if (deliveryAnnotationsPosition != VALUE_NOT_PRESENT || deliveryAnnotations != null || (deliveryAnnotationsForSendBuffer != null && !deliveryAnnotationsForSendBuffer.getValue().isEmpty())) { return createCopyWithSkippedOrExplicitlySetDeliveryAnnotations(deliveryAnnotations); } else { return getData().duplicate(); } }</code><technical_language>redundant null check reference.getProtocolData() instanceof</technical_language>

Target:
public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) { ensureDataIsValid(); DeliveryAnnotations daToWrite; if (reference != null && reference.getProtocolData() instanceof DeliveryAnnotations) { daToWrite = (DeliveryAnnotations) reference.getProtocolData(); } else { daToWrite = deliveryAnnotationsForSendBuffer; } if (deliveryCount > 1 || daToWrite != null || deliveryAnnotationsPosition != VALUE_NOT_PRESENT) { return createDeliveryCopy(deliveryCount, daToWrite); } else { return getData().duplicate(); } }
Source:
<code>private void updateTcpBufferSizes(NetworkAgentInfo nai) { if (isDefaultNetwork(nai) == false) { return; } String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); String[] values = null; if (tcpBufferSizes != null) { values = tcpBufferSizes.split(","); } if (values == null || values.length != 6) { if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; values = tcpBufferSizes.split(","); } if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; try { if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); <START> String rmemValues = values[0] + " " + values[1] + " " +values[2]; String wmemValues = values[3] + " " + values[4] + " " +values[5]; <END> mNetd.setTcpRWmemorySize(rmemValues, wmemValues); mCurrentTcpBufferSizes = tcpBufferSizes; } catch (RemoteException e) { loge("Can't set TCP buffer sizes:" + e); } Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.TCP_DEFAULT_INIT_RWND, mSystemProperties.getInt("net.tcp.default_init_rwnd", 0)); final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; if (rwndValue != 0) { mSystemProperties.set(sysctlKey, rwndValue.toString()); } }</code><technical_language>values[] is a string array, suggest: String rmemValues = String.join(" ", values[0], values[1], values[2]); etc</technical_language>

Target:
private void updateTcpBufferSizes(NetworkAgentInfo nai) { if (isDefaultNetwork(nai) == false) { return; } String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); String[] values = null; if (tcpBufferSizes != null) { values = tcpBufferSizes.split(","); } if (values == null || values.length != 6) { if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; values = tcpBufferSizes.split(","); } if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; try { if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); String rmemValues = String.join(" ", values[0], values[1], values[2]); String wmemValues = String.join(" ", values[3], values[4], values[5]); mNetd.setTcpRWmemorySize(rmemValues, wmemValues); mCurrentTcpBufferSizes = tcpBufferSizes; } catch (RemoteException | ServiceSpecificException e) { loge("Can't set TCP buffer sizes:" + e); } Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.TCP_DEFAULT_INIT_RWND, mSystemProperties.getInt("net.tcp.default_init_rwnd", 0)); final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; if (rwndValue != 0) { mSystemProperties.set(sysctlKey, rwndValue.toString()); } }
Source:
<code><START> public ITmfTrace getTrace() { <END> if (fTrace != null) { fTrace.dispose(); } Bundle bundle = BtfTestPlugin.getBundle(); Path path = new Path(fDirectory + File.separator + fPath); final URL location = FileLocator.find(bundle,path, null); try { File test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new BtfTrace(); fTrace.initTrace(null, test.getAbsolutePath(), null); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (TmfTraceException e) { throw new RuntimeException(e); } return fTrace; }</code><technical_language>return a BtfTrace (so tests BTF-specific methods). avoid plenty of unnecessary casts. class field change BtfTrace too</technical_language>

Target:
public BtfTrace getTrace() { if (fTrace != null) { fTrace.dispose(); } Bundle bundle = BtfTestPlugin.getBundle(); Path path = new Path(fDirectory + File.separator + fPath); final URL location = FileLocator.find(bundle,path, null); File test; try { test = new File(FileLocator.toFileURL(location).toURI()); fTrace = new BtfTrace(); fTrace.initTrace(null, test.getAbsolutePath(), null); } catch (URISyntaxException | IOException | TmfTraceException e) { throw new RuntimeException(e); } return fTrace; }
Source:
<code>public TygronSettingsLoader(String path) { <START> try { <END> readConfig(path); } catch (Exception e) { username = "fallbackusername"; password = "fallbackpassword"; } }</code><technical_language>Please move try catch TygronSettings load data settings loader, if fails, fall default tygron settings</technical_language>

Target:
public TygronSettingsLoader(String path) throws Exception { readConfig(path); }
Source:
<code>private void closeClientQuietly() { if (streamClient != null) { try { streamClient.close(); <START> } catch (IOException e) { <END> LOG.error("Error closing stream client. {}", e.getMessage(), e); } streamClient = null; } }</code><technical_language>this catch (Throwable t)</technical_language>

Target:
private void closeClientQuietly() { if (streamClient != null) { try { streamClient.close(); } catch (Throwable t) { LOG.error("Error closing stream client. {}", t.getMessage(), t); } streamClient = null; } }
Source:
<code>public ScriptServerButtonViewModel(NicosModel model, String buttonLabel) { super(buttonLabel); flash = new FlashingButton(this, SCRIPT_BUTTON_COLOR); flash.setDefaultColour(DEFOCUSSED); Label = buttonLabel; <START> model.addPropertyChangeListener("scriptStatus", arg0->{ <END> status = model.getScriptStatus(); setButtonColor(); updateFlashing(); }); }</code><technical_language>Minor readability suggestion suggestion model.addPropertyChangeListener("scriptStatus", ignored->{</technical_language>

Target:
public ScriptServerButtonViewModel(NicosModel model, String buttonLabel) { super(buttonLabel); flash = new FlashingButton(this, SCRIPT_BUTTON_COLOR); Label = buttonLabel; model.addPropertyChangeListener("scriptStatus", ignored->{ status = model.getScriptStatus(); setButtonColor(); updateFlashing(); }); }
Source:
<code>private ServiceTreeNode step(ServiceTreeNode node, PathSegment pathSegment) { if (isUUID(pathSegment.getPath())) { <START> return node.getSubService("{id}"); <END> } else { if (node.containsSubService(pathSegment.getPath())) { return node.getSubService(pathSegment.getPath()); } else { return node; } } }</code><technical_language>Identifier in patch segments UUIDs. In user identifiers, LUN identifiers, cluster level identifiers graphics consoles identifiers UUIDs. In cases this work correctly. change this method checks if segment corresponds a service, then, if assumes is identifier</technical_language>

Target:
private ServiceTreeNode step(ServiceTreeNode node, PathSegment pathSegment) { if (isID(pathSegment.getPath(), node)) { return node.getSubService("{id}"); } else { if (node.containsSubService(pathSegment.getPath())) { return node.getSubService(pathSegment.getPath()); } else { return node; } } }
Source:
<code>public boolean parse(ByteBuffer buffer) throws IOException { int tag; while (true) { buffer.mark(); int beginning = buffer.position(); tag = FIXTags.get(buffer); if (tag == 0) { buffer.reset(); return false; } if (!beginString.get(buffer)) { buffer.reset(); return false; } if (tag != BeginString) continue; int position = buffer.position(); tag = FIXTags.get(buffer); if (tag == 0) { buffer.reset(); return false; } if (!bodyLength.get(buffer)) { buffer.reset(); return false; } if (tag != BodyLength) { buffer.position(position); continue; } int length = (int)bodyLength.asInt(); if (buffer.remaining() < length + 7) { buffer.reset(); return false; } position = buffer.position(); <START> if (checkSumEnabled && !checkSum(buffer, beginning, position, length)) <END> continue; int limit = buffer.limit(); buffer.limit(position + length); boolean garbled = message.get(buffer) == false; buffer.limit(limit); buffer.position(position + length + 7); if (garbled) continue; listener.message(message); return true; } }</code><technical_language>a good idea</technical_language>

Target:
public boolean parse(ByteBuffer buffer) throws IOException { int tag; while (true) { buffer.mark(); int beginning = buffer.position(); tag = FIXTags.get(buffer); if (tag == 0) { buffer.reset(); return false; } if (!beginString.get(buffer)) { buffer.reset(); return false; } if (tag != BeginString) continue; int position = buffer.position(); tag = FIXTags.get(buffer); if (tag == 0) { buffer.reset(); return false; } if (!bodyLength.get(buffer)) { buffer.reset(); return false; } if (tag != BodyLength) { buffer.position(position); continue; } int length = (int)bodyLength.asInt(); if (buffer.remaining() < length + 7) { buffer.reset(); return false; } position = buffer.position(); if (checkSumEnabled && !acceptCheckSum(buffer, beginning, position, length)) continue; int limit = buffer.limit(); buffer.limit(position + length); boolean garbled = message.get(buffer) == false; buffer.limit(limit); buffer.position(position + length + 7); if (garbled) continue; listener.message(message); return true; } }
Source:
<code>public Schema inferSchema(String json) { try { final JsonNode jsonNode = mapper.readTree(json); return Schema.createRecord("outer_record", null, "org.talend", false, getFields(jsonNode)); <START> } catch (Exception ex) { <END> logger.error(ex.getMessage()); } return null; }</code><technical_language>catch Exception, please specific exceptions</technical_language>

Target:
public Schema inferSchema(String json) { try { final JsonNode jsonNode = mapper.readTree(json); return Schema.createRecord("outer_record", null, "org.talend", false, getFields(jsonNode)); } catch (IOException | TalendRuntimeException e) { throw TalendRuntimeException.createUnexpectedException(e.getCause()); } }
Source:
<code>public PersistentResourceTest() { goodUserScope = new RequestScope(null, null, mock(DataStoreTransaction.class), new User(1), null, elideSettings); badUserScope = new RequestScope(null, null, mock(DataStoreTransaction.class), new User(-1), null, elideSettings); reset(goodUserScope.getTransaction()); <START> assertFalse(goodUserScope.isUseFilterExpressions()); <END> }</code><technical_language>This is a test. assert here</technical_language>

Target:
public PersistentResourceTest() { goodUserScope = buildRequestScope(mock(DataStoreTransaction.class), new User(1)); badUserScope = buildRequestScope(mock(DataStoreTransaction.class), new User(-1)); reset(goodUserScope.getTransaction()); }
Source:
<code>public Page getOutput() { <START> if (!isBlocked().isDone()) { <END> return null; } if (state != State.FINISHING) { return null; } state = State.FINISHED; List<ComputedStatistics> statistics = getComputedStatistics(); outputMetadata = tableFinisher.finishTable(fragmentBuilder.build()); PageBuilder page = new PageBuilder(1, TYPES); page.declarePosition(); BIGINT.writeLong(page.getBlockBuilder(0), rowCount); return page.build(); }</code><technical_language>nit: move if (state != State.FINISHING) { .. }</technical_language>

Target:
public Page getOutput() { if (state != State.FINISHING) { return null; } if (!isBlocked().isDone()) { return null; } state = State.FINISHED; List<ComputedStatistics> statistics = getComputedStatistics(); outputMetadata = tableFinisher.finishTable(fragmentBuilder.build(), statistics); PageBuilder page = new PageBuilder(1, TYPES); page.declarePosition(); BIGINT.writeLong(page.getBlockBuilder(0), rowCount); return page.build(); }
Source:
<code>protected void checkUserFutures() { for (Ignite ignite : G.allGrids()) { IgniteEx ig = (IgniteEx)ignite; <START> final Collection<GridCacheFuture<?>> futs = ig.context().cache().context().mvcc().activeFutures(); <END> boolean hasFutures = false; for (GridCacheFuture<?> fut : futs) { if (!fut.isDone()) { if (fut instanceof GridNearTxPrepareFutureAdapter && ((GridNearTxPrepareFutureAdapter) fut).tx().system()) continue; if (fut instanceof GridDhtTxPrepareFuture && ((GridDhtTxPrepareFuture) fut).tx().system()) continue; log.error("Expecting no active future [node=" + ig.localNode().id() + ", fut=" + fut + ']'); hasFutures = true; } } if (hasFutures) fail("Some mvcc futures are not finished"); Collection<IgniteInternalTx> txs = ig.context().cache().context().tm().activeTransactions() .stream() .filter(tx -> !tx.system()) .collect(Collectors.toSet()); for (IgniteInternalTx tx : txs) log.error("Expecting no active transaction [node=" + ig.localNode().id() + ", tx=" + tx + ']'); if (!txs.isEmpty()) fail("Some transaction are not finished"); } }</code><technical_language>Please add more descriptive variable name. mvccFuts of this</technical_language>

Target:
protected void checkUserFutures() { for (Ignite ignite : G.allGrids()) { IgniteEx ig = (IgniteEx)ignite; final Collection<GridCacheFuture<?>> activeFuts = ig.context().cache().context().mvcc().activeFutures(); boolean hasFutures = false; for (GridCacheFuture<?> fut : activeFuts) { if (!fut.isDone()) { if (fut instanceof GridNearTxPrepareFutureAdapter && ((GridNearTxPrepareFutureAdapter) fut).tx().system()) continue; if (fut instanceof GridDhtTxPrepareFuture && ((GridDhtTxPrepareFuture) fut).tx().system()) continue; log.error("Expecting no active future [node=" + ig.localNode().id() + ", fut=" + fut + ']'); hasFutures = true; } } if (hasFutures) fail("Some mvcc futures are not finished"); Collection<IgniteInternalTx> txs = ig.context().cache().context().tm().activeTransactions() .stream() .filter(tx -> !tx.system()) .collect(Collectors.toSet()); for (IgniteInternalTx tx : txs) log.error("Expecting no active transaction [node=" + ig.localNode().id() + ", tx=" + tx + ']'); if (!txs.isEmpty()) fail("Some transaction are not finished"); } }
Source:
<code>public List<ContentType> findContentTypesForScheme(final WorkflowScheme workflowScheme) { if (!SYSTEM_WORKFLOW_ID.equals(workflowScheme.getId())) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new InvalidLicenseException("Workflow-Schemes-License-required"); } } try { return workFlowFactory.findContentTypesByScheme(workflowScheme); }catch(Exception e){ <START> throw new DoesNotExistException(e); <END> } }</code><technical_language>need log</technical_language>

Target:
public List<ContentType> findContentTypesForScheme(final WorkflowScheme workflowScheme) { if (!SYSTEM_WORKFLOW_ID.equals(workflowScheme.getId())) { if (!hasValidLicense() && !this.getFriendClass().isFriend()) { throw new InvalidLicenseException("Workflow-Schemes-License-required"); } } try { return workFlowFactory.findContentTypesByScheme(workflowScheme); }catch(Exception e){ Logger.debug(this,e.getMessage(),e); throw new DoesNotExistException(e); } }
Source:
<code>private static Client setupClient(HttpClient httpClient, Duration timeout) { <START> ReactorNettyClientHttpEngine engine = <END> new ReactorNettyClientHttpEngine( httpClient, new DefaultChannelGroup(new DefaultEventExecutor()), HttpResources.get(), timeout); final ClientBuilder builder = ClientBuilder.newBuilder(); ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder)builder; clientBuilder.httpEngine(engine); return builder.build(); }</code><technical_language>final please</technical_language>

Target:
private static Client setupClient(HttpClient httpClient, Duration timeout) { final ReactorNettyClientHttpEngine engine = new ReactorNettyClientHttpEngine( httpClient, new DefaultChannelGroup(new DefaultEventExecutor()), HttpResources.get(), timeout); final ClientBuilder builder = ClientBuilder.newBuilder(); final ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder)builder; clientBuilder.httpEngine(engine); return builder.build(); }
Source:
<code>public ChunkBuffer(int x, int z) { <START> super(8192); END> this.x = x; this.z = z; }</code><technical_language>constant COMPRESSED_BUFFER_SIZE here</technical_language>

Target:
public ChunkBuffer(int x, int z) { super(SECTOR_BYTES); this.x = x; this.z = z; }
Source:
<code>public void setMd5(String md5Hash) throws EamDbException { this.md5Hash = md5Hash; boolean useCR = EamDb.isEnabled(); if (useCR) { EamDb.getInstance().updateDataSourceMd5Hash(this); <START> } <END> }</code><technical_language>@dgrove727 @APriestman, is some working a CorrelationDataSource CR in enabled state? EamDb.getInstance call return instance if CR is disabled? I feel confused here</technical_language>

Target:
public void setMd5(String md5Hash) throws EamDbException { this.md5Hash = md5Hash; if (dataSourceObjectID != -1) { EamDb.getInstance().updateDataSourceMd5Hash(this); } }
Source:
<code>private void setupUIFromAdapter(ListView view) { view.setAdapter(adapter); EntitySelectViewSetup.setupDivider(this, view, shortSelect.usesGridView()); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); <START> if (adapter.isFilteringByCalloutResult()) { <END> showSearchBannerWithClearButton(); } }</code><technical_language>do need add this check here, this ? if (!"".equals(adapter.getSearchQuery())) { showSearchBanner(); }</technical_language>

Target:
private void setupUIFromAdapter(ListView view) { view.setAdapter(adapter); EntitySelectViewSetup.setupDivider(this, view, shortSelect.usesGridView()); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); setSearchBannerState(); }
Source:
<code>private boolean areFileassetFieldsPresent(final GraphQLObjectType objectType) { <START> List<String> fileAssetFields = list(FILEASSET_FILE_NAME_FIELD_VAR, <END> FILEASSET_DESCRIPTION_FIELD_VAR, FILEASSET_FILEASSET_FIELD_VAR, FILEASSET_METADATA_FIELD_VAR, FILEASSET_SHOW_ON_MENU_FIELD_VAR, FILEASSET_SORT_ORDER_FIELD_VAR); return objectType.getFieldDefinitions().stream().allMatch((fieldDefinition -> fileAssetFields.contains(fieldDefinition.getName()))); }</code><technical_language>![Codacy](<LINK_0> Issue found: [Local variable 'fileAssetFields' declared final](<LINK_1></technical_language>

Target:
private boolean areFileassetFieldsPresent(final GraphQLObjectType objectType) { final List<String> fileAssetFields = list(FILEASSET_FILE_NAME_FIELD_VAR, FILEASSET_DESCRIPTION_FIELD_VAR, FILEASSET_FILEASSET_FIELD_VAR, FILEASSET_METADATA_FIELD_VAR, FILEASSET_SHOW_ON_MENU_FIELD_VAR, FILEASSET_SORT_ORDER_FIELD_VAR); return objectType.getFieldDefinitions().stream().allMatch(fieldDefinition -> fileAssetFields.contains(fieldDefinition.getName())); }
Source:
<code>@Override public int size() { if (data == null && rawData == null) return 0; else { if (data != null) return data.length; if (rawData != null) return rawData.length; else <START> throw new IllegalStateException(); <END> } }</code><technical_language>Unreachable statement</technical_language>

Target:
@Override public int size() { if (data == null && rawData == null) return 0; else return data != null ? data.length : rawData.length; }
Source:
<code>private static Manifest loadGuavaManifest() { InputStream in = null; try { <START> Enumeration<URL> resources = Resources.class.getClassLoader() <END> .getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { in = resources.nextElement().openStream(); Manifest manifest = new Manifest(in); Attributes mainAttributes = manifest.getMainAttributes(); String symbolicName = mainAttributes.getValue("Bundle-SymbolicName"); if ("com.google.guava".equals(symbolicName)) { return manifest; } } throw new DriverInternalError("Error while looking up Guava manifest: " + "no manifest with symbolic name 'com.google.guava' found in classpath."); } catch (Exception e) { throw new DriverInternalError("Error while looking up Guava manifest", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }</code><technical_language>Resources is part of Guava, is marked @Beta. GuavaCompatibility.class.getClassLoader()</technical_language>

Target:
private static Manifest loadGuavaManifest() { InputStream in = null; try { Enumeration<URL> resources = Preconditions.class.getClassLoader() .getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { in = resources.nextElement().openStream(); Manifest manifest = new Manifest(in); Attributes mainAttributes = manifest.getMainAttributes(); String symbolicName = mainAttributes.getValue("Bundle-SymbolicName"); if ("com.google.guava".equals(symbolicName)) { return manifest; } } throw new DriverInternalError("Error while looking up Guava manifest: " + "no manifest with symbolic name 'com.google.guava' found in classpath."); } catch (Exception e) { throw new DriverInternalError("Error while looking up Guava manifest", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
Source:
<code>public boolean equals(Object other) { if(other == null) { return false;} if(this == other) { return true;} if (other instanceof BindingSetRow) { BindingSetRow row = (BindingSetRow) other; <START> return new EqualsBuilder().append(this.nodeId, row.nodeId).append(this.bindingSetString, row.bindingSetString) <END> .isEquals(); } return false; }</code><technical_language>need implement hashCode() method of this class written equality method</technical_language>

Target:
public boolean equals(Object other) { if(this == other) { return true;} if (other instanceof BindingSetRow) { BindingSetRow row = (BindingSetRow) other; return Objects.equals(nodeId, row.nodeId) && Objects.equals(bindingSetString, row.bindingSetString); } return false; }
Source:
<code>MptrXmlElementAccess(DivType div, Mets parent, InputStreamProviderInterface inputStreamProvider) { String href = null; try { linkedStructure.setOrder(div.getORDER()); href = div.getMptr().stream().findFirst().get().getHref(); URI uri = new URI(href); linkedStructure.setUri(uri); Mets child; try (InputStream in = inputStreamProvider.getInputStream(uri, true)) { child = MetsXmlElementAccess.readMets(in); } ensureParenthood(parent, child, inputStreamProvider); Structure linked = MetsXmlElementAccess.toWorkpiece(child, inputStreamProvider).getStructure(); linkedStructure.setLabel(linked.getLabel()); linkedStructure.setType(linked.getType()); <START> } catch (IOException e) { <END> throw new UncheckedIOException(e); } catch (URISyntaxException e) { throw new DataBindingException("Erroneous URI: \"" + href + "\" (" + e.getMessage() + ')', e); } }</code><technical_language>Please wrap IOException in unchecked</technical_language>

Target:
MptrXmlElementAccess(DivType div, Mets parent, InputStreamProviderInterface inputStreamProvider) throws IOException { String href = null; try { linkedStructure.setOrder(div.getORDER()); href = div.getMptr().stream().findFirst().get().getHref(); URI uri = new URI(href); linkedStructure.setUri(uri); Mets child; try (InputStream inputStream = inputStreamProvider.getInputStream(uri, true)) { child = MetsXmlElementAccess.readMets(inputStream); } ensureParenthood(parent, child, inputStreamProvider); IncludedStructuralElement linked = MetsXmlElementAccess.toWorkpiece(child, inputStreamProvider).getRootElement(); linkedStructure.setLabel(linked.getLabel()); linkedStructure.setType(linked.getType()); } catch (URISyntaxException e) { throw new DataBindingException("Erroneous URI: \"" + href + "\" (" + e.getMessage() + ')', e); } }