auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCheckoutChangeLinkToEmptyDir() throws Exception { String fname = "was_file"; Git git = Git.wrap(db); writeTrashFile(fname, "a"); git.add().addFilepattern(fname).call(); String linkName = "link"; File link = writeLink(linkName, fname).toFile(); git.add().addFilepattern(linkName).call(); git.commit().setMessage("Added file and link").call(); assertWorkDir(mkmap(linkName, "a", fname, "a")); FileUtils.delete(link); FileUtils.mkdir(link); assertTrue("Link must be a directory now", link.isDirectory()); writeTrashFile(fname, "b"); assertWorkDir(mkmap(fname, "b")); git.checkout().setName("master").setStartPoint(Constants.HEAD) .addPath(fname).addPath(linkName).call(); assertWorkDir(mkmap(fname, "a", linkName, "a")); Status st = git.status().call(); assertTrue(st.isClean()); }

Target:
public void testCheckoutChangeLinkToEmptyDir() throws Exception { String fname = "was_file"; Git git = Git.wrap(db); writeTrashFile(fname, "a"); git.add().addFilepattern(fname).call(); String linkName = "link"; File link = writeLink(linkName, fname).toFile(); git.add().addFilepattern(linkName).call(); git.commit().setMessage("Added file and link").call(); assertWorkDir(mkmap(linkName, "a", fname, "a")); FileUtils.delete(link); FileUtils.mkdir(link); assertTrue("Link must be a directory now", link.isDirectory()); writeTrashFile(fname, "b"); assertWorkDir(mkmap(fname, "b", linkName, "/")); git.checkout().setName("master").setStartPoint(Constants.HEAD) .addPath(fname).addPath(linkName).call(); assertWorkDir(mkmap(fname, "a", linkName, "a")); Status st = git.status().call(); assertTrue(st.isClean()); }
Source:
public EditCommitOperation(Repository repository, RevCommit commit) { if (commit.getParentCount() != 1) { throw new UnsupportedOperationException( "commit is expected to have exactly one parent"); } this.repository = repository; this.commit = commit; }

Target:
public EditCommitOperation(Repository repository, RevCommit commit) { if (commit.getParentCount() != 1) throw new UnsupportedOperationException( "commit is expected to have exactly one parent"); this.repository = repository; this.commit = commit; }
Source:
protected RepositoryStatus createErrorStatus(TaskRepository repository, String message) { if (repository != null) { return RepositoryStatus.createStatus(repository, IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, message); } else { return RepositoryStatus.createStatus("Unknown repository", IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, message); } }

Target:
protected Status createErrorStatus(TaskRepository repository, String message) { if (repository != null) { return RepositoryStatus.createStatus(repository, IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, message); } else { return new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, message + " (Repository Unknown)"); } }
Source:
public void testRootLevelAttributeSimpleNameOperator() { simpleAttributeOperatorHelper(OperatorContext.MEMORY_MB, StreamingApplication.DT_PREFIX, true, (Integer)4096, true, true); }

Target:
public void testRootLevelAttributeSimpleNameOperator() { simpleAttributeOperatorHelper(OperatorContext.MEMORY_MB, StreamingApplication.DT_PREFIX, true, 4096, true, true); }
Source:
public long getNumberOfEntities(Session session) { final InfinispanRemoteDatastoreProvider datastoreProvider = getProvider( session ); final SessionFactoryImplementor sessionFactoryImplementor = getSessionFactoryImplementor( session.getSessionFactory() ); final Collection<EntityPersister> persisters = sessionFactoryImplementor.getMetamodel().entityPersisters().values(); final AtomicLong counter = new AtomicLong(); for ( EntityPersister ep : persisters ) { OgmEntityPersister persister = (OgmEntityPersister) ep; String tableName = persister.getTableName(); RemoteCache<Object, Object> cache = datastoreProvider.getCache( tableName ); if ( !( cache instanceof TransactionalRemoteCacheImpl ) ) { counter.addAndGet( cache.size() ); continue; } int size = TransactionalRemoteCacheCounter.count( persister, (TransactionalRemoteCacheImpl) cache, datastoreProvider.getDataMapperForCache( tableName ), session ); counter.addAndGet( size ); } return counter.get(); }

Target:
public long getNumberOfEntities(Session session) { final InfinispanRemoteDatastoreProvider datastoreProvider = getProvider( session ); final SessionFactoryImplementor sessionFactoryImplementor = getSessionFactoryImplementor( session.getSessionFactory() ); final Collection<EntityPersister> persisters = sessionFactoryImplementor.getMetamodel().entityPersisters().values(); final AtomicLong counter = new AtomicLong(); for ( EntityPersister ep : persisters ) { OgmEntityPersister persister = (OgmEntityPersister) ep; String tableName = persister.getTableName(); RemoteCache<Object, Object> cache = datastoreProvider.getCache( tableName ); if ( cache instanceof TransactionalRemoteCacheImpl ) { int size = TransactionalRemoteCacheCounter.count( persister, (TransactionalRemoteCacheImpl) cache, datastoreProvider.getDataMapperForCache( tableName ), session ); counter.addAndGet( size ); } else { counter.addAndGet( cache.size() ); } } return counter.get(); }
Source:
protected Region<String, Integer> createRegion(final String name, final CacheListener<String, Integer> listener) { LogService.getLogger() .info("Params [Redundancy: " + redundancy + " withData:" + withData + "]"); PartitionAttributesFactory<String, Integer> paf = new PartitionAttributesFactory<>(); paf.setRedundantCopies(redundancy); RegionFactory<String, Integer> regionFactory = cacheRule.getCache().createRegionFactory(); if (listener != null) { regionFactory.addCacheListener(listener); } regionFactory.setDataPolicy(DataPolicy.PARTITION); regionFactory.setPartitionAttributes(paf.create()); return regionFactory.create(name); }

Target:
protected Region<String, Integer> createRegion(final String name, final CacheListener<String, Integer> listener) { return createPartitionedRegion(name, listener, false); }
Source:
public String getValue(Pattern headerPattern) { String value = getField(headerPattern); if (value.isEmpty()) { throw new IllegalArgumentException("No value was provided for header pattern" + headerPattern); } else { return value; } }

Target:
public String getValue(Pattern headerPattern) { String value = getField(headerPattern); if (value.isEmpty()) { throw new IllegalArgumentException("No value was found for header pattern" + headerPattern); } else { return value; } }
Source:
protected String getPrivateHostname(NodeMetadata node, Optional<HostAndPort> sshHostAndPort, ConfigBag setup) { String provider = (setup != null) ? setup.get(CLOUD_PROVIDER) : null; if (provider == null) provider= getProvider(); if ("aws-ec2".equals(provider)) { HostAndPort inferredHostAndPort = null; if (!sshHostAndPort.isPresent()) { try { String vmIp = JcloudsUtil.getFirstReachableAddress(this.getComputeService().getContext(), node); int port = node.getLoginPort(); inferredHostAndPort = HostAndPort.fromParts(vmIp, port); } catch (Exception e) { LOG.warn("Error reaching aws-ec2 instance "+node.getId()+"@"+node.getLocation()+" on port "+node.getLoginPort()+"; falling back to jclouds metadata for address", e); } } if (sshHostAndPort.isPresent() || inferredHostAndPort != null) { HostAndPort hostAndPortToUse = sshHostAndPort.isPresent() ? sshHostAndPort.get() : inferredHostAndPort; try { return getPublicHostnameAws(hostAndPortToUse, setup); } catch (Exception e) { LOG.warn("Error querying aws-ec2 instance instance "+node.getId()+"@"+node.getLocation()+" over ssh for its hostname; falling back to jclouds metadata for address", e); } } } return getPrivateHostnameGeneric(node, setup); }

Target:
protected String getPrivateHostname(NodeMetadata node, Optional<HostAndPort> sshHostAndPort, ConfigBag setup) { String provider = (setup != null) ? setup.get(CLOUD_PROVIDER) : null; if (provider == null) provider= getProvider(); if ("aws-ec2".equals(provider)) { Maybe<String> result = getPrivateHostnameAws(node, sshHostAndPort, setup); if (result.isPresent()) return result.get(); } return getPrivateHostnameGeneric(node, setup); }
Source:
private void testWithoutAnyCandidate() throws SQLException { deleteDb(getTestName()); final Connection conn = getJdbcConnection("DATABASE_TO_LOWER=false;DATABASE_TO_UPPER=false"); final Statement stat = conn.createStatement(); stat.execute("CREATE TABLE T2 ( ID INT IDENTITY )"); try { stat.execute("ALTER TABLE t1 DROP COLUMN ID"); fail("Table `t1` was accessible but should not have been."); } catch (SQLException e) { final String message = e.getMessage(); assertContains(message, "Table \"t1\" not found;"); } conn.close(); deleteDb(getTestName()); }

Target:
private void testWithoutAnyCandidate() throws SQLException { deleteDb(getTestName()); Connection conn = getConnectionWithSettings("DATABASE_TO_UPPER=FALSE"); Statement stat = conn.createStatement(); stat.execute("CREATE TABLE T2 ( ID INT IDENTITY )"); try { stat.execute("ALTER TABLE t1 DROP COLUMN ID"); fail("Table `t1` was accessible but should not have been."); } catch (SQLException e) { String message = e.getMessage(); assertContains(message, "Table \"t1\" not found;"); } conn.close(); deleteDb(getTestName()); }
Source:
public List<QuotaBalanceVO> lastQuotaBalanceVO(final Long accountId, final Long domainId, final Date pivotDate) { final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); List<QuotaBalanceVO> quotaUsageRecords = null; List<QuotaBalanceVO> trimmedRecords = new ArrayList<QuotaBalanceVO>(); try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB)) { Filter filter = new Filter(QuotaBalanceVO.class, "updatedOn", false, 0L, 100L); SearchCriteria<QuotaBalanceVO> sc = createSearchCriteria(); if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if ((pivotDate != null)) { sc.addAnd("updatedOn", SearchCriteria.Op.LTEQ, pivotDate); } quotaUsageRecords = search(sc, filter); for (QuotaBalanceVO entry : quotaUsageRecords) { s_logger.info("findQuotaBalance Date=" + entry.getUpdatedOn().toGMTString() + " balance=" + entry.getCreditBalance() + " credit=" + entry.getCreditsId()); if (entry.getCreditsId() > 0) { trimmedRecords.add(entry); } else { trimmedRecords.add(entry); break; } } } catch (Exception e) { throw new CloudRuntimeException("Unable to get last quota balance"); } finally { TransactionLegacy.open(opendb).close(); } return trimmedRecords; }

Target:
public List<QuotaBalanceVO> lastQuotaBalanceVO(final Long accountId, final Long domainId, final Date pivotDate) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<List<QuotaBalanceVO>>() { @Override public List<QuotaBalanceVO> doInTransaction(final TransactionStatus status) { List<QuotaBalanceVO> quotaUsageRecords = null; List<QuotaBalanceVO> trimmedRecords = new ArrayList<QuotaBalanceVO>(); Filter filter = new Filter(QuotaBalanceVO.class, "updatedOn", false, 0L, 100L); QueryBuilder<QuotaBalanceVO> qb = QueryBuilder.create(QuotaBalanceVO.class); if (accountId != null) { qb.and(qb.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); } if (domainId != null) { qb.and(qb.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); } if ((pivotDate != null)) { qb.and(qb.entity().getUpdatedOn(), SearchCriteria.Op.LTEQ, pivotDate); } quotaUsageRecords = search(qb.create(), filter); for (QuotaBalanceVO entry : quotaUsageRecords) { if (s_logger.isDebugEnabled()) { s_logger.debug("FindQuotaBalIance Entry=" + entry); } if (entry.getCreditsId() > 0) { trimmedRecords.add(entry); } else { trimmedRecords.add(entry); break; } } return trimmedRecords; } }); }
Source:
public <T extends Object> T toObject(Class<T> c) { if (JsonSerializable.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Number.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c)) { throw new IllegalArgumentException("c can only be a POJO class or JSONObject"); } if (JSONObject.class.isAssignableFrom(c)) { if (JSONObject.class != c) { throw new IllegalArgumentException("We support JSONObject but not its sub-classes."); } return c.cast(this.propertyBag); } else { if (c.isMemberClass() && !Modifier.isStatic(c.getModifiers())) { throw new IllegalArgumentException("Nested classes must be static."); } try { return new ObjectMapper().readValue(this.toString(), c); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Failed to get POJO.", e); } } }

Target:
public <T extends Object> T toObject(Class<T> c) { if (JsonSerializable.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Number.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c)) { throw new IllegalArgumentException("c can only be a POJO class or JSONObject"); } if (JSONObject.class.isAssignableFrom(c)) { if (JSONObject.class != c) { throw new IllegalArgumentException("We support JSONObject but not its sub-classes."); } return c.cast(this.propertyBag); } else { checkForValidPOJO(c); try { return new ObjectMapper().readValue(this.toString(), c); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Failed to get POJO.", e); } } }
Source:
public boolean containsSensitiveData() { BaseObject familyObject = getXDocument().getXObject(Family.CLASS_REFERENCE); return (familyObject.getIntValue(WARNING) != 0); }

Target:
public boolean containsSensitiveData() { BaseObject familyObject = getXDocument().getXObject(Family.CLASS_REFERENCE); return (familyObject.getIntValue(FIELD_HAS_SENSITIVE_DATA) == FIELD_VALUE_CHECKED); }
Source:
public void logout() { finish(); mOpenMRS.clearUserPreferencesData(); mAuthorizationManager.moveToLoginActivity(); OpenMRSDBOpenHelper.getInstance().closeDatabases(); }

Target:
public void logout() { mOpenMRS.clearUserPreferencesData(); mAuthorizationManager.moveToLoginActivity(); OpenMRSDBOpenHelper.getInstance().closeDatabases(); }
Source:
private S3ProxyRule(Builder builder) { accessKey = builder.accessKey; secretKey = builder.secretKey; Properties properties = new Properties(); try { blobStoreLocation = Files.createTempDirectory("S3ProxyRule") .toFile(); blobStoreLocation.deleteOnExit(); properties.setProperty("jclouds.filesystem.basedir", blobStoreLocation.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException("Unable to initialize Blob Store", e); } BlobStoreContext context = ContextBuilder.newBuilder( builder.blobStoreProvider) .credentials(accessKey, secretKey) .overrides(properties).build(BlobStoreContext.class); S3Proxy.Builder s3ProxyBuilder = S3Proxy.builder() .blobStore(context.getBlobStore()) .awsAuthentication(builder.authType, accessKey, secretKey) .ignoreUnknownHeaders(builder.ignoreUnknownHeaders); if (builder.secretStorePath != null || builder.secretStorePassword != null) { s3ProxyBuilder.keyStore(builder.secretStorePath, builder.secretStorePassword); } int port = builder.port < 0 ? 0 : builder.port; if (builder.useHttps) { endpointFormat = "https://%s:%d"; String endpoint = String.format(endpointFormat, LOCALHOST, port); s3ProxyBuilder.secureEndpoint(URI.create(endpoint)); } else { endpointFormat = "http://%s:%d"; String endpoint = String.format(endpointFormat, LOCALHOST, port); s3ProxyBuilder.endpoint(URI.create(endpoint)); } s3Proxy = s3ProxyBuilder.build(); }

Target:
private S3ProxyRule(Builder builder) { accessKey = builder.accessKey; secretKey = builder.secretKey; Properties properties = new Properties(); try { blobStoreLocation = Files.createTempDirectory("S3ProxyRule") .toFile(); properties.setProperty("jclouds.filesystem.basedir", blobStoreLocation.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException("Unable to initialize Blob Store", e); } blobStoreContext = ContextBuilder.newBuilder( builder.blobStoreProvider) .credentials(accessKey, secretKey) .overrides(properties).build(BlobStoreContext.class); S3Proxy.Builder s3ProxyBuilder = S3Proxy.builder() .blobStore(blobStoreContext.getBlobStore()) .awsAuthentication(builder.authType, accessKey, secretKey) .ignoreUnknownHeaders(builder.ignoreUnknownHeaders); if (builder.secretStorePath != null || builder.secretStorePassword != null) { s3ProxyBuilder.keyStore(builder.secretStorePath, builder.secretStorePassword); } int port = builder.port < 0 ? 0 : builder.port; endpointFormat = "http://%s:%d"; String endpoint = String.format(endpointFormat, LOCALHOST, port); s3ProxyBuilder.endpoint(URI.create(endpoint)); s3Proxy = s3ProxyBuilder.build(); }
Source:
public SimplifiedMasternodeListManager(Context context) { super(context); if (Runtime.getRuntime().totalMemory() <= Math.pow(1024, 3)) { MAX_CACHE_SIZE = 1; } tipBlockHash = params.getGenesisBlock().getHash(); mnList = new SimplifiedMasternodeList(context.getParams()); quorumList = new SimplifiedQuorumList(context.getParams()); lastRequestTime = 0; waitingForMNListDiff = false; pendingBlocks = new ArrayList<StoredBlock>(); pendingBlocksMap = new LinkedHashMap<Sha256Hash, StoredBlock>(); saveOptions = SaveOptions.SAVE_EVERY_CHANGE; syncOptions = SyncOptions.SYNC_MINIMUM; syncInterval = 8; loadedFromFile = false; requiresLoadingFromFile = true; lastRequestMessage = new GetSimplifiedMasternodeListDiff(Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH); }

Target:
public SimplifiedMasternodeListManager(Context context) { super(context); tipBlockHash = params.getGenesisBlock().getHash(); mnList = new SimplifiedMasternodeList(context.getParams()); quorumList = new SimplifiedQuorumList(context.getParams()); lastRequestTime = 0; waitingForMNListDiff = false; pendingBlocks = new ArrayList<StoredBlock>(); pendingBlocksMap = new LinkedHashMap<Sha256Hash, StoredBlock>(); saveOptions = SaveOptions.SAVE_EVERY_CHANGE; syncOptions = SyncOptions.SYNC_MINIMUM; syncInterval = 8; loadedFromFile = false; requiresLoadingFromFile = true; lastRequestMessage = new GetSimplifiedMasternodeListDiff(Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH); }
Source:
public void applyRevisionConstraint(GetObjectRequest request, String revisionId) { if (revisionId != null) { LOG.debug("Restricting request to etag {}", revisionId); request.withMatchingETagConstraint(revisionId); } }

Target:
public void applyRevisionConstraint(GetObjectRequest request, String revisionId) { if (revisionId != null) { LOG.debug("Restricting get request to etag {}", revisionId); request.withMatchingETagConstraint(revisionId); } }
Source:
public PlanNodeStatsEstimate calculateStats(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { if (node instanceof RemoteSourceNode) { return calculateRemoteSourceStats((RemoteSourceNode) node, sourceStats, lookup, session, types); } return delegate.calculateStats(node, sourceStats, lookup, session, types); }

Target:
public PlanNodeStatsEstimate calculateStats(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { if (node instanceof RemoteSourceNode) { return calculateRemoteSourceStats((RemoteSourceNode) node, sourceStats); } return delegate.calculateStats(node, sourceStats, lookup, session, types); }
Source:
@Override public Collection<TableInformation> tablesInformation(String schemaNamePtrn, String tblNamePtrn, String... tblTypes) { Set<String> types = F.isEmpty(tblTypes) ? Collections.emptySet() : new HashSet<>(Arrays.asList(tblTypes)); Collection<TableInformation> infos = new ArrayList<>(); if (F.isEmpty(tblTypes) || types.contains(TableType.TABLE.name())) { schemaMgr.dataTables().stream() .filter(t -> matches(t.getSchema().getName(), schemaNamePtrn)) .filter(t -> matches(t.getName(), tblNamePtrn)) .map(t -> { int cacheGrpId = t.cacheInfo().groupId(); CacheGroupDescriptor cacheGrpDesc = ctx.cache().cacheGroupDescriptors().get(cacheGrpId); if (cacheGrpDesc == null) return null; GridQueryTypeDescriptor type = t.rowDescriptor().type(); IndexColumn affCol = t.getExplicitAffinityKeyColumn(); String affinityKeyCol = affCol != null ? affCol.columnName : null; return new TableInformation(t.getSchema().getName(), t.getName(), TableType.TABLE.name(), cacheGrpId, cacheGrpDesc.cacheOrGroupName(), t.cacheId(), t.cacheName(), affinityKeyCol, type.keyFieldAlias(), type.valueFieldAlias(), type.keyTypeName(), type.valueTypeName()); }) .filter(Objects::nonNull) .forEach(infos::add); } if ((F.isEmpty(tblTypes) || types.contains(TableType.VIEW.name())) && matches(QueryUtils.SCHEMA_SYS, schemaNamePtrn)) { schemaMgr.systemViews().stream() .filter(t -> matches(t.getTableName(), tblNamePtrn)) .map(v -> new TableInformation(QueryUtils.SCHEMA_SYS, v.getTableName(), TableType.VIEW.name())) .forEach(infos::add); } return infos; }

Target:
@Override public Collection<TableInformation> tablesInformation(String schemaNamePtrn, String tblNamePtrn, String... tblTypes) { Set<String> types = F.isEmpty(tblTypes) ? Collections.emptySet() : new HashSet<>(Arrays.asList(tblTypes)); Collection<TableInformation> infos = new ArrayList<>(); boolean allTypes = F.isEmpty(tblTypes); if (allTypes || types.contains(TableType.TABLE.name())) { schemaMgr.dataTables().stream() .filter(t -> matches(t.getSchema().getName(), schemaNamePtrn)) .filter(t -> matches(t.getName(), tblNamePtrn)) .map(t -> { int cacheGrpId = t.cacheInfo().groupId(); CacheGroupDescriptor cacheGrpDesc = ctx.cache().cacheGroupDescriptors().get(cacheGrpId); if (cacheGrpDesc == null) return null; GridQueryTypeDescriptor type = t.rowDescriptor().type(); IndexColumn affCol = t.getExplicitAffinityKeyColumn(); String affinityKeyCol = affCol != null ? affCol.columnName : null; return new TableInformation(t.getSchema().getName(), t.getName(), TableType.TABLE.name(), cacheGrpId, cacheGrpDesc.cacheOrGroupName(), t.cacheId(), t.cacheName(), affinityKeyCol, type.keyFieldAlias(), type.valueFieldAlias(), type.keyTypeName(), type.valueTypeName()); }) .filter(Objects::nonNull) .forEach(infos::add); } if ((allTypes || types.contains(TableType.VIEW.name())) && matches(QueryUtils.SCHEMA_SYS, schemaNamePtrn)) { schemaMgr.systemViews().stream() .filter(t -> matches(t.getTableName(), tblNamePtrn)) .map(v -> new TableInformation(QueryUtils.SCHEMA_SYS, v.getTableName(), TableType.VIEW.name())) .forEach(infos::add); } return infos; }
Source:
public int getCategory() { return 0; }

Target:
public int getCategory() { return Category.MISC; }
Source:
private boolean deleteRowIfExpired(List<Cell> cellList) throws IOException { long cellListSize = cellList.size(); if (cellListSize == 0) { return true; } Iterator<Cell> cellIterator = cellList.iterator(); Cell firstCell = cellIterator.next(); byte[] rowKey = new byte[firstCell.getRowLength()]; System.arraycopy(firstCell.getRowArray(), firstCell.getRowOffset(), rowKey, 0, firstCell.getRowLength()); boolean isRowExpired = !checkRowNotExpired(cellList); if (isRowExpired) { long ttl = ScanUtil.getPhoenixTTL(this.scan); long ts = getMaxTimestamp(cellList); LOG.debug(String.format( "** PHOENIX-TTL: Deleting region = %s, row = %s, delete-ts = %d, max-ts = %d ** ", region.getRegionInfo().getTable().getNameAsString(), Bytes.toString(rowKey), now - ttl, ts)); Delete del = new Delete(rowKey, now - ttl); Mutation[] mutations = new Mutation[] { del }; region.batchMutate(mutations, HConstants.NO_NONCE, HConstants.NO_NONCE); return true; } return false; }

Target:
private boolean deleteRowIfExpired(List<Cell> cellList) throws IOException { long cellListSize = cellList.size(); if (cellListSize == 0) { return true; } Iterator<Cell> cellIterator = cellList.iterator(); Cell firstCell = cellIterator.next(); byte[] rowKey = new byte[firstCell.getRowLength()]; System.arraycopy(firstCell.getRowArray(), firstCell.getRowOffset(), rowKey, 0, firstCell.getRowLength()); boolean isRowExpired = !checkRowNotExpired(cellList); if (isRowExpired) { long ttl = ScanUtil.getPhoenixTTL(this.scan); long ts = ScanUtil.getMaxTimestamp(cellList); LOG.trace(String.format( "PHOENIX-TTL: Deleting row = [%s] belonging to table = %s, " + "scn = %s, now = %d, delete-ts = %d, max-ts = %d", Bytes.toString(rowKey), Bytes.toString(scanTableName), maxTimestamp != HConstants.LATEST_TIMESTAMP, now, now - ttl, ts)); Delete del = new Delete(rowKey, now - ttl); Mutation[] mutations = new Mutation[] { del }; region.batchMutate(mutations, HConstants.NO_NONCE, HConstants.NO_NONCE); return true; } return false; }
Source:
public static void beforeClass() throws Exception { helperJSONTreeMap = new TreeMap<String, Object>(); helperJSONTreeMap.put("Sunrise",true); helperJSONTreeMap.put("Sunset", false); helperJSONTreeMap.put("Data", "A run to the head of the blood"); TreeMap<String,Object> organizer = new TreeMap<String, Object>(); organizer.put("Name", "Tom"); organizer.put( "Sex", "Male" ); helperJSONTreeMap.put( "Organizer",organizer); ArrayList<Number> fullhours = new ArrayList<Number>(); fullhours.add(1); fullhours.add(2); fullhours.add(3); fullhours.add(4); fullhours.add(5); fullhours.add(6); fullhours.add(7); fullhours.add(8); fullhours.add(9); fullhours.add(10); helperJSONTreeMap.put("FullHours", fullhours); TreeMap<String,Object> football = new TreeMap<String, Object>(); football.put("Name", "Football"); football.put("Duration", 2); football.put("DurationUnit","Hours"); TreeMap<String,Object> breakfast = new TreeMap<String, Object>(); breakfast.put("Name","Breakfast"); breakfast.put( "Duration",40); breakfast.put( "DurationUnit","Minutes"); ArrayList<String> attendees = new ArrayList<String>(); attendees.add("Jan"); attendees.add("Damien"); attendees.add("Laura"); attendees.add("Gwendolyn"); attendees.add("Roseanna"); breakfast.put( "Attendees",attendees); ArrayList<TreeMap> activities = new ArrayList<TreeMap>(); activities.add(football); activities.add(breakfast); helperJSONTreeMap.put("Activities", activities); expectedJson = FileUtils.readFileToString( TestUtils.loadFixture("fixture/json_helper_compacted.json") ); }

Target:
public static void beforeClass() throws Exception { expectedJSONMap = new TreeMap<String, Object>(); expectedJSONMap.put("Sunrise", true); expectedJSONMap.put("Sunset", false); expectedJSONMap.put("Data", "A run to the head of the blood"); TreeMap<String,Object> organizer = new TreeMap<String, Object>(); organizer.put("Name", "Tom"); organizer.put( "Sex", "Male"); expectedJSONMap.put("Organizer", organizer); ArrayList<Number> fullhours = new ArrayList<Number>(); fullhours.add(1); fullhours.add(2); fullhours.add(3); fullhours.add(4); fullhours.add(5); fullhours.add(6); fullhours.add(7); fullhours.add(8); fullhours.add(9); fullhours.add(10); expectedJSONMap.put("FullHours", fullhours); TreeMap<String,Object> football = new TreeMap<String, Object>(); football.put("Name", "Football"); football.put("Duration", 2); football.put("DurationUnit", "Hours"); TreeMap<String,Object> breakfast = new TreeMap<String, Object>(); breakfast.put("Name","Breakfast"); breakfast.put("Duration", 40); breakfast.put("DurationUnit", "Minutes"); ArrayList<String> attendees = new ArrayList<String>(); attendees.add("Jan"); attendees.add("Damien"); attendees.add("Laura"); attendees.add("Gwendolyn"); attendees.add("Roseanna"); breakfast.put("Attendees",attendees); ArrayList<TreeMap> activities = new ArrayList<TreeMap>(); activities.add(football); activities.add(breakfast); expectedJSONMap.put("Activities", activities); expectedJson = FileUtils.readFileToString( TestUtils.loadFixture("fixture/json_helper_compacted.json") ); }
Source:
private Collection generateRefactoringActions(final ISelection selection, final IEditorPart editor) { Set<AbstractEObjectRefactoringAction> allActions = Sets.newLinkedHashSet(); allActions.add(new BorderRefactoringAction(editor, selection)); allActions.add(new EdgeMappingRefactoringAction(editor, selection)); allActions.add(new GroupOnToolSectionAction(editor, selection)); allActions.add(new GroupOnToolGroupAction(editor, selection)); allActions.add(new GroupOnToolGroupExtensionAction(editor, selection)); return Sets.filter(allActions, new Predicate<AbstractEObjectRefactoringAction>() { public boolean apply(AbstractEObjectRefactoringAction candidateAction) { return candidateAction.isSelectionValid(); } }); }

Target:
private Collection generateRefactoringActions(final ISelection selection, final IEditorPart editor) { Set<AbstractEObjectRefactoringAction> allActions = Sets.newLinkedHashSet(); allActions.add(new BorderRefactoringAction(editor, selection)); allActions.add(new EdgeMappingRefactoringAction(editor, selection)); allActions.add(new GroupIntoToolSectionAction(editor, selection)); allActions.add(new GroupIntoToolGroupAction(editor, selection)); allActions.add(new GroupIntoToolGroupExtensionAction(editor, selection)); return Sets.filter(allActions, new Predicate<AbstractEObjectRefactoringAction>() { public boolean apply(AbstractEObjectRefactoringAction candidateAction) { return candidateAction.isSelectionValid(); } }); }
Source:
public void should_cleanup_on_lbp_init_failure() throws Exception { try { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .without(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER) .build(); CqlSession.builder() .addContactPoints(simulacronRule.getContactPoints()) .withConfigLoader(loader) .build(); fail("Should have thrown a DriverException for no DC with explicit contact point"); } catch (DriverException e) { } int size = 1; long maxTime = System.currentTimeMillis() + 1000; while (size > 0 && System.currentTimeMillis() < maxTime) { ClusterConnectionReport report = simulacronRule.cluster().getConnections(); size = report.getConnections().size(); } assertThat(size).isEqualTo(0); }

Target:
public void should_cleanup_on_lbp_init_failure() { try { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .without(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER) .build(); CqlSession.builder() .addContactPoints(simulacronRule.getContactPoints()) .withConfigLoader(loader) .build(); fail("Should have thrown a DriverException for no DC with explicit contact point"); } catch (DriverException ignored) { } checkThat(() -> simulacronRule.cluster().getConnections().getConnections().isEmpty()) .before(1, SECONDS) .becomesTrue(); }
Source:
public DiskImage(Boolean active, Date creation_date, Date last_modified_date, long actual_size, String description, Guid image_guid, String internal_drive_mapping, Guid it_guid, long size, Guid parentId, ImageStatus imageStatus, Date lastModified, String appList, VmEntityType vmEntityType, int numberOfVms, Guid quotaId, String quotaName, QuotaEnforcementTypeEnum quotaEnforcementType, boolean isQuotaDefault) { setActive(active); setCreationDate(creation_date); setLastModifiedDate(last_modified_date); actualSizeFromDiskImageDynamic = actual_size; this.description = description; setImageId(image_guid); setImageTemplateGuid(it_guid); setSize(size); setParentId(parentId); setImageStatus(imageStatus); setLastModified(lastModified); setAppList(appList); setVmEntityType(vmEntityType); setNumberOfVms(numberOfVms); setQuotaId(quotaId); setQuotaName(quotaName); setQuotaEnforcementType(quotaEnforcementType); setIsQuotaDefault(isQuotaDefault); }

Target:
public DiskImage(Boolean active, Date creation_date, Date last_modified_date, long actual_size, String description, Guid image_guid, String internal_drive_mapping, Guid it_guid, long size, Guid parentId, ImageStatus imageStatus, Date lastModified, String appList, VmEntityType vmEntityType, int numberOfVms, Guid quotaId, String quotaName, QuotaEnforcementTypeEnum quotaEnforcementType, boolean isQuotaDefault) { setActive(active); setCreationDate(creation_date); setLastModifiedDate(last_modified_date); actualSizeFromDiskImageDynamic = actual_size; setDescription(description); setImageId(image_guid); setImageTemplateId(it_guid); setSize(size); setParentId(parentId); setImageStatus(imageStatus); setLastModified(lastModified); setAppList(appList); setVmEntityType(vmEntityType); setNumberOfVms(numberOfVms); setQuotaId(quotaId); setQuotaName(quotaName); setQuotaEnforcementType(quotaEnforcementType); setIsQuotaDefault(isQuotaDefault); }
Source:
private void templateBasedExport() throws Exception { AtomicBoolean seenTemplateRow = new AtomicBoolean(false); LineBasedProcessor.create(templateFile.name(), templateFile.createInputStream()).run((rowNumber, row) -> { if (row.length() == 0) { return; } if (!dictionary.hasMappings()) { determineMappingsFromRow(rowNumber, row); } else { if (!seenTemplateRow.get()) { process.log(ProcessLog.info().withNLSKey("EntityExportJob.startingTemplateBasedExport")); seenTemplateRow.set(true); } handleTemplateRow(rowNumber, row); } }, error -> { process.handle(error); return true; }); if (!seenTemplateRow.get()) { fullExportWithGivenMapping(); } }

Target:
private void templateBasedExport() throws Exception { Monoflop seenTemplateRow = Monoflop.create(); LineBasedProcessor.create(templateFile.name(), templateFile.createInputStream()).run((rowNumber, row) -> { if (row.length() == 0) { return; } if (!dictionary.hasMappings()) { determineMappingsFromRow(rowNumber, row); } else { if (seenTemplateRow.firstCall()) { process.log(ProcessLog.info().withNLSKey("EntityExportJob.startingTemplateBasedExport")); } handleTemplateRow(rowNumber, row); } }, error -> { process.handle(error); return true; }); if (!seenTemplateRow.isToggled()) { fullExportWithGivenMapping(); } }
Source:
public SslHandler build(ByteBufAllocator bufferAllocator) throws IOException, NoSuchAlgorithmException, CertificateException { SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase); logger.debug("Ciphers: " + String.join(",", ciphers)); builder.ciphers(Arrays.asList(ciphers)); if(requireClientAuth()) { logger.debug("Certificate Authorities: " + String.join(", ", certificateAuthorities)); builder.trustManager(loadCertificateCollection(certificateAuthorities)); } SslContext context = builder.build(); SslHandler sslHandler = context.newHandler(bufferAllocator); logger.debug("TLS: " + String.join(",", protocols)); SSLEngine engine = sslHandler.engine(); engine.setEnabledProtocols(protocols); if(requireClientAuth()) { engine.setUseClientMode(false); if(verifyMode == SslClientVerifyMode.FORCE_PEER) { engine.setNeedClientAuth(true); } else if(verifyMode == SslClientVerifyMode.VERIFY_PEER) { engine.setWantClientAuth(true); } } return sslHandler; }

Target:
public SslHandler build(ByteBufAllocator bufferAllocator) throws IOException, NoSuchAlgorithmException, CertificateException { SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase); if(logger.isDebugEnabled()) logger.debug("Ciphers: ", String.join(",", ciphers)); builder.ciphers(Arrays.asList(ciphers)); if(requireClientAuth()) { if (logger.isDebugEnabled()) logger.debug("Certificate Authorities: " + String.join(", ", certificateAuthorities)); builder.trustManager(loadCertificateCollection(certificateAuthorities)); } SslContext context = builder.build(); SslHandler sslHandler = context.newHandler(bufferAllocator); if(logger.isDebugEnabled()) logger.debug("TLS: " + String.join(",", protocols)); SSLEngine engine = sslHandler.engine(); engine.setEnabledProtocols(protocols); if(requireClientAuth()) { engine.setUseClientMode(false); if(verifyMode == SslClientVerifyMode.FORCE_PEER) { engine.setNeedClientAuth(true); } else if(verifyMode == SslClientVerifyMode.VERIFY_PEER) { engine.setWantClientAuth(true); } } return sslHandler; }
Source:
public OSImageToImage(JustProvider provider) { this.provider = provider; }

Target:
OSImageToImage(JustProvider provider) { this.provider = provider; }
Source:
@Test public void postWithFieldParamList() throws Exception { List<Object> values = new ArrayList<Object>(Arrays.asList(1, 2, "three")); Request request = new Helper() .setMethod("POST") .setUrl("<LINK_1>") .setPath("/foo/bar/") .addField("key", values) .setFormEncoded() .build(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getHeaders()).isEmpty(); assertThat(request.getUrl()).isEqualTo("<LINK_0>"); assertTypedBytes(request.getBody(), "key=1&key=2&key=three"); }

Target:
@Test public void postWithFieldParamList() throws Exception { List<String> values = Arrays.asList("one", "two",null, "three"); Request request = new Helper() .setMethod("POST") .setUrl("<LINK_1>") .setPath("/foo/bar/") .addField("key", values) .setFormEncoded() .build(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getHeaders()).isEmpty(); assertThat(request.getUrl()).isEqualTo("<LINK_0>"); assertTypedBytes(request.getBody(), "key=one&key=two&key=three"); }
Source:
private static boolean referenceByMapping( RexNode joinCondition, List<RexNode>... projectsOfInputs) { List<RexNode> projects = new ArrayList<>(); for (List<RexNode> projectsOfInput: projectsOfInputs) { projects.addAll(projectsOfInput); } try { RexVisitor rexVisitor = new RexVisitorImpl<Void>(true) { @Override public Void visitInputRef(RexInputRef inputRef) { if (!(projects.get(inputRef.getIndex()) instanceof RexInputRef)) { throw new Util.FoundOne(inputRef); } return super.visitInputRef(inputRef); } }; joinCondition.accept(rexVisitor); } catch (Util.FoundOne e) { return false; } return true; }

Target:
private static boolean referenceByMapping( RexNode joinCondition, List<RexNode>... projectsOfInputs) { List<RexNode> projects = new ArrayList<>(); for (List<RexNode> projectsOfInput: projectsOfInputs) { projects.addAll(projectsOfInput); } try { RexVisitor rexVisitor = new RexVisitorImpl<Void>(true) { @Override public Void visitInputRef(RexInputRef inputRef) { if (!(projects.get(inputRef.getIndex()) instanceof RexInputRef)) { throw Util.FoundOne.NULL; } return super.visitInputRef(inputRef); } }; joinCondition.accept(rexVisitor); } catch (Util.FoundOne e) { return false; } return true; }
Source:
public Map<String, Map<Integer, VariableType>> getStandardVariableIdsWithTypeByPropertyNames(final List<String> propertyNames) throws MiddlewareQueryException { final List<String> propertyNamesInUpperCase = Lists.transform(propertyNames, new Function<String, String>() { public String apply(String s) { return s.toUpperCase(); } }); try { if (!propertyNamesInUpperCase.isEmpty()) { Criteria criteria = this.getSession().createCriteria(this.getPersistentClass(), "property") .setProjection(Projections.distinct(Projections.projectionList() .add(Projections.property("alias")) .add(Projections.property("variableId")) .add(Projections.property("typeId")))); criteria.add(Restrictions.in("typeId", VariableType.ids())); criteria.add(Restrictions.in("alias", propertyNames)); criteria.createAlias("property.variable", "variable").add(Restrictions.eq("variable.isObsolete", 0)); List<Object[]> results = criteria.list(); return convertToVariablestandardVariableIdsWithTypeMap(results); } } catch (HibernateException e) { this.logAndThrowException( "Error in getStandardVariableIdsWithTypeByPropertyNames=" + propertyNames + " in ProjectPropertyDao: " + e.getMessage(), e); } return new HashMap<String, Map<Integer, VariableType>>(); }

Target:
public Map<String, Map<Integer, VariableType>> getStandardVariableIdsWithTypeByPropertyNames(final List<String> propertyNames) { final List<String> propertyNamesInUpperCase = Lists.transform(propertyNames, new Function<String, String>() { public String apply(String s) { return s.toUpperCase(); } }); try { if (!propertyNamesInUpperCase.isEmpty()) { Criteria criteria = this.getSession().createCriteria(this.getPersistentClass(), "property") .setProjection(Projections.distinct(Projections.projectionList() .add(Projections.property("alias")) .add(Projections.property("variableId")) .add(Projections.property("typeId")))); criteria.add(Restrictions.in("typeId", VariableType.ids())); criteria.add(Restrictions.in("alias", propertyNames)); criteria.createAlias("property.variable", "variable").add(Restrictions.eq("variable.isObsolete", 0)); List<Object[]> results = criteria.list(); return convertToVariablestandardVariableIdsWithTypeMap(results); } } catch (HibernateException e) { this.logAndThrowException( "Error in getStandardVariableIdsWithTypeByPropertyNames=" + propertyNames + " in ProjectPropertyDao: " + e.getMessage(), e); } return new HashMap<String, Map<Integer, VariableType>>(); }
Source:
public PlayerBackpack(@Nonnull PlayerProfile profile, int id) { this(profile, id, profile.getConfig().getInt(PlayerBackpack.backpacks + id + ".size")); for (int i = 0; i < size; i++) { inventory.setItem(i, cfg.getItem(PlayerBackpack.backpacks + id + ".contents." + i)); } }

Target:
public PlayerBackpack(@Nonnull PlayerProfile profile, int id) { this(profile, id, profile.getConfig().getInt(CONFIG_PREFIX + id + ".size")); for (int i = 0; i < size; i++) { inventory.setItem(i, cfg.getItem(CONFIG_PREFIX + id + ".contents." + i)); } }
Source:
public void testPutRemovePut() { Map<byte[], byte[]> map = cache(0); byte[] key = randomBytes(KEY_SIZE); byte[] value = randomBytes(VALUE_SIZE); byte[] value2 = randomBytes(VALUE_SIZE); assertNull(map.put(key, value)); for (int i = 0; i < 0; ++i) { map.put(randomBytes(KEY_SIZE), value); } assertEquals(value, map.remove(key)); assertNull(map.put(key, value)); assertEquals(value, map.remove(key)); assertNull(map.put(key, value2)); }

Target:
public void testPutRemovePut() { Map<byte[], byte[]> map = cache(0); byte[] key = randomBytes(KEY_SIZE); byte[] value = randomBytes(VALUE_SIZE); byte[] value2 = randomBytes(VALUE_SIZE); assertNull(map.put(key, value)); for (int i = 0; i < 50; ++i) { map.put(randomBytes(KEY_SIZE), value); } assertEquals(value, map.remove(key)); assertNull(map.put(key, value)); assertEquals(value, map.remove(key)); assertNull(map.put(key, value2)); }
Source:
public IdentificationNumber(final String last8Digits) { validateLast8Digits(last8Digits); if (StringUtils.isBlank(last8Digits)) { this.last8Digits = null; } else { this.last8Digits = String.format("%08d", Integer.valueOf(last8Digits)); } }

Target:
private IdentificationNumber(final String last8Digits) { validateLast8Digits(last8Digits); if (StringUtils.isBlank(last8Digits)) { this.last8Digits = null; } else { this.last8Digits = String.format("%08d", Integer.valueOf(last8Digits)); } }
Source:
void removeNestedCopyfiles() { for (RepoProject proj : filteredProjects) { List<CopyFile> copyfiles = new ArrayList<CopyFile>(); copyfiles.addAll(proj.getCopyFiles()); proj.clearCopyFiles(); Iterator<CopyFile> iter = copyfiles.iterator(); while (iter.hasNext()) { if (isNestedCopyfile(iter.next())) iter.remove(); } proj.addCopyFiles(copyfiles); } }

Target:
void removeNestedCopyfiles() { for (RepoProject proj : filteredProjects) { List<CopyFile> copyfiles = new ArrayList<>(); copyfiles.addAll(proj.getCopyFiles()); proj.clearCopyFiles(); Iterator<CopyFile> iter = copyfiles.iterator(); while (iter.hasNext()) { if (isNestedCopyfile(iter.next())) { iter.remove(); } } proj.addCopyFiles(copyfiles); } }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(partitionId); sb.append(" ServerErrorCode=").append(errorCode); if (errorCode == ServerErrorCode.No_Error) { int size = messageInfoAndMetadataListSerde.getMessageInfoList().size(); sb.append(" Token=").append(token); sb.append(" MessageInfoListSize=").append(size); sb.append(" MessagesTotalSize=").append(totalSizeOfAllMessages); sb.append(" MessageInfoListFirstId=") .append(messageInfoAndMetadataListSerde.getMessageInfoList().get(0).getStoreKey()); sb.append(" MessageInfoListLastId=") .append(messageInfoAndMetadataListSerde.getMessageInfoList().get(size - 1).getStoreKey()); sb.append(" RemoteReplicaLagInBytes=").append(remoteReplicaLagInBytes); } return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(partitionId); sb.append(" ServerErrorCode=").append(errorCode); if (errorCode == ServerErrorCode.No_Error) { List<MessageInfo> messageInfos = messageInfoAndMetadataListSerde.getMessageInfoList(); int size = messageInfos.size(); sb.append(" Token=").append(token); sb.append(" MessageInfoListSize=").append(size); sb.append(" MessagesTotalSize=").append(totalSizeOfAllMessages); sb.append(" MessageInfoListFirstId=").append(messageInfos.get(0).getStoreKey()); sb.append(" MessageInfoListLastId=").append(messageInfos.get(size - 1).getStoreKey()); sb.append(" RemoteReplicaLagInBytes=").append(remoteReplicaLagInBytes); } return sb.toString(); }
Source:
public void handleAction(Map<String, Object> parameters) throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException { String templateName = (String) parameters.get(Constants.TEMPLATE_NAME_PARAM); String recipientName = (String) parameters.get(Constants.RECIPIENT_NAME_PARAM); CdaTemplate cdaTemplate = iheTemplateDataService.findByName(templateName); if (cdaTemplate == null) { LOGGER.error("Cannot find template", templateName); throw new TemplateNotFoundException(templateName); } HL7Recipient hl7Recipient = hl7RecipientsService.getRecipientbyName(recipientName); if (hl7Recipient == null) { LOGGER.error("Cannot find recipient", recipientName); throw new RecipientNotFoundException(templateName); } Byte[] templateData = (Byte[]) iheTemplateDataService.getDetachedField(cdaTemplate, TEMPLATE_DATA_FIELD_NAME); StreamingTemplateEngine streamingTemplateEngine = new StreamingTemplateEngine(); Template template = streamingTemplateEngine.createTemplate(new String(ArrayUtils.toPrimitive(templateData))); Writable writable = template.make(parameters); LOGGER.info("Template with name {}:\n{}", cdaTemplate.getTemplateName(), writable.toString()); }

Target:
public void handleAction(Map<String, Object> parameters) throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException { String templateName = (String) parameters.get(Constants.TEMPLATE_NAME_PARAM); String recipientName = (String) parameters.get(Constants.RECIPIENT_NAME_PARAM); CdaTemplate cdaTemplate = iheTemplateDataService.findByName(templateName); if (cdaTemplate == null) { LOGGER.error("Cannot find template", templateName); throw new TemplateNotFoundException(templateName); } HL7Recipient hl7Recipient = hl7RecipientsService.getRecipientbyName(recipientName); if (hl7Recipient == null) { LOGGER.error("Cannot find recipient", recipientName); throw new RecipientNotFoundException(templateName); } Byte[] templateData = (Byte[]) iheTemplateDataService.getDetachedField(cdaTemplate, TEMPLATE_DATA_FIELD_NAME); StreamingTemplateEngine streamingTemplateEngine = new StreamingTemplateEngine(); Template template = streamingTemplateEngine.createTemplate(new String(ArrayUtils.toPrimitive(templateData))); Writable writable = template.make(parameters); LOGGER.info("Template with name {}:\n{}", cdaTemplate.getTemplateName(), writable.toString()); iheTemplateService.sendTemplateToRecipientUrl(hl7Recipient.getRecipientUrl(), writable.toString()); }
Source:
public void validate(FailureCollector collector) { if (Strings.isNullOrEmpty(schema)) { collector.addFailure("Schema must be specified.", null).withConfigProperty(Cassandra.SCHEMA); } if (port != null && (port < 1 || port > 65535)) { collector.addFailure("Invalid port.", "Port number must be an integer from 1 to 65535.") .withConfigProperty(BatchCassandraSink.Cassandra.PORT); } if ((!containsMacro(Cassandra.USERNAME) && !containsMacro(Cassandra.PASSWORD)) && Strings.isNullOrEmpty(username) ^ Strings.isNullOrEmpty(password)) { collector.addFailure("Invalid username and password combination.", "You must either set both username and password or neither username nor password.") .withConfigProperty(Cassandra.USERNAME).withConfigProperty(Cassandra.PASSWORD); } }

Target:
public void validate(FailureCollector collector) { if (Strings.isNullOrEmpty(schema)) { collector.addFailure("Schema must be specified.", null).withConfigProperty(Cassandra.SCHEMA); } if (port != null && (port < 1 || port > 65535)) { collector.addFailure("Invalid port number.", "Port number must be an integer from 1 to 65535.") .withConfigProperty(BatchCassandraSink.Cassandra.PORT); } if (!containsMacro(Cassandra.USERNAME) && !containsMacro(Cassandra.PASSWORD) && Strings.isNullOrEmpty(username) ^ Strings.isNullOrEmpty(password)) { collector.addFailure("Invalid username and password combination.", "You must either set both username and password or neither username nor password.") .withConfigProperty(Cassandra.USERNAME).withConfigProperty(Cassandra.PASSWORD); } }