auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void replaceIcons(Class iconsClass, String iconsRootPath) { for (Field field : iconsClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { try { Object value = field.get(null); Class byClass = value.getClass(); if (byClass.getName().endsWith("$ByClass")) { setFieldValue(value, "myCallerClass", IconReplacer.class); setFieldValue(value, "myWasComputed", Boolean.FALSE); setFieldValue(value, "myIcon", null); } else if (byClass.getName().endsWith("$CachedImageIcon")) { String p = patchUrlIfNeeded(value, iconsRootPath); Icon newIcon = IconLoader.getIcon(p); setFinalStatic(field, newIcon); } } catch (IllegalAccessException e) { } catch (Exception e) { e.printStackTrace(); } } } for (Class subClass : iconsClass.getDeclaredClasses()) { replaceIcons(subClass, iconsRootPath); } }

Target:
public static void replaceIcons(Class iconsClass, String iconsRootPath) { for (Field field : iconsClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { try { Object value = field.get(null); Class byClass = value.getClass(); if (byClass.getName().endsWith("$ByClass")) { setFieldValue(value, "myCallerClass", IconReplacer.class); setFieldValue(value, "myWasComputed", Boolean.FALSE); setFieldValue(value, "myIcon", null); } else if (byClass.getName().endsWith("$CachedImageIcon")) { String newPath = patchUrlIfNeeded(value, iconsRootPath); if (newPath != null) { Icon newIcon = IconLoader.getIcon(newPath); setFinalStatic(field, newIcon); } } } catch (IllegalAccessException e) { } catch (Exception e) { } } } for (Class subClass : iconsClass.getDeclaredClasses()) { replaceIcons(subClass, iconsRootPath); } }
Source:
private void refreshSpinner(String selectedPulse) { mSpinner.setAdapter(mSpinnerAdapter); Collections.sort(mPulseTargets); mPulseTargets.add(0, PulseFragment.GLOBAL); if (selectedPulse == null) { selectedPulse = mPulseTargets.get(0); } mSpinnerAdapter.clear(); mSpinnerAdapter.addAll(mPulseTargets); mSpinner.setSelection(mPulseTargets.indexOf(selectedPulse)); mViewPagerAdapter = new PulsePagerAdapter(this, getSupportFragmentManager()); mViewPagerAdapter.setSelectedPulseTarget(selectedPulse); mViewPager.setAdapter(mViewPagerAdapter); mTabLayout.setupWithViewPager(mViewPager); }

Target:
private void refreshSpinner(String selectedPulse) { if (selectedPulse == null) { selectedPulse = mPulseTargets.get(0); } mSpinner.setSelection(mPulseTargets.indexOf(selectedPulse)); mViewPagerAdapter = new PulsePagerAdapter(this, getSupportFragmentManager()); mViewPagerAdapter.setSelectedPulseTarget(selectedPulse); mViewPager.setAdapter(mViewPagerAdapter); mTabLayout.setupWithViewPager(mViewPager); }
Source:
public Cohort() { members = new TreeSet<CohortMember>((o1, o2) -> o1.getPatientId().getId() - o2.getPatientId().getId()); }

Target:
public Cohort() { members = new TreeSet<CohortMembership>(); }
Source:
private SamplingDistribution(Operator child, SamplingType sampleType, Long randomSeed) { super(child); this.sampleType = sampleType; this.randomSeed = randomSeed; }

Target:
private SamplingDistribution(Operator child, SamplingType sampleType, Long randomSeed) { super(child); this.sampleType = sampleType; rand = new Random(); if (randomSeed != null) { rand.setSeed(randomSeed); } }
Source:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else { if (customSerializers.containsKey(type)) { return customSerializers.get(type); } } String message = String.format("Serializer with type code %s not found. " + "Please check custom serializers for this client.", type.intValue()); log.error(message); throw new RuntimeException(message); }

Target:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else if (customSerializers.containsKey(type)) { return customSerializers.get(type); } log.error("Serializer with type code not found. Please check custom serializers " + "for this client.", type.intValue()); throw new SerializerException(type); }
Source:
private static RegionShortcut setRegionType() { String regionType = System.getProperty(DEFAULT_REGION_SYS_PROP_NAME, "REPLICATE"); RegionShortcut type; try { type = RegionShortcut.valueOf(regionType); } catch (Exception e) { type = RegionShortcut.PARTITION; } return type; }

Target:
private static RegionShortcut setRegionType() { String regionType = System.getProperty(DEFAULT_REGION_SYS_PROP_NAME, "PARTITION"); RegionShortcut type; try { type = RegionShortcut.valueOf(regionType); } catch (Exception e) { type = RegionShortcut.PARTITION; } return type; }
Source:
public SmsDetails getSmsDetails(final DlmsDeviceMessageMetadata messageMetadata, final SmsDetails smsDetailsRequest) throws OsgpException, ProtocolAdapterException { final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); final GetSMSDetailsResponse response = this.smsClient.getSMSDetails(smsDetailsRequest.getSmsMsgId(), device.getIccId()); SmsDetails smsDetailsResponse = null; final List<SmsMessageType> smsMessagesTypes = response.getSmsMessages().getSmsMessage(); for (final SmsMessageType smsMessageType : smsMessagesTypes) { if (smsMessageType.getSmsMsgId() == smsDetailsRequest.getSmsMsgId().longValue()) { smsDetailsResponse = new SmsDetails(device.getDeviceIdentification(), smsMessageType.getSmsMsgId(), smsMessageType.getStatus(), smsMessageType.getSmsMsgAttemptStatus(), smsMessageType.getMsgType()); } } return smsDetailsResponse; }

Target:
public SmsDetails getSmsDetails(final DlmsDeviceMessageMetadata messageMetadata, final SmsDetails smsDetailsRequest) throws OsgpException { final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); final GetSMSDetailsResponse response = this.smsClient.getSMSDetails(smsDetailsRequest.getSmsMsgId(), device.getIccId()); SmsDetails smsDetailsResponse = null; final List<SmsMessageType> smsMessagesTypes = response.getSmsMessages().getSmsMessage(); for (final SmsMessageType smsMessageType : smsMessagesTypes) { if (smsMessageType.getSmsMsgId() == smsDetailsRequest.getSmsMsgId().longValue()) { smsDetailsResponse = new SmsDetails(device.getDeviceIdentification(), smsMessageType.getSmsMsgId(), smsMessageType.getStatus(), smsMessageType.getSmsMsgAttemptStatus(), smsMessageType.getMsgType()); } } return smsDetailsResponse; }
Source:
public void execute(Context context) throws SQLException { if (context.prepareSelect("select count(uuid) from organizations") .get(row -> row.getLong(1)) > 0) { String builtInQGUuid = context.prepareSelect("select uuid from quality_gates where is_built_in = ?") .setBoolean(1, true) .get(row -> row.getString(1)); if (builtInQGUuid == null) { throw new IllegalStateException("Unable to find the builtin quality gate"); } MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select uuid from organizations o " + " where " + " (select count(oqg.uuid) from org_quality_gates oqg where oqg.quality_gate_uuid = ? and oqg.organization_uuid = o.uuid) = 0") .setString(1, builtInQGUuid); massUpdate.rowPluralName("organizations"); massUpdate.update("insert into org_quality_gates (uuid, quality_gate_uuid, organization_uuid) values(?, ?, ?)"); massUpdate.execute((row, update) -> { update.setString(1, uuidFactory.create()); update.setString(2, builtInQGUuid); update.setString(3, row.getString(1)); return true; }); } }

Target:
public void execute(Context context) throws SQLException { Long nbOfOrganizations = context.prepareSelect("select count(uuid) from organizations") .get(row -> row.getLong(1)); if (nbOfOrganizations == 0) { return; } List<String> builtInQGUuids = context.prepareSelect("select uuid from quality_gates where is_built_in = ?") .setBoolean(1, true) .list(row -> row.getString(1)); checkState(!builtInQGUuids.isEmpty(), "Unable to find the builtin quality gate"); checkState(builtInQGUuids.size() == 1, "There are too many built in quality gates, one and only one is expected"); MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select uuid from organizations o " + " where " + " not exists (select 1 from org_quality_gates oqg where oqg.quality_gate_uuid = ? and oqg.organization_uuid = o.uuid)") .setString(1, builtInQGUuids.get(0)); massUpdate.rowPluralName("organizations"); massUpdate.update("insert into org_quality_gates (uuid, quality_gate_uuid, organization_uuid) values(?, ?, ?)"); massUpdate.execute((row, update) -> { update.setString(1, uuidFactory.create()); update.setString(2, builtInQGUuids.get(0)); update.setString(3, row.getString(1)); return true; }); }
Source:
public void testRequestDisabledStore() throws Exception { Catalog catalog = getCatalog(); StoreInfo store = catalog.getStoreByName("cdf", DataStoreInfo.class); store.setEnabled(false); catalog.save(store); Document doc = getAsDOM( "wfs?service=WFS&version=1.0.0&request=GetFeature&typename=cdf:Fifteen"); XMLAssert.assertXpathEvaluatesTo("1", "count( XMLAssert.assertXpathEvaluatesTo("InvalidParameterValue", " doc); XMLAssert.assertXpathEvaluatesTo("typeName", " }

Target:
public void testRequestDisabledStore() throws Exception { Catalog catalog = getCatalog(); StoreInfo store = catalog.getStoreByName("cdf", DataStoreInfo.class); try { store.setEnabled(false); catalog.save(store); Document doc = getAsDOM( "wfs?service=WFS&version=1.0.0&request=GetFeature&typename=cdf:Fifteen"); XMLAssert.assertXpathEvaluatesTo("1", "count( XMLAssert.assertXpathEvaluatesTo("InvalidParameterValue", " XMLAssert.assertXpathEvaluatesTo("typeName", " } finally { store.setEnabled(true); catalog.save(store); } }
Source:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (bucketSpan ^ (bucketSpan >>> 32)); result = 31 * result + (int) (startOfBuckets ^ (startOfBuckets >>> 32)); result = 31 * result + (int) (expiryPoint ^ (expiryPoint >>> 32)); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (bucketSpan ^ (bucketSpan >>> 32)); result = 31 * result + (int) (startOfBuckets ^ (startOfBuckets >>> 32)); result = 31 * result + (int) (endOfBuckets ^ (endOfBuckets >>> 32)); result = 31 * result + (int) (expiryPeriod ^ (expiryPeriod >>> 32)); result = 31 * result + (int) (expiryPoint ^ (expiryPoint >>> 32)); result = 31 * result + (int) (cleanupTimeInMillis ^ (cleanupTimeInMillis >>> 32)); return result; }
Source:
private GroupedExecutionProperties processChildren(PlanNode node) { boolean anyUseful = false; OptionalInt totalLifespans = OptionalInt.empty(); ImmutableList.Builder<PlanNodeId> capableTableScanNodes = ImmutableList.builder(); for (PlanNode source : node.getSources()) { GroupedExecutionProperties properties = source.accept(this, null); if (!properties.isCurrentNodeCapable()) { return GroupedExecutionProperties.notCapable(); } anyUseful |= properties.isSubTreeUseful(); if (!totalLifespans.isPresent()) { totalLifespans = OptionalInt.of(properties.totalLifespans); } else { checkState(totalLifespans.getAsInt() == properties.totalLifespans); } capableTableScanNodes.addAll(properties.capableTableScanNodes); } return new GroupedExecutionProperties(true, anyUseful, capableTableScanNodes.build(), totalLifespans.getAsInt()); }

Target:
private GroupedExecutionProperties processChildren(PlanNode node) { boolean anyUseful = false; OptionalInt totalLifespans = OptionalInt.empty(); ImmutableList.Builder<PlanNodeId> capableTableScanNodes = ImmutableList.builder(); for (PlanNode source : node.getSources()) { GroupedExecutionProperties properties = source.accept(this, null); if (!properties.isCurrentNodeCapable()) { return GroupedExecutionProperties.notCapable(); } anyUseful |= properties.isSubTreeUseful(); if (!totalLifespans.isPresent()) { totalLifespans = OptionalInt.of(properties.totalLifespans); } else { checkState(totalLifespans.getAsInt() == properties.totalLifespans, format("Mismatched number of lifespans among children nodes. Expected: %s, actual: %s", totalLifespans.getAsInt(), properties.totalLifespans)); } capableTableScanNodes.addAll(properties.capableTableScanNodes); } return new GroupedExecutionProperties(true, anyUseful, capableTableScanNodes.build(), totalLifespans.getAsInt()); }
Source:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsWritable(OUTPUT); final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT); if( !ASSUME_SORTED && reader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) { throw new SAMException("Input must be coordinate-sorted, or ASSUME_SORTED must be true."); } if( ASSUME_SORTED && reader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) { log.warn("File indicates sort-order " + reader.getFileHeader().getSortOrder() + " but ASSUME_SORTED is true, so continuing."); } reader.getFileHeader().setSortOrder(SAMFileHeader.SortOrder.coordinate); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, OUTPUT); writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); final ReferenceSequenceFileWalker refSeq = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE); for (final SAMRecord rec : reader) { if (!rec.getReadUnmappedFlag()) { AbstractAlignmentMerger.fixNMandUQ(rec, refSeq, IS_BISULFITE_SEQUENCE); } writer.addAlignment(rec); } CloserUtil.close(reader); writer.close(); return 0; }

Target:
protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsWritable(OUTPUT); final SamReader reader = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(INPUT); if (!ASSUME_SORTED && reader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) { throw new SAMException("Input must be coordinate-sorted, or ASSUME_SORTED must be true."); } if (ASSUME_SORTED && reader.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) { log.warn("File indicates sort-order " + reader.getFileHeader().getSortOrder() + " but ASSUME_SORTED is true, so continuing."); } final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, OUTPUT); writer.setProgressLogger( new ProgressLogger(log, (int) 1e7, "Wrote", "records")); final ReferenceSequenceFileWalker refSeq = new ReferenceSequenceFileWalker(REFERENCE_SEQUENCE); for (final SAMRecord rec : reader) { if (!rec.getReadUnmappedFlag()) { AbstractAlignmentMerger.fixNMandUQ(rec, refSeq, IS_BISULFITE_SEQUENCE); } writer.addAlignment(rec); } CloserUtil.close(reader); writer.close(); return 0; }
Source:
public void setPushRegistrationId(String registrationId) { if (MPConfig.DEBUG) Log.d(LOGTAG, "setting push registraiton id: " + registrationId); mPushPref.edit().putString("push_id", registrationId).commit(); List<String> ids = new LinkedList<String>(); ids.add(registrationId); set("$android_devices", new JSONArray(ids)); }

Target:
public void setPushRegistrationId(String registrationId) { if (MPConfig.DEBUG) Log.d(LOGTAG, "setting push registration id: " + registrationId); if (this.distinct_id == null) { return; } mPushPref.edit().putString("push_id", registrationId).commit(); try { sExecutor.submit(new PeopleQueueTask("$union", new JSONObject().put("$android_devices", new JSONArray("[" + registrationId + "]")))); } catch (JSONException e) { Log.e(LOGTAG, "set push registration id error", e); } }
Source:
private double updateCloudletsProcessing(final double currentTime) { double nextCloudletFinishTime = Double.MAX_VALUE; for (int i = 0; i < cloudletExecList.size(); i++) { final CloudletExecution cle = cloudletExecList.get(i); updateCloudletProcessingAndPacketsDispatch(cle, currentTime); nextCloudletFinishTime = Math.min(nextCloudletFinishTime, cloudletEstimatedFinishTime(cle, currentTime)); cle.getCloudlet().getVm().setFreePesNumber( cle.getCloudlet().getVm().getFreePesNumber() - cle.getCloudlet().getNumberOfPes()); } return nextCloudletFinishTime; }

Target:
private double updateCloudletsProcessing(final double currentTime) { double nextCloudletFinishTime = Double.MAX_VALUE; long usedPes = 0; for (int i = 0; i < cloudletExecList.size(); i++) { final CloudletExecution cle = cloudletExecList.get(i); updateCloudletProcessingAndPacketsDispatch(cle, currentTime); nextCloudletFinishTime = Math.min(nextCloudletFinishTime, cloudletEstimatedFinishTime(cle, currentTime)); usedPes += cle.getCloudlet().getNumberOfPes(); } ((VmSimple) vm).setFreePesNumber(vm.getFreePesNumber() - usedPes); return nextCloudletFinishTime; }
Source:
public IntervalList getLociToGenotype(final Collection<Fingerprint> fingerprints) { final IntervalList intervals = new IntervalList(this.haplotypes.getHeader()); for (final Fingerprint fp : fingerprints) { for (final HaplotypeProbabilities genotype : fp.values()) { final HaplotypeBlock h = genotype.getHaplotype(); for (final Snp snp : h.getSnps()) { intervals.add(new Interval(snp.getChrom(), snp.getPos(), snp.getPos(), false, snp.getName())); } } } return intervals.sorted().uniqued(); }

Target:
public IntervalList getLociToGenotype(final Collection<Fingerprint> fingerprints) { final IntervalList intervals = new IntervalList(this.haplotypes.getHeader()); for (final Fingerprint fp : fingerprints) { for (final HaplotypeProbabilities genotype : fp.values()) { final HaplotypeBlock h = genotype.getHaplotype(); for (final Snp snp : h.getSnps()) { intervals.add(new Interval(snp.getChrom(), snp.getPos(), snp.getPos(), false, snp.getName())); } } } return intervals.uniqued(); }
Source:
public String[] getModules() { if ( module != null ) { return new String[] { module }; } if ( modules == null ) { List<String> gwtModules = DefaultGwtModuleReader.getGwtModules( getProject(), getLog() ); if ( gwtModules.size() > 0 ) { return gwtModules.toArray( new String[gwtModules.size()] ); } else { return new String[] { }; } } return modules; }

Target:
public String[] getModules() { if ( module != null ) { return new String[] { module }; } if ( modules == null ) { modules = convertToArray( new DefaultGwtModuleReader(getProject(), getLog(), classpathBuilder).getGwtModules()); } return modules; }
Source:
public void removeFromUsersTag( @Auth final AccessToken accessToken, @PathParam("tag_name") final String tagName, @PathParam("user_id") final Long userId) { final List<String> ids = new ArrayList<>(); ids.add(String.valueOf(userId)); tagStore.remove(tagName, TagStoreDAODynamoDB.Type.USERS, ids); }

Target:
public void removeFromUsersTag( @Auth final AccessToken accessToken, @PathParam("tag_name") final String tagName, @PathParam("user_id") final Long userId) { final List<String> ids = Lists.newArrayList(); ids.add(String.valueOf(userId)); tagStore.remove(tagName, TagStoreDAODynamoDB.Type.USERS, ids); }
Source:
protected void processMultiValuedEAttribute(EAttribute eAttribute, SIRIUS processedDescription, SIRIUS currentDescription, TransformationCache cache) { Object processedValue = processedDescription.eGet(eAttribute); Object currentValue = currentDescription.eGet(eAttribute); if (currentValue instanceof Iterable<?> && processedValue instanceof Iterable<?>) { List<Object> newValue = new ArrayList<>(); Iterable<?> currentIterable = (Iterable<?>) currentValue; Iterable<?> processedIterable = (Iterable<?>) processedValue; for (Object object : currentIterable) { newValue.add(object); } for (Object object : processedIterable) { newValue.add(object); } processedDescription.eSet(eAttribute, newValue); } }

Target:
protected void processMultiValuedEAttribute(EAttribute eAttribute, SIRIUS processedDescription, SIRIUS currentDescription, TransformationCache cache) { Object processedValue = processedDescription.eGet(eAttribute); Object currentValue = currentDescription.eGet(eAttribute); if (currentValue instanceof Iterable<?> && processedValue instanceof Iterable<?>) { List<Object> newValue = new ArrayList<>(); Iterable<?> currentIterable = (Iterable<?>) currentValue; Iterable<?> processedIterable = (Iterable<?>) processedValue; currentIterable.forEach(newValue::add); processedIterable.forEach(newValue::add); processedDescription.eSet(eAttribute, newValue); } }
Source:
public long getQueryCount() { return 0; }

Target:
public long getQueryCount() { throw new UnsupportedOperationException("Queries on replicated maps are not supported."); }
Source:
TargetNotToolchainException(ToolchainTypeInfo toolchainType, Label resolvedTargetLabel) { super( String.format( "toolchain type %s resolved to target %s, but that target does not provide" + " ToolchainInfo", toolchainType.typeLabel(), resolvedTargetLabel)); }

Target:
TargetNotToolchainException(ToolchainTypeInfo toolchainType, Label resolvedTargetLabel) { super( String.format( "toolchain type %s resolved to target %s, but that target does not provide " + ToolchainInfo.SKYLARK_NAME, toolchainType.typeLabel(), resolvedTargetLabel)); }
Source:
public void onPropertyAdd( KernelStatement state, NodeItem node, DefinedProperty after ) throws EntityNotFoundException { Iterator<NewIndexDescriptor> indexes = getIndexesForProperty( state, after.propertyKeyId() ); nodeIndexMatcher.onMatchingSchema( state, indexes, node, after.propertyKeyId(), index -> { OrderedPropertyValues values = getOrderedPropertyValues( state, node, after, index.schema().getPropertyIds() ); if ( values != null ) { values.validate(); state.txState().indexDoUpdateEntry( index.schema(), node.id(), null, values ); } }); }

Target:
public void onPropertyAdd( KernelStatement state, NodeItem node, DefinedProperty after ) throws EntityNotFoundException { Iterator<NewIndexDescriptor> indexes = getIndexesInvolvingProperty( state, after.propertyKeyId() ); nodeIndexMatcher.onMatchingSchema( state, indexes, node, after.propertyKeyId(), index -> { Validators.INDEX_VALUE_VALIDATOR.validate( after.value() ); OrderedPropertyValues values = getOrderedPropertyValues( state, node, after, index.schema().getPropertyIds() ); state.txState().indexDoUpdateEntry( index.schema(), node.id(), null, values ); }); }
Source:
private void extractFromSource(SearchHit hit) { Map<String, Object> map = hit.getSource(); for (Map.Entry<String, Object> entry : map.entrySet()) { String jsonPath = entry.getKey().toString(); Object entryValue = entry.getValue(); setFieldIfExists(jsonPath, entryValue); } }

Target:
private void extractFromSource(SearchHit hit) { Map<String, Object> map = hit.getSourceAsMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { String jsonPath = entry.getKey(); Object entryValue = entry.getValue(); setFieldIfExists(jsonPath, entryValue); } }
Source:
private String stream2String(InputStream in) { try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
private String stream2String(InputStream in) { try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(UTF_8.name()); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public <T> Enumerable<T> enumerable(Meta.StatementHandle handle, CalcitePrepare.CalciteSignature<T> signature, List<TypedValue> parameterValues0) throws SQLException { Map<String, Object> map = new LinkedHashMap<>(); AvaticaStatement statement = lookupStatement(handle); final List<TypedValue> parameterValues1 = TROJAN.getParameterValues(statement); final List<TypedValue> parameterValues; if (parameterValues0 == null || parameterValues0.isEmpty()) { parameterValues = parameterValues1; } else { parameterValues = parameterValues0; } if (MetaImpl.checkParameterValueHasNull(parameterValues)) { throw new SQLException("exception while executing query: unbound parameter"); } for (Ord<TypedValue> o : Ord.zip(parameterValues)) { map.put("?" + o.i, o.e.toLocal()); } map.putAll(signature.internalParameters); final AtomicBoolean cancelFlag; try { cancelFlag = getCancelFlag(handle); } catch (NoSuchStatementException e) { throw new RuntimeException(e); } map.put(DataContext.Variable.CANCEL_FLAG.camelName, cancelFlag); int queryTimeout = statement.getQueryTimeout(); if (queryTimeout > 0 && queryTimeout < Integer.MAX_VALUE / 1000) { map.put(DataContext.Variable.TIMEOUT.camelName, queryTimeout * 1000L); } final DataContext dataContext = createDataContext(map, signature.rootSchema); return signature.enumerable(dataContext); }

Target:
public <T> Enumerable<T> enumerable(Meta.StatementHandle handle, CalcitePrepare.CalciteSignature<T> signature, List<TypedValue> parameterValues0) throws SQLException { Map<String, Object> map = new LinkedHashMap<>(); AvaticaStatement statement = lookupStatement(handle); final List<TypedValue> parameterValues; if (parameterValues0 == null || parameterValues0.isEmpty()) { parameterValues = TROJAN.getParameterValues(statement); } else { parameterValues = parameterValues0; } if (MetaImpl.checkParameterValueHasNull(parameterValues)) { throw new SQLException("exception while executing query: unbound parameter"); } for (Ord<TypedValue> o : Ord.zip(parameterValues)) { map.put("?" + o.i, o.e.toLocal()); } map.putAll(signature.internalParameters); final AtomicBoolean cancelFlag; try { cancelFlag = getCancelFlag(handle); } catch (NoSuchStatementException e) { throw new RuntimeException(e); } map.put(DataContext.Variable.CANCEL_FLAG.camelName, cancelFlag); int queryTimeout = statement.getQueryTimeout(); if (queryTimeout > 0 && queryTimeout < Integer.MAX_VALUE / 1000) { map.put(DataContext.Variable.TIMEOUT.camelName, queryTimeout * 1000L); } final DataContext dataContext = createDataContext(map, signature.rootSchema); return signature.enumerable(dataContext); }
Source:
private void handleMessage(Message message) { String messageId = message.getMessageId(); String messagePayload = unmarshallMessageBody(message.getBody()); Map<String, String> stringifiedMessageAttributes = message.getMessageAttributes().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); log.debug("Received Amazon sqs message: with payload: {}\n and attributes: {}", messageId, messagePayload, stringifiedMessageAttributes); MessageDescription description = MessageDescription.builder() .subscriptionName(subscriptionName()) .messagePayload(messagePayload) .messageAttributes(stringifiedMessageAttributes) .pubsubSystem(pubsubSystem) .ackDeadlineMillis(5 * TimeUnit.SECONDS.toMillis(10)) .retentionDeadlineMillis(TimeUnit.DAYS.toMillis(7)) .build(); AmazonMessageAcknowledger acknowledger = new AmazonMessageAcknowledger(amazonSQS, queueId, message); if (subscription.getMessageFormat() != AmazonPubsubProperties.MessageFormat.NONE) { description.setArtifacts(parseArtifacts(description.getMessagePayload(), messageId)); } pubsubMessageHandler.handleMessage(description, acknowledger, identity.getIdentity(), messageId); }

Target:
private void handleMessage(Message message) { try { String messageId = message.getMessageId(); String messagePayload = unmarshallMessageBody(message.getBody()); Map<String, String> stringifiedMessageAttributes = message.getMessageAttributes().entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); log.debug("Received Amazon sqs message: with payload: and attributes: {}", messageId, messagePayload, stringifiedMessageAttributes); MessageDescription description = MessageDescription.builder() .subscriptionName(subscriptionName()) .messagePayload(messagePayload) .messageAttributes(stringifiedMessageAttributes) .pubsubSystem(pubsubSystem) .ackDeadlineMillis(TimeUnit.SECONDS.toMillis(50)) .retentionDeadlineMillis(TimeUnit.DAYS.toMillis(7)) .build(); AmazonMessageAcknowledger acknowledger = new AmazonMessageAcknowledger(amazonSQS, queueId, message, registry, getName()); if (subscription.getMessageFormat() != AmazonPubsubProperties.MessageFormat.NONE) { description.setArtifacts(parseArtifacts(description.getMessagePayload(), messageId)); } pubsubMessageHandler.handleMessage(description, acknowledger, identity.getIdentity(), messageId); } catch (Exception e) { log.error("Message from queue failed to be handled", message, queueId); } }
Source:
public Location(Extent extent, Vector3d position) { this.extent = checkNotNull(extent); this.position = checkNotNull(position); this.blockPosition = position.floor().toInt(); }

Target:
public Location(Extent extent, Vector3d position) { this.extent = checkNotNull(extent, "extent"); this.position = checkNotNull(position, "position"); this.blockPosition = position.floor().toInt(); }
Source:
public Mono<Boolean> exists() { try { return existsWithResponse().flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } }

Target:
public Mono<Boolean> exists() { return existsWithResponse().flatMap(FluxUtil::toMono); }
Source:
private void updateContentFiles(List<Process> processes) { for (Process process : processes) { try { FileformatInterface rdf = serviceManager.getProcessService().readMetadataFile(process); rdf.getDigitalDocument().addAllContentFiles(); serviceManager.getFileService().writeMetadataFile(rdf, process); Helper.setMeldung(KITODO_SCRIPT_FIELD, "ContentFiles updated: ", process.getTitle()); } catch (DocStructHasNoTypeException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung("DocStructHasNoTypeException", e.getMessage()); } catch (Exception e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while updating content files", e); } } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "updateContentFiles finished"); }

Target:
private void updateContentFiles(List<Process> processes) { for (Process process : processes) { try { FileformatInterface rdf = serviceManager.getProcessService().readMetadataFile(process); rdf.getDigitalDocument().addAllContentFiles(); serviceManager.getFileService().writeMetadataFile(rdf, process); Helper.setMeldung(KITODO_SCRIPT_FIELD, "ContentFiles updated: ", process.getTitle()); } catch (PreferencesException | IOException | ReadException | WriteException | RuntimeException e) { Helper.setErrorMessage(KITODO_SCRIPT_FIELD, "Error while updating content files", logger, e); } } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "updateContentFiles finished"); }
Source:
public void setUp() throws IOException { birthDate = Calendar.getInstance(); birthDate.set(1973, 4, 19, 22, 13, 0); UserProfileService ups = Framework.getLocalService(UserProfileService.class); DocumentModel up = ups.getUserProfileDocument(session); up.setPropertyValue(USER_PROFILE_PHONENUMBER_FIELD, "mynumber"); up.setPropertyValue(USER_PROFILE_BIRTHDATE_FIELD, birthDate.getTime()); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("data/SmallAvatar.jpg")); up.setPropertyValue(USER_PROFILE_AVATAR_FIELD, (Serializable) blob); session.saveDocument(up); session.save(); DownloadService downloadService = Framework.getService(DownloadService.class); avatarURL = RenderingContext.DEFAULT_URL + downloadService.getDownloadUrl(up, USER_PROFILE_AVATAR_FIELD, blob.getFilename()); }

Target:
public void setUp() throws IOException { birthDate = Calendar.getInstance(); birthDate.set(1973, 4, 19, 22, 13, 0); DocumentModel up = userProfileService.getUserProfileDocument(session); up.setPropertyValue(USER_PROFILE_PHONENUMBER_FIELD, "mynumber"); up.setPropertyValue(USER_PROFILE_BIRTHDATE_FIELD, birthDate.getTime()); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("data/SmallAvatar.jpg")); up.setPropertyValue(USER_PROFILE_AVATAR_FIELD, (Serializable) blob); session.saveDocument(up); session.save(); avatarURL = RenderingContext.DEFAULT_URL + downloadService.getDownloadUrl(up, USER_PROFILE_AVATAR_FIELD, blob.getFilename()); }
Source:
public void testSLAonUserTaskUpdated() throws Exception { CountDownLatch latch = new CountDownLatch(1); TimerIdListener listener = new TimerIdListener(); KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLAOnTask.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); ksession.addEventListener(listener); ProcessInstance processInstance = ksession.startProcess("UserTask"); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); WorkItem workItem = workItemHandler.getWorkItem(); assertNotNull(workItem); assertEquals("john", workItem.getParameter("ActorId")); processInstance = ksession.getProcessInstance(processInstance.getId()); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances(); assertEquals(1, active.size()); long timerId = listener.getTimerId(); assertNotEquals(-1, timerId); ksession.execute(new UpdateTimerCommand(processInstance.getId(), (long) timerId, 10)); boolean slaViolated = latch.await(5, TimeUnit.SECONDS); assertFalse("SLA should not violated by timer", slaViolated); ksession.dispose(); }

Target:
public void testSLAonUserTaskUpdated() throws Exception { CountDownLatch latch = new CountDownLatch(1); TimerIdListener listener = new TimerIdListener(latch); KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLAOnTask.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); ksession.addEventListener(listener); ProcessInstance processInstance = ksession.startProcess("UserTask"); assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); WorkItem workItem = workItemHandler.getWorkItem(); assertNotNull(workItem); assertEquals("john", workItem.getParameter("ActorId")); processInstance = ksession.getProcessInstance(processInstance.getId()); assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances(); assertEquals(1, active.size()); long timerId = listener.getTimerId(); assertNotEquals(-1, timerId); System.out.println(); ksession.execute(new UpdateTimerCommand(processInstance.getId(), (long) timerId, 7)); boolean slaViolated = latch.await(5, TimeUnit.SECONDS); assertFalse("SLA should not be violated by timer", slaViolated); slaViolated = latch.await(5, TimeUnit.SECONDS); assertTrue("SLA should be violated by timer", slaViolated); ksession.dispose(); }
Source:
private void loadResourceXmlFile(FsFile fsFile, XmlLoader... xmlLoaders) { VTDNav vtdNav = parse(fsFile); for (XmlLoader xmlLoader : xmlLoaders) { xmlLoader.processResourceXml(new XpathResourceXmlLoader.XmlNode(vtdNav), new XmlContext(packageName, fsFile)); } }

Target:
private void loadResourceXmlFile(FsFile fsFile, XmlLoader... xmlLoaders) { VTDNav vtdNav = parse(fsFile); XpathResourceXmlLoader.XmlNode xmlNode = new XpathResourceXmlLoader.XmlNode(vtdNav); XmlContext xmlContext = new XmlContext(packageName, fsFile); for (XmlLoader xmlLoader : xmlLoaders) { xmlLoader.processResourceXml(xmlNode, xmlContext); } }
Source:
private void destroy() { AbstractChannelHandlerContext ctx = this.tail.prev; while (ctx != head) { synchronized (handlers) { handlers.remove(ctx); } remove0(ctx); ctx = ctx.prev; } }

Target:
private void destroy() { EventExecutor executor = executor(); if (executor.inEventLoop()) { destroy0(); } else { executor.execute(this::destroy0); } }
Source:
public void findConceptsByUUID_shouldGetCorrectConceptByUUID() { mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity2); mDatabase.conceptRoomDAO().findConceptsByUUID(expectedConceptEntity1.getUuid()).subscribe(new SingleObserver<List<ConceptEntity>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onSuccess(List<ConceptEntity> conceptEntities) { Assert.assertEquals(conceptEntities.get(0), expectedConceptEntity1); Assert.assertEquals(conceptEntities.get(1), expectedConceptEntity2); } @Override public void onError(Throwable e) { Log.i(TAG, e.getMessage()); } }); }

Target:
public void findConceptsByUUID_shouldGetCorrectConceptByUUID() { mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().saveConcept(expectedConceptEntity2); mDatabase.conceptRoomDAO().findConceptsByUUID(expectedConceptEntity1.getUuid()) .test() .assertValue(conceptEntities -> { ConceptEntity actualEntity = conceptEntities.get(0); return Objects.equals(actualEntity.getUuid(), expectedConceptEntity1.getUuid()) && Objects.equals(actualEntity.getName(), expectedConceptEntity1.getName()) && Objects.equals(actualEntity.getDisplay(), expectedConceptEntity1.getDisplay()); }); }
Source:
private Type getType(Expression expression) { return asSymbol(expression) .map(symbol -> requireNonNull(types.get(symbol), () -> format("No type for symbol %s", symbol))) .orElseGet(() -> { ExpressionAnalyzer expressionAnalyzer = ExpressionAnalyzer.createWithoutSubqueries( metadata.getFunctionRegistry(), metadata.getTypeManager(), session, types, ImmutableList.of(), node -> new IllegalStateException("Unexpected Subquery"), WarningCollector.NOOP, false); Type type = expressionAnalyzer.analyze(expression, Scope.create()); return type; }); }

Target:
private Type getType(Expression expression) { if (expression instanceof SymbolReference) { Symbol symbol = Symbol.from(expression); return requireNonNull(types.get(symbol), () -> format("No type for symbol %s", symbol)); } ExpressionAnalyzer expressionAnalyzer = ExpressionAnalyzer.createWithoutSubqueries( metadata.getFunctionRegistry(), metadata.getTypeManager(), session, types, ImmutableList.of(), node -> new VerifyException("Unexpected subquery"), WarningCollector.NOOP, false); return expressionAnalyzer.analyze(expression, Scope.create()); }
Source:
public void cacheManagerStarted(GlobalComponentRegistry gcr) { final EmbeddedCacheManager cacheManager = gcr.getComponent(EmbeddedCacheManager.class); final InternalCacheRegistry internalCacheRegistry = gcr.getComponent(InternalCacheRegistry.class); ClusteredLockManagerConfiguration config = extractConfiguration(gcr); GlobalConfiguration globalConfig = gcr.getGlobalConfiguration(); if (globalConfig.isClustered()) { internalCacheRegistry.registerInternalCache(CLUSTERED_LOCK_CACHE_NAME, createClusteredLockCacheConfiguration(config, globalConfig), EnumSet.of(InternalCacheRegistry.Flag.EXCLUSIVE)); CompletableFuture<CacheHolder> future = startCaches(cacheManager); registerClusteredLockManager(gcr, future, config); } else { log.info("Clustered locks are necessary for clustered infinispan"); } }

Target:
public void cacheManagerStarted(GlobalComponentRegistry gcr) { final EmbeddedCacheManager cacheManager = gcr.getComponent(EmbeddedCacheManager.class); final InternalCacheRegistry internalCacheRegistry = gcr.getComponent(InternalCacheRegistry.class); ClusteredLockManagerConfiguration config = extractConfiguration(gcr); GlobalConfiguration globalConfig = gcr.getGlobalConfiguration(); if (globalConfig.isClustered()) { internalCacheRegistry.registerInternalCache(CLUSTERED_LOCK_CACHE_NAME, createClusteredLockCacheConfiguration(config, globalConfig), EnumSet.of(InternalCacheRegistry.Flag.EXCLUSIVE)); CompletableFuture<CacheHolder> future = startCaches(cacheManager); registerClusteredLockManager(gcr, future, config); } else { log.configurationNotClustered(); } }
Source:
public int getContentLength() { Header contentLength = resp.getFirstHeader("content-length"); if (contentLength == null) { return -1; } else { long l = Long.parseLong(contentLength.getValue()); if (l > Integer.MAX_VALUE) { return -1; } return (int) l; } }

Target:
public int getContentLength() { Header contentLength = resp.getFirstHeader("content-length"); if (contentLength == null) { return -1; } try { long l = Long.parseLong(contentLength.getValue()); if (l > Integer.MAX_VALUE) { return -1; } return (int) l; } catch (NumberFormatException e) { return -1; } }
Source:
public void clickOk() { JButton okButton = robot.finder().find(target, new GenericTypeMatcher<JButton>(JButton.class) { @Override protected boolean isMatching(JButton component) { return "OK".equals(component.getText()); } }); Assert.assertNotNull(okButton); JButtonFixture okButtonFixture = new JButtonFixture(robot, okButton); okButtonFixture.click(); }

Target:
public void clickOk() { JButton okButton = robot.finder().find(target, JButtonMatcher.withText("OK")); assertNotNull(okButton); JButtonFixture okButtonFixture = new JButtonFixture(robot, okButton); okButtonFixture.click(); }
Source:
public abstract void executeTask(CronTaskConfigurationDto config) throws Throwable; @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { String jobKey = jobExecutionContext.getJobDetail().getKey().getName(); CronTaskConfigurationDto configuration = cronTaskConfigurationService.getTaskConfigurationDto(jobKey); configuration = configuration == null ? (CronTaskConfigurationDto) jobExecutionContext.getJobDetail().getJobDataMap().get("config") : configuration; if (configuration == null) { logger.info(String.format("Configuration not found for [%s].", jobKey)); return; } if (!enabled(configuration, environment)) { logger.info(String.format("Cron job [%s] disabled, skip execution.", configuration.getName())); return; } logger.info(String.format("Cron job [%s] enabled, executing.", configuration.getName())); setStatus(CronJobStatusEnum.EXECUTING.getStatus()); cronTaskEventListenerRegistry.dispatchCronTaskExecutingEvent(configuration.getName()); try { executeTask(configuration); logger.info(String.format("Cron job task [%s] execution completed.", configuration.getName())); } catch (Throwable e) { logger.error(String.format("Failed to execute cron job task [%s].", configuration.getName()), e); } manager.addExecutedJob(configuration.getName(), true); cronTaskEventListenerRegistry.dispatchCronTaskExecutedEvent(configuration.getName()); setStatus(CronJobStatusEnum.SLEEPING.getStatus()); }

Target:
public abstract void executeTask(CronTaskConfigurationDto config) throws Throwable; @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { String jobKey = jobExecutionContext.getJobDetail().getKey().getName(); CronTaskConfigurationDto configuration = cronTaskConfigurationService.getTaskConfigurationDto(jobKey); if (configuration == null) { configuration = (CronTaskConfigurationDto) jobExecutionContext.getJobDetail().getJobDataMap().get("config"); } if (configuration == null) { logger.info(String.format("Configuration not found for [%s].", jobKey)); return; } if (!enabled(configuration, environment)) { logger.info(String.format("Cron job [%s] disabled, skip execution.", configuration.getName())); return; } logger.info(String.format("Cron job [%s] enabled, executing.", configuration.getName())); setStatus(CronJobStatusEnum.EXECUTING.getStatus()); cronTaskEventListenerRegistry.dispatchCronTaskExecutingEvent(configuration.getName()); try { executeTask(configuration); logger.info(String.format("Cron job task [%s] execution completed.", configuration.getName())); } catch (Throwable e) { logger.error(String.format("Failed to execute cron job task [%s].", configuration.getName()), e); } manager.addExecutedJob(configuration.getName(), true); cronTaskEventListenerRegistry.dispatchCronTaskExecutedEvent(configuration.getName()); setStatus(CronJobStatusEnum.SLEEPING.getStatus()); }
Source:
public OAuthResponse onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Shared.REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Bundle extras = data.getExtras(); String token = extras.getString(Shared.TOKEN, ""); String tokenSecret = extras.getString(Shared.TOKEN_SECRET, ""); if (callback != null) { callback.onSuccess(extras.getString(Shared.TOKEN, ""), extras.getString(Shared.TOKEN_SECRET, "")); } return OAuthResponse.success(token, tokenSecret); } if (callback != null) { callback.onError(); } return OAuthResponse.error("Aborted"); } return null; }

Target:
public OAuthResponse onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode != Shared.REQUEST_CODE) return null; if (resultCode == Activity.RESULT_OK) { Bundle extras = data.getExtras(); String token = extras.getString(Shared.TOKEN, ""); String tokenSecret = extras.getString(Shared.TOKEN_SECRET, ""); if (callback != null) { callback.onSuccess(extras.getString(Shared.TOKEN, ""), extras.getString(Shared.TOKEN_SECRET, "")); } return OAuthResponse.success(token, tokenSecret); } if (callback != null) { callback.onError(); } return OAuthResponse.error("Aborted"); }
Source:
int expiryQueueSize() { log.warn("The expiry queueSize attribute is deprecated and will be removed"); return expiryQueueSize.get(); }

Target:
int expiryQueueSize() { return expiryQueueSize.get(); }
Source:
public String getWindowTitle() { return "DataCloud Sign In"; }

Target:
public String getWindowTitle() { return "Sign in to DataCloud"; }
Source:
public void uniqueCorrelationIDs() throws MuleException { CoreEvent firstEvent = getEventBuilder().message(of("first")).build(); CoreEvent secondEvent = getEventBuilder().message(of("second")).build(); assertThat("Duplicated correlationID", firstEvent.getContext().getCorrelationId(), not(Is.is(secondEvent.getContext().getCorrelationId()))); }

Target:
public void uniqueCorrelationIDs() throws MuleException { CoreEvent firstEvent = getEventBuilder().message(of("first")).build(); CoreEvent secondEvent = getEventBuilder().message(of("second")).build(); assertThat("Duplicated correlationID", firstEvent.getContext().getCorrelationId(), not(is(secondEvent.getContext().getCorrelationId()))); }
Source:
private static void migrate(MigrateCommand command, WritePType writeType, boolean deleteSource, FileSystem fileSystem) throws Exception { String source = command.getSource(); String destination = command.getDestination(); LOG.debug("Migrating to {}", source, destination); if (deleteSource && writeType.equals(WritePType.ASYNC_THROUGH)) { if (fileSystem.getStatus(new AlluxioURI(source)).isPersisted()) { writeType = WritePType.THROUGH; } } CreateFilePOptions createOptions = CreateFilePOptions.newBuilder().setWriteType(writeType).build(); OpenFilePOptions openFileOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); try (FileOutStream out = fileSystem.createFile(new AlluxioURI(destination), createOptions); FileInStream in = fileSystem.openFile(new AlluxioURI(source), openFileOptions)) { try { IOUtils.copyLarge(in, out, new byte[8 * Constants.MB]); } catch (Throwable t) { try { out.cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } if (deleteSource) { fileSystem.delete(new AlluxioURI(source), DeletePOptions.newBuilder().setUnchecked(true).build()); } }

Target:
private static void migrate(MigrateCommand command, WritePType writeType, boolean deleteSource, FileSystem fileSystem) throws Exception { String source = command.getSource(); String destination = command.getDestination(); LOG.debug("Migrating to {}", source, destination); if (deleteSource && writeType.equals(WritePType.ASYNC_THROUGH)) { if (fileSystem.getStatus(new AlluxioURI(source)).isPersisted()) { writeType = WritePType.CACHE_THROUGH; } } CreateFilePOptions createOptions = CreateFilePOptions.newBuilder().setWriteType(writeType).build(); OpenFilePOptions openFileOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); try (FileOutStream out = fileSystem.createFile(new AlluxioURI(destination), createOptions); FileInStream in = fileSystem.openFile(new AlluxioURI(source), openFileOptions)) { try { IOUtils.copyLarge(in, out, new byte[8 * Constants.MB]); } catch (Throwable t) { try { out.cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } if (deleteSource) { fileSystem.delete(new AlluxioURI(source), DeletePOptions.newBuilder().setUnchecked(true).build()); } }