auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DnsServiceProvider getDnsServiceProvider(final Network network) { final String DnsProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Dns); if (DnsProvider == null) { s_logger.debug("Network " + network + " doesn't support service " + Service.Dhcp.getName()); return null; } return (DnsServiceProvider) _networkModel.getElementImplementingProvider(DnsProvider); }

Target:
public DnsServiceProvider getDnsServiceProvider(final Network network) { final String dnsProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Dns); if (dnsProvider == null) { s_logger.debug("Network " + network + " doesn't support service " + Service.Dhcp.getName()); return null; } return (DnsServiceProvider) _networkModel.getElementImplementingProvider(dnsProvider); }
Source:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { output = ExceptionUtils.getStackTrace(e); } }

Target:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
String dkimSignatureTemplate() { final StringBuilder sb = new StringBuilder(); sb.append("v=1; "); sb.append("a=").append(this.dkimSignOptions.getSignAlgo().getDKIMAlgoName()).append("; "); MessageCanonic bodyCanonic = this.dkimSignOptions.getBodyCanonic(); MessageCanonic headerCanonic = this.dkimSignOptions.getHeaderCanonic(); sb.append("c=").append(headerCanonic.getCanonic()).append("/").append(bodyCanonic.getCanonic()).append("; "); String sdid = dkimQuotedPrintable(this.dkimSignOptions.getSdid()); sb.append("d=").append(sdid).append("; "); String auid = this.dkimSignOptions.getAuid(); if (auid != null) { sb.append("i=").append(dkimQuotedPrintable(auid)).append("; "); } else { sb.append("i=").append("@").append(sdid).append("; "); } sb.append("s=").append(dkimQuotedPrintable(this.dkimSignOptions.getSelector())).append("; "); String signHeadersString = String.join(":", this.dkimSignOptions.getSignedHeaders()); sb.append("h=").append(signHeadersString).append("; "); if (this.dkimSignOptions.getBodyLimit() > 0) { sb.append("l=").append(this.dkimSignOptions.getBodyLimit()).append("; "); } if (this.dkimSignOptions.isSignatureTimestamp() || this.dkimSignOptions.getExpireTime() > 0) { long time = new Date().getTime() / 1000; sb.append("t=").append(time).append("; "); if (this.dkimSignOptions.getExpireTime() > 0) { long expire = time + this.dkimSignOptions.getExpireTime(); sb.append("x=").append(expire).append("; "); } } return sb.toString(); }

Target:
String dkimSignatureTemplate() { final StringBuilder sb = new StringBuilder(); sb.append("v=1; "); sb.append("a=").append(this.dkimSignOptions.getSignAlgo().dkimAlgoName()).append("; "); MessageCanonic bodyCanonic = this.dkimSignOptions.getBodyCanonic(); MessageCanonic headerCanonic = this.dkimSignOptions.getHeaderCanonic(); sb.append("c=").append(headerCanonic.canonic()).append("/").append(bodyCanonic.canonic()).append("; "); String sdid = dkimQuotedPrintable(this.dkimSignOptions.getSdid()); sb.append("d=").append(sdid).append("; "); String auid = this.dkimSignOptions.getAuid(); if (auid != null) { sb.append("i=").append(dkimQuotedPrintable(auid)).append("; "); } else { sb.append("i=").append("@").append(sdid).append("; "); } sb.append("s=").append(dkimQuotedPrintable(this.dkimSignOptions.getSelector())).append("; "); String signHeadersString = String.join(":", this.dkimSignOptions.getSignedHeaders()); sb.append("h=").append(signHeadersString).append("; "); if (this.dkimSignOptions.getBodyLimit() > 0) { sb.append("l=").append(this.dkimSignOptions.getBodyLimit()).append("; "); } if (this.dkimSignOptions.isSignatureTimestamp() || this.dkimSignOptions.getExpireTime() > 0) { long time = System.currentTimeMillis() / 1000; sb.append("t=").append(time).append("; "); if (this.dkimSignOptions.getExpireTime() > 0) { long expire = time + this.dkimSignOptions.getExpireTime(); sb.append("x=").append(expire).append("; "); } } return sb.toString(); }
Source:
private void processOptions() throws IllegalArgumentException { if (committer == null) { committer = new PersonIdent(repo); } if (author == null) { author = committer; } if (message == null) { throw new IllegalArgumentException("commit message not specified"); } }

Target:
private void processOptions() throws IllegalArgumentException { if (message == null) throw new IllegalArgumentException(COMMIT_MESSAGE_NOT_SPECIFIED); }
Source:
public boolean containsKey(final String key) { return super.get(key.toLowerCase()) != null; }

Target:
public boolean containsKey(final String key) { return this.map.containsKey(key.toLowerCase()); }
Source:
public void showInterstitial() { mMediationInterstitialListener.onAdOpened(UnityAdapter.this); Activity activityReference = mActivityWeakReference == null ? null : mActivityWeakReference.get(); if (activityReference != null) { if (UnityAds.isReady(getPlacementId())) { UnityAds.show(activityReference, getPlacementId()); } else { Log.w(TAG, "Unity Ads failed to show interstitial ad for placement ID '" + getPlacementId() + "'. Placement is not ready."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); } } else { Log.w(TAG, "Failed to show interstitial ad for placement ID '" + getPlacementId() + "' from Unity Ads: Activity context is null."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); } }

Target:
public void showInterstitial() { mMediationInterstitialListener.onAdOpened(UnityAdapter.this); Activity activityReference = mActivityWeakReference == null ? null : mActivityWeakReference.get(); if (activityReference == null) { Log.w(TAG, "Failed to show interstitial ad for placement ID '" + mPlacementId + "' from Unity Ads: Activity context is null."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); return; } if (!UnityAds.isReady(mPlacementId)) { Log.w(TAG, "Unity Ads failed to show interstitial ad for placement ID '" + mPlacementId + "'. Placement is not ready."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); return; } UnityAds.show(activityReference, mPlacementId); }
Source:
public void updateTableView( List<Object[]> rows ) { updateTableView( rows, tableView ); }

Target:
public void updateTableView( List<Object[]> rows ) { int itemCount = tableView.table.getItemCount(); for ( int i = 0; i < rows.size(); i++ ) { TableItem item = i < itemCount ? tableView.table.getItem( i ) : new TableItem( tableView.table, SWT.NONE ); applyRowDataToTableItem( rows.get( i ), item ); } tableView.table.setItemCount( rows.size() ); tableView.setRowNums(); }
Source:
public void packRefs() throws IOException { Set<Entry<String, Ref>> refEntries = repo.getAllRefs().entrySet(); if (pm == null) pm = NullProgressMonitor.INSTANCE; pm.beginTask("pack refs", refEntries.size()); try { Collection<RefDirectoryUpdate> updates = new LinkedList<RefDirectoryUpdate>(); for (Map.Entry<String, Ref> entry : refEntries) { Ref ref = entry.getValue(); if (!ref.isSymbolic() && ref.getStorage().isLoose()) { updates.add(new RefDirectoryUpdate((RefDirectory) repo .getRefDatabase(), ref)); } pm.update(1); } ((RefDirectory) repo.getRefDatabase()).pack(updates); } finally { pm.endTask(); } }

Target:
public void packRefs() throws IOException { Collection<Ref> refs = repo.getAllRefs().values(); ArrayList<String> refsToBePacked = new ArrayList<String>(refs.size()); int packRefsCnt = 0; pm.beginTask(JGitText.get().packRefs, refs.size()); try { for (Ref ref : refs) { if (!ref.isSymbolic() && ref.getStorage().isLoose()) { refsToBePacked.add(ref.getName()); packRefsCnt++; } pm.update(1); } ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked .toArray(new String[packRefsCnt])); } finally { pm.endTask(); } }
Source:
public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { BigtableOptions bigtableOptions = configuration.toBigtableOptions(); long totalEstimatedSizeBytes = 0; Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); try (BigtableSession session = new BigtableSession(bigtableOptions)) { BigtableClusterName clusterName = bigtableOptions.getClusterName(); BigtableTableName tableName = clusterName.toTableName(configuration.getTableId()); SampleRowKeysRequest.Builder request = SampleRowKeysRequest.newBuilder(); request.setTableName(tableName.toString()); List<SampleRowKeysResponse> sampleRowKeys = session.getDataClient().sampleRowKeys(request.build()); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : sampleRowKeys) { byte[] currentEndKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, currentEndKey) && startKey.length != 0) { continue; } long offset = response.getOffsetBytes(); if ((scanStartKey.length == 0 || currentEndKey.length == 0 || Bytes.compareTo(scanStartKey, currentEndKey) < 0) && (scanEndKey.length == 0 || Bytes.compareTo(scanEndKey, startKey) > 0)) { totalEstimatedSizeBytes += (offset - lastOffset); } lastOffset = offset; startKey = currentEndKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey)) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } } return totalEstimatedSizeBytes; }

Target:
public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { long totalEstimatedSizeBytes = 0; Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : getSampleRowKeys()) { byte[] currentEndKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, currentEndKey) && startKey.length != 0) { continue; } long offset = response.getOffsetBytes(); if (isWithinRange(scanStartKey, scanEndKey, startKey, currentEndKey)) { totalEstimatedSizeBytes += (offset - lastOffset); } lastOffset = offset; startKey = currentEndKey; } return totalEstimatedSizeBytes; }
Source:
public CrawlFilter(@ServiceUrl String serviceUrl, @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }

Target:
CrawlFilter(@ServiceUrl String serviceUrl, @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }
Source:
StatDetails(Stream<StatDetails> details) { this.latencies = details.flatMap(stat -> stat.latencies.stream()) .collect(Collectors.groupingBy(LatencyStat::getBucket, Collectors.groupingBy(LatencyStat::getPercentile, Collectors.averagingDouble(LatencyStat::getLatencyMs)))) .entrySet().stream().flatMap(bucketEntry -> bucketEntry.getValue().entrySet().stream().map(latencyEntry -> new LatencyStat(bucketEntry.getKey(), latencyEntry.getKey(), latencyEntry.getValue()))) .collect(Collectors.toList()); }

Target:
StatDetails(Stream<StatDetails> details) { this.latencies = details.flatMap(stat -> stat.latencies.stream()) .collect(groupingBy(LatencyStat::getBucket, groupingBy(LatencyStat::getPercentile, averagingDouble(stat -> stat.getLatency().nanos())))) .entrySet().stream().flatMap(bucketEntry -> bucketEntry.getValue().entrySet().stream().map(latencyEntry -> { TimeValue tv = TimeValue.timeValueNanos(Math.round(latencyEntry.getValue())); return new LatencyStat(bucketEntry.getKey(), latencyEntry.getKey(), tv); })) .collect(toList()); }
Source:
public byte[] marshal(ByteBuffer bb) throws Exception { return bb.array(); }

Target:
public byte[] marshal(ByteBuffer bb) { if (bb.hasArray()) { return bb.array(); } else { final int originalPosition = bb.position(); bb.rewind(); byte[] bytes = new byte[bb.remaining()]; bb.get(bytes); bb.position(originalPosition); return bytes; } }
Source:
public List<ServiceReference> listServiceReferences(Class<?> clazz) { List<ServiceReference> result = new ArrayList<ServiceReference>(); try { CollectionUtils.addAll(result, bundleContext.getServiceReferences(clazz.getName(), null)); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e); } return result; }

Target:
public List<ServiceReference> listServiceReferences(Class<?> clazz) { List<ServiceReference> result = new ArrayList<ServiceReference>(); try { ServiceReference[] serviceReferences = bundleContext.getServiceReferences(clazz.getName(), null); if (serviceReferences == null) { return result; } CollectionUtils.addAll(result, serviceReferences); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e); } return result; }
Source:
public void runMigrations(File migrationDirectory) { LOGGER.debug("Starting the flyway modules migrations from {}.", migrationDirectory.getAbsolutePath()); if (!migrationDirectory.exists()) { LOGGER.debug("The migration directory doesn't exist. Skipping migration."); return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mdsSqlProperties.getProperty(CONNECTION_DRIVER_KEY)); dataSource.setUrl(mdsSqlProperties.getProperty(CONNECTION_URL_KEY)); dataSource.setUsername(mdsSqlProperties.getProperty(CONNECTION_USER_NAME_KEY)); dataSource.setPassword(mdsSqlProperties.getProperty(CONNECTION_USER_PASSWORD_KEY)); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setLocations(Constants.EntitiesMigration.FILESYSTEM_PREFIX + migrationDirectory.getAbsolutePath()); flyway.setSqlMigrationPrefix(Constants.EntitiesMigration.ENTITY_MIGRATIONS_PREFIX); flyway.setOutOfOrder(true); flyway.setInitOnMigrate(true); flyway.migrate(); Thread.currentThread().setContextClassLoader(cl); LOGGER.info("Modules migration completed."); }

Target:
public void runMigrations(File migrationDirectory) { LOGGER.debug("Starting the flyway modules migrations from {}.", migrationDirectory.getAbsolutePath()); if (!migrationDirectory.exists()) { LOGGER.debug("The migration directory doesn't exist. Skipping migration."); return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mdsSqlProperties.getProperty(CONNECTION_DRIVER_KEY)); dataSource.setUrl(mdsSqlProperties.getProperty(CONNECTION_URL_KEY)); dataSource.setUsername(mdsSqlProperties.getProperty(CONNECTION_USER_NAME_KEY)); dataSource.setPassword(mdsSqlProperties.getProperty(CONNECTION_USER_PASSWORD_KEY)); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setLocations(Constants.EntitiesMigration.FILESYSTEM_PREFIX + migrationDirectory.getAbsolutePath()); flyway.setSqlMigrationPrefix(Constants.EntitiesMigration.ENTITY_MIGRATIONS_PREFIX); flyway.setOutOfOrder(true); flyway.setInitOnMigrate(true); flyway.migrate(); } finally { Thread.currentThread().setContextClassLoader(cl); LOGGER.info("Modules migration completed."); } }
Source:
private SslContext getSSLContext() { long now = System.currentTimeMillis(); if (isServerCtx && (certRefreshTime <= 0 || now > (certLastRefreshTime + certRefreshTime))) { if (tTLSCertificatePath.checkAndRefresh() || tLSKeyStoreFilePath.checkAndRefresh() || tLSKeyStorePasswordFilePath.checkAndRefresh() || tLSTrustStoreFilePath.checkAndRefresh() || tLSTrustStorePasswordFilePath.checkAndRefresh()) { try { updateServerContext(); } catch (Exception e) { LOG.info("Failed to refresh tls certs", e); } } } return sslContext; }

Target:
private synchronized SslContext getSSLContext() { long now = System.currentTimeMillis(); if (isServerCtx && (certRefreshTime > 0 && now > (certLastRefreshTime + certRefreshTime))) { if (tTLSCertificatePath.checkAndRefresh() || tLSKeyStoreFilePath.checkAndRefresh() || tLSKeyStorePasswordFilePath.checkAndRefresh() || tLSTrustStoreFilePath.checkAndRefresh() || tLSTrustStorePasswordFilePath.checkAndRefresh()) { try { updateServerContext(); } catch (Exception e) { LOG.info("Failed to refresh tls certs", e); } } } return sslContext; }
Source:
public B setConfiguredProperty(ConfiguredPropertyDescriptor configuredProperty, Object value) { final boolean changed = setConfiguredPropertyIfChanged(configuredProperty, value); if (changed) { if (configuredProperty.isInputColumn()) { for (TransformedInputColumn<?> transformedInputColumn : getTransformedInputColumns(value)) { getAnalysisJobBuilder().getTransformerComponentBuilders().stream().filter( transformer -> (isProvidingColumn(transformedInputColumn, transformer))).forEach( transformer -> transformer.addChangeListener( new ComponentBuilderTransformerChangeListener(this, configuredProperty))); } } onConfigurationChanged(); } return (B) this; }

Target:
public B setConfiguredProperty(ConfiguredPropertyDescriptor configuredProperty, Object value) { final boolean changed = setConfiguredPropertyIfChanged(configuredProperty, value); if (changed) { if (configuredProperty.isInputColumn()) { registerListenerIfLinkedToTransformer(configuredProperty, value); } onConfigurationChanged(); } return (B) this; }
Source:
public void setAndGetIncludedPath() { String path = "/*"; IncludedPath includedPath = new IncludedPath(path); List<Index> indexes = new ArrayList<>(); indexes.add(Index.range(DataType.STRING, -1)); indexes.add(Index.range(DataType.NUMBER, -1)); includedPath.setIndexes(indexes); List<Index> includedPathIndexes = new ArrayList<>(includedPath.getIndexes()); Assertions.assertThat(includedPathIndexes).hasSize(2); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(0)).getDataType()).isEqualTo(DataType.STRING); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(0)).getPrecision()).isEqualTo(-1); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(1)).getDataType()).isEqualTo(DataType.NUMBER); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(1)).getPrecision()).isEqualTo(-1); Assertions.assertThat(includedPath.getPath()).isEqualTo(path); }

Target:
public void setAndGetIncludedPath() { String path = "/*"; IncludedPath includedPath = new IncludedPath(path); List<Index> indexes = new ArrayList<>(); indexes.add(Index.range(DataType.STRING, -1)); indexes.add(Index.range(DataType.NUMBER, -1)); includedPath.setIndexes(indexes); List<Index> includedPathIndexes = new ArrayList<>(includedPath.getIndexes()); assertThat(includedPathIndexes).hasSize(2); assertThat(((RangeIndex) includedPathIndexes.get(0)).getDataType()).isEqualTo(DataType.STRING); assertThat(((RangeIndex) includedPathIndexes.get(0)).getPrecision()).isEqualTo(-1); assertThat(((RangeIndex) includedPathIndexes.get(1)).getDataType()).isEqualTo(DataType.NUMBER); assertThat(((RangeIndex) includedPathIndexes.get(1)).getPrecision()).isEqualTo(-1); assertThat(includedPath.getPath()).isEqualTo(path); }
Source:
static <T> Stringifier<T> getStringifier(Type typeOfT) { final Optional<Stringifier<T>> stringifierOptional = getInstance().get(typeOfT); if (!stringifierOptional.isPresent()) { final String errMsg = format("No stringifier registered for the type: %s", typeOfT); throw new MissingStringifierException(errMsg); } final Stringifier<T> stringifier = stringifierOptional.get(); return stringifier; }

Target:
static <T> Stringifier<T> getStringifier(Type typeOfT) { checkNotNull(typeOfT); final Optional<Stringifier<T>> stringifierOptional = getInstance().get(typeOfT); if (!stringifierOptional.isPresent()) { final String errMsg = format("No stringifier registered for the type: %s", typeOfT); throw new MissingStringifierException(errMsg); } final Stringifier<T> stringifier = stringifierOptional.get(); return stringifier; }
Source:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP && action != Action.REJECT && action != Action.RETURN) throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); }

Target:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP && action != Action.REJECT && action != Action.RETURN) { throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); } }
Source:
public List<QueryResult> lookup( List<GHPoint> points, FlagEncoder encoder ) { double distanceInMeter = ghRequest.getHints().getDouble("round_trip.distance", 1000); long seed = ghRequest.getHints().getLong("round_trip.seed", 0L); GHPoint start = ghRequest.getPoints().get(0); TourStrategy strategy = new SinglePointTour(new Random(seed), distanceInMeter); queryResults = new ArrayList<>(2 + strategy.getNumberOfGeneratedPoints()); EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); QueryResult startQR = locationIndex.findClosest(start.lat, start.lon, edgeFilter); queryResults.add(startQR); GHPoint last = points.get(0); for (int i = 0; i < strategy.getNumberOfGeneratedPoints(); i++) { QueryResult result = generateValidPoint(last, strategy.getDistanceForIteration(i), strategy.getHeadingForIteration(i), edgeFilter); if (result == null) { ghResponse.addError(new IllegalStateException("Could not find a valid point after " + maxRetries + " tries, for the point:" + last)); return Collections.emptyList(); } last = result.getSnappedPoint(); queryResults.add(result); } queryResults.add(startQR); return queryResults; }

Target:
public List<QueryResult> lookup( List<GHPoint> points, FlagEncoder encoder ) { double distanceInMeter = ghRequest.getHints().getDouble("round_trip.distance", 1000); long seed = ghRequest.getHints().getLong("round_trip.seed", 0L); if (points.isEmpty()) { ghResponse.addError(new IllegalStateException("For round trip calculation one point is required")); return Collections.emptyList(); } GHPoint start = ghRequest.getPoints().get(0); TourStrategy strategy = new SinglePointTour(new Random(seed), distanceInMeter); queryResults = new ArrayList<>(2 + strategy.getNumberOfGeneratedPoints()); EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); QueryResult startQR = locationIndex.findClosest(start.lat, start.lon, edgeFilter); queryResults.add(startQR); GHPoint last = points.get(0); for (int i = 0; i < strategy.getNumberOfGeneratedPoints(); i++) { QueryResult result = generateValidPoint(last, strategy.getDistanceForIteration(i), strategy.getHeadingForIteration(i), edgeFilter); if (result == null) { ghResponse.addError(new IllegalStateException("Could not find a valid point after " + maxRetries + " tries, for the point:" + last)); return Collections.emptyList(); } last = result.getSnappedPoint(); queryResults.add(result); } queryResults.add(startQR); return queryResults; }
Source:
public void testIndexedGZIPVCF(final String testPath, final int expectedCount) throws IOException { final VCFCodec codec = new VCFCodec(); final TribbleIndexedFeatureReader<VariantContext, LineIterator> featureReaderHttp = new TribbleIndexedFeatureReader(testPath, codec, false); final CloseableTribbleIterator<VariantContext> localIterator = featureReaderHttp.iterator(); int count = 0; for (final Feature feat : featureReaderHttp.iterator()) { localIterator.next(); count++; } Assert.assertEquals(count, expectedCount); }

Target:
public void testIndexedGZIPVCF(final String testPath, final int expectedCount) throws IOException { final VCFCodec codec = new VCFCodec(); try (final TribbleIndexedFeatureReader<VariantContext, LineIterator> featureReader = new TribbleIndexedFeatureReader(testPath, codec, false)) { final CloseableTribbleIterator<VariantContext> localIterator = featureReader.iterator(); int count = 0; for (final Feature feat : featureReader.iterator()) { localIterator.next(); count++; } Assert.assertEquals(count, expectedCount); } }
Source:
public List<Workflow> findByPaths(List<String> paths, boolean findPublished) { List<Predicate> predicates = new ArrayList<>(); SourceControlConverter converter = new SourceControlConverter(); Predicate predicate; CriteriaBuilder cb = currentSession().getCriteriaBuilder(); CriteriaQuery<Workflow> q = cb.createQuery(Workflow.class); Root<Workflow> entry = q.from(Workflow.class); for (String path : paths) { String[] splitPath = Workflow.splitPath(path); if (splitPath == null) { continue; } String sourcecontrol = splitPath[registryIndex]; String organization = splitPath[orgIndex]; String repository = splitPath[repoIndex]; String workflowname = splitPath[entryNameIndex]; if (splitPath[entryNameIndex] == null) { if (findPublished) { predicate = cb.and( cb.isNull(entry.get("workflowName")), cb.isTrue(entry.get("isPublished")) ); } else { predicate = cb.isNull(entry.get("workflowName")); } } else { if (findPublished) { predicate = cb.and( cb.equal(entry.get("workflowName"), workflowname), cb.isTrue(entry.get("isPublished")) ); } else { predicate = cb.equal(entry.get("workflowName"), workflowname); } } predicates.add(cb.and( cb.equal(entry.get("sourceControl"), converter.convertToEntityAttribute(sourcecontrol)), cb.equal(entry.get("organization"), organization), cb.equal(entry.get("repository"), repository), predicate) ); } q.where(cb.or(predicates.toArray(new Predicate[]{}))); EntityManager entityManager = currentSession().getEntityManagerFactory().createEntityManager(); return entityManager.createQuery(q).getResultList(); }

Target:
public List<Workflow> findByPaths(List<String> paths, boolean findPublished) { List<Predicate> predicates = new ArrayList<>(); SourceControlConverter converter = new SourceControlConverter(); CriteriaBuilder cb = currentSession().getCriteriaBuilder(); CriteriaQuery<Workflow> q = cb.createQuery(Workflow.class); Root<Workflow> entry = q.from(Workflow.class); for (String path : paths) { String[] splitPath = Workflow.splitPath(path); if (splitPath == null) { continue; } String sourcecontrol = splitPath[registryIndex]; String organization = splitPath[orgIndex]; String repository = splitPath[repoIndex]; String workflowname = splitPath[entryNameIndex]; Predicate predicate; if (splitPath[entryNameIndex] == null) { if (findPublished) { predicate = cb.and( cb.isNull(entry.get(WORKFLOW_NAME)), cb.isTrue(entry.get(IS_PUBLISHED)) ); } else { predicate = cb.isNull(entry.get(WORKFLOW_NAME)); } } else { if (findPublished) { predicate = cb.and( cb.equal(entry.get(WORKFLOW_NAME), workflowname), cb.isTrue(entry.get(IS_PUBLISHED)) ); } else { predicate = cb.equal(entry.get(WORKFLOW_NAME), workflowname); } } predicates.add(cb.and( cb.equal(entry.get("sourceControl"), converter.convertToEntityAttribute(sourcecontrol)), cb.equal(entry.get("organization"), organization), cb.equal(entry.get("repository"), repository), predicate) ); } q.where(cb.or(predicates.toArray(new Predicate[]{}))); EntityManager entityManager = currentSession().getEntityManagerFactory().createEntityManager(); return entityManager.createQuery(q).getResultList(); }
Source:
public CustomizePerspectiveDialog(IWorkbenchWindowConfigurer configurer, Perspective persp, IEclipseContext context) { super(configurer.getWindow().getShell()); this.treeManager = new TreeManager(); this.configurer = configurer; this.context = context; perspective = persp; window = (WorkbenchWindow) configurer.getWindow(); wPage = (WorkbenchPage) window.getActivePage(); menuMngrRenderer = context.get(MenuManagerRenderer.class); toolbarMngrRenderer = context.get(ToolBarManagerRenderer.class); resUtils = (ISWTResourceUtilities) context.get(IResourceUtilities.class); initializeIcons(); initializeActionSetInput(); loadMenuAndToolbarStructure(); }

Target:
public CustomizePerspectiveDialog(IWorkbenchWindowConfigurer configurer, Perspective persp, IEclipseContext context) { super(configurer.getWindow().getShell()); this.treeManager = new TreeManager(); this.configurer = configurer; this.context = context; perspective = persp; window = (WorkbenchWindow) configurer.getWindow(); windowPage = (WorkbenchPage) window.getActivePage(); menuMngrRenderer = context.get(MenuManagerRenderer.class); toolbarMngrRenderer = context.get(ToolBarManagerRenderer.class); resUtils = (ISWTResourceUtilities) context.get(IResourceUtilities.class); initializeIcons(); initializeActionSetInput(); loadMenuAndToolbarStructure(); }
Source:
private boolean isHostHealthy(InetSocketAddress host) { try { CassandraClientPoolingContainer testingContainer = currentPools.get(host); testingContainer.runWithPooledResource(describeRing); testingContainer.runWithPooledResource(validatePartitioner); return true; } catch (Exception e) { log.error("We tried to add back into the pool, but got an exception" + " that caused us to distrust this host further.", SafeArg.of("host", host), e); return false; } }

Target:
private boolean isHostHealthy(InetSocketAddress host) { try { CassandraClientPoolingContainer testingContainer = currentPools.get(host); testingContainer.runWithPooledResource(describeRing); testingContainer.runWithPooledResource(validatePartitioner); return true; } catch (Exception e) { log.warn("We tried to add back into the pool, but got an exception" + " that caused us to distrust this host further. Exception message was: : {}", SafeArg.of("host", host), SafeArg.of("exceptionClass", e.getClass().getTypeName()), UnsafeArg.of("exceptionMessage", e.getMessage())); return false; } }
Source:
private Triple<Boolean, Integer, Double> checkFixedCompounded(ResolvedSwapLeg leg) { if(leg.getPaymentPeriods().size() != 1) { return Triple.of(false, 0, 0.0d); }; if(leg.getPaymentEvents().size() != 0) { return Triple.of(false, 0, 0.0d); } PaymentPeriod paymentPeriods = leg.getPaymentPeriods().get(0); if(!(paymentPeriods instanceof RatePaymentPeriod)) { return Triple.of(false, 0, 0.0d); } RatePaymentPeriod ratePaymentPeriod = (RatePaymentPeriod) paymentPeriods; if (ratePaymentPeriod.getCompoundingMethod() == CompoundingMethod.NONE) { return Triple.of(false, 0, 0.0d); } ImmutableList<RateAccrualPeriod> accrualPeriods = ratePaymentPeriod.getAccrualPeriods(); int nbAccrualPeriods = accrualPeriods.size(); double fixedRate = 0; for (int i = 0; i < nbAccrualPeriods; i++) { if (!(accrualPeriods.get(i).getRateComputation() instanceof FixedRateComputation)) { return Triple.of(false, 0, 0.0d); } if ((i > 0) && (((FixedRateComputation) accrualPeriods.get(i).getRateComputation()).getRate() != fixedRate)) { return Triple.of(false, 0, 0.0d); } fixedRate = ((FixedRateComputation) accrualPeriods.get(i).getRateComputation()).getRate(); if (accrualPeriods.get(i).getSpread() != 0) { return Triple.of(false, 0, 0.0d); } if (accrualPeriods.get(i).getGearing() != 1.0d) { return Triple.of(false, 0, 0.0d); } if (accrualPeriods.get(i).getYearFraction() != 1.0d) { return Triple.of(false, 0, 0.0d); } } return Triple.of(true, nbAccrualPeriods, fixedRate); }

Target:
private Triple<Boolean, Integer, Double> checkFixedCompounded(ResolvedSwapLeg leg) { if(leg.getPaymentEvents().size() != 0) { return Triple.of(false, 0, 0.0d); } RatePaymentPeriod ratePaymentPeriod = (RatePaymentPeriod) leg.getPaymentPeriods().get(0); if (ratePaymentPeriod.getCompoundingMethod() == CompoundingMethod.NONE) { return Triple.of(false, 0, 0.0d); } ImmutableList<RateAccrualPeriod> accrualPeriods = ratePaymentPeriod.getAccrualPeriods(); int nbAccrualPeriods = accrualPeriods.size(); double fixedRate = 0; for (int i = 0; i < nbAccrualPeriods; i++) { if (!(accrualPeriods.get(i).getRateComputation() instanceof FixedRateComputation)) { return Triple.of(false, 0, 0.0d); } if ((i > 0) && (((FixedRateComputation) accrualPeriods.get(i).getRateComputation()).getRate() != fixedRate)) { return Triple.of(false, 0, 0.0d); } fixedRate = ((FixedRateComputation) accrualPeriods.get(i).getRateComputation()).getRate(); if (accrualPeriods.get(i).getSpread() != 0) { return Triple.of(false, 0, 0.0d); } if (accrualPeriods.get(i).getGearing() != 1.0d) { return Triple.of(false, 0, 0.0d); } if (accrualPeriods.get(i).getYearFraction() != 1.0d) { return Triple.of(false, 0, 0.0d); } } return Triple.of(true, nbAccrualPeriods, fixedRate); }
Source:
private ArrayList<ReceiverGroup> getReceiverGroups() { ArrayList<ReceiverGroup> receiverGroups = new ArrayList<ReceiverGroup>(); for (ThriftClientInfo thriftClientInfo : thriftClientInfoList) { if (thriftClientInfo.isStatsPublisherEnabled()) { ArrayList<DataPublisherHolder> dataPublisherHolders = new ArrayList<DataPublisherHolder>(); DataPublisherHolder aNode = new DataPublisherHolder(null, buildUrl(thriftClientInfo), thriftClientInfo.getUsername(), thriftClientInfo.getPassword()); dataPublisherHolders.add(aNode); ReceiverGroup group = new ReceiverGroup(dataPublisherHolders); receiverGroups.add(group); } } return receiverGroups; }

Target:
private ArrayList<ReceiverGroup> getReceiverGroups() { for (ThriftClientInfo thriftClientInfo : thriftClientInfoList) { if (thriftClientInfo.isStatsPublisherEnabled()) { dataPublisherHolders.add(new DataPublisherHolder(null, buildUrl(thriftClientInfo), thriftClientInfo.getUsername(), thriftClientInfo.getPassword())); if (log.isDebugEnabled()) { log.debug(String.format("Thrift client [id] %s [ip] %s [port] %s is added to data publisher holder", thriftClientInfo.getId(), thriftClientInfo.getIp(), thriftClientInfo.getPort())); } } } receiverGroups.add(new ReceiverGroup(dataPublisherHolders)); return receiverGroups; }
Source:
public static Interceptor.Chain buildChain( @NonNull List<Interceptor> registeredInterceptors, @NonNull Interceptor realInterceptor ) { final List<Interceptor> interceptors = new ArrayList<Interceptor>(registeredInterceptors.size() + 1); interceptors.addAll(registeredInterceptors); interceptors.add(realInterceptor); return new ChainImpl(interceptors, 0); }

Target:
public static Interceptor.Chain buildChain( @NonNull List<Interceptor> registeredInterceptors, @NonNull Interceptor realInterceptor ) { final List<Interceptor> interceptors = new ArrayList<Interceptor>(registeredInterceptors.size() + 1); interceptors.addAll(registeredInterceptors); interceptors.add(realInterceptor); return new ChainImpl(interceptors.listIterator()); }
Source:
private MultiPolygon parseElement(Element extentObj) throws Exception { GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); gc.getBean(DataManager.class).getEditLib().removeEditingInfo(extentObj); MultiPolygon geometry = null; if ("polygon".equals(extentObj.getName())) { geometry = parsePolygon(extentObj); } else if ("EX_BoundingPolygon".equals(extentObj.getName())) { Element polygon = extentObj.getChild("polygon", Namespaces.GMD); geometry = parsePolygon(polygon); } else if ("EX_GeographicBoundingBox".equals(extentObj.getName())) { double minx = Double.parseDouble(extentObj.getChild("westBoundLongitude", Geonet.Namespaces.GMD).getChildText("Decimal", Geonet.Namespaces.GCO)); double maxx = Double.parseDouble(extentObj.getChild("eastBoundLongitude", Geonet.Namespaces.GMD).getChildText("Decimal", Geonet.Namespaces.GCO)); double miny = Double.parseDouble(extentObj.getChild("southBoundLatitude", Geonet.Namespaces.GMD).getChildText("Decimal", Geonet.Namespaces.GCO)); double maxy = Double.parseDouble(extentObj.getChild("northBoundLatitude", Geonet.Namespaces.GMD).getChildText("Decimal", Geonet.Namespaces.GCO)); Polygon[] polygons = {(Polygon)factory.toGeometry(new Envelope(minx, maxx, miny, maxy))}; geometry = factory.createMultiPolygon(polygons); } return geometry; }

Target:
private MultiPolygon parseElement(Element extentObj) throws Exception { GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); gc.getBean(DataManager.class).getEditLib().removeEditingInfo(extentObj); MultiPolygon geometry = null; if ("polygon".equals(extentObj.getName())) { geometry = parsePolygon(extentObj); } else if ("EX_BoundingPolygon".equals(extentObj.getName())) { Element polygon = Xml.selectElement(extentObj, "*[local-name()='polygon']"); geometry = parsePolygon(polygon); } else if ("EX_GeographicBoundingBox".equals(extentObj.getName())) { double minx = Double.parseDouble(Xml.selectString(extentObj, "*[local-name()='westBoundLongitude']/*")); double maxx = Double.parseDouble(Xml.selectString(extentObj, "*[local-name()='eastBoundLongitude']/*")); double miny = Double.parseDouble(Xml.selectString(extentObj, "*[local-name()='southBoundLatitude']/*")); double maxy = Double.parseDouble(Xml.selectString(extentObj, "*[local-name()='northBoundLatitude']/*")); Polygon[] polygons = {(Polygon)factory.toGeometry(new Envelope(minx, maxx, miny, maxy))}; geometry = factory.createMultiPolygon(polygons); } return geometry; }
Source:
public CompletableFuture<Void> putAllAsync(List<Entry<K, V>> entries) { putAll(entries); return CompletableFuture.completedFuture(null); }

Target:
public CompletableFuture<Void> putAllAsync(List<Entry<K, V>> entries) { CompletableFuture<Void> future = new CompletableFuture<>(); try { List<K> delKeys = new ArrayList<>(); List<Entry<K, V>> putRecords = new ArrayList<>(); entries.forEach(r -> { if (r.getValue() != null) { putRecords.add(r); } else { delKeys.add(r.getKey()); } }); cache.invalidateAll(delKeys); putRecords.forEach(e -> put(e.getKey(), e.getValue())); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } return future; }
Source:
private String messageFormatter(String msg, String vmid){ String temp = ""; return temp.format("{\"params\": {\"notify_time\": %s, \"%s\": {\"status\": [\"%s\"], \"hash\": \"%s\"}}, \"jsonrpc\": \"2.0\", \"method\": \"|virt|VM_status|%s\"}", String.valueOf(System.currentTimeMillis()), vmid, msg, Integer.toString(vmid.hashCode()), vmid); }

Target:
private String messageFormatter(String msg, String vmid){ StringBuilder sb = new StringBuilder(); return sb.append("{\"params\": {\"notify_time\": ") .append(String.valueOf(System.currentTimeMillis())) .append(", \"") .append(vmid) .append("\": {\"status\": [\"") .append(msg) .append("\"], \"hash\": \"") .append(Integer.toString(vmid.hashCode())) .append("\"}}, \"jsonrpc\": \"2.0\", \"method\": \"|virt|VM_status|") .append(vmid) .append("\"}").toString(); }
Source:
public void shouldReturnTeamId_withTeamInContext() { final String userId = randomId(); final String teamId = randomId(); final String identityProviderId = randomId(); final String agentUserId = randomBoolean() ? null : randomId(); final String appId = randomBoolean() ? null : randomId(); final DefaultSecurityContext context = new DefaultSecurityContext(userId, teamId, identityProviderId, agentUserId, appId); final Optional<String> returnedTeamId = context.teamId(); assertEquals(Optional.of(teamId), returnedTeamId); }

Target:
public void shouldReturnTeamId_withTeamInContext() { final String userId = randomId(); final String teamId = randomId(); final String identityProviderId = randomBoolean() ? null : randomId(); final String agentUserId = randomBoolean() ? null : randomId(); final String appId = randomBoolean() ? null : randomId(); final DefaultSecurityContext context = new DefaultSecurityContext(userId, teamId, identityProviderId, agentUserId, appId); final Optional<String> returnedTeamId = context.teamId(); assertEquals(Optional.of(teamId), returnedTeamId); }
Source:
public List<String> validateResponsesDetails(List<FeedbackResponseDetails> responses, int numRecipients) { List<String> errors = new ArrayList<>(); for (FeedbackResponseDetails response : responses) { FeedbackNumericalScaleResponseDetails details = (FeedbackNumericalScaleResponseDetails) response; boolean isAnswerOutOfRange = details.getAnswer() < minScale || details.getAnswer() > maxScale; if (isAnswerOutOfRange) { errors.add(details.getAnswerString() + Const.FeedbackQuestion.NUMSCALE_ERROR_OUT_OF_RANGE + "(min=" + minScale + ", max=" + maxScale + ")"); } BigDecimal answer = BigDecimal.valueOf(details.getAnswer()); BigDecimal stepBd = BigDecimal.valueOf(step); BigDecimal remainder = answer.remainder(stepBd); boolean isAnsMultipleOfStep = remainder.compareTo(BigDecimal.ZERO) == 0; if (!isAnsMultipleOfStep && !isAnswerOutOfRange) { double posValSmall = answer.subtract(remainder).setScale(5, RoundingMode.HALF_UP).doubleValue(); double posValBig = answer.subtract(remainder).add(stepBd).setScale(5, RoundingMode.HALF_UP).doubleValue(); errors.add("Please enter a valid value. The two nearest valid values are " + posValSmall + " and " + posValBig + "."); } } return errors; }

Target:
public List<String> validateResponsesDetails(List<FeedbackResponseDetails> responses, int numRecipients) { List<String> errors = new ArrayList<>(); for (FeedbackResponseDetails response : responses) { FeedbackNumericalScaleResponseDetails details = (FeedbackNumericalScaleResponseDetails) response; boolean isAnswerOutOfRange = details.getAnswer() < minScale || details.getAnswer() > maxScale; if (isAnswerOutOfRange) { errors.add(details.getAnswerString() + Const.FeedbackQuestion.NUMSCALE_ERROR_OUT_OF_RANGE + "(min=" + minScale + ", max=" + maxScale + ")"); } BigDecimal minval = BigDecimal.valueOf(this.minScale); BigDecimal answer = BigDecimal.valueOf(details.getAnswer()); BigDecimal stepBd = BigDecimal.valueOf(step); BigDecimal remainder = answer.subtract(minval).remainder(stepBd); boolean isAnsMultipleOfStep = remainder.compareTo(BigDecimal.ZERO) == 0; if (!isAnsMultipleOfStep && !isAnswerOutOfRange) { double posValSmall = answer.subtract(remainder).setScale(5, RoundingMode.HALF_UP).doubleValue(); double posValBig = answer.subtract(remainder).add(stepBd).setScale(5, RoundingMode.HALF_UP).doubleValue(); errors.add("Please enter a valid value. The two nearest valid values are " + posValSmall + " and " + posValBig + "."); } } return errors; }
Source:
void handleNext(Title title, List<Description> descriptions) { Timber.e("Inside handleNext"); view.showProgressDialog(); prevTitleDescription setTitleAndDescription(title, descriptions); uploadModel.getImageQuality(uploadModel.getCurrentItem(), true) compositeDisposable.add(uploadModel.getImageQuality(uploadModel.getCurrentItem(), true) master .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(imageResult -> handleImage(title, descriptions, imageResult), throwable -> Timber.e(throwable, "Error occurred while handling image"))); }

Target:
void handleNext(Title title, List<Description> descriptions) { Timber.e("Inside handleNext"); view.showProgressDialog(); setTitleAndDescription(title, descriptions); compositeDisposable.add(uploadModel.getImageQuality(uploadModel.getCurrentItem(), true) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(imageResult -> handleImage(title, descriptions, imageResult), throwable -> Timber.e(throwable, "Error occurred while handling image"))); }
Source:
public boolean pathExists(String path) { String url = getContextBaseUrl() + (path.startsWith("/") ? path : '/' + path); logger.debug("Path to artifact: " + url); WebTarget resource = getClientInstance().target(url); setupAuthentication(resource); Response response = resource.request(MediaType.TEXT_PLAIN).get(); System.out.println(response.getStatus()); return response.getStatus() == 200; }

Target:
public boolean pathExists(String path) { String url = getContextBaseUrl() + (path.startsWith("/") ? path : '/' + path); logger.debug("Path to artifact: " + url); WebTarget resource = getClientInstance().target(url); setupAuthentication(resource); Response response = resource.request(MediaType.TEXT_PLAIN).get(); return response.getStatus() == 200; }
Source:
public static void deleteOnExit(final Path path) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Files.delete(path); } catch (IOException e) { throw new RuntimeIOException(e); } } }); }

Target:
public static void deleteOnExit(final Path path) { Runtime.getRuntime().addShutdownHook(new DeletePathThread(path)); }
Source:
public static RGB getRGBFromCssString(String cssValue) { try { if (cssValue.startsWith("rgb(")) { String rest = cssValue.substring(4, cssValue.length()); if (rest.contains("rgb(")) { rest = rest.substring(rest.indexOf("rgb(") + 4, rest.length()); } String[] rgbValues = rest.substring(0, rest.indexOf(")")).split(","); if (rgbValues.length == 3) { return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); } } else if (cssValue.startsWith("#")) { String rest = cssValue.substring(1, cssValue.length()); if (rest.contains("#")) { rest = rest.substring(rest.indexOf("#") + 1, rest.length()); } if (rest.length() > 5) { return new RGB(Integer.parseInt(rest.substring(0, 2), 16), Integer.parseInt(rest.substring(2, 4), 16), Integer.parseInt(rest.substring(4, 6), 16)); } } throw new E4CssParseException("RGB", cssValue); } catch (NumberFormatException | E4CssParseException e) { logOnce(e); return null; } }

Target:
public static RGB getRGBFromCssString(String cssValue) { try { if (cssValue.startsWith("rgb(")) { String rest = cssValue.substring(4, cssValue.length()); int idx = rest.indexOf("rgb("); if (idx != -1) { rest = rest.substring(idx + 4, rest.length()); } idx = rest.indexOf(")"); if (idx != -1) { rest = rest.substring(0, idx); } String[] rgbValues = rest.split(","); if (rgbValues.length == 3) { return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); } } else if (cssValue.startsWith("#")) { String rest = cssValue.substring(1, cssValue.length()); int idx = rest.indexOf("#"); if (idx != -1) { rest = rest.substring(idx + 1, rest.length()); } if (rest.length() > 5) { return new RGB(Integer.parseInt(rest.substring(0, 2), 16), Integer.parseInt(rest.substring(2, 4), 16), Integer.parseInt(rest.substring(4, 6), 16)); } } throw new E4CssParseException("RGB", cssValue); } catch (NumberFormatException | E4CssParseException e) { logOnce(e); return null; } }
Source:
public void copy(String sourceResourcePath, String destinationFileName) throws IOException { Path destinationPath = this.basePath.resolve(destinationFileName); Files.createDirectories(destinationPath.getParent()); Files.copy(EmbulkMigrate.class.getClassLoader().getResourceAsStream(sourceResourcePath), destinationPath,REPLACE_EXISTING); this.modifiedFiles.add(destinationPath); }

Target:
public void copy(String sourceResourcePath, String destinationFileName) throws IOException { Path destinationPath = this.basePath.resolve(destinationFileName); Files.createDirectories(destinationPath.getParent()); Files.copy(EmbulkMigrate.class.getClassLoader().getResourceAsStream(sourceResourcePath), destinationPath, StandardCopyOption.REPLACE_EXISTING); this.modifiedFiles.add(destinationPath); }
Source:
public void parseJobs() throws IOException { final String json = Resources .toString(Resources.getResource(JsonUtilsTest.class, "jobs.json"), Charset.defaultCharset()); final InjectableValues injectables = new InjectableValues.Std().addValue("client", EasyMock.createNiceMock(Client.class)); final JavaType javaType = new ObjectMapper().getTypeFactory() .constructCollectionType(ArrayList.class, Job.class); final List<Job> jobs = JsonUtils.parse(json, javaType, injectables); assertThat(jobs, notNullValue()); assertThat(jobs, hasSize(2)); final List<String> jobIds = new ArrayList<String>(); jobIds.add(jobs.get(0).getJid()); jobIds.add(jobs.get(1).getJid()); assertThat(jobIds, containsInAnyOrder("8fbb94d60c3249f9a466c74ef57740f1", "8fbb94d60c3249f9a466c74ef57740f2")); }

Target:
public void parseJobs() throws IOException { final String json = Resources .toString(Resources.getResource(JsonUtilsTest.class, "jobs.json"), Charset.defaultCharset()); final InjectableValues injectables = new InjectableValues.Std().addValue("client", EasyMock.createNiceMock(Client.class)); final JavaType javaType = new ObjectMapper().getTypeFactory() .constructCollectionType(ArrayList.class, Job.class); final List<Job> jobs = JsonUtils.parse(json, javaType, injectables); assertThat(jobs, notNullValue()); assertThat(jobs, hasSize(2)); final List<String> jobIds = new ArrayList<>(); jobIds.add(jobs.get(0).getJid()); jobIds.add(jobs.get(1).getJid()); assertThat(jobIds, containsInAnyOrder("8fbb94d60c3249f9a466c74ef57740f1", "8fbb94d60c3249f9a466c74ef57740f2")); }