auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static <T> Iterable<T> chain( final Iterable<? extends T>... itArray ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { class MyIt implements Iterator<T> { ArrayList<Iterator<? extends T>> iL; int indexA = 0; public MyIt( ArrayList<Iterator<? extends T>> iL ) { this.iL = iL; } @Override public boolean hasNext() { if( indexA < iL.size() - 1 ) { if ( iL.get( indexA ).hasNext() ) { return true; } else { ++indexA; return hasNext(); } } if( indexA >= iL.size() ) { return false; } return iL.get( indexA ).hasNext() ; } @Override public T next() { return iL.get( indexA ).hasNext() ? iL.get( indexA ).next() : ( iL.get( ++indexA ).hasNext() ? iL.get( indexA ).next() : next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } } ArrayList<Iterator<? extends T>> newIL = new ArrayList<Iterator<? extends T>>(); for ( Iterable<? extends T> it: itArray ) { newIL.add( it.iterator() ); } return new MyIt(newIL); } }; }

Target:
public static <T> Iterable<T> chain( final Iterable<? extends T>... itArray ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { class MyIt implements Iterator<T> { Iterator<Iterator<? extends T>> iI; Iterator<? extends T> i; public MyIt( Iterator<Iterator<? extends T>> iI ) { this.iI = iI; i = iI.next(); } @Override public boolean hasNext() { if ( i.hasNext() ) { return true; } else { if ( iI.hasNext() ) { i = iI.next(); return this.hasNext(); } else { return false; } } } @Override public T next() { if ( i.hasNext() ) { return i.next(); } else { i = iI.next(); return this.next(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } List<Iterator<? extends T>> newIL = new ArrayList<Iterator<? extends T>>(); for ( Iterable<? extends T> it: itArray ) { newIL.add( it.iterator() ); } return new MyIt(newIL.iterator()); } }; }
Source:
private static LinkedHashSet<String> getSuggestedNames(GoExpression expression) { if (expression instanceof GoCallExpr) { List<String> names = ContainerUtil.newArrayList(); GoReferenceExpression callReference = PsiTreeUtil.getChildOfType(expression, GoReferenceExpression.class); if (callReference != null) { String name = StringUtil.decapitalize(callReference.getIdentifier().getText()); if (name.startsWith("get")) { name = name.substring(3); } else if (name.startsWith("is")) { name = name.substring(2); } for (int i = 0; i < name.length(); i++) { if (i == 0 || (Character.isLowerCase(name.charAt(i - 1)) && Character.isUpperCase(name.charAt(i)))) { names.add(StringUtil.decapitalize(name.substring(i))); } } } return ContainerUtil.newLinkedHashSet(ContainerUtil.reverse(names)); } return ContainerUtil.newLinkedHashSet("i"); }

Target:
private static LinkedHashSet<String> getSuggestedNames(GoExpression expression) { LinkedHashSet<String> usedNames = getNamesInContext(PsiTreeUtil.getParentOfType(expression, GoBlock.class)); LinkedHashSet<String> names = ContainerUtil.newLinkedHashSet(); if (expression instanceof GoCallExpr) { GoReferenceExpression callReference = PsiTreeUtil.getChildOfType(expression, GoReferenceExpression.class); if (callReference != null) { String name = StringUtil.decapitalize(callReference.getIdentifier().getText()); for (String candidate : NameUtil.getSuggestionsByName(name, "", "", false, false, false)) { if (!usedNames.contains(candidate)) names.add(candidate); } } } if (names.isEmpty()) { if (usedNames.contains("i")) { int counter = 1; while (usedNames.contains("i" + counter)) counter++; names.add("i" + counter); } else { names.add("i"); } } return names; }
Source:
private static CRAMFileReader writeAndReadFromInMemoryCram(Collection<SAMRecord> records, CRAMReferenceSource source, SAMFileHeader header) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); CRAMFileWriter cramFileWriter = new CRAMFileWriter(baos, source, header, "whatever"); for (SAMRecord record : records) { cramFileWriter.addAlignment(record); } cramFileWriter.close(); return new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (SeekableStream) null, source, ValidationStringency.SILENT); }

Target:
private static CRAMFileReader writeAndReadFromInMemoryCram(Collection<SAMRecord> records, CRAMReferenceSource source, SAMFileHeader header) throws IOException { try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); CRAMFileWriter cramFileWriter = new CRAMFileWriter(baos, source, header, "whatever")){ records.forEach(cramFileWriter::addAlignment); cramFileWriter.close(); return new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (SeekableStream) null, source, ValidationStringency.SILENT); } }
Source:
protected void applyCustomColor(GC gc, TraditionalMemoryByte bytes[], int col) { boolean anyByteEditing = false; for(int n = 0; n < bytes.length && !anyByteEditing; n++) if(bytes[n] instanceof TraditionalMemoryByte) if(bytes[n].isEdited()) anyByteEditing = true; TraditionalRendering ren = fRendering.getTraditionalRendering(); if(isOdd(col)) gc.setForeground(ren.getColorText()); else gc.setForeground(ren.getColorTextAlternate()); gc.setBackground(ren.getColorBackground()); if(anyByteEditing) { gc.setForeground(ren.getColorEdit()); gc.setFont(ren.getFontEdit(gc.getFont())); } else { boolean isColored = false; for(int i = 0; i < fRendering.getHistoryDepth() && !isColored; i++) { for(int n = 0; n < bytes.length; n++) { if(bytes[n].isChanged(i)) { if(i == 0) { gc.setForeground(ren.getColorsChanged()[i]); gc.setFont(ren.getFontChanged(gc.getFont())); } else { gc.setBackground(ren.getColorsChanged()[i]); gc.setFont(ren.getFontChanged(gc.getFont())); } isColored = true; break; } } } } }

Target:
protected void applyCustomColor(GC gc, TraditionalMemoryByte bytes[], int col) { boolean anyByteEditing = false; for (int n = 0; n < bytes.length && !anyByteEditing; n++) if (bytes[n] instanceof TraditionalMemoryByte) if (bytes[n].isEdited()) anyByteEditing = true; TraditionalRendering ren = fRendering.getTraditionalRendering(); if (isOdd(col)) gc.setForeground(ren.getColorText()); else gc.setForeground(ren.getColorTextAlternate()); gc.setBackground(ren.getColorBackground()); if (anyByteEditing) { gc.setForeground(ren.getColorEdit()); gc.setFont(ren.getFontEdit(gc.getFont())); } else { boolean isColored = false; for (int i = 0; i < fRendering.getHistoryDepth() && !isColored; i++) { for (int n = 0; n < bytes.length; n++) { if (bytes[n].isChanged(i)) { if (i == 0) gc.setForeground(ren.getColorsChanged()[i]); else gc.setBackground(ren.getColorsChanged()[i]); gc.setFont(ren.getFontChanged(gc.getFont())); isColored = true; break; } } } } }
Source:
public static FirewallPolicy create(String id, String name, String description, String state, String creationDate, String defaultState, List<Rule> rules, List<ServerIp> serverIps, String cloudpanelId) { return new AutoValue_FirewallPolicy(id, name, description, state, creationDate, defaultState, rules == null ? ImmutableList.<Rule>of() : rules, serverIps == null ? ImmutableList.<ServerIp>of() : serverIps, cloudpanelId); }

Target:
public static FirewallPolicy create(String id, String name, String description, String state, String creationDate, String defaultState, List<Rule> rules, List<ServerIp> serverIps, String cloudpanelId) { return new AutoValue_FirewallPolicy(id, name, description, state, creationDate, defaultState, rules == null ? ImmutableList.<Rule>of() : ImmutableList.copyOf(rules), serverIps == null ? ImmutableList.<ServerIp>of() : ImmutableList.copyOf(serverIps), cloudpanelId); }
Source:
public void aboutToBeHidden() { super.aboutToBeHidden(); if (this.text != null && !this.text.isDisposed() && this.hyperlinkListener != null) { this.text.removeMouseListener(this.hyperlinkListener); } }

Target:
public void aboutToBeHidden() { super.aboutToBeHidden(); if (this.hyperlink != null && !this.hyperlink.isDisposed() && this.hyperlinkListener != null) { this.hyperlink.removeMouseListener(this.hyperlinkListener); } }
Source:
public void zoomToRegion() { ObaRegion region = Application.get().getCurrentRegion(); if (region != null && mMap != null) { LatLngBounds b = MapHelpV2.getRegionBounds(region); int width = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels; int padding = (int) (width * 0.12); mMap.animateCamera((CameraUpdateFactory.newLatLngBounds(b, width, height, padding))); } }

Target:
public void zoomToRegion() { ObaRegion region = Application.get().getCurrentRegion(); if (region != null && mMap != null) { LatLngBounds b = MapHelpV2.getRegionBounds(region); int width = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels; int padding = 0; mMap.animateCamera((CameraUpdateFactory.newLatLngBounds(b, width, height, padding))); } }
Source:
public CustomColumnNamingStrategy(String... columnNames) { this.columnNames = Arrays.asList(columnNames); }

Target:
public CustomColumnNamingStrategy(String... columnNames) { this(Arrays.asList(columnNames)); }
Source:
public static boolean isWindows() { return WildFlySecurityManager.getPropertyPrivileged("os.name", null).toLowerCase(Locale.ENGLISH).contains("windows"); }

Target:
public static boolean isWindows() { return WildFlySecurityManager.getPropertyPrivileged("os.name", null).toLowerCase(Locale.ENGLISH).indexOf("windows") >= 0; }
Source:
public void refresh(final KeyType key) { final String redisKey = generateRedisKey(key); final String redisLockKey = redisLockKey(redisKey); rdbi.withHandle(new Callback<Void>() { @Override public Void run(Handle handle) { if (acquireLock(handle.jedis(), redisLockKey)) { log.debug("{}: Attempting to refresh data asynchonously for", cacheName); long start = System.currentTimeMillis(); try { final ValueType value = loader.apply(key); if (value != null) { log.info("{}: Async refresh for {}", cacheName); final Jedis j = handle.jedis(); cacheData(key, j, value, valueTtl); cacheLoadSuccessCount.incrementAndGet(); loadSuccessAction.run(); } return null; } catch (Exception ex) { cacheLoadExceptionCount.incrementAndGet(); loadExceptionAction.run(); } finally { handle.jedis().del(redisLockKey); long timeToLoad = System.currentTimeMillis() - start; cacheTotalLoadTime.addAndGet(timeToLoad); } } else { log.debug("{}: Unable to acquire refresh lock for", cacheName); } return null; } }); }

Target:
public void refresh(final KeyType key) { asyncService.submit(new AsyncCacheRefresher<>(this, rdbi, key)); }
Source:
public void testSimplePreemption() { RMNode node = createNode(); FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false); saturateCluster(schedulerNode); assertEquals("Container should be allocated", Resources.multiply(containers.get(0).getContainer().getResource(), containerNum), schedulerNode.getAllocatedResource()); FSAppAttempt starvingApp = createStarvingApp(schedulerNode, Resource.newInstance(1024, 1)); schedulerNode.addContainersForPreemption( Collections.singletonList(containers.get(0)), starvingApp); assertEquals( "No resource amount should be reserved for preemptees", containers.get(0).getAllocatedResource(), schedulerNode.getTotalReserved()); schedulerNode.releaseContainer(containers.get(0).getContainerId(), true); allocateContainers(schedulerNode); assertEquals("Container should be allocated", schedulerNode.getTotalResource(), schedulerNode.getAllocatedResource()); for (int i = 1; i < containerNum; ++i) { schedulerNode.releaseContainer(containers.get(i).getContainerId(), true); } finalValidation(schedulerNode); }

Target:
public void testSimplePreemption() { RMNode node = createNode(); FSSchedulerNode schedulerNode = new FSSchedulerNode(node, false); saturateCluster(schedulerNode); assertEquals("Container should be allocated", Resources.multiply(containers.get(0).getContainer().getResource(), containers.size()), schedulerNode.getAllocatedResource()); FSAppAttempt starvingApp = createStarvingApp(schedulerNode, Resource.newInstance(1024, 1)); schedulerNode.addContainersForPreemption( Collections.singletonList(containers.get(0)), starvingApp); assertEquals( "No resource amount should be reserved for preemptees", containers.get(0).getAllocatedResource(), schedulerNode.getTotalReserved()); schedulerNode.releaseContainer(containers.get(0).getContainerId(), true); allocateContainers(schedulerNode); assertEquals("Container should be allocated", schedulerNode.getTotalResource(), schedulerNode.getAllocatedResource()); for (int i = 1; i < containers.size(); ++i) { schedulerNode.releaseContainer(containers.get(i).getContainerId(), true); } finalValidation(schedulerNode); }
Source:
public void nodeConfigOverridesGlobalConfig() { PlatformLabelerGlobalConfiguration globalConfig = GlobalConfiguration.all().getInstance(PlatformLabelerGlobalConfiguration.class); LabelConfig globalLabelConfig = new LabelConfig(); globalLabelConfig.setVersion(false); globalLabelConfig.setArchitecture(false); globalConfig.setLabelConfig(globalLabelConfig); PlatformLabelerNodeProperty nodeProperty = new PlatformLabelerNodeProperty(); LabelConfig labelConfig = new LabelConfig(); labelConfig.setVersion(false); nodeProperty.setLabelConfig(labelConfig); r.jenkins.getNodeProperties().add(nodeProperty); nodeLabelCache.onConfigurationChange(); Set<LabelAtom> labelsAfter = computer.getNode().getAssignedLabels(); System.err.println(labelsAfter); assertThat(nodeLabelCache.getLabelsForNode(computer.getNode()).size(), is(5)); assertThat(labelsAfter.size(), is(6)); }

Target:
public void nodeConfigOverridesGlobalConfig() { PlatformLabelerGlobalConfiguration globalConfig = GlobalConfiguration.all().getInstance(PlatformLabelerGlobalConfiguration.class); LabelConfig globalLabelConfig = new LabelConfig(); globalLabelConfig.setVersion(false); globalLabelConfig.setArchitecture(false); globalConfig.setLabelConfig(globalLabelConfig); PlatformLabelerNodeProperty nodeProperty = new PlatformLabelerNodeProperty(); LabelConfig labelConfig = new LabelConfig(); labelConfig.setVersion(false); nodeProperty.setLabelConfig(labelConfig); r.jenkins.getNodeProperties().add(nodeProperty); nodeLabelCache.onConfigurationChange(); Collection<LabelAtom> expected = new HashSet<>(); expected.add(r.jenkins.getLabelAtom("master")); expected.add(r.jenkins.getLabelAtom(platformDetails.getArchitecture())); expected.add(r.jenkins.getLabelAtom(platformDetails.getName())); expected.add(r.jenkins.getLabelAtom(platformDetails.getNameVersion())); expected.add(r.jenkins.getLabelAtom(platformDetails.getArchitectureName())); expected.add(r.jenkins.getLabelAtom(platformDetails.getArchitectureNameVersion())); Set<LabelAtom> labelsAfter = computer.getNode().getAssignedLabels(); assertEquals(expected, labelsAfter); }
Source:
public boolean validate() { getBond().validateSelectedItem(new IValidation[] { new NotEmptyValidation(), new LengthValidation(BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH), new BondNameValidation() }); if (getBondingOptions().getSelectedItem().getKey().equals(CUSTOM_BONDING_MODE)) { getCustomBondEditor().validateEntity(new IValidation[] { new KeyValueFormatValidation() }); } return getBond().getIsValid() && getCustomBondEditor().getIsValid(); }

Target:
public boolean validate() { getBond().validateSelectedItem(new IValidation[] { new NotEmptyValidation(), new LengthValidation(BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH), new BondNameValidation() }); getCustomBondEditor().setIsValid(true); if (getBondingOptions().getSelectedItem().getKey().equals(CUSTOM_BONDING_MODE)) { getCustomBondEditor().validateEntity(new IValidation[] { new KeyValueFormatValidation() }); } return getBond().getIsValid() && getCustomBondEditor().getIsValid(); }
Source:
private void sendForm(HttpServletRequest req, HttpServletResponse res, @Nullable String errorMessage) throws IOException { String self = req.getRequestURI(); String cancel = Objects.firstNonNull(urlProvider.get(req), "/"); String token = LoginUrlToken.getToken(req); cancel += token; Document doc = headers.parse(LdapLoginServlet.class, "LoginForm.html"); HtmlDomUtil.find(doc, "hostName").setTextContent(req.getServerName()); HtmlDomUtil.find(doc, "login_form").setAttribute("action", self); HtmlDomUtil.find(doc, "cancel_link").setAttribute("href", cancel); Element emsg = HtmlDomUtil.find(doc, "error_message"); if (Strings.isNullOrEmpty(errorMessage)) { emsg.getParentNode().removeChild(emsg); } else { emsg.setTextContent(errorMessage); } byte[] bin = HtmlDomUtil.toUTF8(doc); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setContentType("text/html"); res.setCharacterEncoding("UTF-8"); res.setContentLength(bin.length); ServletOutputStream out = res.getOutputStream(); try { out.write(bin); } finally { out.close(); } }

Target:
private void sendForm(HttpServletRequest req, HttpServletResponse res, @Nullable String errorMessage) throws IOException { String self = req.getRequestURI(); String cancel = Objects.firstNonNull(urlProvider.get(req), "/"); cancel += LoginUrlToken.getToken(req); Document doc = headers.parse(LdapLoginServlet.class, "LoginForm.html"); HtmlDomUtil.find(doc, "hostName").setTextContent(req.getServerName()); HtmlDomUtil.find(doc, "login_form").setAttribute("action", self); HtmlDomUtil.find(doc, "cancel_link").setAttribute("href", cancel); Element emsg = HtmlDomUtil.find(doc, "error_message"); if (Strings.isNullOrEmpty(errorMessage)) { emsg.getParentNode().removeChild(emsg); } else { emsg.setTextContent(errorMessage); } byte[] bin = HtmlDomUtil.toUTF8(doc); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setContentType("text/html"); res.setCharacterEncoding("UTF-8"); res.setContentLength(bin.length); ServletOutputStream out = res.getOutputStream(); try { out.write(bin); } finally { out.close(); } }
Source:
public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(this.getDimension()); byte[] lowerBytes = this.getLower() == null ? new byte[0] : StringUtils.toUtf8(this.getLower()); byte[] upperBytes = this.getUpper() == null ? new byte[0] : StringUtils.toUtf8(this.getUpper()); byte boundType = 0x1; if (this.getLower() == null) { boundType = 0x2; } else if (this.getUpper() == null) { boundType = 0x3; } byte lowerStrictByte = (this.isLowerStrict() == false) ? 0x0 : (byte) 1; byte upperStrictByte = (this.isUpperStrict() == false) ? 0x0 : (byte) 1; byte AlphaNumericByte = (this.isAlphaNumeric() == false) ? 0x0 : (byte) 1; ByteBuffer boundCacheBuffer = ByteBuffer.allocate( 8 + dimensionBytes.length + upperBytes.length + lowerBytes.length ); boundCacheBuffer.put(DimFilterCacheHelper.BOUND_CACHE_ID) .put(boundType) .put(upperStrictByte) .put(lowerStrictByte) .put(AlphaNumericByte) .put((byte) 0xFF) .put(dimensionBytes) .put((byte) 0xFF) .put(upperBytes) .put((byte) 0xFF) .put(lowerBytes); return boundCacheBuffer.array(); }

Target:
public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(this.getDimension()); byte[] lowerBytes = this.getLower() == null ? new byte[0] : StringUtils.toUtf8(this.getLower()); byte[] upperBytes = this.getUpper() == null ? new byte[0] : StringUtils.toUtf8(this.getUpper()); byte boundType = 0x1; if (this.getLower() == null) { boundType = 0x2; } else if (this.getUpper() == null) { boundType = 0x3; } byte lowerStrictByte = (this.isLowerStrict() == false) ? 0x0 : (byte) 1; byte upperStrictByte = (this.isUpperStrict() == false) ? 0x0 : (byte) 1; byte AlphaNumericByte = (this.isAlphaNumeric() == false) ? 0x0 : (byte) 1; ByteBuffer boundCacheBuffer = ByteBuffer.allocate( 8 + dimensionBytes.length + upperBytes.length + lowerBytes.length ); boundCacheBuffer.put(DimFilterCacheHelper.BOUND_CACHE_ID) .put(boundType) .put(upperStrictByte) .put(lowerStrictByte) .put(AlphaNumericByte) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(dimensionBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(upperBytes) .put(DimFilterCacheHelper.STRING_SEPARATOR) .put(lowerBytes); return boundCacheBuffer.array(); }
Source:
public String getResourceCrnByResourceName(String resourceName) { return getByName(resourceName).getResourceCrn().toString(); }

Target:
public String getResourceCrnByResourceName(String resourceName) { return repository.findResourceCrnByName(resourceName).orElseThrow(NotFoundException.notFound("database", resourceName)).toString(); }
Source:
private void fillValues(IMarkerEvent marker) { Map<String, String> toolTips = fTimeGraphProvider.getEventHoverToolTipInfo(marker); String label = marker.getLabel(); addItem("Marker", label == null ? "" : label); if(toolTips != null) { for (Entry<String, String> tooltip : toolTips.entrySet()) { addItem(" " + tooltip.getKey(), tooltip.getValue()); } } }

Target:
private void fillValues(IMarkerEvent marker) { Map<String, String> toolTips = fTimeGraphProvider.getEventHoverToolTipInfo(marker); String category = marker.getCategory(); addItem("Marker", category == null ? "" : category); String label = marker.getLabel(); if(label != null && !label.isEmpty()) { addItem(" name", label); } Long timestamp = marker.getTime(); long duration = marker.getDuration(); if (duration == 0) { addItem(" Timestamp", TmfTimestamp.fromNanos(timestamp).toString()); } else { addItem(" Start Time", TmfTimestamp.fromNanos(timestamp).toString()); addItem(" End Time", TmfTimestamp.fromNanos(timestamp + duration).toString()); } if(toolTips != null) { for (Entry<String, String> tooltip : toolTips.entrySet()) { addItem(" " + tooltip.getKey(), tooltip.getValue()); } } }
Source:
private void validateSettings() { final Job job = new Job(Messages.GerritServerDialog_30) { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(Messages.GerritServerDialog_30, 100); try { if (validateURL(monitor)) { completeURLValidation(validConnection(monitor)); } else { if (!ok.isDisposed()) { Utils.displayInformation(null, DIALOG_TITLE, INVALID_MESSAGE); } } } catch (URISyntaxException e) { setProgress(monitor, 100); if (!ok.isDisposed()) { Utils.displayInformation(shell, DIALOG_TITLE, e.getLocalizedMessage()); } this.cancel(); } catch (EGerritException e) { setProgress(monitor, 100); if (!ok.isDisposed()) { Utils.displayInformation(shell, DIALOG_TITLE, e.getLocalizedMessage()); } this.cancel(); } return Status.OK_STATUS; } }; job.setUser(false); job.schedule(); }

Target:
private void validateSettings() { final Job job = new Job(Messages.GerritServerDialog_30) { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(Messages.GerritServerDialog_30, 100); try { isServerInfoReady(); if (validateURL(monitor)) { completeURLValidation(validConnection(monitor)); } else { if (!ok.isDisposed()) { Utils.displayInformation(null, DIALOG_TITLE, INVALID_MESSAGE); } } } catch (URISyntaxException e) { setProgress(monitor, 100); if (!ok.isDisposed()) { Utils.displayInformation(shell, DIALOG_TITLE, e.getLocalizedMessage()); } this.cancel(); } catch (EGerritException e) { setProgress(monitor, 100); if (!ok.isDisposed()) { Utils.displayInformation(shell, DIALOG_TITLE, e.getLocalizedMessage()); } this.cancel(); } return Status.OK_STATUS; } }; job.setUser(false); job.schedule(); }
Source:
public void close() { if(file != null && file.isOpen()) { try { if (fileLock != null && fileLock.isValid()) { fileLock.release(); } file.close(); freeSpace.clear(); } catch (Exception e) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_WRITING_FAILED, "Closing failed for file {0}", fileName, e); } finally { fileLock = null; file = null; } } }

Target:
public void close() { try { if(file != null && file.isOpen()) { if (fileLock != null) { fileLock.release(); } file.close(); } } catch (Exception e) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_WRITING_FAILED, "Closing failed for file {0}", fileName, e); } finally { fileLock = null; file = null; } }
Source:
default void sendTo(Iterable<MessageReceiver> receivers) { receivers.forEach(this::sendTo); }

Target:
default void sendTo(Iterable<MessageReceiver> receivers) { sendTo(receivers, 1); }
Source:
public void execute() { if (!hypervisor.equalsIgnoreCase("kvm")) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Currently supporting KVM hosts only"); } if (name.equalsIgnoreCase("cloud")) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Please provide a different alias name for the certificate"); } try { LOG.debug("Uploading certificate " + name + " to agents for Direct Download"); boolean result = directDownloadManager.uploadCertificateToHosts(certificate, name, hypervisor, zoneId); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } catch (Exception e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } }

Target:
public void execute() { if (!hypervisor.equalsIgnoreCase("kvm")) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Currently supporting KVM hosts only"); } try { LOG.debug("Uploading certificate " + name + " to agents for Direct Download"); boolean result = directDownloadManager.uploadCertificateToHosts(certificate, name, hypervisor); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } catch (Exception e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } }
Source:
private <R> R getDeserializedResponse(RestAction<R> action, Response response) throws ActionException { String resultClass = action.getResultClass(); if (resultClass != null) { ContentType contentType = ContentType.valueOf(response.getHeader(HttpHeaders.CONTENT_TYPE)); Serialization serialization = findSerialization(resultClass, contentType); if (serialization != null) { try { return deserializeValue(serialization, resultClass, contentType, response.getText()); } catch (SerializationException e) { throw new ActionDeserializationException(response, e); } } } throw new ActionDeserializationException(response, "Unable to deserialize response. No serializer found."); }

Target:
private <R> R getDeserializedResponse(RestAction<R> action, Response response) throws ActionException { String resultClass = action.getResultClass(); if (resultClass != null) { ContentType contentType = ContentType.valueOf(response.getHeader(HttpHeaders.CONTENT_TYPE)); Serialization serialization = findSerialization(resultClass, contentType); if (serialization != null) { return deserializeValue(serialization, resultClass, contentType, response); } } throw new ActionDeserializationException(response, "Unable to deserialize response. No serializer found."); }
Source:
public void testOverrides() { when(channelResolver.forAliases("<LINK_3>")) .thenReturn(ImmutableMap.of("<LINK_0>", BBC_ONE)); when(channelResolver.forAliases("<LINK_2>")) .thenReturn(ImmutableMap.of("<LINK_2>456", BBC_ONE)); DefaultYouViewChannelResolver yvChannelResolver = new DefaultYouViewChannelResolver(channelResolver, ALIAS_PREFIXES); assertThat(yvChannelResolver.getChannel(456).get(), is(BBC_ONE)); assertFalse(yvChannelResolver.getChannel(123).isPresent()); assertThat(yvChannelResolver.getChannelServiceAlias(456), is("<LINK_1>")); }

Target:
public void testOverrides() { when(channelResolver.forAliases("<LINK_3>")) .thenReturn(ImmutableMap.of("<LINK_0>", BBC_ONE)); when(channelResolver.forAliases("<LINK_2>")) .thenReturn(ImmutableMap.of("<LINK_2>456", BBC_ONE)); DefaultYouViewChannelResolver yvChannelResolver = new DefaultYouViewChannelResolver(channelResolver, ALIAS_PREFIXES); assertThat(yvChannelResolver.getChannel(456).get(), is(BBC_ONE)); assertFalse("Shouldn't be able to look up by overridden service ID", yvChannelResolver.getChannel(123).isPresent()); assertThat(yvChannelResolver.getChannelServiceAlias(456), is("<LINK_1>")); }
Source:
default double getDistanceSquared(Point2D<?, ?> pt) { assert pt != null : "Point must not be null"; final int dx; if (pt.ix() < getMinX()) { dx = getMinX() - pt.ix(); } else if (pt.ix() > getMaxX()) { dx = pt.ix() - getMaxX(); } else { dx = 0; } final int dy; if (pt.iy() < getMinY()) { dy = getMinY() - pt.iy(); } else if (pt.iy() > getMaxY()) { dy = pt.iy() - getMaxY(); } else { dy = 0; } return dx * dx + (double) dy * dy; }

Target:
default double getDistanceSquared(Point2D<?, ?> pt) { assert pt != null : "Point must not be null"; final int dx; if (pt.ix() < getMinX()) { dx = getMinX() - pt.ix(); } else if (pt.ix() > getMaxX()) { dx = pt.ix() - getMaxX(); } else { dx = 0; } final int dy; if (pt.iy() < getMinY()) { dy = getMinY() - pt.iy(); } else if (pt.iy() > getMaxY()) { dy = pt.iy() - getMaxY(); } else { dy = 0; } return (double) (dx * dx + dy * dy); }
Source:
protected void executeCommand() { ScanDiskAlignmentVDSCommandParameters parameters; acquireDiskLocks(); if (getDiskType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) getDisk(); ScanDiskImageAlignmentVDSCommandParameters imageParameters = new ScanDiskImageAlignmentVDSCommandParameters(getVdsIdInPool(), getVm().getId()); imageParameters.setPoolId(getStoragePoolId()); imageParameters.setDomainId(diskImage.getStorageIds().get(0)); imageParameters.setImageGroupId(diskImage.getimage_group_id()); imageParameters.setImageId(diskImage.getImageId()); parameters = imageParameters; } else if (getDiskType() == DiskStorageType.LUN) { LunDisk lunDisk = (LunDisk) getDisk(); ScanDiskLunAlignmentVDSCommandParameters lunParameters = new ScanDiskLunAlignmentVDSCommandParameters(getVdsIdInPool(), getVm().getId()); lunParameters.setLunGuid(lunDisk.getLun().getLUN_id()); parameters = lunParameters; } else { throw new RuntimeException("Unknown DiskStorageType " + getDiskType().toString()); } Boolean isDiskAligned = (Boolean) runVdsCommand( VDSCommandType.ScanDiskAlignment, parameters).getReturnValue(); getDisk().setAlignment(isDiskAligned ? DiskAlignment.Aligned : DiskAlignment.Misaligned); getDisk().setLastAlignmentScan(new Date()); getBaseDiskDao().update(getDisk()); setSucceeded(true); releaseDiskLocks(); }

Target:
protected void executeCommand() { ScanDiskAlignmentVDSCommandParameters parameters; acquireExclusiveDiskLocks(); if (getDiskType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) getDisk(); ScanDiskImageAlignmentVDSCommandParameters imageParameters = new ScanDiskImageAlignmentVDSCommandParameters(getVdsIdInPool(), getVm().getId()); imageParameters.setPoolId(getStoragePoolId()); imageParameters.setDomainId(diskImage.getStorageIds().get(0)); imageParameters.setImageGroupId(diskImage.getimage_group_id()); imageParameters.setImageId(diskImage.getImageId()); parameters = imageParameters; } else if (getDiskType() == DiskStorageType.LUN) { LunDisk lunDisk = (LunDisk) getDisk(); ScanDiskLunAlignmentVDSCommandParameters lunParameters = new ScanDiskLunAlignmentVDSCommandParameters(getVdsIdInPool(), getVm().getId()); lunParameters.setLunGuid(lunDisk.getLun().getLUN_id()); parameters = lunParameters; } else { throw new VdcBLLException(VdcBllErrors.ENGINE, "Unknown DiskStorageType: " + getDiskType().toString() + " Disk id: " + getDisk().getId().toString()); } Boolean isDiskAligned = (Boolean) runVdsCommand( VDSCommandType.ScanDiskAlignment, parameters).getReturnValue(); getDisk().setAlignment(isDiskAligned ? DiskAlignment.Aligned : DiskAlignment.Misaligned); getDisk().setLastAlignmentScan(new Date()); getBaseDiskDao().update(getDisk()); setSucceeded(true); releaseExclusiveDiskLocks(); }
Source:
public double yieldFromPrice(double price, LocalDate settlementDate) { double accrualFactor = dayCount.relativeYearFraction(settlementDate, notional.getDate().getUnadjusted()); if (yieldConvention.equals(DISCOUNT)) { return (1.0d - price) / accrualFactor; } if (yieldConvention.equals(INTEREST_AT_MATURITY) || yieldConvention.equals(FRANCE_CD) || yieldConvention.equals(JAPAN_BILLS)) { return (1.0d / price - 1) / accrualFactor; } throw new UnsupportedOperationException("The convention " + yieldConvention.name() + " is not supported."); }

Target:
public double yieldFromPrice(double price, LocalDate settlementDate) { double accrualFactor = dayCount.relativeYearFraction(settlementDate, notional.getDate().getUnadjusted()); return yieldConvention.yieldFromPrice(price, accrualFactor); }
Source:
public AbstractGraphStatement setGraphKeyspace(String graphKeyspace) { if (graphKeyspace == null || graphKeyspace.isEmpty()) { throw new InvalidQueryException("You cannot set null value or empty string to the keyspace for the Graph, this field is mandatory."); } this.payload.put(GraphSession.GRAPH_LANGUAGE_KEY, ByteBuffer.wrap(graphKeyspace.getBytes())); return this; }

Target:
public AbstractGraphStatement setGraphKeyspace(String graphKeyspace) { if (graphKeyspace == null || graphKeyspace.isEmpty()) { throw new InvalidQueryException("You cannot set null value or empty string to the keyspace for the Graph, this field is mandatory."); } this.graphOptions.put(GraphSession.GRAPH_KEYSPACE_KEY, graphKeyspace); return this; }
Source:
public void handle(Willie bot, Command cmd, CommandType type, Channel channel, User sender, String[] args) { ConfigurationBuilder cb = new ConfigurationBuilder(); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); String handle = args[0]; if (!handle.startsWith("@")) { handle = "@" + handle; } try { Status status = twitter.showUser(handle).getStatus(); bot.send("(" + sender.getNick() + ")" + Colors.BOLD + "@" + status.getUser().getScreenName() + ": " + Colors.NORMAL + status.getText(), channel, sender, CommandType.SEND_CHANNEL); } catch (TwitterException e) { bot.send("(" + sender.getNick() + ") " + Colors.RED + "Failed to retrieve status for " + Colors.BOLD + args[0], channel, sender, CommandType.SEND_CHANNEL); e.printStackTrace(); } }

Target:
public void handle(Willie bot, Command cmd, CommandType type, Channel channel, User sender, String[] args) { ConfigurationBuilder cb = new ConfigurationBuilder(); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); String handle = args[0]; if (!handle.startsWith("@")) { handle = "@" + handle; } try { Status status = twitter.showUser(handle).getStatus(); bot.send("(" + sender.getNick() + ")" + Colors.BOLD + "@" + status.getUser().getScreenName() + ": " + Colors.NORMAL + status.getText(), channel, sender, type); } catch (TwitterException e) { bot.send("(" + sender.getNick() + ") " + Colors.RED + "Failed to retrieve status for " + Colors.BOLD + args[0], channel, sender, type); e.printStackTrace(); } }
Source:
private void populateTmpfs(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) { Object value = cattleServiceData.get(ServiceConstants.FIELD_TMPFS); if (value instanceof Map) { if (!((Map<?, ?>) value).isEmpty()) { Map<String, Object> map = (Map<String, Object>)value; Iterator<String> it = map.keySet().iterator(); ArrayList<String> list = new ArrayList<>(); while (it.hasNext()) { String key = it.next(); list.add(key); } composeServiceData.put("tmpfs", list); } } }

Target:
private void populateTmpfs(Map<String, Object> cattleServiceData, Map<String, Object> composeServiceData) { Object value = cattleServiceData.get(ServiceConstants.FIELD_TMPFS); if (value instanceof Map) { if (!((Map<?, ?>) value).isEmpty()) { Map<String, Object> map = (Map<String, Object>)value; Iterator<String> it = map.keySet().iterator(); ArrayList<String> list = new ArrayList<>(); while (it.hasNext()) { String key = it.next(); String option = ""; if (map.get(key) != null) { option = map.get(key).toString(); } list.add(key + ":" + option); } composeServiceData.put("tmpfs", list); } } }
Source:
public static void afterClass() { System.clearProperty(OCFL_ROOT_PROP); }

Target:
public static void afterClass() { System.clearProperty(OcflPropsConfig.FCREPO_OCFL_ROOT); }
Source:
public void suggestTime(@NonNull TimeSignal timeSignal) { enforceSetTimePermission(); long callerIdToken = Binder.clearCallingIdentity(); try { mHandler.post(() -> mTimeDetectorStrategy.suggestTime(timeSignal)); } finally { Binder.restoreCallingIdentity(callerIdToken); } }

Target:
public void suggestTime(@NonNull TimeSignal timeSignal) { enforceSetTimePermission(); Objects.requireNonNull(timeSignal); mHandler.post(() -> mTimeDetectorStrategy.suggestTime(timeSignal)); }
Source:
public void testCatalogEntitiesCommand() throws Exception { try { String[] args = {"catalog-entities"}; brooklynClient.run(args); assertThat(standardOut(), containsString("brooklyn.entity.basic.BasicEntity")); } catch (Exception e) { LOG.error("\nstdout="+standardOut()+"\nstderr="+standardErr()+"\n", e); throw e; } }

Target:
public void testCatalogEntitiesCommand() throws Exception { try { String[] args = {"catalog-entities"}; brooklynClient.run(args); assertThat(standardOut(), containsString(BasicEntity.class.getName())); } catch (Exception e) { LOG.error("\nstdout="+standardOut()+"\nstderr="+standardErr()+"\n", e); throw e; } }
Source:
public ItemsWidget(Context context, QuestionDetails prompt) { super(context, prompt); if (isFastExternalItemsetWidget()) { items = new FastExternalItemsReader(getFormEntryPrompt(), new XPathParseTool(), new ItemsetDbAdapter(), new FileUtil()).getItems(); } else { readItems(); } }

Target:
public ItemsWidget(Context context, QuestionDetails prompt) { super(context, prompt); if (isFastExternalItemsetUsed()) { readFastExternalItems(); } else if (isSearchPulldataItemsetUsed()) { readSearchPulldataItems(); } else { items = getFormEntryPrompt().getSelectChoices(); } }
Source:
static BasicMachineDetails forSshMachineLocation(SshMachineLocation location) { return DynamicTasks.queue(taskForSshMachineLocation(location)) .getUnchecked(); }

Target:
static BasicMachineDetails forSshMachineLocation(SshMachineLocation location) { return DynamicTasks.queueIfPossible(taskForSshMachineLocation(location)) .orSubmitAsync() .asTask() .getUnchecked(); }
Source:
private int[] entityTokenIds( List<SchemaDescriptor> nodeDescriptors ) { if ( nodeDescriptors.stream().anyMatch( descriptor -> descriptor.schema().getEntityTokenIds().length == 0 ) ) { return new int[0]; } return nodeDescriptors.stream().flatMapToInt( descriptor -> Arrays.stream( descriptor.schema().getEntityTokenIds() ) ).toArray(); }

Target:
private int[] entityTokenIds( List<SchemaDescriptor> nodeDescriptors ) { if ( nodeDescriptors.stream().anyMatch( descriptor -> Arrays.equals( descriptor.schema().getEntityTokenIds(), ANY_ENTITY_TOKEN ) ) ) { return ANY_ENTITY_TOKEN; } return nodeDescriptors.stream().flatMapToInt( descriptor -> Arrays.stream( descriptor.schema().getEntityTokenIds() ) ).toArray(); }
Source:
public OSFileStore[] getFileStores(boolean localOnly) { ArrayList<OSFileStore> result; result = getLocalVolumes(null); Map<String, OSFileStore> volumeMap = new HashMap<>(); for (OSFileStore volume : result) { volumeMap.put(volume.getMount(), volume); } for (OSFileStore wmiVolume : getWmiVolumes(null)) { if (volumeMap.containsKey(wmiVolume.getMount())) { volumeMap.get(wmiVolume.getMount()).setName(wmiVolume.getName()); } else { if (!localOnly) { result.add(wmiVolume); } } } return result.toArray(new OSFileStore[0]); }

Target:
public OSFileStore[] getFileStores(boolean localOnly) { ArrayList<OSFileStore> result; result = getLocalVolumes(null); Map<String, OSFileStore> volumeMap = new HashMap<>(); for (OSFileStore volume : result) { volumeMap.put(volume.getMount(), volume); } for (OSFileStore wmiVolume : getWmiVolumes(null, localOnly)) { if (volumeMap.containsKey(wmiVolume.getMount())) { volumeMap.get(wmiVolume.getMount()).setName(wmiVolume.getName()); } else if (!localOnly) { result.add(wmiVolume); } } return result.toArray(new OSFileStore[0]); }
Source:
public final boolean equals( Object other ) { if ( (other instanceof SequenceValue) && (this instanceof SequenceValue) ) { return ((SequenceValue) this).equals( (SequenceValue) other ); } return other != null && other instanceof VirtualValue && equals( (VirtualValue) other ); }

Target:
public final boolean equals( Object other ) { if ( other == null ) { return false; } if ( other instanceof SequenceValue && this.isSequenceValue() ) { return ((SequenceValue) this).equals( (SequenceValue) other ); } return other instanceof VirtualValue && equals( (VirtualValue) other ); }
Source:
private void testFetchSize() throws SQLException { if (config.memory && config.mvStore) { return; } org.h2.Driver.load(); Connection ca = DriverManager.getConnection("jdbc:h2:mem:one", "sa", "sa"); Connection cb = DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa"); Statement sa = ca.createStatement(); Statement sb = cb.createStatement(); sa.execute("DROP TABLE IF EXISTS TEST; " + "CREATE TABLE TEST as select st_makepoint(-60 + n*random()/500.00, 30 + n*random()/500.00), n as id from generate_series(1,1000) as n;"); String sql = "CREATE LINKED TABLE T(NULL, " + "'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') FETCH_SIZE 10"; sb.execute(sql); try (ResultSet rs = sb.executeQuery("SELECT * FROM T")) { assertTrue(rs.next()); assertEquals("POINT (1 1)", rs.getString("THE_GEOM")); } sb.execute("DROP TABLE T"); ca.close(); cb.close(); }

Target:
private void testFetchSize() throws SQLException { if (config.memory) { return; } org.h2.Driver.load(); Connection ca = DriverManager.getConnection("jdbc:h2:mem:one", "sa", "sa"); Connection cb = DriverManager.getConnection("jdbc:h2:mem:two", "sa", "sa"); Statement sa = ca.createStatement(); Statement sb = cb.createStatement(); sa.execute("DROP TABLE IF EXISTS TEST; " + "CREATE TABLE TEST as select * from SYSTEM_RANGE(1,1000) as n;"); String sql = "CREATE LINKED TABLE T(NULL, " + "'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') FETCH_SIZE 10"; sb.execute(sql); try (ResultSet rs = sb.executeQuery("SELECT count(*) FROM T")) { assertTrue(rs.next()); assertEquals(1000, rs.getInt(1)); } ResultSet res = sb.executeQuery("CALL DB_OBJECT_SQL('TABLE', 'PUBLIC', 'T')"); res.next(); assertEquals("CREATE FORCE LINKED TABLE \"PUBLIC\".\"T\"(NULL, 'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') FETCH_SIZE 10 ", res.getString(1)); sb.execute("DROP TABLE T"); ca.close(); cb.close(); }
Source:
private void beforeShowFeedInformation(Feed feed) { final HtmlToPlainText formatter = new HtmlToPlainText(); if (Feed.TYPE_ATOM1.equals(feed.getType()) && feed.getDescription() != null) { Log.d(TAG, "Removing HTML from feed description"); Document feedDescription = Jsoup.parse(feed.getDescription()); feed.setDescription(StringUtils.trim(formatter.getPlainText(feedDescription))); } Log.d(TAG, "Removing HTML from shownotes"); if (feed.getItems() != null) { for (FeedItem item : feed.getItems()) { if (item.getDescription() != null) { Document itemDescription = Jsoup.parse(item.getDescription()); item.setDescription(StringUtils.trim(formatter.getPlainText(itemDescription))); } } } }

Target:
private void beforeShowFeedInformation(Feed feed) { Log.d(TAG, "Removing HTML from feed description"); feed.setDescription(HtmlToPlainText.getPlainText(feed.getDescription())); Log.d(TAG, "Removing HTML from shownotes"); if (feed.getItems() != null) { for (FeedItem item : feed.getItems()) { item.setDescription(HtmlToPlainText.getPlainText(item.getDescription())); } } }
Source:
StorageObject open() throws StorageFileNotFoundException; } private final StorageManager storageManager; private final LoadingCache<ArchiveType, Storage> storageCache; private final ArchiveType uploadArchiveType; private final Config systemConfig; private final String pathPrefix; private final boolean directDownloadEnabled; @Inject public ArchiveManager(StorageManager storageManager, Config systemConfig) { this.storageManager = storageManager; this.storageCache = CacheBuilder.newBuilder() .maximumSize(2) .build( new CacheLoader<ArchiveType, Storage>() { public Storage load(ArchiveType key) { return openStorage(key); } }); this.systemConfig = systemConfig; this.uploadArchiveType = systemConfig.get("archive.type", ArchiveType.class, ArchiveType.DB); this.pathPrefix = getArchivePathPrefix(systemConfig, uploadArchiveType); this.directDownloadEnabled = systemConfig.get("archive." + uploadArchiveType + ".direct_download", Boolean.class, false); }

Target:
StorageObject open() throws StorageFileNotFoundException; } private final StorageManager storageManager; private final LoadingCache<ArchiveType, Storage> storageCache; private final ArchiveType uploadArchiveType; private final Config systemConfig; private final String pathPrefix; private final boolean directDownloadEnabled; @Inject public ArchiveManager(StorageManager storageManager, Config systemConfig) { this.storageManager = storageManager; this.storageCache = CacheBuilder.newBuilder() .maximumSize(2) .build( new CacheLoader<ArchiveType, Storage>() { public Storage load(ArchiveType type) { return openStorage(type); } }); this.systemConfig = systemConfig; this.uploadArchiveType = systemConfig.get("archive.type", ArchiveType.class, ArchiveType.DB); this.pathPrefix = getArchivePathPrefix(systemConfig, uploadArchiveType); this.directDownloadEnabled = systemConfig.get("archive." + uploadArchiveType + ".direct_download", Boolean.class, false); }
Source:
private static void getPackageExports(ModuleRevisionBuilder builder, ManifestElement[] exportElements, Collection<Map<String, Object>> exportedPackages) throws BundleException { if (exportElements == null) return; for (ManifestElement exportElement : exportElements) { String[] packageNames = exportElement.getValueComponents(); Map<String, Object> attributes = getAttributes(exportElement); Map<String, String> directives = getDirectives(exportElement); directives.remove(PackageNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE); String versionAttr = (String) attributes.remove(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); @SuppressWarnings("deprecation") String specVersionAttr = (String) attributes.remove(Constants.PACKAGE_SPECIFICATION_VERSION); Version version = versionAttr == null ? (specVersionAttr == null ? Version.emptyVersion : Version.parseVersion(specVersionAttr)) : Version.parseVersion(versionAttr); attributes.put(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, version); attributes.put(PackageNamespace.CAPABILITY_BUNDLE_SYMBOLICNAME_ATTRIBUTE, builder.getSymbolicName()); attributes.put(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, builder.getVersion()); for (String packageName : packageNames) { Map<String, Object> packageAttrs = new HashMap<>(attributes); packageAttrs.put(PackageNamespace.PACKAGE_NAMESPACE, packageName); builder.addCapability(PackageNamespace.PACKAGE_NAMESPACE, directives, packageAttrs); exportedPackages.add(packageAttrs); } } }

Target:
private static void getPackageExports(ModuleRevisionBuilder builder, ManifestElement[] exportElements, Collection<Map<String, Object>> exportedPackages) throws BundleException { if (exportElements == null) return; for (ManifestElement exportElement : exportElements) { String[] packageNames = exportElement.getValueComponents(); Map<String, Object> attributes = getAttributes(exportElement); Map<String, String> directives = getDirectives(exportElement); directives.remove(PackageNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE); String versionAttr = (String) attributes.remove(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); @SuppressWarnings("deprecation") String specVersionAttr = (String) attributes.remove(Constants.PACKAGE_SPECIFICATION_VERSION); Version version = versionAttr == null ? (specVersionAttr == null ? Version.emptyVersion : Version.parseVersion(specVersionAttr)) : Version.parseVersion(versionAttr); attributes.put(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, version); String symbolicName = builder.getSymbolicName(); if (symbolicName != null) { attributes.put(PackageNamespace.CAPABILITY_BUNDLE_SYMBOLICNAME_ATTRIBUTE, symbolicName); } attributes.put(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, builder.getVersion()); for (String packageName : packageNames) { Map<String, Object> packageAttrs = new HashMap<>(attributes); packageAttrs.put(PackageNamespace.PACKAGE_NAMESPACE, packageName); builder.addCapability(PackageNamespace.PACKAGE_NAMESPACE, directives, packageAttrs); exportedPackages.add(packageAttrs); } } }