auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void commitSingleEntry(CacheEntry entry, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { int segment; Object key = entry.getKey(); if (command instanceof SegmentSpecificCommand) { segment = ((SegmentSpecificCommand) command).getSegment(); } else { <START> segment = distributionManager.getCacheTopology().getSegment(key); <END> } stateTransferLock.acquireSharedTopologyLock(); try { Commit doCommit = commitType(command, ctx, segment, entry.isRemoved()); if (doCommit.isCommit()) { boolean created = false; boolean removed = false; boolean expired = false; if (doCommit.isLocal()) { created = entry.isCreated(); removed = entry.isRemoved(); if (removed && entry instanceof MVCCEntry) { expired = ((MVCCEntry) entry).isExpired(); } } InternalCacheEntry previousEntry; if (segment != -1) { previousEntry = ((InternalDataContainer) dataContainer).peek(segment, key); } else { previousEntry = dataContainer.peek(key); } Object previousValue = null; Metadata previousMetadata = null; if (previousEntry != null) { previousValue = previousEntry.getValue(); previousMetadata = previousEntry.getMetadata(); } commitManager.commit(entry, trackFlag, segment, l1Invalidation, ctx); if (doCommit.isLocal()) { NotifyHelper.entryCommitted(notifier, functionalNotifier, created, removed, expired, entry, ctx, command, previousValue, previousMetadata); } } } finally { stateTransferLock.releaseSharedTopologyLock(); } }</code><technical_language>inject key partitioner SegmentSpecificCommand.extractSegment()</technical_language>

Target:
protected void commitSingleEntry(CacheEntry entry, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { Object key = entry.getKey(); int segment = SegmentSpecificCommand.extractSegment(command, key, keyPartitioner); stateTransferLock.acquireSharedTopologyLock(); try { Commit doCommit = commitType(command, ctx, segment, entry.isRemoved()); if (doCommit.isCommit()) { boolean created = false; boolean removed = false; boolean expired = false; if (doCommit.isLocal()) { created = entry.isCreated(); removed = entry.isRemoved(); if (removed && entry instanceof MVCCEntry) { expired = ((MVCCEntry) entry).isExpired(); } } InternalCacheEntry previousEntry = dataContainer.peek(segment, key); Object previousValue = null; Metadata previousMetadata = null; if (previousEntry != null) { previousValue = previousEntry.getValue(); previousMetadata = previousEntry.getMetadata(); } commitManager.commit(entry, trackFlag, segment, l1Invalidation, ctx); if (doCommit.isLocal()) { NotifyHelper.entryCommitted(notifier, functionalNotifier, created, removed, expired, entry, ctx, command, previousValue, previousMetadata); } } } finally { stateTransferLock.releaseSharedTopologyLock(); } }
Source:
<code>public T open() { if (streamName != null) { streamID = CorfuRuntime.getStreamID(streamName); <START> log.info("CorfuObject: creating stream id {}", streamName, streamID); <END> } try { if (options.contains(ObjectOpenOptions.NO_CACHE)) { return CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); } else { ObjectsView.ObjectID<T> oid = new ObjectsView.ObjectID(streamID, type); return (T) runtime.getObjectsView().objectCache.computeIfAbsent(oid, x -> { try { T result = CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); ISerializer objectSerializer = ((CorfuCompileProxy) ((ICorfuSMR) result). getCorfuSMRProxy()) .getSerializer(); if (serializer != objectSerializer) { log.warn("open: Attempt to open an existing object with a different serializer {}. " + "Object opened with original serializer {}.", serializer.getClass().getSimpleName(), oid, objectSerializer.getClass().getSimpleName()); } return result; } catch (Exception ex) { throw new UnrecoverableCorfuError(ex); } } ); } } catch (Exception ex) { log.error("Runtime instrumentation no longer supported and no compiled class found" + " for {}", type); throw new UnrecoverableCorfuError(ex); } }</code><technical_language>CorfuObject -> ObjectBuilder</technical_language>

Target:
public T open() { if (streamName != null) { streamID = CorfuRuntime.getStreamID(streamName); } log.info("ObjectBuilder: open Corfu stream id {}", streamName, streamID); try { if (options.contains(ObjectOpenOptions.NO_CACHE)) { return CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); } else { ObjectsView.ObjectID<T> oid = new ObjectsView.ObjectID(streamID, type); return (T) runtime.getObjectsView().objectCache.computeIfAbsent(oid, x -> { try { T result = CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); ISerializer objectSerializer = ((CorfuCompileProxy) ((ICorfuSMR) result). getCorfuSMRProxy()) .getSerializer(); if (serializer != objectSerializer) { log.warn("open: Attempt to open an existing object with a different serializer {}. " + "Object opened with original serializer {}.", serializer.getClass().getSimpleName(), oid, objectSerializer.getClass().getSimpleName()); } return result; } catch (Exception ex) { throw new UnrecoverableCorfuError(ex); } } ); } } catch (Exception ex) { log.error("Runtime instrumentation no longer supported and no compiled class found" + " for {}", type); throw new UnrecoverableCorfuError(ex); } }
Source:
<code>private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }) .onErrorMap(this::mapError) <START> .then(); <END> }</code><technical_language>I then() is needed here</technical_language>

Target:
private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults() .onErrorMap(this::mapError) .next() .handle((response, sink) -> { if (response != AmqpResponseCode.ACCEPTED && response != AmqpResponseCode.OK) { final String message = String.format("User does not have authorization to perform operation " + "[%s] on entity [%s]. Response: [%s]", operation, entityPath, response); final Throwable exc = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, message, getErrorContext()); sink.error(new ServiceBusException(exc, ServiceBusErrorSource.MANAGEMENT)); } else { sink.complete(); } }); }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { PyFunctionDefTree func = ((PyFunctionDefTree) ctx.syntaxNode()); ReturnCountVisitor returnCountVisitor = new ReturnCountVisitor(); func.body().accept(returnCountVisitor); if (returnCountVisitor.returnStatements.size() > max) { PreciseIssue preciseIssue = ctx.addIssue(func.name(), String.format(MESSAGE, returnCountVisitor.returnStatements.size(), max)); <START> returnCountVisitor.returnStatements.forEach(r -> { <END> preciseIssue.secondary(r, null); }); } }); }</code><technical_language>need for block for this lambda. remove braces. #lessIsMore</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { PyFunctionDefTree func = ((PyFunctionDefTree) ctx.syntaxNode()); ReturnCountVisitor returnCountVisitor = new ReturnCountVisitor(); func.body().accept(returnCountVisitor); if (returnCountVisitor.returnStatements.size() > max) { PreciseIssue preciseIssue = ctx.addIssue(func.name(), String.format(MESSAGE, returnCountVisitor.returnStatements.size(), max)); returnCountVisitor.returnStatements.forEach(r -> preciseIssue.secondary(r, null)); } }); }
Source:
<code>public void onReplicaError(ReplicaId replicaId, ReplicaFailureType error) { switch (error) { case Disk_Error: <START> replicaId.getDiskId().onDiskError(); <END> case Node_Timeout: replicaId.getDataNodeId().onNodeTimeout(); case Partition_ReadOnly: replicaId.getPartitionId().onPartitionReadOnly(); } }</code><technical_language>want cast original Replica, Disk, Node Partition avoid interface</technical_language>

Target:
public void onReplicaError(ReplicaId replicaId, ReplicaFailureType error) { switch (error) { case Disk_Error: ((Disk) replicaId.getDiskId()).onDiskError(); case Node_Timeout: ((DataNode) replicaId.getDataNodeId()).onNodeTimeout(); case Partition_ReadOnly: ((Partition) replicaId.getPartitionId()).onPartitionReadOnly(); } }
Source:
<code>public EchoResponse.Void handle(Notification notification) { if (log.isDebugEnabled()) { try { <START> log.debug("Notification received: " + mapper.writerWithDefaultPrettyPrinter() <END> .writeValueAsString(notification)); } catch (JsonProcessingException jpe) { log.warn("Error parsing notification", jpe); } } if (notification.getTo() == null || notification.getTo().isEmpty()) { return new Void(); } String topic = notification.getTo().iterator().next(); publishers.publishersMatchingType(PubsubSystem.GOOGLE) .stream() .map(p -> (GooglePubsubPublisher) p) .filter(p -> StringUtils.equalsIgnoreCase(topic, p.getTopicName())) .forEach(p -> publishNotification(p, notification)); return new EchoResponse.Void(); }</code><technical_language>this trouble in this method? wondering if this is validation need in cases & report it</technical_language>

Target:
public EchoResponse.Void handle(Notification notification) { if (log.isDebugEnabled() && mapper != null) { try { log.debug("Notification received: " + mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(notification)); } catch (JsonProcessingException jpe) { log.warn("Error parsing notification", jpe); } } if (notification.getTo() == null || notification.getTo().isEmpty()) { return new Void(); } String topic = notification.getTo().iterator().next(); publishers.publishersMatchingType(PubsubSystem.GOOGLE) .stream() .map(p -> (GooglePubsubPublisher) p) .filter(p -> StringUtils.equalsIgnoreCase(topic, p.getTopicName())) .forEach(p -> publishNotification(p, notification)); return new EchoResponse.Void(); }
Source:
<code>public final void collect(T record) { <START> collect(record, Long.MIN_VALUE); <END> }</code><technical_language>Is this a symbolic special of "NO_TIMESTAMP" trigger retraction in downstream operators</technical_language>

Target:
public final void collect(T record) { collect(record, TimestampAssigner.NO_TIMESTAMP); }
Source:
<code>} catch (Exception e) { <START> throw new XmlBeanDefinitionException("Error occurred to initialize xmlReader", e); <END> }</code><technical_language>Error occurred initialize XMLReader</technical_language>

Target:
} catch (Exception e) { throw new XmlBeanDefinitionException("Error occurred while initializing DocumentBuilderFactory", e); }
Source:
<code>public void shutdown() { acceptTasks = false; queue.submit(new Runnable() { @Override public void run() { db.close(); } }); queue.shutdown(); try { <START> queue.awaitTermination(200, TimeUnit.SECONDS); <END> } catch (InterruptedException e){ logger.log(Level.WARNING,"Interrupted while waiting for queue to shutdown",e); } }</code><technical_language>bother waiting here? adds goal. I want calls shutdownNow() db.close() called. call task itself</technical_language>

Target:
public void shutdown() { acceptTasks = false; queue.submit(new Runnable() { @Override public void run() { db.close(); } }); queue.shutdown(); try { queue.awaitTermination(5,TimeUnit.MINUTES); } catch (InterruptedException e) { logger.log(Level.SEVERE,"Interrupted while waiting for queue to terminate",e); } }
Source:
<code>private TriggerResponse triggerWithRetries(Pipeline pipeline) { int attempts = 0; while (true) { try { attempts++; return orca.trigger(pipeline); } catch (RetrofitError e) { if ((attempts >= retryCount) || !isRetryableError(e)) { throw e; } } try { Thread.sleep(retryDelayMillis); } catch (InterruptedException ignored) { } <START> log.warn("Retrying pipeline trigger for {}", pipeline); <END> } }</code><technical_language>log.warn("Retrying pipeline trigger (attempt {}/{}) for {}", attempts, retryCount, pipeline);</technical_language>

Target:
private TriggerResponse triggerWithRetries(Pipeline pipeline) { int attempts = 0; while (true) { try { attempts++; return orca.trigger(pipeline); } catch (RetrofitError e) { if ((attempts >= retryCount) || !isRetryableError(e)) { throw e; } else { log.warn( "Error triggering with (attempt {}/{}). Retrying...", pipeline, e, attempts, retryCount); } } try { Thread.sleep(retryDelayMillis); registry.counter("orca.trigger.retries").increment(); } catch (InterruptedException ignored) { } } }
Source:
<code>public void copyFrom( final Transfer f ) throws IOException { provider.waitForWriteUnlock( resource ); provider.lockWrite( resource ); try { if ( decorator != null ) { <START> decorator.decorateCopyFrom( f, this, new EventMetadata( ) ); <END> } provider.copy( f.getResource(), resource ); } finally { provider.unlockWrite( resource ); } }</code><technical_language>another place a variant of copyFrom() need event metadata eventually</technical_language>

Target:
public void copyFrom( final Transfer f ) throws IOException { copyFrom( f, new EventMetadata( ) ); }
Source:
<code>public void visitToken(DetailAST ast) { final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); switch (ast.getType()) { case TokenTypes.PACKAGE_DEF: packageName = extractQualifiedName(ast); break; case TokenTypes.CLASS_DEF: currentDepthLevel++; <START> final ClassDesc classDesc = buildClassDesc(ast, modifiers); <END> classes.push(classDesc); break; case TokenTypes.CTOR_DEF: registerClassConstructors(ast, modifiers); break; default: throw new IllegalStateException(ast.toString()); } }</code><technical_language>a buildClassDesc a registerClassDesc for CTOR_DEF</technical_language>

Target:
public void visitToken(DetailAST ast) { final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); switch (ast.getType()) { case TokenTypes.PACKAGE_DEF: packageName = extractQualifiedName(ast); break; case TokenTypes.CLASS_DEF: currentDepthLevel++; final ClassDesc classDesc = registerClassDesc(ast, modifiers); classes.push(classDesc); break; case TokenTypes.CTOR_DEF: registerClassConstructors(ast, modifiers); break; default: throw new IllegalStateException(ast.toString()); } }
Source:
<code>public static int compare(StarlarkInt x, StarlarkInt y) { long xl = 0, yl = 0; boolean xbig = false, ybig = false; try { xl = x.toLongFast(); } catch (Overflow unused) { xbig = true; } try { yl = y.toLongFast(); } catch (Overflow unused) { ybig = true; } <START> if (xbig && ybig) { <END> return ((Big) x).v.compareTo(((Big) y).v); } else if (xbig) { return ((Big) x).v.signum(); } else if (ybig) { return -((Big) y).v.signum(); } else { return Long.compare(xl, yl); } }</code><technical_language>FWIW, this version requires 4 branches reach common case (Long.compare), version I proposed a control tree of depth two. a big deal, especially mystery unpredictability of measurements JVM, bear in mind optimizing (especially in a language C++ assembly)</technical_language>

Target:
public static int compare(StarlarkInt x, StarlarkInt y) { try { long xl = x.toLongFast(); try { long yl = y.toLongFast(); return Long.compare(xl, yl); } catch (Overflow unused) { return -((Big) y).v.signum(); } } catch (Overflow unused) { try { y.toLongFast(); return ((Big) x).v.signum(); } catch (Overflow unused2) { return ((Big) x).v.compareTo(((Big) y).v); } } }
Source:
<code>public void testQueryExactMatch() { <START> Assert.assertEquals(0, testRealmResource().users().search("a", true).size()); Assert.assertEquals(1, testRealmResource().users().search("apollo", true).size()); Assert.assertEquals(1, testRealmResource().users().search("tbrady", true).size()); <END> }</code><technical_language>suggestion Assert.assertThat(testRealmResource().users().search("a", true), Matchers.hasSize(0)); Assert.assertThat(testRealmResource().users().search("apollo", true), Matchers.hasSize(1)); Assert.assertThat(testRealmResource().users().search("tbrady", true), Matchers.hasSize(1)); output failure shows search results is for debugging potential failures</technical_language>

Target:
public void testQueryExactMatch() { Assert.assertThat(testRealmResource().users().search("a", true), Matchers.hasSize(0)); Assert.assertThat(testRealmResource().users().search("apollo", true), Matchers.hasSize(1)); Assert.assertThat(testRealmResource().users().search("tbrady", true), Matchers.hasSize(1)); }
Source:
<code>private static final boolean allCellsHaveTimestamps(Iterable<Mutation> mutations) { for (Mutation mut : mutations) { <START> if (mut.getSetCell().getTimestampMicros() == -1) { <END> return false; } } return true; }</code><technical_language>if 0? default in Cell proto set a clear</technical_language>

Target:
private static final boolean allCellsHaveTimestamps(Iterable<Mutation> mutations) { for (Mutation mut : mutations) { if (mut.getSetCell().getTimestampMicros() <= 0) { return false; } } return true; }
Source:
<code>public Map<ByteBuffer, List<ColumnOrSuperColumn>> multiget_slice(List<ByteBuffer> keys, ColumnParent column_parent, SlicePredicate predicate, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { qosClient.checkLimit(); Map<ByteBuffer, List<ColumnOrSuperColumn>> result = delegate.multiget_slice(keys, column_parent, predicate, consistency_level); try { recordBytesRead(getApproximateReadByteCount(result)); <START> } catch (Exception e) { <END> log.warn("Encountered an exception when recording write metrics for multiget_slice.", e); } return result; }</code><technical_language>I need catch exceptions metrics code remove of these</technical_language>

Target:
public Map<ByteBuffer, List<ColumnOrSuperColumn>> multiget_slice(List<ByteBuffer> keys, ColumnParent column_parent, SlicePredicate predicate, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { qosClient.checkLimit(); Map<ByteBuffer, List<ColumnOrSuperColumn>> result = delegate.multiget_slice(keys, column_parent, predicate, consistency_level); recordBytesRead(getApproximateReadByteCount(result)); return result; }
Source:
<code>public void testGetAPI() { VersionRange v1 = new VersionRange(1, 2); VersionRange v2 = new VersionRange(3, 4); <START> Map<String, VersionRange> allFeatures = new HashMap<String, VersionRange>() { <END> { put("feature_1", v1); put("feature_2", v2); } }; Features<VersionRange> features = Features.supportedFeatures(allFeatures); assertEquals(v1, features.get("feature_1")); assertEquals(v2, features.get("feature_2")); assertNull(features.get("nonexistent_feature")); }</code><technical_language>org.apache.kafka.common.utils.Utils#mkMap</technical_language>

Target:
public void testGetAPI() { SupportedVersionRange v1 = new SupportedVersionRange((short) 1, (short) 2); SupportedVersionRange v2 = new SupportedVersionRange((short) 3, (short) 4); Map<String, SupportedVersionRange> allFeatures = mkMap(mkEntry("feature_1", v1), mkEntry("feature_2", v2)); Features<SupportedVersionRange> features = Features.supportedFeatures(allFeatures); assertEquals(v1, features.get("feature_1")); assertEquals(v2, features.get("feature_2")); assertNull(features.get("nonexistent_feature")); }
Source:
<code><START> public boolean equals(Object o) { <END> if (this == o) { return true; } if (!(o instanceof Attribute)) { return false; } Attribute other = (Attribute) o; return ObjectUtils.equals(uuid, other.uuid) && ObjectUtils.equals(display, other.display) && ObjectUtils.equals(value, other.value) && ObjectUtils.equals(name, other.name) && ObjectUtils.equals(description, other.description) && ObjectUtils.equals(format, other.format) && ObjectUtils.equals(attributeType, other.attributeType) && ObjectUtils.equals(links, other.links); }</code><technical_language>stick conventation for equals hashcode methods in domain classes ? Currently Objects.equals Objects.hash, hashCode method equals method</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Attribute)) { return false; } Attribute other = (Attribute) o; return Objects.equals(uuid, other.uuid) && Objects.equals(display, other.display) && Objects.equals(value, other.value) && Objects.equals(name, other.name) && Objects.equals(description, other.description) && Objects.equals(format, other.format) && Objects.equals(attributeType, other.attributeType) && Objects.equals(links, other.links); }
Source:
<code>public void reset() { super.reset(); traits = null; <START> clearlisteners(); <END> }</code><technical_language>this super.reset(), it</technical_language>

Target:
public void reset() { super.reset(); traits = null; }
Source:
<code>protected int getExpirationDays(final int expirationDays) { final int jsonWebTokenMaxAllowedExpirationDay = Config.getIntProperty(LoginService.JSON_WEB_TOKEN_MAX_ALLOWED_EXPIRATION_DAYS, -1); final int maxAllowedExpirationDays = (jsonWebTokenMaxAllowedExpirationDay > 0 && (expirationDays > jsonWebTokenMaxAllowedExpirationDay))? jsonWebTokenMaxAllowedExpirationDay: expirationDays; <START> <END> Logger.debug(this, "Json Web Token Expiration days value: " + expirationDays + " days"); return maxAllowedExpirationDays; }</code><technical_language>write in file log if (expirationDays > jsonWebTokenMaxAllowedExpirationDay)</technical_language>

Target:
protected int getExpirationDays(final int expirationDays) { final int jsonWebTokenMaxAllowedExpirationDay = Config.getIntProperty(LoginService.JSON_WEB_TOKEN_MAX_ALLOWED_EXPIRATION_DAYS, -1); final int maxAllowedExpirationDays = (jsonWebTokenMaxAllowedExpirationDay > 0 && (expirationDays > jsonWebTokenMaxAllowedExpirationDay))? this.getJsonWebTokenMaxAllowedExpirationDay(jsonWebTokenMaxAllowedExpirationDay, expirationDays): expirationDays; Logger.debug(this, "Json Web Token Expiration days value: " + expirationDays + " days"); return maxAllowedExpirationDays; }
Source:
<code>public String createNew(User user) { String content = String.format("%s%d", PageContent.ARTICLE_TEXT, DateTime.now().getMillis()); String boardName = String.format("%s%d", "ForumBoard", DateTime.now().getMillis()); <START> String boardTitle = String.format("%s:%s", URLsContent.FORUM_BOARD_NAMESPACE, boardName); <END> new ForumBoardContent(user, boardTitle, content).call(); try { Thread.sleep(5000); } catch (InterruptedException e) { PageObjectLogging.logInfo("Sleep interrupted after forum board creation", e); } return boardName; }</code><technical_language>move adding FORUM_BORD_NAMESPACE ForumBoardContent</technical_language>

Target:
public String createNew(User user) { String content = String.format("%s%d", PageContent.ARTICLE_TEXT, DateTime.now().getMillis()); String boardName = String.format("%s%d", "ForumBoard", DateTime.now().getMillis()); new ForumBoardContent(user, boardName, content).call(); try { Thread.sleep(5000); } catch (InterruptedException e) { PageObjectLogging.logInfo("Sleep interrupted after forum board creation", e); } return boardName; }
Source:
<code>public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); <START> return parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https") <END> ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); }</code><technical_language>I tend avoid trigraphs absolutely necessary, you. However, please () condition of || here... code is correct non-obvious parts of [the precedence chart (13 14)](<LINK_0> LGTM</technical_language>

Target:
public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); return (parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https")) ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); }
Source:
<code>private static StateListener getStateListener(final KafkaStreams streams) { try { final Field field = streams.getClass().getDeclaredField("stateListener"); field.setAccessible(true); return (StateListener) field.get(streams); <START> } catch (IllegalAccessException | NoSuchFieldException e) { <END> throw new RuntimeException("Failed to get StateListener through reflection", e); } }</code><technical_language>nit: add missing final (I assume checkstyle fail)</technical_language>

Target:
private static StateListener getStateListener(final KafkaStreams streams) { try { final Field field = streams.getClass().getDeclaredField("stateListener"); field.setAccessible(true); return (StateListener) field.get(streams); } catch (final IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException("Failed to get StateListener through reflection", e); } }
Source:
<code>public void testReentrantLockMultinode(final boolean fair) throws Exception { final AtomicInteger inx = new AtomicInteger(0); GridTestUtils.runMultiThreadedAsync(new Runnable() { @Override public void run() { try { <START> IgniteLock lock = createReentrantLock(inx.getAndIncrement(), fair ? "lock1" : "lock2", fair); <END> lock.lock(); try { assertTrue(lock.isLocked()); Thread.sleep(1_000L); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } catch (Exception e) { e.printStackTrace(); } } }, NODES_CNT, "worker").get(30_000L); }</code><technical_language>hmm, mb newline</technical_language>

Target:
private void testReentrantLockMultinode(final boolean fair) throws IgniteCheckedException { final AtomicInteger inx = new AtomicInteger(0); GridTestUtils.runMultiThreadedAsync((Callable<Void>) () -> { IgniteLock lock = createReentrantLock(inx.getAndIncrement() % NODES_CNT, fair ? "fair lock" : "unfair lock", fair); lock.lock(); try { assertTrue(lock.isLocked()); } finally { lock.unlock(); } return null; }, NODES_CNT * THREAD_CNT, "worker").get(30_000L); }
Source:
<code>private Message getMessageFromSchema(String topic, String filename) { DynamicMessage message = null; DynamicSchema.Builder schemaBuilder = DynamicSchema.newBuilder(); topic = StringUtils.capitalize(topic.replaceAll("-", " ")).replaceAll("\\s+", ""); schemaBuilder.setName("SecorBuilder" + topic + ".proto"); <START> com.github.os72.protobuf.dynamic.MessageDefinition.Builder builder = MessageDefinition.newBuilder(topic); <END> try { BufferedReader reader = new BufferedReader(new FileReader(new File(filename))); String line; int i=0; while ((line = reader.readLine()) != null) { String[] splits = line.split(COLON_SEPARATOR); builder.addField("optional", splits[1], splits[0], ++i); } reader.close(); MessageDefinition msgDef = builder.build(); schemaBuilder.addMessageDefinition(msgDef); DynamicSchema schema = schemaBuilder.build(); DynamicMessage.Builder msgBuilder = schema.newMessageBuilder(topic); message = msgBuilder.build(); } catch (IOException e) { LOG.error("Unable to read schema for Orc due to {}, Orc conversion cannot work", e); Throwables.propagate(e); } catch (DescriptorValidationException e) { LOG.error("Unable to create protobuf messages for OrcScheme due to {}", e); Throwables.propagate(e); } return message; }</code><technical_language>This class/package able explicitly listed in import statements</technical_language>

Target:
private Message getMessageFromSchema(String topic, String filename) { DynamicMessage message = null; DynamicSchema.Builder schemaBuilder = DynamicSchema.newBuilder(); topic = StringUtils.capitalize(topic.replaceAll("-", " ")).replaceAll("\\s+", ""); schemaBuilder.setName("SecorBuilder" + topic + ".proto"); Builder builder = MessageDefinition.newBuilder(topic); try { BufferedReader reader = new BufferedReader(new FileReader(new File(filename))); String line; int i=0; while ((line = reader.readLine()) != null) { String[] splits = line.split(COLON_SEPARATOR); builder.addField("optional", splits[1], splits[0], ++i); } reader.close(); MessageDefinition msgDef = builder.build(); schemaBuilder.addMessageDefinition(msgDef); DynamicSchema schema = schemaBuilder.build(); DynamicMessage.Builder msgBuilder = schema.newMessageBuilder(topic); message = msgBuilder.build(); } catch (IOException e) { LOG.error("Unable to read schema for Orc due to {}, Orc conversion cannot work", e); Throwables.propagate(e); } catch (DescriptorValidationException e) { LOG.error("Unable to create protobuf messages for OrcScheme due to {}", e); Throwables.propagate(e); } return message; }
Source:
<code>public Diagnostics(Configuration config, Context context, Client client) { super(config); <START> this.client = client; <END> applicationContext = context; Diagnostics.startSessionTimer(); packageName = applicationContext.getPackageName(); client.setUser(getUUID(), null, null); client.setOsVersion(android.os.Build.VERSION.RELEASE); client.setAppVersion(getPackageVersion(packageName)); client.setReleaseStage(guessReleaseStage(packageName)); client.setProjectPackages(packageName); }</code><technical_language>if avoid this client relationship</technical_language>

Target:
public Diagnostics(Configuration config, Context context, Client client) { super(config); applicationContext = context; Diagnostics.startSessionTimer(); packageName = applicationContext.getPackageName(); config.setProjectPackages(packageName); config.getOsVersion().set(android.os.Build.VERSION.RELEASE); config.getAppVersion().set(getPackageVersion(packageName)); config.getReleaseStage().set(guessReleaseStage(packageName)); this.initialiseDeviceData(); this.initialiseAppData(); }
Source:
<code>public void close() throws Exception { if (released || isEmpty()) return; if (!closeable()) <START> throw new ND4JIllegalStateException("Can't release this INDArray"); <END> data.close(); released = true; }</code><technical_language>great is closeable</technical_language>

Target:
public void close() { if (released || isEmpty()) return; if (!closeable()) throw new ND4JIllegalStateException("Can't release this INDArray"); data.close(); released = true; }
Source:
<code>private static void showInAppReview() { Context context = mContext.get(); if (context == null) { return; } ReviewManager manager = ReviewManagerFactory.create(context); Task<ReviewInfo> request = manager.requestReviewFlow(); request <START> .addOnCompleteListener(task -> { <END> if (task.isSuccessful()) { ReviewInfo reviewInfo = task.getResult(); Task<Void> flow = manager.launchReviewFlow((Activity) context, reviewInfo); flow .addOnCompleteListener(task1 -> { saveRated(); Toast.makeText(context, "Review saved", Toast.LENGTH_SHORT).show(); Log.i("ReviewDialog", "Successfully finished in-app review"); }) .addOnFailureListener(error -> { Log.i("ReviewDialog", "failed in reviewing process"); }); } }) .addOnFailureListener(error -> { Log.i("ReviewDialog", "failed to get in-app review request"); }); }</code><technical_language>Please this line instead of breaking next line. lines intended a bit less. way, code is a lot more "compact"</technical_language>

Target:
private static void showInAppReview() { Context context = mContext.get(); if (context == null) { return; } ReviewManager manager = ReviewManagerFactory.create(context); Task<ReviewInfo> request = manager.requestReviewFlow(); request.addOnCompleteListener(task -> { if (task.isSuccessful()) { ReviewInfo reviewInfo = task.getResult(); Task<Void> flow = manager.launchReviewFlow((Activity) context, reviewInfo); flow.addOnCompleteListener(task1 -> { int previousAttempts = mPreferences.getInt(KEY_NUMBER_OF_REVIEWS, 0); if (previousAttempts >= 3) { saveRated(); } else { resetStartDate(); mPreferences .edit() .putInt(KEY_NUMBER_OF_REVIEWS, previousAttempts + 1) .apply(); } Log.i("ReviewDialog", "Successfully finished in-app review"); }) .addOnFailureListener(error -> { Log.i("ReviewDialog", "failed in reviewing process"); }); } }) .addOnFailureListener(error -> { Log.i("ReviewDialog", "failed to get in-app review request"); }); }
Source:
<code>protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<>(); locks.put(getVmId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED)); <START> return locks; <END> }</code><technical_language>do change this</technical_language>

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getVmId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED)); }
Source:
<code>public void testUpdateWhenNotCachingData() throws Exception { client.create().forPath("/test"); <START> cache = new TreeCache(client, "/test", false); <END> cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test/foo", "first".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); client.setData().forPath("/test/foo", "something new".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/foo"); assertNoMoreEvents(); }</code><technical_language>setup() do this? is this allocation needed? tests do this</technical_language>

Target:
public void testUpdateWhenNotCachingData() throws Exception { client.create().forPath("/test"); cache = new MyTreeCache(client, "/test", false); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.create().forPath("/test/foo", "first".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/foo"); client.setData().forPath("/test/foo", "something new".getBytes()); assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/foo"); assertNoMoreEvents(); }
Source:
<code>public void loadLaunchConfigOsgiRepoTestCase() throws MalformedURLException { URL osgiRepoURL = launchConfig.getCarbonOSGiRepository(); <START> Path expectedPath = Paths.get(System.getProperty(Constants.CARBON_HOME), "wso2/lib"); <END> if (System.getProperty("os.name").toLowerCase(Locale.getDefault()).contains("windows")) { Assert.assertEquals(Paths.get(osgiRepoURL.getPath()).toUri().toURL().toString(), expectedPath.toUri().toURL().toString()); } else { Assert.assertEquals(osgiRepoURL.toString(), "file:".concat(expectedPath.toString())); } }</code><technical_language>move "wso2/lib" a constant</technical_language>

Target:
public void loadLaunchConfigOsgiRepoTestCase() throws MalformedURLException { final String osgiRepo = "wso2/lib"; URL osgiRepoURL = launchConfig.getCarbonOSGiRepository(); Path expectedPath = Paths.get(System.getProperty(Constants.CARBON_HOME), osgiRepo); if (System.getProperty("os.name").toLowerCase(Locale.getDefault()).contains("windows")) { Assert.assertEquals(Paths.get(osgiRepoURL.getPath()).toUri().toURL().toString(), expectedPath.toUri().toURL().toString()); } else { Assert.assertEquals(osgiRepoURL.toString(), "file:".concat(expectedPath.toString())); } }
Source:
<code>public void testLoadOpportunityMRUObjectsFromServer() throws Exception { final List<SalesforceObject> mruObjects_before = metadataManager.loadMRUObjects(Constants.OPPORTUNITY, MAX_QUERY_LIMIT, CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, REFRESH_INTERVAL, null); Map<String, String> idToNames = new HashMap<String, String>(); int numberOfRecords = 1; <START> idToNames = createRecordsOnServer(numberOfRecords, Constants.OPPORTUNITY); <END> String[] names = idToNames.values().toArray(new String[numberOfRecords]);; String[] ids = idToNames.keySet().toArray(new String[numberOfRecords]); try { Thread.sleep(2000); final List<SalesforceObject> mruObjects = metadataManager.loadMRUObjects(Constants.OPPORTUNITY, MAX_QUERY_LIMIT, CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, REFRESH_INTERVAL, null); assertNotNull("MRU list should not be null", mruObjects); assertEquals("MRU list size should not be changed", mruObjects_before.size()+numberOfRecords, mruObjects.size()); assertEquals("Recently viewed object name is incorrect", names[0], mruObjects.get(0).getName()); } finally { deleteRecordsOnServer(ids, Constants.OPPORTUNITY); } }</code><technical_language>initialize this line 120</technical_language>

Target:
public void testLoadOpportunityMRUObjectsFromServer() throws Exception { final List<SalesforceObject> mruObjects_before = metadataManager.loadMRUObjects(Constants.OPPORTUNITY, MAX_QUERY_LIMIT, CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, REFRESH_INTERVAL, null); int numberOfRecords = 1; Map<String, String> idToNames = createRecordsOnServer(numberOfRecords, Constants.OPPORTUNITY); Collection<String> names = idToNames.values(); Set<String> ids = idToNames.keySet(); try { Thread.sleep(2000); final List<SalesforceObject> mruObjects = metadataManager.loadMRUObjects(Constants.OPPORTUNITY, MAX_QUERY_LIMIT, CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, REFRESH_INTERVAL, null); assertNotNull("MRU list should not be null", mruObjects); assertEquals("MRU list size should not be changed", mruObjects_before.size()+numberOfRecords, mruObjects.size()); assertEquals("Recently viewed object name is incorrect", names.toArray()[0], mruObjects.get(0).getName()); } finally { deleteRecordsOnServer(ids, Constants.OPPORTUNITY); } }
Source:
<code>private static List<URI> findPreferredURIs(AbstractInvocationContext context, List<URI> uris) { Collection<URI> attachment = context.getAttachment(TransactionInterceptor.PREFERRED_DESTINATIONS); if (attachment == null) { return null; } HashSet<URI> preferred = new HashSet<>(attachment); List<URI> result = null; for (URI check : uris) { if (preferred.contains(check) && !isBlackListed(context, check)) { if (result == null) { result = new ArrayList<>(preferred.size()); } result.add(check); } } if (Logs.INVOCATION.isDebugEnabled()) { <START> Logs.INVOCATION.debugf("NamingEJBClientInterceptor: computing preffered URIs: URIs = %s, preferred URIs = %s", uris, result); <END> } return result; }</code><technical_language>Another typo: preffered instead of preferred</technical_language>

Target:
private static List<URI> findPreferredURIs(AbstractInvocationContext context, List<URI> uris) { Collection<URI> attachment = context.getAttachment(TransactionInterceptor.PREFERRED_DESTINATIONS); if (attachment == null) { return null; } HashSet<URI> preferred = new HashSet<>(attachment); List<URI> result = null; for (URI check : uris) { if (preferred.contains(check) && !isBlackListed(context, check)) { if (result == null) { result = new ArrayList<>(preferred.size()); } result.add(check); } } if (Logs.INVOCATION.isDebugEnabled()) { Logs.INVOCATION.debugf("NamingEJBClientInterceptor: computing preferred URIs: URIs = %s, preferred URIs = %s", uris, result); } return result; }
Source:
<code><START> public String injectOrganisationId(String path) { <END> String organisationId = organisationIdSupplier.get(); List<String> list = Lists.newArrayList(Splitter.on("/").split(path)); if (list.size() > ORGANIZATION_ID_INDEX && !list.get(ORGANIZATION_ID_INDEX).equals(organisationId)) { list.add(ORGANIZATION_ID_INDEX, organisationId); } return Joiner.on("/").join(list); }</code><technical_language>public if is visible for testing. Remove public modifier leave in default scope</technical_language>

Target:
String injectOrganisationId(String path) { String organisationId = organisationIdSupplier.get(); List<String> list = Lists.newArrayList(Splitter.on("/").split(path)); if (list.size() > ORGANIZATION_ID_INDEX && !list.get(ORGANIZATION_ID_INDEX).equals(organisationId)) { list.add(ORGANIZATION_ID_INDEX, organisationId); } return Joiner.on("/").join(list); }
Source:
<code><START> private String getProcessingTitleForAction(String actionType) { <END> if (actionType.equals(ARG_ACTION_LIKE)) { return getString(R.string.comment_q_action_liking); } else if (actionType.equals(ARG_ACTION_APPROVE)) { return getString(R.string.comment_q_action_approving); } else if (actionType.equals(ARG_ACTION_REPLY)) { return getString(R.string.comment_q_action_replying); } else { return getString(R.string.comment_q_action_processing); } }</code><technical_language>a switch statement here</technical_language>

Target:
private String getProcessingTitleForAction(String actionType) { if (actionType != null) { switch (actionType) { case ARG_ACTION_LIKE: return getString(R.string.comment_q_action_liking); case ARG_ACTION_APPROVE: return getString(R.string.comment_q_action_approving); case ARG_ACTION_REPLY: return getString(R.string.comment_q_action_replying); default: return getString(R.string.comment_q_action_processing); } } else { return getString(R.string.comment_q_action_processing); } }
Source:
<code>private void normalizeMachine(String name, CheServiceImpl service, ExtendedMachine extendedMachine) { <START> if (extendedMachine.getAttributes() != null && <END> extendedMachine.getAttributes().containsKey("memoryLimitBytes")) { try { service.setMemLimit(Long.parseLong(extendedMachine.getAttributes().get("memoryLimitBytes"))); } catch (NumberFormatException e) { throw new IllegalArgumentException( format("Value of attribute 'memoryLimitBytes' of machine '%s' is illegal", name)); } } if (service.getExpose() != null) { service.setExpose(service.getExpose() .stream() .map(expose -> expose.contains("/") ? expose : expose + "/tcp") .collect(toList())); } if (extendedMachine.getServers() != null) { extendedMachine.getServers().forEach((serverRef, serverConf) -> { String normalizedPort = serverConf.getPort().contains("/") ? serverConf.getPort() : serverConf.getPort() + "/tcp"; service.getExpose().add(normalizedPort); service.getLabels().put(SERVER_CONF_LABEL_PREFIX + normalizedPort + SERVER_CONF_LABEL_REF_SUFFIX, serverRef); if (serverConf.getProperties() != null && serverConf.getProperties().get("path") != null) { service.getLabels().put(SERVER_CONF_LABEL_PREFIX + normalizedPort + SERVER_CONF_LABEL_PATH_SUFFIX, serverConf.getProperties().get("path")); } if (serverConf.getProtocol() != null) { service.getLabels().put(SERVER_CONF_LABEL_PREFIX + normalizedPort + SERVER_CONF_LABEL_PROTOCOL_SUFFIX, serverConf.getProtocol()); } }); } }</code><technical_language>I POJO DTO objects return empty collections instead of null values</technical_language>

Target:
private void normalizeMachine(String name, CheServiceImpl service, ExtendedMachine extendedMachine) { if (extendedMachine.getAttributes().containsKey("memoryLimitBytes")) { try { service.setMemLimit(Long.parseLong(extendedMachine.getAttributes().get("memoryLimitBytes"))); } catch (NumberFormatException e) { throw new IllegalArgumentException( format("Value of attribute 'memoryLimitBytes' of machine '%s' is illegal", name)); } } service.setExpose(service.getExpose() .stream() .map(expose -> expose.contains("/") ? expose : expose + "/tcp") .collect(toList())); extendedMachine.getServers().forEach((serverRef, serverConf) -> { String normalizedPort = serverConf.getPort().contains("/") ? serverConf.getPort() : serverConf.getPort() + "/tcp"; service.getExpose().add(normalizedPort); String portLabelPrefix = SERVER_CONF_LABEL_PREFIX + normalizedPort; service.getLabels().put(portLabelPrefix + SERVER_CONF_LABEL_REF_SUFFIX, serverRef); if (serverConf.getProperties() != null && serverConf.getProperties().get("path") != null) { service.getLabels().put(portLabelPrefix + SERVER_CONF_LABEL_PATH_SUFFIX, serverConf.getProperties().get("path")); } if (serverConf.getProtocol() != null) { service.getLabels().put(portLabelPrefix + SERVER_CONF_LABEL_PROTOCOL_SUFFIX, serverConf.getProtocol()); } }); }
Source:
<code>public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { if(run instanceof AbstractBuild) { AbstractBuild<?,?> abstractBuild = (AbstractBuild<?,?>) run; Updater updater = new Updater(abstractBuild.getParent().getScm(), labels); <START> updater.perform(run, listener, getIssueSelector()); <END> } else if(scm != null) { Updater updater = new Updater(scm, labels); updater.perform(run, listener, getIssueSelector()); } else { throw new IllegalArgumentException("Unsupported job type "+run.getClass().getName()); } }</code><technical_language>Breaks behavior for <code> MatrixRun</code>s I</technical_language>

Target:
public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { if (run instanceof MatrixRun) { return; } else if(run instanceof AbstractBuild) { AbstractBuild<?,?> abstractBuild = (AbstractBuild<?,?>) run; Updater updater = new Updater(abstractBuild.getParent().getScm(), labels); updater.perform(run, listener, getIssueSelector()); } else if(scm != null) { Updater updater = new Updater(scm, labels); updater.perform(run, listener, getIssueSelector()); } else { throw new IllegalArgumentException("Unsupported run type "+run.getClass().getName()); } }
Source:
<code>public DistributedQueryRunner(Session defaultSession, int workersCount, Map<String, String> extraProperties) throws Exception { this(defaultSession, workersCount, extraProperties, ImmutableMap.of(), DEFAULT_SQL_PARSER_OPTIONS, ENVIRONMENT); <START> } <END></code><technical_language>please public constructors deprecated</technical_language>

Target:
public DistributedQueryRunner(Session defaultSession, int workersCount, Map<String, String> extraProperties) throws Exception { this(defaultSession, workersCount, extraProperties, ImmutableMap.of(), DEFAULT_SQL_PARSER_OPTIONS, ENVIRONMENT, DEFAULT_PROTOCOL_VERSION); }
Source:
<code>public void prepareRun(BatchSourceContext context) throws IOException { Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); CopybookInputFormat.setCopybookInputformatCblContents(job, config.copybookContents); CopybookInputFormat.setBinaryFilePath(job, config.binaryFilePath); CopybookInputFormat.setInputPaths(job, config.binaryFilePath); <START> CopybookInputFormat.setMaxInputSplitSize(job, conf.getLong(CopybookInputFormat.MAX_SPLIT_SIZE_DESCRIPTION, <END> DEFAULT_MAX_SPLIT_SIZE)); context.setInput(Input.of(config.referenceName, new SourceInputFormatProvider(CopybookInputFormat.class, conf))); }</code><technical_language>this config.maxSplitSize</technical_language>

Target:
public void prepareRun(BatchSourceContext context) throws IOException { Job job = JobUtils.createInstance(); CopybookInputFormat.setCopybookInputformatCblContents(job, config.copybookContents); CopybookInputFormat.setBinaryFilePath(job, config.binaryFilePath); CopybookInputFormat.setInputPaths(job, config.binaryFilePath); CopybookInputFormat.setMaxInputSplitSize(job, config.maxSplitSize); context.setInput(Input.of(config.referenceName, new SourceInputFormatProvider(CopybookInputFormat.class, job.getConfiguration()))); }
Source:
<code>private SAMFileHeader loadSamHeader() throws ErrorMsg { if (run == null) { throw new RuntimeException("Cannot load SAMFileHeader - SRA run is uninitialized"); } String runName = run.getName(); SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); ReadGroupIterator itRg = run.getReadGroups(); while (itRg.nextReadGroup()) { String rgName = itRg.getName(); <START> if (rgName.equals("")) <END> rgName = "_"; SAMReadGroupRecord rg = new SAMReadGroupRecord(rgName); rg.setSample(runName); header.addReadGroup(rg); } ReferenceIterator itRef = run.getReferences(); while (itRef.nextReference()) { header.addSequence(new SAMSequenceRecord(itRef.getCanonicalName(), (int) itRef.getLength())); } return header; }</code><technical_language>if (rgName.isEmpty())</technical_language>

Target:
private SAMFileHeader loadSamHeader() throws ErrorMsg { if (run == null) { throw new RuntimeException("Cannot load SAMFileHeader - SRA run is uninitialized"); } String runName = run.getName(); SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); ReadGroupIterator itRg = run.getReadGroups(); while (itRg.nextReadGroup()) { String rgName = itRg.getName(); if (rgName.isEmpty()) rgName = runName; SAMReadGroupRecord rg = new SAMReadGroupRecord(rgName); rg.setSample(runName); header.addReadGroup(rg); } ReferenceIterator itRef = run.getReferences(); while (itRef.nextReference()) { header.addSequence(new SAMSequenceRecord(itRef.getCanonicalName(), (int) itRef.getLength())); } return header; }