auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } final String arg = args.get(0).eval(bindings).asString(); if (arg == null) { return ExprEval.of(null); } final int index = args.get(1).eval(bindings).asInt(); final int length = args.get(2).eval(bindings).asInt(); if (index < arg.length()) { if (length >= 0) { return ExprEval.of(arg.substring(index, Math.min(index + length, arg.length()))); } else { return ExprEval.of(arg.substring(index)); } } else { return ExprEval.of(NullHandlingUtil.nullToEmptyIfNeeded((String) null)); } }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } final String arg = args.get(0).eval(bindings).asString(); if (arg == null) { return ExprEval.of(null); } final int index = args.get(1).eval(bindings).asInt(); final int length = args.get(2).eval(bindings).asInt(); if (index < arg.length()) { if (length >= 0) { return ExprEval.of(arg.substring(index, Math.min(index + length, arg.length()))); } else { return ExprEval.of(arg.substring(index)); } } else { return ExprEval.of(NullHandling.defaultStringValue()); } }
Source:
public static DataSource createDataSource( final String jdbcUrl, final Properties properties ) { final DriverConnectionKey key = new DriverConnectionKey( jdbcUrl, properties ); final Object o = cache.get( key ); if ( o instanceof DataSource ) { return (DataSource) o; } final DriverManagerDataSource managerDataSource = new DriverManagerDataSource( jdbcUrl, properties ); cache.put( key, managerDataSource ); return managerDataSource; }

Target:
public static DataSource createDataSource( final String jdbcUrl, final Properties properties ) { final DriverConnectionKey key = new DriverConnectionKey( jdbcUrl, properties ); lock.readLock().lock(); try { final Object o = cache.get( key ); if ( o instanceof DataSource ) { return (DataSource) o; } } finally { lock.readLock().unlock(); } final DriverManagerDataSource managerDataSource = new DriverManagerDataSource( jdbcUrl, properties ); lock.writeLock().lock(); try { cache.put( key, managerDataSource ); } finally { lock.writeLock().unlock(); } return managerDataSource; }
Source:
private void fetchRangedGETResponse() throws IOException { if (rangedGETResponseStatus == 0) { ResourceInfo info; try { info = getResourceInfo(); } catch (InterruptedException | TimeoutException e) { LOGGER.error(e.getMessage(), e); throw new IOException(e); } catch (Exception e) { LOGGER.error("fetchRangedGETResponse(): {}", e.getMessage()); throw new IOException(e.getMessage(), e); } try { final HttpClient client = getHTTPClient(info); InputStreamResponseListener listener = new InputStreamResponseListener(); client.newRequest(info.getURI()) .timeout(getRequestTimeout(), TimeUnit.SECONDS) .header("Range", "bytes=0-" + (FORMAT_INFERENCE_RANGE_LENGTH - 1)) .method(HttpMethod.GET) .send(listener); Response response = listener.get(getRequestTimeout(), TimeUnit.SECONDS); rangedGETResponseStatus = response.getStatus(); rangedGETResponseHeaders = response.getHeaders(); rangedGETResponseEntity = IOUtils.toByteArray(listener.getInputStream()); } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new IOException(e); } } }

Target:
private void fetchRangedGETResponse() throws IOException { if (rangedGETResponseStatus == 0) { ResourceInfo info; try { info = getResourceInfo(); } catch (InterruptedException | TimeoutException e) { LOGGER.error(e.getMessage(), e); throw new IOException(e); } catch (Exception e) { LOGGER.error("fetchRangedGETResponse(): {}", e.getMessage()); throw new IOException(e.getMessage(), e); } try { final HttpClient client = getHTTPClient(info); InputStreamResponseListener listener = new InputStreamResponseListener(); client.newRequest(info.getURI()) .timeout(getRequestTimeout(), TimeUnit.SECONDS) .header("Range", "bytes=0-" + (FORMAT_INFERENCE_RANGE_LENGTH - 1)) .method(HttpMethod.GET) .send(listener); Response response = listener.get(getRequestTimeout(), TimeUnit.SECONDS); rangedGETResponseStatus = response.getStatus(); rangedGETResponseHeaders = response.getHeaders(); try(InputStream ris = listener.getInputStream()) { rangedGETResponseEntity = IOUtils.toByteArray(ris); } catch (Exception e) { throw new IOException(e); } } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new IOException(e); } } }
Source:
private static byte[] compressGZIP(byte[] input) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(input, 0, input.length); gzip.close(); return out.toByteArray(); }

Target:
private static byte[] compressGZIP(byte[] input) { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(out); gzip.write(input, 0, input.length); } catch (IOException e) { return null; } finally { if (gzip != null) { try { gzip.close(); } catch (IOException e) { return null; } } } return out.toByteArray(); }
Source:
private BratTextAnnotation splitNewline(AnnotationFS aFS) { Pattern p = Pattern.compile("(.+?)(?:\\R|$)+", Pattern.DOTALL); Matcher m = p.matcher(aFS.getCoveredText()); int i = 0; while (m.find()) { i++; } int[] begins = new int[i]; int[] ends = new int[i]; m = p.matcher(aFS.getCoveredText()); i = 0; while (m.find()) { System.out.println(m.group(1)); begins[i] = m.start(1) + aFS.getBegin(); ends[i] = m.end(1) + aFS.getBegin(); i++; } return new BratTextAnnotation(nextTextAnnotationId, getBratType(aFS.getType()), begins, ends, new String[] { aFS.getCoveredText().replaceAll("\\R+", " ") }); }

Target:
private BratTextAnnotation splitNewline(AnnotationFS aFS) { Matcher m = NEWLINE_EXTRACT_PATTERN.matcher(aFS.getCoveredText()); List<Offsets> offsets = new ArrayList<>(); while (m.find()) { Offsets offset = new Offsets(m.start(1) + aFS.getBegin(), m.end(1) + aFS.getBegin() ); offsets.add(offset); } String[] texts = new String[] { aFS.getCoveredText().replaceAll("\\R+", " ") }; return new BratTextAnnotation(nextTextAnnotationId, getBratType(aFS.getType()), offsets, texts); }
Source:
public static VariantContext subsetVCToMatchSnp(final VariantContext ctx, final Snp snp) { if (ctx.isFiltered()) return null; if (ctx.getReference().length() != 1) return null; final Optional<Byte> referenceAlleleMaybe = Stream.of(snp.getAllele1(), snp.getAllele2()) .filter(b -> b == ctx.getReference().getBases()[0]).findAny(); if (!referenceAlleleMaybe.isPresent()) return null; final byte refAllele = referenceAlleleMaybe.get(); final byte otherAllele = snp.getAllele1() == refAllele ? snp.getAllele2() : snp.getAllele1(); final Optional<Allele> altAlleleMaybe = ctx.getAlternateAlleles() .stream() .filter(a -> a.length() == 1 && a.getBases()[0] == otherAllele) .findAny(); if (altAlleleMaybe.isPresent()) { if (ctx.getAlleles().size() == 2) return ctx; return AlleleSubsettingUtils.subsetAlleles(ctx, Arrays.asList(ctx.getReference(), altAlleleMaybe.get())); } final Optional<Allele> nonRefAlleleMaybe = ctx.getAlternateAlleles().stream().filter(a -> a.equals(NON_REF_ALLELE)).findAny(); if (nonRefAlleleMaybe.isPresent()) { final VariantContext vcSubsetted = ctx.getAlleles().size() == 2 ? ctx : AlleleSubsettingUtils.subsetAlleles(ctx, Arrays.asList(ctx.getReference(), nonRefAlleleMaybe.get())); return AlleleSubsettingUtils.swapAlleles(vcSubsetted, NON_REF_ALLELE, Allele.create(otherAllele)); } return null; }

Target:
public static VariantContext subsetVCToMatchSnp(final VariantContext ctx, final Snp snp) { if (ctx.isFiltered()) return null; if (ctx.getReference().length() != 1) return null; final Optional<Byte> referenceAlleleMaybe = Stream.of(snp.getAllele1(), snp.getAllele2()) .filter(b -> b == ctx.getReference().getBases()[0]).findAny(); if (!referenceAlleleMaybe.isPresent()) return null; final byte refAllele = referenceAlleleMaybe.get(); final byte otherAllele = snp.getAllele1() == refAllele ? snp.getAllele2() : snp.getAllele1(); final Optional<Allele> altAlleleMaybe = ctx.getAlternateAlleles() .stream() .filter(a -> a.length() == 1 && a.getBases()[0] == otherAllele) .findAny(); if (altAlleleMaybe.isPresent()) { if (ctx.isBiallelic()) return ctx; return AlleleSubsettingUtils.subsetAlleles(ctx, Arrays.asList(ctx.getReference(), altAlleleMaybe.get())); } final Optional<Allele> nonRefAlleleMaybe = ctx.getAlternateAlleles().stream().filter(a -> a.equals(NON_REF_ALLELE)).findAny(); if (nonRefAlleleMaybe.isPresent()) { final VariantContext vcSubsetted = ctx.isBiallelic() ? ctx : AlleleSubsettingUtils.subsetAlleles(ctx, Arrays.asList(ctx.getReference(), nonRefAlleleMaybe.get())); return AlleleSubsettingUtils.swapAlleles(vcSubsetted, NON_REF_ALLELE, Allele.create(otherAllele)); } return null; }
Source:
protected void prepareExecution() throws KettleException { if ( service.isStreaming() ) { prepareStreamingExecution(); } else { prepareDefaultExecution(); } }

Target:
protected void prepareExecution() throws KettleException { ImmutableMultimap.Builder<ExecutionPoint, Runnable> builder = ImmutableMultimap.builder(); builder.putAll( ExecutionPoint.PREPARE, new CopyParameters( parameters, serviceTrans ), new PrepareExecution( serviceTrans ) ); if ( !service.isStreaming() ) { builder.put( ExecutionPoint.PREPARE, new PrepareExecution( genTrans ) ); builder.putAll( ExecutionPoint.READY, new DefaultTransWiring( this ) ); builder.putAll( ExecutionPoint.START, new TransStarter( genTrans ), new TransStarter( serviceTrans ) ); } listenerMap.putAll( builder.build() ); }
Source:
private static void checkIfSdcardSymlinkSameAsExternalStorageDirectory() { isSdcardSymlinkChecked = true; try { File shortPathFile = File.createTempFile("odk", null, new File("/sdcard")); String name = shortPathFile.getName(); File longPathFile = new File(Environment.getExternalStorageDirectory(), name); if (shortPathFile.exists() && longPathFile.exists()) { longPathFile.delete(); if (!shortPathFile.exists()) { isSdcardSymlinkSameAsExternalStorageDirectory = true; return; } } } catch (IOException e) { } isSdcardSymlinkSameAsExternalStorageDirectory = false; }

Target:
private static void checkIfSdcardSymlinkSameAsExternalStorageDirectory() { try { File shortPathFile = File.createTempFile("odk", null, new File("/sdcard")); try { String name = shortPathFile.getName(); File longPathFile = new File(Environment.getExternalStorageDirectory(), name); if (shortPathFile.exists() && longPathFile.exists()) { longPathFile.delete(); if (!shortPathFile.exists()) { isSdcardSymlinkSameAsExternalStorageDirectory = true; return; } } } finally { shortPathFile.delete(); } } catch (IOException e) { } isSdcardSymlinkSameAsExternalStorageDirectory = false; }
Source:
public void logsIn() throws Exception { final String octocat = "octocat"; final String urn = "urn:google:1"; final Take take = new TkFork( this.requestToken(), new FkRegex( PsGoogleTest.REGEX_PATTERN, new Take() { @Override public Response act(final Request req) throws IOException { MatcherAssert.assertThat( new RqPrint(req).printHead(), Matchers.containsString( PsGoogleTest.ACT_HEAD ) ); MatcherAssert.assertThat( new RqHref.Base(req).href() .param(PsGoogleTest.ACCESS_TOKEN) .iterator().next(), Matchers.containsString(PsGoogleTest.GOOGLE_TOKEN) ); return new RsJson( jsonBuilder("1").add("displayName", octocat).build() ); } } ) ); new FtRemote(take).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { final Identity identity = new PsGoogle( PsGoogleTest.APP, PsGoogleTest.KEY, PsGoogleTest.ACCOUNT, home.toString(), home.toString() ).enter( new RqFake(PsGoogleTest.GET, PsGoogleTest.CODE_PARAM) ).get(); MatcherAssert.assertThat( identity.urn(), Matchers.equalTo(urn) ); MatcherAssert.assertThat( identity.properties().get(PsGoogleTest.NAME), Matchers.equalTo(octocat) ); MatcherAssert.assertThat( identity.properties().get(PsGoogleTest.PICTURE), Matchers.equalTo(PsGoogleTest.AVATAR) ); } } ); }

Target:
public void logsIn() throws Exception { final String octocat = "octocat"; final String urn = "urn:google:1"; final Take take = new TkFork( this.requestToken(), new FkRegex( PsGoogleTest.REGEX_PATTERN, new Take() { @Override public Response act(final Request req) throws IOException { MatcherAssert.assertThat( new RqPrint(req).printHead(), Matchers.containsString( PsGoogleTest.ACT_HEAD ) ); MatcherAssert.assertThat( new RqHref.Base(req).href() .param(PsGoogleTest.ACCESS_TOKEN) .iterator().next(), Matchers.containsString(PsGoogleTest.GOOGLE_TOKEN) ); return new RsJson( Json.createObjectBuilder() .add("displayName", octocat) .add("id", "1") .add( PsGoogleTest.IMAGE, Json.createObjectBuilder() .add( PsGoogleTest.URL, PsGoogleTest.AVATAR ) ) .build() ); } } ) ); new FtRemote(take).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { final Identity identity = new PsGoogle( PsGoogleTest.APP, PsGoogleTest.KEY, PsGoogleTest.ACCOUNT, home.toString(), home.toString() ).enter( new RqFake(PsGoogleTest.GET, PsGoogleTest.CODE_PARAM) ).get(); MatcherAssert.assertThat( identity.urn(), Matchers.equalTo(urn) ); MatcherAssert.assertThat( identity.properties().get(PsGoogleTest.NAME), Matchers.equalTo(octocat) ); MatcherAssert.assertThat( identity.properties().get(PsGoogleTest.PICTURE), Matchers.equalTo(PsGoogleTest.AVATAR) ); } } ); }
Source:
private void newTestSubject(int cachedEvents, long fetchDelay, long cleanupDelay) { Optional.ofNullable(testSubject).ifPresent(EmbeddedEventStore::shutDown); testSubject = new EmbeddedEventStore(storageEngine, NoOpMessageMonitor.INSTANCE, cachedEvents, fetchDelay, cleanupDelay, MILLISECONDS, SnapshotResolver.lastSnapshotResolver()); }

Target:
private void newTestSubject(int cachedEvents, long fetchDelay, long cleanupDelay) { Optional.ofNullable(testSubject).ifPresent(EmbeddedEventStore::shutDown); testSubject = new EmbeddedEventStore(storageEngine, NoOpMessageMonitor.INSTANCE, cachedEvents, fetchDelay, cleanupDelay, MILLISECONDS); }
Source:
private String getTopicName(Datastream datastream) { URI sourceUri = URI.create(datastream.getSource().getConnectionString()); String path = sourceUri.getPath().replace("/", "_").replaceAll(REGEX_NON_ALPHA, ""); return String.format("%s_%s", path, UUID.randomUUID()); }

Target:
private String getTopicName(Datastream datastream) { URI sourceUri = URI.create(datastream.getSource().getConnectionString()); String path = sourceUri.getAuthority() + sourceUri.getPath(); path = path.replace("/", "_").replaceAll(REGEX_NON_ALPHA, ""); return String.format("%s_%s", path, UUID.randomUUID()); }
Source:
public Money getStickerPrice() { if(null == unit && getChildParts().isEmpty()) { return alternateCost; } Money cost = Money.zero(); switch(weightClass) { case EntityWeightClass.WEIGHT_MEDIUM: cost = cost.plus(100000); if(jumpType == EntityMovementMode.VTOL) { cost = cost.plus(jumpMP * 100000); } else { cost = cost.plus(jumpMP * 75000); } break; case EntityWeightClass.WEIGHT_HEAVY: cost = cost.plus(200000); if(jumpType == EntityMovementMode.INF_UMU) { cost = cost.plus(jumpMP * 100000); } else { cost = cost.plus(jumpMP * 150000); } break; case EntityWeightClass.WEIGHT_ASSAULT: cost = cost.plus(400000); if(jumpType == EntityMovementMode.INF_UMU) { cost = cost.plus(jumpMP * 150000); } else { cost = cost.plus(jumpMP * 300000); } break; default: cost = cost.plus(50000 * (jumpMP + 1)); } cost = cost.plus(25000 * (groundMP-1)); for(Part p : getChildParts()) { if (p instanceof BaArmor) { cost = cost.plus(p.getCurrentValue()); } else if (!(p instanceof BattleArmorSuit)) { cost = cost.plus(p.getStickerPrice()); } } return cost; }

Target:
public Money getStickerPrice() { if ((null == unit) && getChildParts().isEmpty()) { return alternateCost; } Money cost = Money.zero(); switch(weightClass) { case EntityWeightClass.WEIGHT_MEDIUM: cost = cost.plus(100000); if(jumpType == EntityMovementMode.VTOL) { cost = cost.plus(jumpMP * 100000); } else { cost = cost.plus(jumpMP * 75000); } break; case EntityWeightClass.WEIGHT_HEAVY: cost = cost.plus(200000); if(jumpType == EntityMovementMode.INF_UMU) { cost = cost.plus(jumpMP * 100000); } else { cost = cost.plus(jumpMP * 150000); } break; case EntityWeightClass.WEIGHT_ASSAULT: cost = cost.plus(400000); if(jumpType == EntityMovementMode.INF_UMU) { cost = cost.plus(jumpMP * 150000); } else { cost = cost.plus(jumpMP * 300000); } break; default: cost = cost.plus(50000 * (jumpMP + 1)); } cost = cost.plus(25000 * (groundMP-1)); for (Part p : getChildParts()) { if (p instanceof BaArmor) { cost = cost.plus(p.getCurrentValue()); } else if (!(p instanceof BattleArmorSuit)) { cost = cost.plus(p.getStickerPrice()); } } return cost; }
Source:
public final ModelAndView display(String idString, ModelMap model) throws IOException { return prepare(model, create, verb + " " + qcTarget + " QCs", parseIds(idString).stream().flatMap(WhineyFunction.log(log, this::load)) .collect(Collectors.toList())); }

Target:
public final ModelAndView display(String idString, ModelMap model) throws IOException { return prepare(model, create, verb + " " + qcTarget + " QCs", parseIds(idString).stream().flatMap(WhineyFunction.rethrow(this::load)) .collect(Collectors.toList())); }
Source:
protected int countChildrenOf(IResource checkResource) throws CoreException { if (checkResource.getType() == IResource.FILE) { return 1; } int count = 0; if (checkResource.isAccessible()) { for (IResource resource : ((IContainer) checkResource).members()) { count += countChildrenOf(resource); } } return count; }

Target:
protected int countChildrenOf(IResource checkResource) throws CoreException { if (checkResource.getType() == IResource.FILE) { return 1; } int count = 0; if (checkResource.isAccessible()) { for (IResource child : ((IContainer) checkResource).members()) { count += countChildrenOf(child); } } return count; }
Source:
private void checkThresholdsRelation(List<Limit> inputList) { List<Limit> limitsWithErrors = new ArrayList<Limit>(); for(Limit limit : inputList) { if (limit.getLEL() > limit.getLWL()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. LEL "+ limit.getLEL() + " should be less than LWL " + limit.getLWL()); continue; } if (limit.getLWL() > limit.getUWL()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. LWL " + limit.getLWL() + " should be less than UWL " + limit.getUWL()); continue; } if (limit.getUWL() > limit.getUEL()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. UWL " + limit.getUWL() + " should be less than UEL " + limit.getUEL()); continue; } } inputList.removeAll(limitsWithErrors); }

Target:
private void checkThresholdsRelation(List<Limit> inputList) { List<Limit> limitsWithErrors = new ArrayList<Limit>(); for(Limit limit : inputList) { if (limit.getLowerErrorThreshold() > limit.getLowerWarningThreshold()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. LowerErrorThreshold "+ limit.getLowerErrorThreshold() + " should be less than LowerWarningThreshold " + limit.getLowerWarningThreshold()); continue; } if (limit.getLowerWarningThreshold() > limit.getUpperWarningThreshold()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. LowerWarningThreshold " + limit.getLowerWarningThreshold() + " should be less than UpperWarningThreshold " + limit.getUpperWarningThreshold()); continue; } if (limit.getUpperWarningThreshold() > limit.getUpperErrorThreshold()) { limitsWithErrors.add(limit); log.error("Limit with metricName '" + limit.getMetricName() + "' has wrong relation of thresholds. UpperWarningThreshold " + limit.getUpperWarningThreshold() + " should be less than UpperErrorThreshold " + limit.getUpperErrorThreshold()); continue; } } inputList.removeAll(limitsWithErrors); }
Source:
private static byte[] downloadBlob( GrpcRemoteDownloader downloader, URL url, Optional<Checksum> checksum) throws IOException, InterruptedException { final List<URL> urls = ImmutableList.<URL>of(url); com.google.common.base.Optional<Checksum> guavaChecksum = com.google.common.base.Optional.<Checksum>absent(); if (checksum.isPresent()) { guavaChecksum = com.google.common.base.Optional.<Checksum>of(checksum.get()); } final Map<URI, Map<String, String>> authHeaders = ImmutableMap.<URI, Map<String, String>>of(); final String canonicalId = ""; final ExtendedEventHandler eventHandler = mock(ExtendedEventHandler.class); final Map<String, String> clientEnv = ImmutableMap.<String, String>of(); Scratch scratch = new Scratch(); final Path destination = scratch.resolve("output file path"); downloader.download( urls, authHeaders, guavaChecksum, canonicalId, destination, eventHandler, clientEnv); try (InputStream in = destination.getInputStream()) { return ByteStreams.toByteArray(in); } }

Target:
private static byte[] downloadBlob( GrpcRemoteDownloader downloader, URL url, Optional<Checksum> checksum) throws IOException, InterruptedException { final List<URL> urls = ImmutableList.of(url); com.google.common.base.Optional<Checksum> guavaChecksum = com.google.common.base.Optional.<Checksum>absent(); if (checksum.isPresent()) { guavaChecksum = com.google.common.base.Optional.<Checksum>of(checksum.get()); } final Map<URI, Map<String, String>> authHeaders = ImmutableMap.of(); final String canonicalId = ""; final ExtendedEventHandler eventHandler = mock(ExtendedEventHandler.class); final Map<String, String> clientEnv = ImmutableMap.of(); Scratch scratch = new Scratch(); final Path destination = scratch.resolve("output file path"); downloader.download( urls, authHeaders, guavaChecksum, canonicalId, destination, eventHandler, clientEnv); try (InputStream in = destination.getInputStream()) { return ByteStreams.toByteArray(in); } }
Source:
public void removeStandaloneMenuItems(Menu menu) { removeItem(R.id.pocketpaint_nav_save_image); removeItem(R.id.pocketpaint_nav_save_duplicate); removeItem(R.id.pocketpaint_nav_new_image); }

Target:
public void removeStandaloneMenuItems(Menu menu) { menu.removeItem(R.id.pocketpaint_nav_save_image); menu.removeItem(R.id.pocketpaint_nav_save_duplicate); menu.removeItem(R.id.pocketpaint_nav_new_image); }
Source:
public String toString() { return "LeastBytesUsedStorageLocationSelectorStrategy{" + "ordering=" + ORDERING + ", storageLocations=" + storageLocations + '}'; }

Target:
public String toString() { return "LeastBytesUsedStorageLocationSelectorStrategy{" + "storageLocations=" + storageLocations + '}'; }
Source:
public void testTransform_nullParams() throws Exception { verifyZeroInteractions(layer); }

Target:
public void testTransform_nullParams() throws Exception { transformer.transform(layer, null); verifyZeroInteractions(layer); }
Source:
public static String generateMarkdownSnippet(String id, Set<FactoryImage> factoryImages, String style, URI baseUri) { String factoryURL = UriBuilder.fromUri(baseUri).replacePath("factory").queryParam("id", id).build().toString(); StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); switch (style) { case "Advanced": case "Advanced with Counter": formatter.format("[![alt](%1$s/api/factory/%2$s/image?imgId=%3$s)](%4$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), id, factoryImages.iterator().next().getName(), factoryURL); break; case "White": case "Horizontal,White": case "Vertical,White": formatter.format("[![alt](%1$s/factory/resources/factory-white.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), factoryURL); break; case "Dark": case "Horizontal,Dark": case "Vertical,Dark": formatter.format("[![alt](%1$s/factory/resources/factory-dark.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), factoryURL); break; default: throw new IllegalArgumentException("Invalid factory style."); } return sb.toString(); }

Target:
public static String generateMarkdownSnippet(String id, Set<FactoryImage> factoryImages, String style, URI baseUri) { String factoryURL = UriBuilder.fromUri(baseUri).replacePath("factory").queryParam("id", id).build().toString(); Formatter formatter = new Formatter(); switch (style) { case "Advanced": case "Advanced with Counter": if (factoryImages.size() > 0) { formatter.format("[![alt](%1$s/api/factory/%2$s/image?imgId=%3$s)](%4$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), id, factoryImages.iterator().next().getName(), factoryURL); } else { throw new IllegalArgumentException("Factory with advanced style MUST have at leas one image."); } break; case "White": case "Horizontal,White": case "Vertical,White": formatter.format("[![alt](%1$s/factory/resources/factory-white.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), factoryURL); break; case "Dark": case "Horizontal,Dark": case "Vertical,Dark": formatter.format("[![alt](%1$s/factory/resources/factory-dark.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), factoryURL); break; default: throw new IllegalArgumentException("Invalid factory style."); } return formatter.toString(); }
Source:
public DataTransactionResult set(DataHolder dataHolder, FlyingData manipulator, MergeFunction function) { return null; }

Target:
public DataTransactionResult set(DataHolder dataHolder, FlyingData manipulator, MergeFunction function) { if (this.supports(dataHolder)) { final FlyingData merged = checkNotNull(function, "MergeFunction cannot be null!").merge(checkNotNull(manipulator).copy(), from(dataHolder).orNull()); manipulator.set(Keys.IS_FLYING, merged.flying().get()); final ImmutableValue<Boolean> oldFlying = merged.flying().asImmutable(); final boolean value = merged.flying().get(); if (dataHolder instanceof EntityPlayer) { ((EntityPlayer) (dataHolder)).capabilities.isFlying = value; } else { ((Entity) (dataHolder)).isAirBorne = value; } return DataTransactionBuilder.successReplaceResult( ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_FLYING, oldFlying.get(), false), (ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_FLYING, value, false))); } return DataTransactionBuilder.failResult(manipulator.getValues()); }
Source:
private void setupDynamicMdcFieldTypes(PropertyProvider propertyProvider) { int fieldNumber = 0; while (true) { final String property = propertyProvider.getProperty(PropertyProvider.PROPERTY_DYNAMIC_MDC_FIELD_TYPES + fieldNumber); if (null == property) { break; } final int index = property.indexOf('='); if (-1 != index) { String field = property.substring(0, index); String type = property.substring(index + 1); setDynamicMdcFieldType(field, type); } fieldNumber++; } }

Target:
private void setupDynamicMdcFieldTypes(PropertyProvider propertyProvider) { int fieldNumber = 0; while (true) { String property = propertyProvider.getProperty(PropertyProvider.PROPERTY_DYNAMIC_MDC_FIELD_TYPES + fieldNumber); if (null == property) { break; } int index = property.indexOf('='); if (-1 != index) { String field = property.substring(0, index); String type = property.substring(index + 1); setDynamicMdcFieldType(field, type); } fieldNumber++; } }
Source:
public static <E extends Enum<E>> String validateEnum(String reason, String detail, Class<E> clz,Set<String> externalValues, String name, boolean toUppercase) { if (externalValues.contains(name)) { return name; } try { return Enum.valueOf(clz, toUppercase ? name.toUpperCase() : name).name(); } catch (IllegalArgumentException e) { detail = detail + getPossibleValues(clz, OsTypeUtils.getAllValues()); throw new WebApplicationException(response(reason, MessageFormat.format(detail, name, clz.getSimpleName()))); } }

Target:
public static <E extends Enum<E>> String validateEnum(String reason, String detail, Class<E> clz,Set<String> externalValues, String name, boolean toUppercase) { if (externalValues.contains(toUppercase ? name.toUpperCase() : name)) { return name; } try { return Enum.valueOf(clz, toUppercase ? name.toUpperCase() : name).name(); } catch (IllegalArgumentException e) { detail = detail + getPossibleValues(clz, OsTypeUtils.getAllValues()); throw new WebApplicationException(response(reason, MessageFormat.format(detail, name, clz.getSimpleName()))); } }
Source:
DefaultSyncPoller(Duration pollInterval, Function<PollingContext<T>, PollResponse<T>> syncActivationOperation, Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation, BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation, Function<PollingContext<T>, Mono<U>> fetchResultOperation) { Objects.requireNonNull(pollInterval, "'defaultPollInterval' cannot be null."); if (pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.defaultPollInterval = pollInterval; Objects.requireNonNull(syncActivationOperation, "'syncActivationOperation' cannot be null."); this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null."); this.cancelOperation = Objects.requireNonNull(cancelOperation, "'cancelOperation' cannot be null."); this.fetchResultOperation = Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null."); this.activationResponse = syncActivationOperation.apply(this.pollingContext); this.pollingContext.setOnetimeActivationResponse(this.activationResponse); this.pollingContext.setLatestResponse(this.activationResponse); }

Target:
DefaultSyncPoller(Duration pollInterval, Function<PollingContext<T>, PollResponse<T>> syncActivationOperation, Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation, BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation, Function<PollingContext<T>, Mono<U>> fetchResultOperation) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.defaultPollInterval = pollInterval; Objects.requireNonNull(syncActivationOperation, "'syncActivationOperation' cannot be null."); this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null."); this.cancelOperation = Objects.requireNonNull(cancelOperation, "'cancelOperation' cannot be null."); this.fetchResultOperation = Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null."); this.activationResponse = syncActivationOperation.apply(this.pollingContext); this.pollingContext.setOnetimeActivationResponse(this.activationResponse); this.pollingContext.setLatestResponse(this.activationResponse); }
Source:
public void run() { while (!kernel.isConnected()) { try { this.coordinator.registerNode(kernel.getContext(), kernel.getWorkers(), new StatusChangeListener() { @Override public void onNodeStatusChanged(NodeId nodeId, NodeStatus status) { } @Override public void onCoordinatorDisconnected() { } @Override public void onCoordinatorConnected() { } }); kernel.setConnected(true); } catch (Throwable e) { log.info("ThreadId {}. KernelID Unable to connect to Coordinator. Waiting for ms", new Object[]{Thread.currentThread().getId(), kernel.getKernelId(), kernel.getReconnectPeriod()}); log.warn("cause: ", e); try { Thread.sleep(kernel.getReconnectPeriod()); } catch (InterruptedException ee) { log.warn("Reconnection thread was interrupted", ee); } } } }

Target:
public void run() { while (!kernel.isConnected()) { try { this.coordinator.registerNode(kernel.getContext(), kernel.getWorkers(), new StatusChangeListener() { @Override public void onNodeStatusChanged(NodeId nodeId, NodeStatus status) { } @Override public void onCoordinatorDisconnected() { } @Override public void onCoordinatorConnected() { } }); kernel.setConnected(true); } catch (Throwable e) { log.warn("ThreadId {}. KernelID Unable to connect to Coordinator. Waiting for ms", new Object[]{Thread.currentThread().getId(), kernel.getKernelId(), kernel.getReconnectPeriod()}); log.warn("cause: ", e); try { Thread.sleep(kernel.getReconnectPeriod()); } catch (InterruptedException ee) { log.warn("Reconnection thread was interrupted", ee); } } } }
Source:
public Map<String, String> extractStoreConfigs(String name) { Map<String, String> configs = new HashMap<>(); for (Map.Entry<String, String> store : storeConfigs.entrySet()) { if (store.getKey().startsWith(name)) { configs.put(store.getKey().replace(name + ".", ""), store.getValue()); } } return configs; }

Target:
public Map<String, String> extractStoreConfigs(String name) { Map<String, String> configs = new HashMap<>(); for (Map.Entry<String, String> store : storeConfigs.entrySet()) { if (store.getKey().startsWith(name)) { configs.put(store.getKey().replaceFirst(name + ".", ""), store.getValue()); } } return configs; }
Source:
public void preImport(final SubMonitor subMonitor) { subMonitor.setWorkRemaining(importers.size()); for (final Importer importer : importers) { importer.preImport(subMonitor.newChild(1, SubMonitor.SUPPRESS_NONE)); } if (getImportBranchPath().getPath().equals(IBranchPath.MAIN_BRANCH)) { getExistingVersions(importContext.getEditingContext()); } else { try (SnomedEditingContext snomedEditingContext = new SnomedEditingContext(BranchPathUtils.createMainPath())) { getExistingVersions(snomedEditingContext); } } }

Target:
public void preImport(final SubMonitor subMonitor) { subMonitor.setWorkRemaining(importers.size()); for (final Importer importer : importers) { importer.preImport(subMonitor.newChild(1, SubMonitor.SUPPRESS_NONE)); } collectExistingVersions(); }
Source:
private static void copyDirectory(File src, File dest) { for (String current : src.list()) { final File srcFile = new File(src, current); final File destFile = new File(dest, current); if (srcFile.isDirectory()) { destFile.mkdir(); copyDirectory(srcFile, destFile); } else { try { final InputStream in = new BufferedInputStream(new FileInputStream(srcFile)); final OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); try { int i; while ((i = in.read()) != -1) { out.write(i); } } catch (IOException e) { throw ServerLogger.ROOT_LOGGER.errorCopyingFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath(), e); } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(out); } } catch (FileNotFoundException e) { throw EmbeddedLogger.ROOT_LOGGER.cannotSetupEmbeddedServer(e); } } } }

Target:
private static void copyDirectory(File src, File dest) { for (String current : src.list()) { final File srcFile = new File(src, current); final File destFile = new File(dest, current); try { Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); if (srcFile.isDirectory()) { copyDirectory(srcFile, destFile); } } catch (IOException e) { throw ServerLogger.ROOT_LOGGER.errorCopyingFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath(), e); } } }
Source:
public static String getSelectedElementUUID(ClientSession clientSession) { SelectionControl selectionControl = null; if (clientSession instanceof EditorSession) { selectionControl = ((EditorSession) clientSession).getSelectionControl(); } else if (clientSession instanceof ViewerSession) { selectionControl = ((ViewerSession) clientSession).getSelectionControl(); } if (selectionControl != null) { @SuppressWarnings("unchecked") final Collection<String> selectedItems = selectionControl.getSelectedItems(); if (selectedItems != null && !selectedItems.isEmpty()) { return selectedItems.iterator().next(); } } return null; }

Target:
public static String getSelectedElementUUID(ClientSession clientSession) { Optional<Collection<String>> selectedItems = Optional.empty(); if (clientSession instanceof EditorSession) { selectedItems = Optional.ofNullable(((EditorSession) clientSession).getSelectionControl().getSelectedItems()); } else if (clientSession instanceof ViewerSession) { selectedItems = Optional.ofNullable(((ViewerSession) clientSession).getSelectionControl().getSelectedItems()); } return selectedItems.map(strings -> strings.stream().findFirst().orElse(null)).orElse(null); }
Source:
public void run() { long now = System.currentTimeMillis(); lastUpdateTimeMs = now; List<RawPacket> pkts = report(); if (pkts == null || pkts.isEmpty()) { return; } for (RawPacket pkt : pkts) { try { getStream().injectPacket( pkt, false, BasicRTCPTerminationStrategy.this); } catch (TransmissionFailedException e) { logger.error(e); } } }

Target:
public void run() { lastUpdateTimeMs = System.currentTimeMillis(); List<RawPacket> pkts = report(); if (pkts == null || pkts.isEmpty()) { return; } for (RawPacket pkt : pkts) { try { getStream().injectPacket( pkt, false, BasicRTCPTerminationStrategy.this); } catch (TransmissionFailedException e) { logger.error(e); } } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + fFilePath.hashCode(); result = prime * result + (int) (fOffset ^ (fOffset >>> 32)); return result; }

Target:
public int hashCode() { return Objects.hashCode(fFilePath, fOffset); }
Source:
protected boolean canDoAction() { boolean retVal = true; List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); retVal = canDoAction_beforeCloneVm(retVal, canDoActionMessages, domainsMap); if (retVal && getParameters().isImportAsNewEntity()) { initImportClonedVm(); } retVal = retVal && canDoAction_afterCloneVm(retVal, canDoActionMessages, domainsMap); if (!retVal) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } return retVal; }

Target:
protected boolean canDoAction() { boolean retVal = true; List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); retVal = canDoAction_beforeCloneVm(retVal, canDoActionMessages, domainsMap); if (retVal && getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return retVal && canDoAction_afterCloneVm(retVal, canDoActionMessages, domainsMap); }
Source:
public ActivationKey createActivationKey( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, ActivationKey activationKey) { Owner owner = findOwner(ownerKey); activationKey.setOwner(owner); if (activationKey.getName() == null || activationKey.getName().trim().equals("")) { throw new BadRequestException( i18n.tr("Must provide a name for activation key.")); } String testName = activationKey.getName().replace("-", "0") .replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters '-' or '_'", activationKey.getName())); } if (activationKeyCurator.lookupForOwner(activationKey.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", activationKey.getName(), ownerKey)); } if (activationKey.getContentOverrides() != null) { contentOverrideValidator.validate(activationKey.getContentOverrides()); } if (activationKey.getServiceLevel() != null) { serviceLevelValidator.validate(owner, activationKey.getServiceLevel()); } ActivationKey newKey = activationKeyCurator.create(activationKey); sink.emitActivationKeyCreated(newKey); return newKey; }

Target:
public ActivationKey createActivationKey( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, ActivationKey activationKey) { Owner owner = findOwner(ownerKey); activationKey.setOwner(owner); if (activationKey.getName() == null || activationKey.getName().trim().equals("")) { throw new BadRequestException( i18n.tr("Must provide a name for activation key.")); } String testName = activationKey.getName().replace("-", "0") .replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters '-' or '_'", activationKey.getName())); } if (activationKeyCurator.lookupForOwner(activationKey.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", activationKey.getName(), ownerKey)); } if (activationKey.getContentOverrides() != null) { contentOverrideValidator.validate(activationKey.getContentOverrides()); } serviceLevelValidator.validate(owner, activationKey.getServiceLevel()); ActivationKey newKey = activationKeyCurator.create(activationKey); sink.emitActivationKeyCreated(newKey); return newKey; }
Source:
public void testJSEEJava8() throws IOException { assumeTrue(System.getProperty("java.version").startsWith("1.8")); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.Default_JSSE); assertTrue(Arrays.stream(OpenSSLSocketFactory.getDefaultFactory() .getSupportedCipherSuites()).noneMatch("GCM"::contains)); }

Target:
public void testJSEEJava8() throws IOException { assumeTrue(System.getProperty("java.version").startsWith("1.8")); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.Default_JSSE); assertThat(Arrays.stream(OpenSSLSocketFactory.getDefaultFactory() .getSupportedCipherSuites())).noneMatch("GCM"::contains); }
Source:
protected List<File> mGet(Message<?> message, Session<F> session, String remoteDirectory, String remoteFilename) throws IOException { if (this.options.contains(Option.RECURSIVE)) { if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) { logger.warn("File name pattern must be '*' when using recursion"); } if (this.options.contains(Option.NAME_ONLY)) { this.options.remove(Option.NAME_ONLY); } return mGetWithRecursion(message, session, remoteDirectory, remoteFilename); } else { remoteDirectory = (remoteDirectory != null ? remoteDirectory : "." + this.remoteFileTemplate.getRemoteFileSeparator()); return mGetWithoutRecursion(message, session, remoteDirectory, remoteFilename); } }

Target:
protected List<File> mGet(Message<?> message, Session<F> session, String remoteDirectory, String remoteFilename) throws IOException { if (this.options.contains(Option.RECURSIVE)) { if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) { logger.warn("File name pattern must be '*' when using recursion"); } if (this.options.contains(Option.NAME_ONLY)) { this.options.remove(Option.NAME_ONLY); } return mGetWithRecursion(message, session, remoteDirectory, remoteFilename); } else { return mGetWithoutRecursion(message, session, remoteDirectory, remoteFilename); } }
Source:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); throttled.json(); MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo("{}") ); }

Target:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); throttled.json(); }
Source:
public void testPackageLink() { when(menu.findMenuItemPath(NAVIGATOR)).thenReturn("menu/main/navigation/navigator"); when(menuReaderService.getMenu()).thenReturn(menu); LinkedList<NavigatorLink> expected = new LinkedList(); expected.add(NavigatorLink.create("menu/main/navigation/navigator/", "glyphicon-home")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/parentId", "parent")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/packId", "pack")); assertEquals(controller.getNavigatorLinks(entityTypeId), expected); }

Target:
public void testPackageLink() { when(menu.findMenuItemPath(NAVIGATOR)).thenReturn("menu/main/navigation/navigator"); when(menuReaderService.getMenu()).thenReturn(menu); List<NavigatorLink> expected = new LinkedList<>(); expected.add(NavigatorLink.create("menu/main/navigation/navigator/", "glyphicon-home")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/parentId", "parent")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/packId", "pack")); assertEquals(controller.getNavigatorLinks(entityTypeId), expected); }
Source:
public void testMissingProfile() { org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester tableRequirementTester = new org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester(); org.eclipse.uml2.uml.Package pck = UMLFactory.eINSTANCE.createPackage(); IStatus missingStereotypeNotAllowed = tableRequirementTester.isAllowed(pck); Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); }

Target:
public void testMissingProfile() { RequirementTableTester tableRequirementTester = new RequirementTableTester(); org.eclipse.uml2.uml.Package pck = UMLFactory.eINSTANCE.createPackage(); IStatus missingStereotypeNotAllowed = tableRequirementTester.isAllowed(pck); Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); }
Source:
public static LinkdEdge create(String id, AbstractVertex sourceV, AbstractVertex targetV, OnmsSnmpInterface sourceinterface, OnmsSnmpInterface targetInterface, String sourceAddr, String targetAddr, ProtocolSupported discoveredBy) { SimpleConnector source = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, sourceV.getId()+"-"+id+"-connector", sourceV); SimpleConnector target = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, targetV.getId()+"-"+id+"-connector", targetV); LinkdEdge edge = new LinkdEdge(id, source, target,discoveredBy); try { edge.setSourceNodeid(Integer.parseInt(sourceV.getId())); } catch (NumberFormatException e) { } try { edge.setTargetNodeid(Integer.parseInt(targetV.getId())); } catch (NumberFormatException e) { } edge.setSourceLabel(sourceV.getLabel()); edge.setTargetLabel(targetV.getLabel()); if (sourceinterface != null) { edge.setSourceIfIndex(sourceinterface.getIfIndex()); edge.setSourceIfName(sourceinterface.getIfName()); if (sourceinterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(sourceinterface.getIfSpeed())); } } if (targetInterface != null) { edge.setTargetIfIndex(targetInterface.getIfIndex()); edge.setTargetIfName(targetInterface.getIfName()); if (edge.getSpeed() == null && targetInterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(targetInterface.getIfSpeed())); } } edge.setSourceAddr(sourceAddr); edge.setTargetAddr(targetAddr); return edge; }

Target:
public static LinkdEdge create(String id, AbstractVertex sourceV, AbstractVertex targetV, OnmsSnmpInterface sourceinterface, OnmsSnmpInterface targetInterface, String sourceAddr, String targetAddr, ProtocolSupported discoveredBy) { SimpleConnector source = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, sourceV.getId()+"-"+id+"-connector", sourceV); SimpleConnector target = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, targetV.getId()+"-"+id+"-connector", targetV); LinkdEdge edge = new LinkdEdge(id, source, target,discoveredBy); edge.setSourceNodeid(sourceV.getNodeID()); edge.setTargetNodeid(targetV.getNodeID()); edge.setSourceLabel(sourceV.getLabel()); edge.setTargetLabel(targetV.getLabel()); if (sourceinterface != null) { edge.setSourceIfIndex(sourceinterface.getIfIndex()); edge.setSourceIfName(sourceinterface.getIfName()); if (sourceinterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(sourceinterface.getIfSpeed())); } } if (targetInterface != null) { edge.setTargetIfIndex(targetInterface.getIfIndex()); edge.setTargetIfName(targetInterface.getIfName()); if (edge.getSpeed() == null && targetInterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(targetInterface.getIfSpeed())); } } edge.setSourceAddr(sourceAddr); edge.setTargetAddr(targetAddr); return edge; }