auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkEbsVolumeStatus(AuthenticatedContext ac, AmazonEC2Client client, String volumeId) { Waiter<DescribeVolumesRequest> volumeChecker = client.waiters().volumeAvailable(); DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withVolumeIds(volumeId); StackCancellationCheck stackCancellationCheck = new StackCancellationCheck(ac.getCloudContext().getId()); run(volumeChecker, describeVolumesRequest, stackCancellationCheck, "Volume creation failed"); }

Target:
private void checkEbsVolumeStatus(AuthenticatedContext ac, AmazonEC2Client client, String volumeId) { Waiter<DescribeVolumesRequest> volumeChecker = client.waiters().volumeAvailable(); DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withVolumeIds(volumeId); StackCancellationCheck stackCancellationCheck = new StackCancellationCheck(ac.getCloudContext().getId()); run(volumeChecker, describeVolumesRequest, stackCancellationCheck, String.format("Volume creation failed (volume id: %s)", volumeId)); }
Source:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { boolean basicType = value.getType() instanceof BasicType; boolean toOneType = value.getType() instanceof ManyToOneType || value.getType() instanceof OneToOneType; if ( basicType || toOneType ) { if ( value.getColumnSpan() == 1 ) { Selectable selectable = value.getColumnIterator().next(); if ( selectable instanceof Column ) { String columnName = propertyAuditingData.getModifiedFlagName(); if ( !propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = ( (Column) selectable ).getName() + globalCfg.getModifiedFlagSuffix(); } else { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } MetadataTools.addModifiedFlagPropertyWithColumn( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName(), columnName ); return; } } } MetadataTools.addModifiedFlagProperty( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName() ); }

Target:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { boolean basicType = value.getType() instanceof BasicType; boolean toOneType = value.getType() instanceof ManyToOneType || value.getType() instanceof OneToOneType; if ( basicType || toOneType ) { if ( value.getColumnSpan() == 1 ) { Selectable selectable = value.getColumnIterator().next(); if ( selectable instanceof Column ) { final String columnName; if ( !propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = ( (Column) selectable ).getName() + globalCfg.getModifiedFlagSuffix(); } else { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } MetadataTools.addModifiedFlagPropertyWithColumn( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName(), columnName ); return; } } } super.addModifiedColumns( globalCfg, value, parent, propertyAuditingData ); }
Source:
public List<SingleColumn> generateChecksumColumns(Column column) { checkArgument(column.getType() instanceof ArrayType, "Expect ArrayType, found %s", column.getType().getDisplayName()); Type elementType = ((ArrayType) column.getType()).getElementType(); Expression checksum; if (elementType.isOrderable()) { FunctionCall arraySort = new FunctionCall(QualifiedName.of("array_sort"), ImmutableList.of(column.getIdentifier())); if (elementType instanceof ArrayType || elementType instanceof RowType) { checksum = new CoalesceExpression( new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(new TryExpression(arraySort))), new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier()))); } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(arraySort)); } } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier())); } FunctionCall arrayCardinality = new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new FunctionCall(QualifiedName.of("cardinality"), ImmutableList.of(column.getIdentifier())))); return ImmutableList.of(new SingleColumn(checksum, Optional.of(delimitedIdentifier(getChecksumColumnAlias(column)))), new SingleColumn(arrayCardinality, Optional.of(delimitedIdentifier(getCardinalityColumnAlias(column))))); }

Target:
public List<SingleColumn> generateChecksumColumns(Column column) { checkArgument(column.getType() instanceof ArrayType, "Expect ArrayType, found %s", column.getType().getDisplayName()); Type elementType = ((ArrayType) column.getType()).getElementType(); Expression checksum; if (elementType.isOrderable()) { FunctionCall arraySort = new FunctionCall(QualifiedName.of("array_sort"), ImmutableList.of(column.getIdentifier())); if (elementType instanceof ArrayType || elementType instanceof RowType) { checksum = new CoalesceExpression( new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(new TryExpression(arraySort))), new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier()))); } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(arraySort)); } } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier())); } Expression arrayCardinalitySum = new CoalesceExpression( new FunctionCall( QualifiedName.of("sum"), ImmutableList.of(new FunctionCall(QualifiedName.of("cardinality"), ImmutableList.of(column.getIdentifier())))), new LongLiteral("0")); return ImmutableList.of( new SingleColumn(checksum, Optional.of(delimitedIdentifier(getChecksumColumnAlias(column)))), new SingleColumn(arrayCardinalitySum, Optional.of(delimitedIdentifier(getCardinalitySumColumnAlias(column))))); }
Source:
private void rename( final boolean saveCurrentChanges ) { final DataObject[] modifiedDataObject = new DataObject[ 1 ]; if ( saveCurrentChanges ) { if ( isDirty() ) { if ( context.isEditorChanged() ) { modifiedDataObject[ 0 ] = context.getDataObject(); } else { modifiedDataObject[ 0 ] = null; } } } renamePopUpPresenter.show( versionRecordManager.getPathToLatest(), javaFileNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( final FileNameAndCommitMessage details ) { view.showBusyIndicator( org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE.Renaming() ); modelerService.call( getRenameSuccessCallback( renamePopUpPresenter.getView(), context.getDataObject().getPackageName(), details.getNewFileName() ), getRenameErrorCallback( renamePopUpPresenter.getView() ) ).rename( versionRecordManager.getPathToLatest(), details.getNewFileName(), details.getCommitMessage(), true, saveCurrentChanges, getSource(), modifiedDataObject[ 0 ], metadata ); } } ); }

Target:
private void rename( final boolean saveCurrentChanges ) { final DataObject[] modifiedDataObject = new DataObject[ 1 ]; if ( saveCurrentChanges ) { if ( isDirty() ) { if ( context.isEditorChanged() ) { modifiedDataObject[ 0 ] = context.getDataObject(); } else { modifiedDataObject[ 0 ] = null; } } } renamePopUpPresenter.show( versionRecordManager.getPathToLatest(), javaFileNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( final FileNameAndCommitMessage details ) { view.showBusyIndicator( org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE.Renaming() ); modelerService.call( getRenameSuccessCallback( renamePopUpPresenter.getView() ), getRenameErrorCallback( renamePopUpPresenter.getView() ) ).rename( versionRecordManager.getPathToLatest(), details.getNewFileName(), details.getCommitMessage(), true, saveCurrentChanges, getSource(), modifiedDataObject[ 0 ], metadata ); } } ); }
Source:
public void testUseMeta() throws IOException { DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>()); File f = new File(DIR.getRoot().getPath(), "testDataFileMeta.avro"); w.setMeta("hello", "bar"); w.create(Schema.create(Type.NULL), f); w.close(); DataFileStream<Void> r = new DataFileStream<>(new FileInputStream(f), new GenericDatumReader<>()); assertTrue(r.getMetaKeys().contains("hello")); assertEquals("bar", r.getMetaString("hello")); r.close(); }

Target:
public void testUseMeta() throws IOException { File f = new File(DIR.getRoot().getPath(), "testDataFileMeta.avro"); try (DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>())) { w.setMeta("hello", "bar"); w.create(Schema.create(Type.NULL), f); } try (DataFileStream<Void> r = new DataFileStream<>(new FileInputStream(f), new GenericDatumReader<>())) { assertTrue(r.getMetaKeys().contains("hello")); assertEquals("bar", r.getMetaString("hello")); } }
Source:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, "")).get(); assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }

Target:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, EMPTY_EXPIRES, EMPTY_REGISTRATION_DOMAIN)).get(); assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }
Source:
public void testUnhandledExceptionStoredOnNoPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.storeUnhandledException(exception); assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }

Target:
public void testUnhandledExceptionStoredOnNoPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
public void removeSchemaObject(Session session, SchemaObject obj) { int type = obj.getType(); if (type == DbObject.TABLE_OR_VIEW) { Table table = (Table) obj; if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTable(table); return; } } else if (type == DbObject.INDEX) { Index index = (Index) obj; Table table = index.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableIndex(index); return; } } else if (type == DbObject.CONSTRAINT) { Constraint constraint = (Constraint) obj; Table table = constraint.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableConstraint(constraint); return; } } checkWritingAllowed(); lockMeta(session); synchronized (this) { Comment comment = findComment(obj); if (comment != null) { removeDatabaseObject(session, comment); } obj.getSchema().remove(obj); int id = obj.getId(); if (!starting) { Table t = getDependentTable(obj, null); if (t != null) { obj.getSchema().add(obj); throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(), t.getSQL()); } obj.removeChildrenAndResources(session); } removeMeta(session, id); return; } }

Target:
public void removeSchemaObject(Session session, SchemaObject obj) { int type = obj.getType(); if (type == DbObject.TABLE_OR_VIEW) { Table table = (Table) obj; if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTable(table); return; } } else if (type == DbObject.INDEX) { Index index = (Index) obj; Table table = index.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableIndex(index); return; } } else if (type == DbObject.CONSTRAINT) { Constraint constraint = (Constraint) obj; Table table = constraint.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableConstraint(constraint); return; } } checkWritingAllowed(); lockMeta(session); synchronized (this) { Comment comment = findComment(obj); if (comment != null) { removeDatabaseObject(session, comment); } obj.getSchema().remove(obj); int id = obj.getId(); if (!starting) { Table t = getDependentTable(obj, null); if (t != null) { obj.getSchema().add(obj); throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(), t.getSQL()); } obj.removeChildrenAndResources(session); } removeMeta(session, id); } }
Source:
public List<StackImpl> searchStacks(List<String> tags, int skipCount, int maxItems) { lock.readLock().lock(); try { return FluentIterable.from(stacks.values()) .skip(skipCount) .filter(new Predicate<DecoratedStack>() { @Override public boolean apply(DecoratedStack decoratedStack) { return tags == null || decoratedStack.getTags().containsAll(tags); } }) .limit(maxItems) .toList(); } finally { lock.readLock().unlock(); } }

Target:
public List<DecoratedStackImpl> searchStacks(List<String> tags, int skipCount, int maxItems) { lock.readLock().lock(); try { return stacks.values().stream() .skip(skipCount) .filter(decoratedStack -> tags == null || decoratedStack.getTags().containsAll(tags)) .limit(maxItems) .collect(toList()); } finally { lock.readLock().unlock(); } }
Source:
public TileEntity createNewTileEntity(World worldIn, int meta) { return createNewTileEntityDefault(worldIn, meta); }

Target:
public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileCoverable(); }
Source:
public void setAcl(AlluxioURI path, SetAclAction action, List<AclEntry> entries, SetAclContext context) throws FileDoesNotExistException, AccessControlException, InvalidPathException, IOException { Metrics.SET_ACL_OPS.inc(); addFileSystemMasterCallTrackers(context); try (RpcContext rpcContext = createRpcContext(); FileSystemMasterAuditContext auditContext = createAuditContext("setAcl", path, null, null)) { syncMetadata(rpcContext, path, context.getOptions().getCommonOptions(), context.getOptions().getRecursive() ? DescendantType.ALL : DescendantType.NONE, auditContext, LockedInodePath::getInodeOrNull, (inodePath, permChecker) -> permChecker.checkSetAttributePermission(inodePath, false, true, false) ); LockingScheme lockingScheme = createLockingScheme(path, context.getOptions().getCommonOptions(), LockPattern.WRITE_INODE); try (LockedInodePath inodePath = mInodeTree.lockInodePath(lockingScheme)) { mPermissionChecker.checkSetAttributePermission(inodePath, false, true, false); if (context.getOptions().getRecursive()) { try (LockedInodePathList descendants = mInodeTree.getDescendants(inodePath)) { for (LockedInodePath child : descendants) { mPermissionChecker.checkSetAttributePermission(child, false, true, false); } } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; } } if (!inodePath.fullPathExists()) { throw new FileDoesNotExistException(ExceptionMessage .PATH_DOES_NOT_EXIST.getMessage(path)); } setAclInternal(rpcContext, action, inodePath, entries, context); auditContext.setSucceeded(true); } } }

Target:
public void setAcl(AlluxioURI path, SetAclAction action, List<AclEntry> entries, SetAclContext context) throws FileDoesNotExistException, AccessControlException, InvalidPathException, IOException { Metrics.SET_ACL_OPS.inc(); try (RpcContext rpcContext = createRpcContext(); FileSystemMasterAuditContext auditContext = createAuditContext("setAcl", path, null, null)) { syncMetadata(rpcContext, path, context.getOptions().getCommonOptions(), context.getOptions().getRecursive() ? DescendantType.ALL : DescendantType.NONE, auditContext, LockedInodePath::getInodeOrNull, (inodePath, permChecker) -> permChecker.checkSetAttributePermission(inodePath, false, true, false) ); LockingScheme lockingScheme = createLockingScheme(path, context.getOptions().getCommonOptions(), LockPattern.WRITE_INODE); try (LockedInodePath inodePath = mInodeTree.lockInodePath(lockingScheme)) { mPermissionChecker.checkSetAttributePermission(inodePath, false, true, false); if (context.getOptions().getRecursive()) { try (LockedInodePathList descendants = mInodeTree.getDescendants(inodePath)) { for (LockedInodePath child : descendants) { mPermissionChecker.checkSetAttributePermission(child, false, true, false); } } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; } } if (!inodePath.fullPathExists()) { throw new FileDoesNotExistException(ExceptionMessage .PATH_DOES_NOT_EXIST.getMessage(path)); } setAclInternal(rpcContext, action, inodePath, entries, context); auditContext.setSucceeded(true); } } }
Source:
public ProcessContext<CartOperationRequest> execute(ProcessContext<CartOperationRequest> context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); Integer orderItemQuantity = orderItemRequestDTO.getQuantity(); if (!hasQuantity(orderItemQuantity)) { context.stopProcess(); } else if (orderItemQuantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative"); } else if (request.getOrder() == null) { throw new IllegalArgumentException("Order is required when adding item to order"); } else { Product product = determineProduct(orderItemRequestDTO); Sku sku; try { sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes(), (ActivityMessages) context); addSkuToCart(sku, orderItemRequestDTO, product, request); }catch(InventoryUnavailableException e){ throw e; } if (!hasSameCurrency(orderItemRequestDTO, request, sku)) { throw new IllegalArgumentException("Cannot have items with differing currencies in one cart"); } validateIfParentOrderItemExists(orderItemRequestDTO); } return context; }

Target:
public ProcessContext<CartOperationRequest> execute(ProcessContext<CartOperationRequest> context) throws Exception { CartOperationRequest request = context.getSeedData(); OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest(); Integer orderItemQuantity = orderItemRequestDTO.getQuantity(); if (!hasQuantity(orderItemQuantity)) { context.stopProcess(); } else if (orderItemQuantity < 0) { throw new IllegalArgumentException("Quantity cannot be negative"); } else if (request.getOrder() == null) { throw new IllegalArgumentException("Order is required when adding item to order"); } else { Product product = determineProduct(orderItemRequestDTO); Sku sku = determineSku(product, orderItemRequestDTO.getSkuId(), orderItemRequestDTO.getItemAttributes(), (ActivityMessages) context); addSkuToCart(sku, orderItemRequestDTO, product, request); if (!hasSameCurrency(orderItemRequestDTO, request, sku)) { throw new IllegalArgumentException("Cannot have items with differing currencies in one cart"); } validateIfParentOrderItemExists(orderItemRequestDTO); } return context; }
Source:
private void addEmptyLabelIfNeeded() { if (emptyLabel != null && getComponentCount() == 0) { add(emptyLabel); } }

Target:
private void addEmptyLabelIfNeeded() { if (style == Style.SMALL_ICONS_WRAPPED_WITH_LABEL_WHEN_EMPTY && getComponentCount() == 0) { add(new JLabel("(None)")); } }
Source:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }

Target:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }
Source:
public UpdateRef setNewValue(@Nullable ObjectId newValue) { this.newValue = newValue == null ? null : newValue; return this; }

Target:
public UpdateRef setNewValue(@Nullable ObjectId newValue) { this.newValue = newValue; return this; }
Source:
private PrioritizedSplitRunner pollSplit() { if (levelAbsolutePriority) { return pollFirstSplit(); } long expectedScheduledTime = updateLevelTimes(); double worstRatio = 1; int selectedLevel = -1; for (int level = 0; level < LEVELS.length; level++) { if (!levelWaitingSplits.get(level).isEmpty()) { double ratio = levelScheduledTime[level] == 0 ? 0 : expectedScheduledTime / (1.0 * levelScheduledTime[level]); if (selectedLevel == -1 || ratio > worstRatio) { worstRatio = ratio; selectedLevel = level; } } expectedScheduledTime /= levelPriorityMultiplier; } if (selectedLevel == -1) { return null; } return levelWaitingSplits.get(selectedLevel).poll(); }

Target:
private PrioritizedSplitRunner pollSplit() { if (levelAbsolutePriority) { return pollFirstSplit(); } long targetScheduledTime = updateLevelTimes(); double worstRatio = 1; int selectedLevel = -1; for (int level = 0; level < LEVEL_THRESHOLD_SECONDS.length; level++) { if (!levelWaitingSplits.get(level).isEmpty()) { double ratio = levelScheduledTime[level] == 0 ? 0 : targetScheduledTime / (1.0 * levelScheduledTime[level]); if (selectedLevel == -1 || ratio > worstRatio) { worstRatio = ratio; selectedLevel = level; } } targetScheduledTime /= levelTimeMultiplier; } if (selectedLevel == -1) { return null; } PrioritizedSplitRunner result = levelWaitingSplits.get(selectedLevel).poll(); checkState(result != null, "pollSplit cannot return null"); return result; }
Source:
protected boolean checkIfLongSession(MethodTree method) { List<AnnotationTree> annotations = method.modifiers().annotations(); for (AnnotationTree annotationTree : annotations) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) { IdentifierTree idf = (IdentifierTree) annotationTree.annotationType(); if (idf.name().equals(ACTIVATE)) { checkIfLongSessionOpened(method); return true; } else if (idf.name().equals(DEACTIVATE)) { checkIfLongSessionClosed(method); return true; } } } return false; }

Target:
protected boolean checkIfLongSession(MethodTree method) { List<AnnotationTree> annotations = method.modifiers().annotations(); for (AnnotationTree annotationTree : annotations) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER)) { IdentifierTree idf = (IdentifierTree) annotationTree.annotationType(); if (idf.name().equals(Activate.class.getSimpleName())) { collectLongSessionOpened(method); return true; } else if (idf.name().equals(Deactivate.class.getSimpleName())) { collectLongSessionClosed(method); return true; } } } return false; }
Source:
public ListSessionsResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[PACKET_FIXED_SIZE]; inNet.readFully(data); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); int nbSessions = bb.getInt(); ArrayList<SessionResponse> sl = new ArrayList<>(nbSessions); for (int session = 0; session < nbSessions; session++) { sl.add(session, new SessionResponse(inNet)); } fSessionList = ImmutableList.copyOf(sl); }

Target:
public ListSessionsResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[PACKET_FIXED_SIZE]; inNet.readFully(data); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); int nbSessions = bb.getInt(); Builder<SessionResponse> sl = new ImmutableList.Builder<>(); for (int session = 0; session < nbSessions; session++) { sl.add(new SessionResponse(inNet)); } fSessionList = sl.build(); }
Source:
public BlockCacheConfiguration(AccumuloConfiguration conf, CacheType type, String implName) { switch (type) { case INDEX: this.maxSize = conf.getAsBytes(Property.TSERV_INDEXCACHE_SIZE); break; case DATA: this.maxSize = conf.getAsBytes(Property.TSERV_DATACACHE_SIZE); break; case SUMMARY: this.maxSize = conf.getAsBytes(Property.TSERV_SUMMARYCACHE_SIZE); break; default: this.maxSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); break; } this.blockSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); }

Target:
public BlockCacheConfiguration(AccumuloConfiguration conf, CacheType type, String implName) { defaultPrefix = getDefaultPrefix(implName); prefix = getPrefix(type, implName); genProps = conf.getAllPropertiesWithPrefix(Property.GENERAL_ARBITRARY_PROP_PREFIX); switch (type) { case INDEX: this.maxSize = conf.getAsBytes(Property.TSERV_INDEXCACHE_SIZE); break; case DATA: this.maxSize = conf.getAsBytes(Property.TSERV_DATACACHE_SIZE); break; case SUMMARY: this.maxSize = conf.getAsBytes(Property.TSERV_SUMMARYCACHE_SIZE); break; default: throw new IllegalArgumentException("Unknown block cache type"); } this.blockSize = conf.getAsBytes(Property.TSERV_DEFAULT_BLOCKSIZE); }
Source:
public int hashCode() { return Objects.hashCode(name.hashCode(), uri.hashCode()); }

Target:
public int hashCode() { return Objects.hashCode(name, uri); }
Source:
public void testDatastreamProperties() throws ClientProtocolException, URISyntaxException, IOException { final GraphStore g = getResourceTriples(idMapper.mapDatastreamPath("example:1", "DS1") + "/fcr:metadata"); assertTrue("Unable to find datastream lable in migrated resource RDF assertions.", g.contains(ANY, ANY, NodeFactory.createURI("<LINK_0>"), NodeFactory.createLiteral("Example inline XML datastream"))); }

Target:
public void testDatastreamProperties() throws ClientProtocolException, URISyntaxException, IOException { final GraphStore g = getResourceTriples(idMapper.mapDatastreamPath("example:1", "DS1") + "/fcr:metadata"); assertTrue("Unable to find datastream label in migrated resource RDF assertions.", g.contains(ANY, ANY, NodeFactory.createURI("<LINK_0>"), NodeFactory.createLiteral("Example inline XML datastream"))); }
Source:
public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService ) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, executorService, disableBulkMutations, flusIntervalSeconds)); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }

Target:
public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService ) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, executorService, disableBulkMutations, flushIntervalSeconds)); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }
Source:
@Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } writeDeferredName(); beforeValue(); sink.writeUtf8(value ? "true" : "false"); pathIndices[stackSize - 1]++; return this; }

Target:
@Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } return value(value.booleanValue()); }
Source:
public Map<String, String> getConnectionFactoryProperties() { DefaultConnectionFactoryBuilder builder = createDefaultConnectionFactoryBuilderIfRequired(); return builder.getConnectionFactoryProperties(); }

Target:
public Map<String, String> getConnectionFactoryProperties() { if (connectionFactoryBuilder == null) { connectionFactoryBuilder = createDefaultConnectionFactoryBuilderIfRequired(); } if (connectionFactoryBuilder instanceof DefaultConnectionFactoryBuilder) { return ((DefaultConnectionFactoryBuilder)connectionFactoryBuilder).getConnectionFactoryProperties(); } else { throw new UnsupportedOperationException("ConnectionFactoryBuilder does not support connectionFactoryProperties"); } }
Source:
public synchronized void close() { isOpen = false; }

Target:
public void close() { isOpen = false; }
Source:
private void updateActionAvailability() { VM entity = (VM) getItem().getEntity(); getItem().getTakeVmCommand().setIsAvailable(false); ArrayList<VM> entities = new ArrayList<VM>(); entities.add(entity); getItem().getRunCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.RunVm)); getItem().getPauseCommand().setIsExecutionAllowed(entities.size() > 0 && VdcActionUtils.canExecute(entities, VM.class, VdcActionType.HibernateVm) && AsyncDataProvider.canVmsBePaused(entities)); getItem().getShutdownCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.ShutdownVm)); getItem().getStopCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.StopVm)); getItem().getRebootCommand().setIsExecutionAllowed(AsyncDataProvider.isRebootCommandExecutionAllowed(entities)); if (entity.getVmPoolId() != null) { AsyncDataProvider.getPoolById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmItemBehavior behavior = (VmItemBehavior) target; VmPool pool = (VmPool) returnValue; boolean isManualPool = pool.getVmPoolType() == VmPoolType.Manual; behavior.updateCommandsAccordingToPoolType(isManualPool); } }), entity.getVmPoolId()); } else { updateCommandsAccordingToPoolType(true); } }

Target:
private void updateActionAvailability() { VM entity = (VM) getItem().getEntity(); getItem().getTakeVmCommand().setIsAvailable(false); ArrayList<VM> entities = new ArrayList<VM>(); entities.add(entity); getItem().getRunCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.RunVm)); getItem().getPauseCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.HibernateVm) && AsyncDataProvider.canVmsBePaused(entities)); getItem().getShutdownCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.ShutdownVm)); getItem().getStopCommand().setIsExecutionAllowed(VdcActionUtils.canExecute(entities, VM.class, VdcActionType.StopVm)); getItem().getRebootCommand().setIsExecutionAllowed(AsyncDataProvider.isRebootCommandExecutionAllowed(entities)); if (entity.getVmPoolId() != null) { AsyncDataProvider.getPoolById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmItemBehavior behavior = (VmItemBehavior) target; VmPool pool = (VmPool) returnValue; boolean isManualPool = pool.getVmPoolType() == VmPoolType.Manual; behavior.updateCommandsAccordingToPoolType(isManualPool); } }), entity.getVmPoolId()); } else { updateCommandsAccordingToPoolType(true); } }
Source:
public void waitForFinish(Duration timeout) { JobConfig jobConfig = new JobConfig(config); long timeoutInMs = timeout.toMillis(); long startTimeInMs = System.currentTimeMillis(); long sleepDurationInMs = Math.min(timeoutInMs, DEFAULT_TIME_TO_SLEEP_DURING_WAIT); long timeElapsed = 0L; ApplicationStatus status; try { while(timeoutInMs < 1 || timeElapsed <= timeoutInMs) { status = getApplicationStatus(jobConfig); if (status == SuccessfulFinish || status == UnsuccessfulFinish) { LOG.info("Application finished with status {}", status); break; } Thread.sleep(sleepDurationInMs); timeElapsed = System.currentTimeMillis() - startTimeInMs; } if(timeElapsed > timeoutInMs) { LOG.error("Waiting to shutdown remote application runner timed out."); throw new TimeoutException("Waiting to shutdown remote application runner timed out."); } } catch (Exception e) { LOG.error("Wait for application finish failed due to", e); throw new SamzaException(e); } }

Target:
public boolean waitForFinish(Duration timeout) { JobConfig jobConfig = new JobConfig(config); boolean finished = true; long timeoutInMs = timeout.toMillis(); long startTimeInMs = System.currentTimeMillis(); long timeElapsed = 0L; long sleepDurationInMs = timeoutInMs < 1 ? DEFAULT_SLEEP_DURATION_MS : Math.min(timeoutInMs, DEFAULT_SLEEP_DURATION_MS); ApplicationStatus status; try { while (timeoutInMs < 1 || timeElapsed <= timeoutInMs) { status = getApplicationStatus(jobConfig); if (status == SuccessfulFinish || status == UnsuccessfulFinish) { LOG.info("Application finished with status {}", status); break; } Thread.sleep(sleepDurationInMs); timeElapsed = System.currentTimeMillis() - startTimeInMs; } if (timeElapsed > timeoutInMs) { LOG.warn("Timed out waiting for application to finish."); finished = false; } } catch (Exception e) { LOG.error("Error waiting for application to finish", e); throw new SamzaException(e); } return finished; }
Source:
private static String formatToString(List<String> tagExpressions) { return tagExpressions.stream().map(String::trim).collect(Collectors.joining(",")); }

Target:
private static String formatToString(List<String> tagExpressions) { return tagExpressions.stream().map(String::trim).sorted().collect(Collectors.joining(",")); }
Source:
private void maybeUpdateAssignment(SubscriptionState subscription) { int newAssignmentId = subscription.assignmentId(); if (this.assignmentId != newAssignmentId) { Set<TopicPartition> newAssignedPartitions = subscription.assignedPartitions(); for (TopicPartition tp : this.assignedPartitions) { if (!newAssignedPartitions.contains(tp)) { metrics.removeSensor(partitionLagMetricName(tp)); metrics.removeSensor(partitionLeadMetricName(tp)); metrics.removeMetric(partitionPreferredReadReplicaMetricName(tp)); } } for (TopicPartition tp : newAssignedPartitions) { if (!this.assignedPartitions.contains(tp)) { MetricName metricName = partitionPreferredReadReplicaMetricName(tp); if (metrics.metric(metricName) == null) { metrics.addMetric(metricName, (Gauge<Integer>) (config, now) -> { try { return subscription.preferredReadReplica(tp, 0L).orElse(-1); } catch (IllegalStateException e) { return -1; } }); } } } this.assignedPartitions = newAssignedPartitions; this.assignmentId = newAssignmentId; } }

Target:
private void maybeUpdateAssignment(SubscriptionState subscription) { int newAssignmentId = subscription.assignmentId(); if (this.assignmentId != newAssignmentId) { Set<TopicPartition> newAssignedPartitions = subscription.assignedPartitions(); for (TopicPartition tp : this.assignedPartitions) { if (!newAssignedPartitions.contains(tp)) { metrics.removeSensor(partitionLagMetricName(tp)); metrics.removeSensor(partitionLeadMetricName(tp)); metrics.removeMetric(partitionPreferredReadReplicaMetricName(tp)); } } for (TopicPartition tp : newAssignedPartitions) { if (!this.assignedPartitions.contains(tp)) { MetricName metricName = partitionPreferredReadReplicaMetricName(tp); if (metrics.metric(metricName) == null) { metrics.addMetric( metricName, (Gauge<Integer>) (config, now) -> subscription.preferredReadReplica(tp, 0L).orElse(-1) ); } } } this.assignedPartitions = newAssignedPartitions; this.assignmentId = newAssignmentId; } }
Source:
List<FeedScopedId> getTripIdForTripShortNameServiceDateAndMode(String tripShortName, ServiceDate serviceDate, TraverseMode traverseMode ) { Set<Trip> cachedTripsBySiriId = getCachedTripsBySiriId(tripShortName); if (cachedTripsBySiriId.isEmpty()) { cachedTripsBySiriId = getCachedTripsByVehicleRef(tripShortName); } List<FeedScopedId> matches = new ArrayList<>(); for (Trip trip : cachedTripsBySiriId) { if (GtfsLibrary.getTransitMode(trip.getRoute()).equals(traverseMode) ) { Set<ServiceDate> serviceDates = routingService.getCalendarService().getServiceDatesForServiceId(trip.getServiceId()); if (serviceDates.contains(serviceDate) && trip.getTripShortName() != null && trip.getTripShortName().equals(tripShortName)) { matches.add(trip.getId()); } } } return matches; }

Target:
List<FeedScopedId> getTripIdForTripShortNameServiceDateAndMode(String tripShortName, ServiceDate serviceDate, TraverseMode traverseMode ) { Set<Trip> cachedTripsBySiriId = getCachedTripsBySiriId(tripShortName); if (cachedTripsBySiriId.isEmpty()) { cachedTripsBySiriId = getCachedTripsByVehicleRef(tripShortName); } List<FeedScopedId> matches = new ArrayList<>(); for (Trip trip : cachedTripsBySiriId) { if (trip.getRoute().getMode().equals(traverseMode) ) { Set<ServiceDate> serviceDates = routingService.getCalendarService().getServiceDatesForServiceId(trip.getServiceId()); if (serviceDates.contains(serviceDate) && trip.getTripShortName() != null && trip.getTripShortName().equals(tripShortName)) { matches.add(trip.getId()); } } } return matches; }
Source:
public static Value toStratosphere(Object java) { if (java instanceof java.lang.Boolean) return new BooleanValue(((java.lang.Boolean)java).booleanValue()); if (java instanceof java.lang.Integer) return new IntValue(((java.lang.Integer)java).intValue()); if (java instanceof java.lang.Byte) return new ByteValue(((java.lang.Byte)java).byteValue()); if (java instanceof java.lang.Character) return new CharValue(((java.lang.Character)java).charValue()); if (java instanceof java.lang.Double) return new DoubleValue(((java.lang.Double)java).doubleValue()); if (java instanceof java.lang.Float) return new FloatValue(((java.lang.Float)java).floatValue()); if (java instanceof java.lang.Long) return new LongValue(((java.lang.Long)java).longValue()); if (java instanceof java.lang.Short) return new ShortValue(((java.lang.Short)java).shortValue()); if (java instanceof java.lang.String) return new StringValue(((java.lang.String)java).toString()); return NullValue.getInstance(); }

Target:
public static Value toStratosphere(Object java) { if (java.getClass() == java.lang.Boolean.class) { return new BooleanValue(((java.lang.Boolean)java).booleanValue()); } if (java.getClass() == java.lang.Integer.class) { return new IntValue(((java.lang.Integer)java).intValue()); } if (java.getClass() == java.lang.Byte.class) { return new ByteValue(((java.lang.Byte)java).byteValue()); } if (java.getClass() == java.lang.Character.class) { return new CharValue(((java.lang.Character)java).charValue()); } if (java.getClass() == java.lang.Double.class) { return new DoubleValue(((java.lang.Double)java).doubleValue()); } if (java.getClass() == java.lang.Float.class) { return new FloatValue(((java.lang.Float)java).floatValue()); } if (java.getClass() == java.lang.Long.class) { return new LongValue(((java.lang.Long)java).longValue()); } if (java.getClass() == java.lang.Short.class) { return new ShortValue(((java.lang.Short)java).shortValue()); } if (java.getClass() == java.lang.String.class) { return new StringValue(((java.lang.String)java).toString()); } if (java == null) { return NullValue.getInstance(); } throw new IllegalArgumentException("unsupported java value"); }
Source:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { String result = " [ "; for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); result += iter.getName(); if (iterator.hasNext()) { result += " , "; } } result += " ]"; return result; }

Target:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { StringBuilder result = new StringBuilder(" [ "); for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); result.append(iter.getName()); if (iterator.hasNext()) { result.append(" , "); } } result.append(" ]"); return result.toString(); }
Source:
public void setAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException { convertEmptyAttrValueToNull(attribute); if (attribute.getValue() == null) { removeAttribute(sess, resource, group, attribute); return; } if (setAttributeWithoutCheck(sess, resource, group, attribute)) { this.checkAttributeDependencies(sess, new RichAttribute<>(resource, group, attribute)); checkAttributeSyntax(sess, resource, group, attribute); checkAttributeSemantics(sess, resource, group, attribute); } }

Target:
public void setAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException { convertEmptyAttrValueToNull(attribute); if (attribute.getValue() == null) { removeAttribute(sess, resource, group, attribute); return; } checkAttributeSyntax(sess, resource, group, attribute); if (setAttributeWithoutCheck(sess, resource, group, attribute)) { checkAttributeSemantics(sess, resource, group, attribute); this.checkAttributeDependencies(sess, new RichAttribute<>(resource, group, attribute)); } }
Source:
public void missingMapping(FMLMissingMappingsEvent event){ for (FMLMissingMappingsEvent.MissingMapping evt:event.getAll()) { if (evt.name.equals("minecraft:totem")) { ResourceLocation newTotem = new ResourceLocation("minecraft:totem_of_undying"); evt.remap(Item.REGISTRY.getObject(newTotem)); } } }

Target:
public void missingMapping(FMLMissingMappingsEvent event) { for (FMLMissingMappingsEvent.MissingMapping entry : event.getAll()) { if (entry.name.equals("minecraft:totem")) { ResourceLocation newTotem = new ResourceLocation("minecraft:totem_of_undying"); entry.remap(ForgeRegistries.ITEMS.getValue(newTotem)); } } }
Source:
public String getServerFingerprint(String serverName) { String fingerPrint = null; SSHClient client = null; try { long timeout = Config.<Integer>GetValue( ConfigValues.SSHInactivityTimoutSeconds ) * 1000; client = new SSHClient(); client.setHardTimeout(timeout); client.setSoftTimeout(timeout); client.setHost(serverName, 22); client.connect(); PublicKey serverKey = client.getServerKey(); if (serverKey == null) { throw new Exception("No server key"); } fingerPrint = OpenSSHUtils.getKeyFingerprintString(serverKey); } catch (Throwable e) { log.errorFormat("Could not fetch fingerprint of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { if (client != null) { client.disconnect(); } } return fingerPrint; }

Target:
public String getServerFingerprint(String serverName) { String fingerPrint = null; SSHDialog dialog = new SSHDialog(); try { dialog.setHost(serverName); dialog.connect(); fingerPrint = dialog.getHostFingerprint(); } catch (Throwable e) { log.errorFormat("Could not fetch fingerprint of host {0} with message: {1}", serverName, ExceptionUtils.getMessage(e) ); } finally { dialog.disconnect(); } return fingerPrint; }
Source:
public void interceptReceivedText(String text) { try { incomingTextSplitter.write(text.getBytes(Charset.defaultCharset())); } catch (IOException e) { LOGGER.log(Level.WARNING, "IOException encountered while parsing received text" + text, e); } }

Target:
public void interceptReceivedText(String text) { try { incomingTextSplitter.write(text.getBytes(Charset.defaultCharset())); } catch (IOException e) { LOGGER.log(Level.WARNING, "IOException encountered while parsing received text: " + text, e); } }
Source:
private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(EndpointQualifier.REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } restApiConfig.enableAllGroups(); return restApiConfig; }

Target:
private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } return restApiConfig; }
Source:
public <K extends Serializable, V extends Serializable> ConcurrentMap<K, V> getPersistentConcurrentMap(String name, Class<K> keyClass, Class<V> valueClass) { knownMaps.putIfAbsent(name, new ConcurrentClusteredMap<K, V>(clusterCacheIdentifier.getId(), composedId + "-" + name, clientEntity)); return knownMaps.get(name); }

Target:
public <K extends Serializable, V extends Serializable> ConcurrentMap<K, V> getPersistentConcurrentMap(String name, Class<K> keyClass, Class<V> valueClass) { return new ConcurrentClusteredMap<K, V>(clusterCacheIdentifier.getId(), composedId + "-" + name, clientEntity); }
Source:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null) { continue; } runs.add(entry.getBuild()); } return runs; }

Target:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null || entry.getBuild() == null) { continue; } runs.add(entry.getBuild()); } return runs; }
Source:
private CRAMFileWriter createCRAMWriterWithSettings( final SAMFileHeader header, final boolean presorted, final Path outputFile, final File referenceFasta) { OutputStream cramOS = null; OutputStream indexOS = null ; if (createIndex) { if (!IOUtil.isRegularPath(outputFile)) { log.warn("Cannot create index for CRAM because output file is not a regular file: " + outputFile); } else { final Path indexPath = IOUtil.addExtension(outputFile, BAMIndex.BAMIndexSuffix); try { indexOS = Files.newOutputStream(indexPath); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating index file for: " + indexPath); } } } try { cramOS = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputFile), bufferSize); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating CRAM file: " + outputFile.toString()); } final Path md5Path = IOUtil.addExtension(outputFile, ".md5"); final CRAMFileWriter writer = new CRAMFileWriter( createMd5File ? new Md5CalculatingOutputStream(cramOS, md5Path) : cramOS, indexOS, presorted, new ReferenceSource(referenceFasta), header, outputFile.toUri().toString()); setCRAMWriterDefaults(writer); return writer; }

Target:
private CRAMFileWriter createCRAMWriterWithSettings( final SAMFileHeader header, final boolean presorted, final Path outputFile, final File referenceFasta) { OutputStream cramOS = null; OutputStream indexOS = null ; if (createIndex) { if (!IOUtil.isRegularPath(outputFile)) { log.warn("Cannot create index for CRAM because output file is not a regular file: " + outputFile.toUri()); } else { final Path indexPath = IOUtil.addExtension(outputFile, BAMIndex.BAMIndexSuffix); try { indexOS = Files.newOutputStream(indexPath); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating index file for: " + indexPath.toUri()); } } } try { cramOS = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputFile), bufferSize); } catch (final IOException ioe) { throw new RuntimeIOException("Error creating CRAM file: " + outputFile.toUri()); } final Path md5Path = IOUtil.addExtension(outputFile, ".md5"); final CRAMFileWriter writer = new CRAMFileWriter( createMd5File ? new Md5CalculatingOutputStream(cramOS, md5Path) : cramOS, indexOS, presorted, new ReferenceSource(referenceFasta), header, outputFile.toUri().toString()); setCRAMWriterDefaults(writer); return writer; }