auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Collection<T> queryExpression(final String expr, Collection<T> ret, DBConnection connection){ if (ret == null) { ret = new LinkedList<T>(); } boolean setConnection = connection != PersistentObject.getDefaultConnection(); Stm stm = connection.getStatement(); try (ResultSet res = stm.query(expr)) { log.debug("Executed " + expr); while ((res != null) && (res.next() == true)) { final String id = res.getString(1); T o = (T) load.invoke(null, new Object[] { id }); if (o == null) { continue; } else if (setConnection) { ((PersistentObject) o).setDBConnection(connection); } if (fetchVals.length > 1) { PersistentObject po = (PersistentObject) o; for (int i = 1; i < fetchVals.length; i++) { Object prefetchVal = res.getObject(i + 1); po.putInCache(fetchVals[i], prefetchVal); } } boolean bAdd = true; for (IFilter fi : postQueryFilters) { if (fi.select(o) == false) { bAdd = false; break; } } if (bAdd == true) { ret.add(o); } } return ret; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei Datenbankabfrage " + ex.getMessage(), ex, ElexisStatus.LOG_ERRORS); <START> log.warn(String.format("Fehler %s bei Datenbankabfrage:\n%s;", ex.getMessage(), expr)); <END> throw new PersistenceException(status); } finally { connection.releaseStatement(stm); } }</code><technical_language>try slf4j log native expression log.warn(Error in database query: [{}]", ex.getMessage, expr); log4j automatically replaces expressions resp. parameter. Additionally I prefer put error content square brackets for differentiation copy/paste selection :)</technical_language>

Target:
public Collection<T> queryExpression(final String expr, Collection<T> ret, DBConnection connection){ if (ret == null) { ret = new LinkedList<T>(); } boolean setConnection = connection != PersistentObject.getDefaultConnection(); Stm stm = connection.getStatement(); try (ResultSet res = stm.query(expr)) { log.debug("Executed " + expr); while ((res != null) && (res.next() == true)) { final String id = res.getString(1); T o = (T) load.invoke(null, new Object[] { id }); if (o == null) { continue; } else if (setConnection) { ((PersistentObject) o).setDBConnection(connection); } if (fetchVals.length > 1) { PersistentObject po = (PersistentObject) o; for (int i = 1; i < fetchVals.length; i++) { Object prefetchVal = res.getObject(i + 1); po.putInCache(fetchVals[i], prefetchVal); } } boolean bAdd = true; for (IFilter fi : postQueryFilters) { if (fi.select(o) == false) { bAdd = false; break; } } if (bAdd == true) { ret.add(o); } } return ret; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei Datenbankabfrage " + ex.getMessage(), ex, ElexisStatus.LOG_ERRORS); log.warn("Fehler bei Datenbankabfrage:\n[{};]", ex.getMessage(), expr); throw new PersistenceException(status); } finally { connection.releaseStatement(stm); } }
Source:
<code><START> private XMLGregorianCalendar getTimestamp() throws DatatypeConfigurationException { <END> DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(System.currentTimeMillis()); return datatypeFactory.newXMLGregorianCalendar(gc); }</code><technical_language>Duplicate code XMLDateUtil.long2Gregorian()</technical_language>

Target:
private XMLGregorianCalendar getTimestamp() throws DatatypeConfigurationException { return XMLDateUtil.long2Gregorian(System.currentTimeMillis()); }
Source:
<code>private String getFsCopyStatus() { <START> WebElement copyModalStatusMessage = browser.driver.findElement(By.id("feedback-copy-modal-status")); <END> return copyModalStatusMessage.getText(); }</code><technical_language>Declare WebElements start of class instead</technical_language>

Target:
private String getFsCopyStatus() { return copyModalStatusMessage.getText(); }
Source:
<code>private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { try { index.close(); } catch ( IOException closeException ) { <START> e.addSuppressed( closeException ); <END> } } } ); indexesToDropAfterCompletedRecovery.clear(); }</code><technical_language>If swallowing exception need addSuppressed</technical_language>

Target:
private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { try { index.close(); } catch ( IOException closeException ) { } } } ); indexesToDropAfterCompletedRecovery.clear(); }
Source:
<code>private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canDelete()) { } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { <START> reject(cmd, "Deleting the project configuration is not allowed"); <END> } else { rp.sendMessage("You need 'Push' rights with the 'Force Push' flag set to delete references." + MESSAGE_FOOTER); reject(cmd, "Current user '" + ctl.getCurrentUser().getUserName() + "' can not delete references"); } } }</code><technical_language>I prefer put longer explanation rp.sendMessage() a shorter message in reject() (see below)</technical_language>

Target:
private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canDelete()) { } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { reject(cmd, "Cannot delete project configuration"); } else { addError(Error.DELETE, ctl.getRefName()); reject(cmd, String.format("%s cannot delete references", displayName(destBranchCtl))); } } }
Source:
<code>public static void validateHostName(Boolean clusterMapResolveHostnames, String hostName) { if (clusterMapResolveHostnames) { String fqdn = getFullyQualifiedDomainName(hostName); if (!fqdn.equals(hostName)) { throw new IllegalStateException( <START> "Hostname for AmbryDataNode (" + hostName + ") does not match its fully qualified domain name: " + fqdn); <END> } } }</code><technical_language>Remove "for AmbryDataNode"</technical_language>

Target:
public static void validateHostName(Boolean clusterMapResolveHostnames, String hostName) { if (clusterMapResolveHostnames) { String fqdn = getFullyQualifiedDomainName(hostName); if (!fqdn.equals(hostName)) { throw new IllegalArgumentException( "Hostname(" + hostName + ") does not match its fully qualified domain name: " + fqdn); } } }
Source:
<code>private void handleException(final URIish uri, Exception e, String userMessage) { <START> if (uri != null) <END> operationResult.addOperationResult(uri, userMessage); String uriString; if (uri == null) uriString = "retrieving URI failed"; else uriString = uri.toString(); String userMessageForUri = NLS.bind( CoreText.PushOperation_ExceptionOccurredDuringPushOnUriMessage, uriString, userMessage); Activator.logError(userMessageForUri, e); }</code><technical_language>This convoluted ... instead do String uriString; if (uri != null) { operationResult.addOperationResult(uri, userMessage); uriString = uri.toString(); } else uriString = "retrieving URI failed"; //$NON-NLS-1$</technical_language>

Target:
private void handleException(final URIish uri, Exception e, String userMessage) { String uriString; if (uri != null) { operationResult.addOperationResult(uri, userMessage); uriString = uri.toString(); } else uriString = "retrieving URI failed"; String userMessageForUri = NLS.bind( CoreText.PushOperation_ExceptionOccurredDuringPushOnUriMessage, uriString, userMessage); Activator.logError(userMessageForUri, e); }
Source:
<code>private boolean canCloneVolume() { <START> return new Boolean(getDriver().getCapabilities().get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString())); <END> }</code><technical_language>new Boolean skips constant pool -- placing unnecessary pressure garbage collector. Please Boolean.valueOf instead</technical_language>

Target:
private boolean canCloneVolume() { return Boolean.valueOf(getDriver().getCapabilities().get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString())); }
Source:
<code><START> public ChannelModelTransformer( <END> NumberToShortStringCodec v4Codec, ImageModelTranslator imageTranslator ) { this.v4Codec = v4Codec; this.imageTranslator = imageTranslator; }</code><technical_language>Code style. Constructor private. a static factory method named create(...) create a new transformer</technical_language>

Target:
private ChannelModelTransformer( NumberToShortStringCodec v4Codec, ImageModelTranslator imageTranslator ) { this.v4Codec = checkNotNull(v4Codec); this.imageTranslator = checkNotNull(imageTranslator); }
Source:
<code><START> public static String indexFile(final String filename, final String extension) { <END> return ParsingUtils.appendToPath(filename, extension); }</code><technical_language>is this public</technical_language>

Target:
private static String indexFile(final String filename, final String extension) { return ParsingUtils.appendToPath(filename, extension); }
Source:
<code><START> public List<Object> getContent() { <END> if (this.getJaxbElement()==null) { this.setJaxbElement( Context.getWmlObjectFactory().createCTFootnotes() ); } if (content == null) { content = new ArrayListWml<Object>(this.getJaxbElement()); } return this.content; }</code><technical_language>of it, this work properly. getContent().add(foo) add foo endnote object</technical_language>

Target:
public List<CTFtnEdn> getContent() { try { CTFootnotes contents = this.getContents(); if (contents==null) { contents = Context.getWmlObjectFactory().createCTFootnotes(); this.setContents(contents); } return contents.getFootnote(); } catch (Docx4JException e) { log.error(e.getMessage(), e); return null; } }
Source:
<code>public void deleteRelatedContent(final Contentlet contentlet, final Relationship relationship, final boolean hasParent, final User user, final boolean respectFrontendRoles) throws DotDataException, DotSecurityException,DotContentletStateException { if(!permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_EDIT, user, respectFrontendRoles)){ throw new DotSecurityException("User: " + (user != null ? user.getUserId() : "Unknown") + " cannot edit Contentlet"); } List<Relationship> rels = FactoryLocator.getRelationshipFactory().byContentType(contentlet.getContentType()); if(!rels.contains(relationship)){ throw new DotContentletStateException( "Error deleting existing relationships in contentlet: " + (contentlet != null ? contentlet.getInode() : "Unknown")); } List<Contentlet> cons = relationshipAPI.dbRelatedContent(relationship, contentlet, hasParent); cons = permissionAPI.filterCollection(cons, PermissionAPI.PERMISSION_READ, respectFrontendRoles, user); FactoryLocator.getRelationshipFactory().deleteByContent(contentlet, relationship, cons); if(cons != null) { for (final Contentlet relatedContentlet : cons) { relatedContentlet.setIndexPolicy(contentlet.getIndexPolicyDependencies()); relatedContentlet.setIndexPolicyDependencies(contentlet.getIndexPolicyDependencies()); refreshNoDeps(relatedContentlet); } } <START> if (contentlet.get(CHECKIN_IN_PROGRESS) == null || !contentlet.getBoolProperty(CHECKIN_IN_PROGRESS)) { <END> refreshNoDeps(contentlet); } }</code><technical_language>shortened: if (!contentlet.getBoolProperty(CHECKIN_IN_PROGRESS))</technical_language>

Target:
public void deleteRelatedContent(final Contentlet contentlet, final Relationship relationship, final boolean hasParent, final User user, final boolean respectFrontendRoles) throws DotDataException, DotSecurityException,DotContentletStateException { if(!permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_EDIT, user, respectFrontendRoles)){ throw new DotSecurityException("User: " + (user != null ? user.getUserId() : "Unknown") + " cannot edit Contentlet"); } List<Relationship> rels = FactoryLocator.getRelationshipFactory().byContentType(contentlet.getContentType()); if(!rels.contains(relationship)){ throw new DotContentletStateException( "Error deleting existing relationships in contentlet: " + (contentlet != null ? contentlet.getInode() : "Unknown")); } List<Contentlet> cons = relationshipAPI.dbRelatedContent(relationship, contentlet, hasParent); cons = permissionAPI.filterCollection(cons, PermissionAPI.PERMISSION_READ, respectFrontendRoles, user); FactoryLocator.getRelationshipFactory().deleteByContent(contentlet, relationship, cons); if(cons != null) { for (final Contentlet relatedContentlet : cons) { relatedContentlet.setIndexPolicy(contentlet.getIndexPolicyDependencies()); relatedContentlet.setIndexPolicyDependencies(contentlet.getIndexPolicyDependencies()); refreshNoDeps(relatedContentlet); } } if (!contentlet.getBoolProperty(CHECKIN_IN_PROGRESS)) { refreshNoDeps(contentlet); } }
Source:
<code>static ParameterizedTypeName get(ParameterizedType type, Map<Type, TypeVariableName> map) { ParameterizedType toTest = type; Deque<ParameterizedType> enclosingStack = new ArrayDeque<ParameterizedType>(); do { enclosingStack.push(toTest); toTest = (toTest.getOwnerType() instanceof ParameterizedType) <START> && !Modifier.isFinal(((Class<?>) type.getRawType()).getModifiers()) <END> ? (ParameterizedType) toTest.getOwnerType() : null; } while (toTest != null); ParameterizedTypeName paramTypeName = null; while (!enclosingStack.isEmpty()) { ParameterizedType ownerType = enclosingStack.pop(); ClassName rawType = ClassName.get((Class<?>) type.getRawType()); List<TypeName> typeArguments = TypeName.list(ownerType.getActualTypeArguments(), map); paramTypeName = (paramTypeName != null) ? paramTypeName.nestedClass(rawType.simpleName(), typeArguments) : new ParameterizedTypeName(rawType, typeArguments); } return paramTypeName; }</code><technical_language>isStatic</technical_language>

Target:
static ParameterizedTypeName get(ParameterizedType type, Map<Type, TypeVariableName> map) { ClassName rawType = ClassName.get((Class<?>) type.getRawType()); ParameterizedType ownerType = (type.getOwnerType() instanceof ParameterizedType) && !Modifier.isStatic(((Class<?>) type.getRawType()).getModifiers()) ? (ParameterizedType) type.getOwnerType() : null; List<TypeName> typeArguments = TypeName.list(type.getActualTypeArguments(), map); return (ownerType != null) ? get(ownerType, map).nestedClass(rawType.simpleName(), typeArguments) : new ParameterizedTypeName(rawType, typeArguments); }
Source:
<code>public boolean hasCredentials() { <START> OAuth2AuthzSession storedAccount = sessionStore.read(AuthEndPoints.NAME); <END> return storedAccount != null; }</code><technical_language>simplify ;-) return sessionStore.read(AuthEndpoints.NAME) != null</technical_language>

Target:
public boolean hasCredentials() { return sessionStore.read(AuthData.NAME) != null; }
Source:
<code>public Set<Stream> getResultStreams() { <START> Set<Stream> streams = new HashSet<Stream>(); <END> streams.add(this.resultStream); return streams; }</code><technical_language>ImmutableSet.of(this.resultStream)</technical_language>

Target:
public Set<Stream> getResultStreams() { Set<Stream> streams = ImmutableSet.of(this.resultStream); return streams; }
Source:
<code>public void init() { super.init(); connectSensorsAsync(); <START> ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING); <END> }</code><technical_language>sets expected state Lifecycle.RUNNING</technical_language>

Target:
public void init() { super.init(); connectSensorsAsync(); setAttribute(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STARTING); }
Source:
<code>public void refresh() { final Set<DRepresentation> representationsToDelete = new HashSet<DRepresentation>(); Iterator<DRepresentation> it = getAllRepresentations().iterator(); while (it.hasNext()) { final DRepresentation representation = it.next(); if (representation instanceof DSemanticDecorator) { <START> if (DialectManager.INSTANCE.isRepresentationConsideredAsDangling(representation)) { <END> representationsToDelete.add(representation); } } if (!representationsToDelete.contains(representation)) { representation.refresh(); } } it = representationsToDelete.iterator(); while (it.hasNext()) { final EObject next = it.next(); final Session session; if (next instanceof DSemanticDecorator) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) next).getTarget()); } else { session = SessionManager.INSTANCE.getSession(next); } SiriusPlugin.getDefault().getModelAccessorRegistry().getModelAccessor(next).eDelete(next, session != null ? session.getSemanticCrossReferencer() : null); } }</code><technical_language>I be: if (representation instanceof DSemanticDecorator) && ((DSemanticDecorator) representation).getTarget() == null) { DSemanticDiagram.getRootContent() is EOperation marked @Deprecated in DSemanticDiagram.java. is in refresh (org.eclipse.sirius.business.api.query.DiagramElementMappingQuery.getRootContent(DSemanticDiagram, IInterpreter, DragAndDropTarget)). do need add this entry point in DialectServices. Furthermore, I relevant call DRepresentationContainer.refresh()</technical_language>

Target:
public void refresh() { final Set<DRepresentation> representationsToDelete = new HashSet<DRepresentation>(); Iterator<DRepresentation> it = getAllRepresentations().iterator(); while (it.hasNext()) { final DRepresentation representation = it.next(); if (representation instanceof DSemanticDecorator && ((DSemanticDecorator) representation).getTarget() == null) { representationsToDelete.add(representation); } if (!representationsToDelete.contains(representation)) { representation.refresh(); } } it = representationsToDelete.iterator(); while (it.hasNext()) { final EObject next = it.next(); final Session session; if (next instanceof DSemanticDecorator) { session = SessionManager.INSTANCE.getSession(((DSemanticDecorator) next).getTarget()); } else { session = SessionManager.INSTANCE.getSession(next); } SiriusPlugin.getDefault().getModelAccessorRegistry().getModelAccessor(next).eDelete(next, session != null ? session.getSemanticCrossReferencer() : null); } }
Source:
<code>public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); ValueType type = ValueType.value(trigger.getThreshold()); switch (type) { <START> case INT: <END> case LONG: jgen.writeNumberField("thresholdLong", trigger.getThreshold().longValue()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); break; case DOUBLE: jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); break; default: throw new IllegalStateException(); } if(trigger.getSecondaryThreshold() != null) { ValueType type2 = ValueType.value(trigger.getSecondaryThreshold()); switch (type2) { case INT: case LONG: jgen.writeNumberField("secondaryThresholdLong", trigger.getSecondaryThreshold().longValue()); jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold().doubleValue()); break; case DOUBLE: jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold().doubleValue()); break; default: throw new IllegalStateException(); } } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); }</code><technical_language>is usecase for INT LONG DOUBLE. If is need for FLOAT</technical_language>

Target:
public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); ValueType type = ValueType.value(trigger.getThreshold()); switch (type) { case LONG: jgen.writeNumberField("thresholdLong", trigger.getThreshold().longValue()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); break; case DOUBLE: jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); break; default: throw new IllegalStateException(); } if(trigger.getSecondaryThreshold() != null) { ValueType type2 = ValueType.value(trigger.getSecondaryThreshold()); switch (type2) { case LONG: jgen.writeNumberField("secondaryThresholdLong", trigger.getSecondaryThreshold().longValue()); jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold().doubleValue()); break; case DOUBLE: jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold().doubleValue()); break; default: throw new IllegalStateException(); } } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); }
Source:
<code>public boolean sendCommand(VeluxBridge bridge, int nodeId, VeluxProductPosition value) { logger.trace("sendCommand(nodeId={},value={}) called.", nodeId, value); SendCommand bcp = bridge.bridgeAPI().sendCommand(); int veluxValue = value.getPositionAsVeluxType(); bcp.setNodeAndMainParameter(nodeId, veluxValue); <START> if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { <END> logger.debug("sendCommand() finished successfully."); return true; } else { logger.trace("sendCommand() finished with failure."); return false; } }</code><technical_language>redundant parentheses</technical_language>

Target:
public boolean sendCommand(VeluxBridge bridge, int nodeId, VeluxProductPosition value) { logger.trace("sendCommand(nodeId={},value={}) called.", nodeId, value); SendCommand bcp = bridge.bridgeAPI().sendCommand(); int veluxValue = value.getPositionAsVeluxType(); bcp.setNodeAndMainParameter(nodeId, veluxValue); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.debug("sendCommand() finished successfully."); return true; } else { logger.trace("sendCommand() finished with failure."); return false; } }
Source:
<code><START> public long getPreciseDateFor(JobState state) { <END> Date date = instance.getStartedDateFor(state); if (date != null) { return date.getTime(); } return -1; }</code><technical_language>package-local</technical_language>

Target:
private long getPreciseDateFor(JobState state) { Date date = instance.getStartedDateFor(state); if (date != null) { return date.getTime(); } return -1; }
Source:
<code>protected S getNext() { do { if (currentIterator == null) { <START> if (complete) { <END> break; } if (cacheTopology != null) { try { int nextTopology = cacheTopology.getTopologyId() + 1; log.tracef("Waiting for topology %d to continue iterator operation with segments %s", nextTopology, segmentsToUse); stateTransferLock.topologyFuture(nextTopology).get(timeout, timeoutUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new CacheException(e); } } cacheTopology = dm.getCacheTopology(); log.tracef("Creating rehash iterator for segments %s using topology id: %d", segmentsToUse, cacheTopology.getTopologyId()); currentIterator = nonRehashRemoteIterator(cacheTopology.getReadConsistentHash(), segmentsToUse, receivedKeys::get, publisherDecorator(completedHandler, lostSegments -> { }, k -> { Set<Object> set = receivedKeys.get(keyPartitioner.getSegment(k)); if (set != null) { set.add(k); } }), intermediateOperations); } if (currentIterator.hasNext()) { return currentIterator.next(); } else { currentIterator = null; } } while (!segmentsToUse.isEmpty()); complete = true; return null; }</code><technical_language>complete is set loop, I this check loop. if (currentIterator == null) body is a large, start loop "else" branch instead: if (currentIterator != null && currentIterator.hasNext()) { return currentIterator.next(); } If this return currentIterator is null exhausted, need set currentIterator = null</technical_language>

Target:
protected S getNext() { while (true){ CloseableIterator<S> iterator = currentIterator; if (iterator != null && iterator.hasNext()) { return iterator.next(); } if (segmentsToUse.isEmpty()) { return null; } if (iterator != null) { try { int nextTopology = cacheTopology.getTopologyId() + 1; log.tracef("Waiting for topology %d to continue iterator operation with segments %s", nextTopology, segmentsToUse); stateTransferLock.topologyFuture(nextTopology).get(timeout, timeoutUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new CacheException(e); } } cacheTopology = dm.getCacheTopology(); log.tracef("Creating non-rehash iterator for segments %s using topology id: %d", segmentsToUse, cacheTopology.getTopologyId()); currentIterator = nonRehashRemoteIterator(cacheTopology.getReadConsistentHash(), segmentsToUse, receivedKeys::get, publisherDecorator(completedHandler, lostSegments -> { }, k -> { Set<Object> set = receivedKeys.get(keyPartitioner.getSegment(k)); if (set != null) { set.add(k); } }), intermediateOperations); } }
Source:
<code>public void setUp() throws Exception { String chromosome = "1"; long start = 10000000000L; long end = 10000000005L; String reference = "A"; String alternate = "T"; String vepVersion = "88"; String vepCacheVersion = "89"; String mainId = "rs1"; <START> testVariantEntity = new VariantWithSamplesAndAnnotation(chromosome, start, end, reference, alternate, mainId); <END> Annotation variantAnnotation = new Annotation(chromosome, start, end, vepVersion, vepCacheVersion, Collections .singleton(new Xref(GENE_ID, "HGNC")), null); testVariantEntity.setAnnotation(variantAnnotation); List<VariantWithSamplesAndAnnotation> variantEntities = Collections.singletonList(testVariantEntity); List<String> geneIds = new ArrayList<>(); geneIds.add(GENE_ID); given(service.findByGenesAndComplexFilters(eq(geneIds), any(), any(), any(), any())).willReturn(variantEntities); given(service.countByGenesAndComplexFilters(eq(geneIds), any())).willReturn(1L); }</code><technical_language>Check main Id returned, equals method compare it</technical_language>

Target:
public void setUp() throws Exception { String chromosome = "1"; long start = 10000000000L; long end = 10000000005L; String reference = "A"; String alternate = "T"; String vepVersion = "88"; String vepCacheVersion = "89"; testVariantEntity = new VariantWithSamplesAndAnnotation(chromosome, start, end, reference, alternate, MAIN_ID); Annotation variantAnnotation = new Annotation(chromosome, start, end, vepVersion, vepCacheVersion, Collections .singleton(new Xref(GENE_ID, "HGNC")), null); testVariantEntity.setAnnotation(variantAnnotation); List<VariantWithSamplesAndAnnotation> variantEntities = Collections.singletonList(testVariantEntity); List<String> geneIds = new ArrayList<>(); geneIds.add(GENE_ID); given(service.findByGenesAndComplexFilters(eq(geneIds), any(), any(), any(), any())).willReturn(variantEntities); given(service.countByGenesAndComplexFilters(eq(geneIds), any())).willReturn(1L); }
Source:
<code><START> public ASTNode visit(SetBuiltin node, Void _) { <END> ArrayList<Term> items = new ArrayList<>(); for (Term element : node.elements()) { items.add(KApp.of(DataStructureSort.DEFAULT_SET_ITEM_LABEL, (Term) this.visitNode(element))); } Collections.sort(items, unparserLexicalComparator); for (Term base : node.baseTerms()) { items.add((Term)this.visitNode(base)); } if(items.size()==0){ return KApp.of(DataStructureSort.DEFAULT_SET_UNIT_LABEL); } Term basedKapp = items.get(items.size()-1); for(int i = items.size()-2; i >= 0; --i){ ArrayList<Term> tempTerm = new ArrayList<Term>(); tempTerm.add(items.get(i)); tempTerm.add(basedKapp); basedKapp = new KApp(new KLabelConstant(DataStructureSort.DEFAULT_SET_LABEL),new KList(tempTerm)); } return basedKapp; }</code><technical_language>this method call node.toKApp(), this transformation is useful in other settings</technical_language>

Target:
public ASTNode visit(SetBuiltin node, Void _) { return ((SetBuiltin)super.visit(node, _)).toKApp(context); }
Source:
<code>public String getProxyHost() { <START> if (proxyHost != null) { <END> return proxyHost; } else { return getProxyHostProperty(); } }</code><technical_language>Minor: ternary operator here</technical_language>

Target:
public String getProxyHost() { return (proxyHost != null) ? proxyHost : getProxyHostProperty(); }
Source:
<code>public void testSharedPreferencesClearedAfterLoggingException() { CrashReporter.storeUnhandledException(exception); <START> assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); <END> CrashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }</code><technical_language>assertFalse(...);</technical_language>

Target:
public void testSharedPreferencesClearedAfterLoggingException() { CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
<code>public static Collection<Supplier<ByteArray>> data() throws IOException { <START> fixture = prepareDirectoryAndPageCache( ByteArrayTest.class ); <END> PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = autoWithPageCacheFallback( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); int chunkSize = LENGTH / 10; return Arrays.asList( () -> HEAP.newByteArray( LENGTH, DEFAULT ), () -> HEAP.newDynamicByteArray( chunkSize, DEFAULT ), () -> OFF_HEAP.newByteArray( LENGTH, DEFAULT ), () -> OFF_HEAP.newDynamicByteArray( chunkSize, DEFAULT ), () -> AUTO.newByteArray( LENGTH, DEFAULT ), () -> AUTO.newDynamicByteArray( chunkSize, DEFAULT ), () -> autoWithPageCacheFallback.newByteArray( LENGTH, DEFAULT ), () -> autoWithPageCacheFallback.newDynamicByteArray( chunkSize, DEFAULT ), () -> pageCacheArrayFactory.newByteArray( LENGTH, DEFAULT ), () -> pageCacheArrayFactory.newDynamicByteArray( chunkSize, DEFAULT ) ); }</code><technical_language>do need fixture manual interaction directories page cache, class rules instead</technical_language>

Target:
public static Collection<Supplier<ByteArray>> data() throws IOException { fixture = prepareDirectoryAndPageCache( ByteArrayTest.class ); PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = auto( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); int chunkSize = LENGTH / ChunkedNumberArrayFactory.MAGIC_CHUNK_COUNT; return Arrays.asList( () -> HEAP.newByteArray( LENGTH, DEFAULT ), () -> HEAP.newDynamicByteArray( chunkSize, DEFAULT ), () -> OFF_HEAP.newByteArray( LENGTH, DEFAULT ), () -> OFF_HEAP.newDynamicByteArray( chunkSize, DEFAULT ), () -> AUTO_WITHOUT_PAGECACHE.newByteArray( LENGTH, DEFAULT ), () -> AUTO_WITHOUT_PAGECACHE.newDynamicByteArray( chunkSize, DEFAULT ), () -> autoWithPageCacheFallback.newByteArray( LENGTH, DEFAULT ), () -> autoWithPageCacheFallback.newDynamicByteArray( chunkSize, DEFAULT ), () -> pageCacheArrayFactory.newByteArray( LENGTH, DEFAULT ), () -> pageCacheArrayFactory.newDynamicByteArray( chunkSize, DEFAULT ) ); }
Source:
<code>public static String unQuote( String str ) { StringBuilder builder = new StringBuilder( str ); <START> if ( builder.indexOf( "\"\"" ) > 0 && builder.length() > 0 && builder.charAt( 0 ) == '"' <END> && builder.charAt( builder.length() - 1 ) == '"' ) { builder.deleteCharAt( builder.length() - 1 ); builder.deleteCharAt( 0 ); } return builder.toString(); }</code><technical_language>Please replace this with: if ( str.startsWith("\"") && str.endsWith("\"")) { return str.substring(1, str.length() - 1 ); } else { return str; } Performance indexof creating intermediate object</technical_language>

Target:
public static String unQuote( String str ) { if ( str.contains( "\"\"" ) && str.length() > 0 && str.startsWith( "\"" ) && str.endsWith( "\"" ) ) { return str.substring( 1, str.length() - 1 ); } return str; }
Source:
<code>public <V> ListenableFuture<V> executeQuery(CqlQuerySpec<V> querySpec) { PreparedStatement statement = statementPreparer.prepare(querySpec); <START> BoundStatement boundStatement = querySpec.bind(statement.bind()); <END> return execute(boundStatement, querySpec.executor(), querySpec.rowStreamAccumulatorFactory().get()); }</code><technical_language>set consistency level here</technical_language>

Target:
public <V> ListenableFuture<V> executeQuery(CqlQuerySpec<V> querySpec) { PreparedStatement statement = statementPreparer.prepare(querySpec); Statement executableStatement = querySpec.makeExecutableStatement(statement) .setConsistencyLevel(querySpec.queryConsistency()); return execute(executableStatement, querySpec.executor(), querySpec.rowStreamAccumulatorFactory().get()); }
Source:
<code>public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); context.record( <START> TransformLineageRecorderUtils.oneInToOneOut(config.inputField, config.outputField, <END> "xmlToJson", "Convert XML string to JSON string.`")); }</code><technical_language>In this transform, config.inputField is transformed json fields, is one-to-many, other fields identity one-to-one transform, lineage reflect this</technical_language>

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); generateOutputSchema(); if (context.getInputSchema() == null || context.getInputSchema().getFields() == null || context.getOutputSchema() == null || context.getOutputSchema().getFields() == null) { return; } List<String> identityFields = context.getInputSchema().getFields().stream().map(Schema.Field::getName) .filter(field -> outputSchema.getField(field) != null && !field.equals(config.inputField)) .collect(Collectors.toList()); List<String> processedFields = new ArrayList<>(TransformLineageRecorderUtils.getFields(context.getOutputSchema())); processedFields.removeAll(identityFields); List<FieldOperation> outputList = new ArrayList<>( TransformLineageRecorderUtils.generateOneToMany(config.inputField, processedFields, "xmlToJson", "Converted XML string to JSON string.")); outputList.addAll(TransformLineageRecorderUtils.generateOneToOnes(identityFields, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); context.record(outputList); }
Source:
<code>public void anonymizationWikiEdits() { Credentials credentials = new Credentials(); String timestamp = Long.toString(DateTime.now().getMillis()); String qanon = "QAanon" + timestamp; String passw = "makak"; SignUpUser user = new SignUpUser(qanon, credentials.emailAnonymousUserTestWikia, passw, LocalDate.of(1990, 3, 19)); UserRegistration.registerUserEmailConfirmed(user); new WikiBasePageObject().loginAs(user.getUsername(), user.getPassword(), wikiURL); <START> new ArticleContent(user.getUsername()).push("Test" + timestamp, "AnonymizationTest"); <END> ArticleHistoryPage articleHistoryPage = new ArticleHistoryPage().open("AnonymizationTest"); String id = articleHistoryPage.getHistoryID(user.getUsername()); Assertion.assertTrue(articleHistoryPage.isUserInHistory(user.getUsername())); articleHistoryPage.logOut(); SpecialAnonymizationUserPage anonymizationStaff = new SpecialAnonymizationUserPage().open(); anonymizationStaff.loginAs(User.SUS_STAFF); anonymizationStaff.fillFutureAnon(qanon) .submitAnonymization(); Assertion.assertStringContains(anonymizationStaff.getAnonConfirmation(), qanon); UserProfilePage userProfilePage = new UserProfilePage().open(qanon); articleHistoryPage = new ArticleHistoryPage().open("AnonymizationTest"); Assertion.assertFalse(articleHistoryPage.isUserInHistory(user.getUsername())); ArticleHistoryPage articleHistoryPageID = new ArticleHistoryPage().openArticleId(id); String anonUser = articleHistoryPageID.getAnonByArticleID(); }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Define a constant instead of duplicating this literal "AnonymizationTest" 6 times. [![rule](<LINK_0>](http://sonar-s4/coding_rules#rule_key=squid%3AS1192)</technical_language>

Target:
public void anonymizationWikiEdits() { Credentials credentials = new Credentials(); String timestamp = Long.toString(DateTime.now().getMillis()); String qanon = "QAanon" + timestamp; String passw = "makak"; SignUpUser user = new SignUpUser(qanon, credentials.emailAnonymousUserTestWikia, passw, LocalDate.of(1990, 3, 19)); UserRegistration.registerUserEmailConfirmed(user); new WikiBasePageObject().loginAs(user.getUsername(), user.getPassword(), wikiURL); new ArticleContent(user.getUsername()).push("Test" + timestamp, "AnonymizationTest"); ArticleHistoryPage articleHistoryPage = new ArticleHistoryPage().open("AnonymizationTest"); String id = articleHistoryPage.getHistoryID(user.getUsername()); Assertion.assertTrue(articleHistoryPage.isUserInHistory(user.getUsername())); articleHistoryPage.logOut(); SpecialAnonymizationUserPage anonymizationStaff = new SpecialAnonymizationUserPage().open(); anonymizationStaff.loginAs(User.SUS_STAFF); anonymizationStaff.fillFutureAnon(qanon) .submitAnonymization(); Assertion.assertStringContains(anonymizationStaff.getAnonConfirmation(), qanon); articleHistoryPage = new ArticleHistoryPage().open("AnonymizationTest"); Assertion.assertFalse(articleHistoryPage.isUserInHistory(user.getUsername())); }
Source:
<code><START> public void shouldNotAddRedundantVersions() throws Exception { <END> String databaseName = mongoRule.getRandomTemporaryDatabaseName(); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); mongoOperations.save(new AnnotationMetadata("70", "72")); String vepCacheVersion = "87"; String vepVersion = "88"; assertStepCompletes(databaseName, vepCacheVersion, vepVersion); List<AnnotationMetadata> annotationMetadatas = mongoOperations.findAll(AnnotationMetadata.class); assertEquals(2, annotationMetadatas.size()); }</code><technical_language>I suspect method names swapped shouldNotAddRedundantVersions shouldKeepOtherVersions, currently inserts 2 versions insert twice. opposite</technical_language>

Target:
public void shouldNotAddRedundantVersions() throws Exception { String databaseName = mongoRule.getRandomTemporaryDatabaseName(); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); String vepCacheVersion = "87"; String vepVersion = "88"; mongoOperations.save(new AnnotationMetadata(vepVersion, vepCacheVersion)); assertStepIsComplete(databaseName, vepCacheVersion, vepVersion); List<AnnotationMetadata> annotationMetadataList = mongoOperations.findAll(AnnotationMetadata.class); assertEquals(1, annotationMetadataList.size()); }
Source:
<code>private static void createDummyTrace(String metadata) { try { File dir; dir = new File(tempTraceDir); if (dir.exists()) { deltree(dir); } dir.mkdirs(); File metadataFile; metadataFile = new File(tempTraceDir + "/metadata"); FileWriter fw = new FileWriter(metadataFile); fw.write(metadata); fw.close(); byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC, (byte) 0xC1 }; byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7, 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b, (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d }; Event ev = new Event(2, 2); int dataSize = 4096; final int headerSize = 24 + 44; final int packetSize = dataSize + headerSize + 512; final int nbEvents = (dataSize / ev.getSize()) - 1; final int contentSize = (nbEvents * ev.getSize() + headerSize) * 8; ByteBuffer data = ByteBuffer.allocate(packetSize); data.order(ByteOrder.LITTLE_ENDIAN); <START> <END> data.put(magicLE); data.put(uuid); data.putInt(0); data.putLong(0xa500); data.putLong(nbEvents * 0x10000 + 0xa5a6); data.putLong(contentSize); data.putLong(packetSize * 8); data.putLong(0); data.putInt(0); for (int i = 0; i < nbEvents; i++) { ev.setEventTimestamp(i * 0x10000 + 0xa5a5); ev.setEventContent(i); ev.writeEvent(data); } File dummyFile; dummyFile = new File(tempTraceDir + "/dummyChan"); FileOutputStream fos = new FileOutputStream(dummyFile); data.rewind(); fos.getChannel().write(data); fos.close(); } catch (IOException e) { e.printStackTrace(); } finally { } }</code><technical_language>call data.clear() it. Yeah, ByteBuffer API is full of nitpicks that..</technical_language>

Target:
private static void createDummyTrace(String metadata) { try { File dir; dir = new File(tempTraceDir); if (dir.exists()) { deltree(dir); } dir.mkdirs(); File metadataFile; metadataFile = new File(tempTraceDir + "/metadata"); FileWriter fw = new FileWriter(metadataFile); fw.write(metadata); fw.close(); byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC, (byte) 0xC1 }; byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7, 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b, (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d }; Event ev = new Event(2, 2); final int nbEvents = (DATA_SIZE / ev.getSize()) - 1; final int contentSize = (nbEvents * ev.getSize() + HEADER_SIZE) * 8; ByteBuffer data = ByteBuffer.allocate(PAKET_SIZE); data.order(ByteOrder.LITTLE_ENDIAN); data.clear(); data.put(magicLE); data.put(uuid); data.putInt(0); data.putLong(0xa500); data.putLong(nbEvents * 0x10000 + 0xa5a6); data.putLong(contentSize); data.putLong(PAKET_SIZE * 8); data.putLong(0); data.putInt(0); for (int i = 0; i < nbEvents; i++) { ev.setEventTimestamp(i * 0x10000 + 0xa5a5); ev.setEventContent(i); ev.writeEvent(data); } File dummyFile; dummyFile = new File(tempTraceDir + "/dummyChan"); FileOutputStream fos = new FileOutputStream(dummyFile); data.flip(); fos.getChannel().write(data); fos.close(); } catch (IOException e) { e.printStackTrace(); } finally { } }
Source:
<code>static boolean isAlgorithmPresent(Properties props) { String profile = props.getProperty(AmazonS3.Keys.CRYPTO_ALG); String version = props.getProperty(AmazonS3.Keys.CRYPTO_VER, WalkEncryption.Vals.DEFAULT_VERS); String crytoAlgo; String keyAlgo; switch (version) { case WalkEncryption.Vals.DEFAULT_VERS: case WalkEncryption.JGitV1.VERSION: crytoAlgo = profile; keyAlgo = profile; break; case WalkEncryption.JGitV2.VERSION: crytoAlgo = props .getProperty(profile + WalkEncryption.Keys.X_ALGO); keyAlgo = props .getProperty(profile + WalkEncryption.Keys.X_KEY_ALGO); break; default: return false; } try { <START> InsecureCipherFactory.create(keyAlgo); <END> SecretKeyFactory.getInstance(keyAlgo); return true; } catch (Throwable e) { return false; } }</code><technical_language>cryptoAlgo</technical_language>

Target:
static boolean isAlgorithmPresent(Properties props) { String profile = props.getProperty(AmazonS3.Keys.CRYPTO_ALG); String version = props.getProperty(AmazonS3.Keys.CRYPTO_VER, WalkEncryption.Vals.DEFAULT_VERS); String cryptoAlgo; String keyAlgo; switch (version) { case WalkEncryption.Vals.DEFAULT_VERS: case WalkEncryption.JGitV1.VERSION: cryptoAlgo = profile; keyAlgo = profile; break; case WalkEncryption.JGitV2.VERSION: cryptoAlgo = props .getProperty(profile + WalkEncryption.Keys.X_ALGO); keyAlgo = props .getProperty(profile + WalkEncryption.Keys.X_KEY_ALGO); break; default: return false; } try { InsecureCipherFactory.create(cryptoAlgo); SecretKeyFactory.getInstance(keyAlgo); return true; } catch (Throwable e) { return false; } }
Source:
<code>public void exempt(Person responsible, String justification) { DateTime when = new DateTime(); DebtInterestCalculator debtInterestCalculator = getDebtInterestCalculator(when); Money dueInterestAmount = new Money(debtInterestCalculator.getDueInterestAmount()); Money dueFineAmount = new Money(debtInterestCalculator.getDueFineAmount()); Money dueAmount = new Money(debtInterestCalculator.getDueAmount()); when = when.plusSeconds(1); if (dueInterestAmount.isPositive()) { FixedAmountInterestExemption fixedAmountInterestExemption = new FixedAmountInterestExemption(this, responsible, dueInterestAmount, EventExemptionJustificationType.CANCELLED, new DateTime(), justification); fixedAmountInterestExemption.setWhenCreated(when); when = when.plusSeconds(1); } if (dueFineAmount.isPositive()) { FixedAmountFineExemption fixedAmountFineExemption = <START> new FixedAmountFineExemption(this, responsible, dueInterestAmount, <END> EventExemptionJustificationType.CANCELLED, new DateTime(), justification); fixedAmountFineExemption.setWhenCreated(when); when = when.plusSeconds(1); } EventExemption eventExemption = new EventExemption(this, responsible, dueAmount, EventExemptionJustificationType.CANCELLED, new DateTime(), justification); eventExemption.setWhenCreated(when); }</code><technical_language>This dueFineAmount</technical_language>

Target:
public void exempt(Person responsible, String justification) { DateTime when = new DateTime(); DebtInterestCalculator debtInterestCalculator = getDebtInterestCalculator(when); Money dueInterestAmount = new Money(debtInterestCalculator.getDueInterestAmount()); Money dueFineAmount = new Money(debtInterestCalculator.getDueFineAmount()); Money dueAmount = new Money(debtInterestCalculator.getDueAmount()); if (dueInterestAmount.isPositive()) { FixedAmountInterestExemption fixedAmountInterestExemption = new FixedAmountInterestExemption(this, responsible, dueInterestAmount, EventExemptionJustificationType.CANCELLED, new DateTime(), justification); fixedAmountInterestExemption.setWhenCreated(when); when = when.plusSeconds(1); } if (dueFineAmount.isPositive()) { FixedAmountFineExemption fixedAmountFineExemption = new FixedAmountFineExemption(this, responsible, dueFineAmount, EventExemptionJustificationType.CANCELLED, new DateTime(), justification); fixedAmountFineExemption.setWhenCreated(when); when = when.plusSeconds(1); } if (dueAmount.isPositive()) { EventExemption eventExemption = new EventExemption(this, responsible, dueAmount, EventExemptionJustificationType.CANCELLED, new DateTime(), justification); eventExemption.setWhenCreated(when); } }
Source:
<code>private void checkState() { final EditorSession session = getSession(); <START> if (session.equals(session)) { <END> setEnabled(!session.getCommandRegistry().getCommandHistory().isEmpty()); fire(); } }</code><technical_language>@treblereel, build failing due this line. comparing session itself. a bug me. check locally executing mvn clean package -Dfull more details this bug mvn spotbugs:gui</technical_language>

Target:
private void checkState() { if (getSession() != null) { setEnabled(!getSession().getCommandRegistry().getCommandHistory().isEmpty()); fire(); } }
Source:
<code>public void testEmptyQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = ""; <START> mDns.query(network, dname, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, mHandler, <END> answer -> { if (answer == null) { fail("Raw Query empty dname(ROOT) no answer returned"); } try { new CheckedDnsPacket(answer); fail("Raw Query empty dname(ROOT) get valid answer"); } catch (DnsPacket.ParseException e) { e.getMessage().equals("No available answer"); latch.countDown(); } } ); String msg = "Raw query empty dname(ROOT) but no answer after " + TIMEOUT_MS + "ms."; try { assertTrue(msg, latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }</code><technical_language>for other places. strange that: 1. query primitive parameters in arguments, 2. aggregate results in a defined structure. more sense if "build" a dns request a Builder class, instead of creating types of query function. E.g. DnsQueryBuilder dqb = new DnsQueryBuilder().setClass(CLASS_IN).setType()... finally: dqb.query() mDns.query(dqb.build());</technical_language>

Target:
public void testEmptyQuery() throws ErrnoException { final String dname = ""; final String msg = "Raw query empty dname(ROOT)"; for (Network network : getTestableNetworks()) { final CountDownLatch latch = new CountDownLatch(1); mDns.query(network, dname, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, mHandler, answer -> { if (answer == null) { fail(msg + " no answer returned"); } try { assertValidEmptyAnswer(msg, new DnsAnswer(answer)); latch.countDown(); } catch (DnsPacket.ParseException e) { fail(msg + e.getMessage()); } } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }