id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
21,985
14
//Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code
protected Model filterModel(Model model, URI documentBaseUri) throws IOException { final boolean IGNORE_STYLESHEETS = true; final boolean IGNORE_FAVICON = true; final boolean DOCBASE_ONLY = false; ValueFactory factory = SimpleValueFactory.getInstance(); String documentBaseUriStr = documentBaseUri.toString(); Iterator<Statement> iter = model.iterator(); //Note that the model has a "predictable iteration order", and since we get a ConcurrentModException while altering the model itself, // we choose to instance a new one, and add the valid filtered nodes in order to this new one Model filteredModel = new LinkedHashModel(); while (iter.hasNext()) { Statement stmt = iter.next(); //!!! Note !!! //The double (eg. both XHTML_NS_STYLESHEET and LOCAL_NS_STYLESHEET) checks below are the result of a bug: //Because we set the @vocab attribute on the <html> element, all the stylesheet-links are prefixed with that namespace, //so they're actually not real XHTML predicates, but changed into eg. http://www.mot.be/ontology/stylesheet //Because it's quite a hard fix to implement, we work around it here. //remove all the XHTML stylesheets predicates from the model boolean removed = false; if (!removed && IGNORE_STYLESHEETS && (stmt.getPredicate().toString().equals(XHTML_NS_STYLESHEET) || stmt.getPredicate().toString().equals(LOCAL_NS_STYLESHEET))) { removed = true; } //removes all favicon statements. Note that this last check isn't waterproof (we can use any name for our favicons), but it works 99% of the time if (!removed && IGNORE_FAVICON && stmt.getObject().toString().contains("favicon") && (stmt.getPredicate().toString().equals(XHTML_NS_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_ICON) || stmt.getPredicate().toString().equals(XHTML_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_MANIFEST) )) { removed = true; } //remove all non-documentBaseUri subjects from the model if (!removed && DOCBASE_ONLY && !stmt.getSubject().toString().equals(documentBaseUriStr)) { removed = true; } //we're not interested in blank nodes because they don't have a page as subject, so we might as well filter them out if (!removed && stmt.getSubject() instanceof BNode) { removed = true; } //we'll use this loop to whitespace-trim the values while we're at it //Note that this is a bit hacky. The more proper way would be to edit the com.beligum.blocks.rdf.importers.semargl.SesameSink.addPlainLiteral() // method, but that class is supposed to be part of the core Sesame library (only copied over to have RDFa support in Sesame4), so I opted to implement it here //Also note that this implementation doens't trim the non-plain literal values (like datetime). They are passed over via the @content attribute inside RDFa, // so it should be quite clean already. Also because the HTML input stream, coming from JSoup is minified before passed to Sesame. // But it can be easily supported (the part where the exception is thrown) if (!removed) { //these will hold possible modified pieces of the statement Resource newSubject = null; IRI newPredicate = null; Value newObject = null; //trim all "lang" params from the subject //This is an important change: // From time to time, the eg. ?lang=en part of an URI seeps through, even though we set every RDFa html tag with a clear @about attribute // eg. this is the case as subject of "http://www.w3.org/ns/rdfa#usesVocabulary" // Because we don't save the statements of a resource by language (the @lang tag makes sure it is added statement-per-statement for certain datatypes), // the subject of the resource needs to be cleared from all lang query params to avoid false doubles while querying the triplestore (eg. using SPARQL). // We group by subject-URI and double (or triple, or ..., depends on the amount of languages in the system) entries mess up the counts, iterations, group-by's, etc. // That's why we try hard here to avoid these during import. if (stmt.getSubject() instanceof IRI) { URI subject = URI.create(stmt.getSubject().stringValue()); MultivaluedMap<String, String> queryParams = StringFunctions.getQueryParameters(subject); if (queryParams != null && queryParams.containsKey(I18nFactory.LANG_QUERY_PARAM)) { URI noLangUri = UriBuilder.fromUri(subject).replaceQueryParam(I18nFactory.LANG_QUERY_PARAM).build(); newSubject = factory.createIRI(noLangUri.toString()); } } //if the object is a literal, check if it needs to be trimmed //BIG NOTE: XSD.anyURI is also an instance of a Literal!! if (stmt.getObject() instanceof Literal) { Literal literal = (Literal) stmt.getObject(); String objectValue = literal.getLabel(); //we like to use and save relative URIs as relative URIs because it means we don't need to //update them if the site domain changes. But the RDFa doc clearly states all relative URIs need //to be converted to absolute URIs: https://www.w3.org/TR/rdfa-core/#s_curieprocessing //However, when dealing with custom html tags (eg. <meta datatype="xsd:anyURI"> tags), this doesn't happen //automatically, so let's do it manually. if (literal.getDatatype().equals(XMLSchema.ANYURI)) { //this is important: blank URIs (and this happens; eg. a tag <meta property="sameAs" datatype="xsd:anyURI" /> will yield a blank value for "sameAs"!) // would get filled in without this check; eg. a "" value would become "http://localhost:8080/en/" by default and this is bad! (eg. for sameAs properties) if (!StringUtils.isBlank(objectValue)) { URI objectUri = URI.create(objectValue); if (!objectUri.isAbsolute()) { objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
NONSATD
true
String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get());
objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else {
//update them if the site domain changes. But the RDFa doc clearly states all relative URIs need //to be converted to absolute URIs: https://www.w3.org/TR/rdfa-core/#s_curieprocessing //However, when dealing with custom html tags (eg. <meta datatype="xsd:anyURI"> tags), this doesn't happen //automatically, so let's do it manually. if (literal.getDatatype().equals(XMLSchema.ANYURI)) { //this is important: blank URIs (and this happens; eg. a tag <meta property="sameAs" datatype="xsd:anyURI" /> will yield a blank value for "sameAs"!) // would get filled in without this check; eg. a "" value would become "http://localhost:8080/en/" by default and this is bad! (eg. for sameAs properties) if (!StringUtils.isBlank(objectValue)) { URI objectUri = URI.create(objectValue); if (!objectUri.isAbsolute()) { objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject();
21,985
15
//After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on
protected Model filterModel(Model model, URI documentBaseUri) throws IOException { final boolean IGNORE_STYLESHEETS = true; final boolean IGNORE_FAVICON = true; final boolean DOCBASE_ONLY = false; ValueFactory factory = SimpleValueFactory.getInstance(); String documentBaseUriStr = documentBaseUri.toString(); Iterator<Statement> iter = model.iterator(); //Note that the model has a "predictable iteration order", and since we get a ConcurrentModException while altering the model itself, // we choose to instance a new one, and add the valid filtered nodes in order to this new one Model filteredModel = new LinkedHashModel(); while (iter.hasNext()) { Statement stmt = iter.next(); //!!! Note !!! //The double (eg. both XHTML_NS_STYLESHEET and LOCAL_NS_STYLESHEET) checks below are the result of a bug: //Because we set the @vocab attribute on the <html> element, all the stylesheet-links are prefixed with that namespace, //so they're actually not real XHTML predicates, but changed into eg. http://www.mot.be/ontology/stylesheet //Because it's quite a hard fix to implement, we work around it here. //remove all the XHTML stylesheets predicates from the model boolean removed = false; if (!removed && IGNORE_STYLESHEETS && (stmt.getPredicate().toString().equals(XHTML_NS_STYLESHEET) || stmt.getPredicate().toString().equals(LOCAL_NS_STYLESHEET))) { removed = true; } //removes all favicon statements. Note that this last check isn't waterproof (we can use any name for our favicons), but it works 99% of the time if (!removed && IGNORE_FAVICON && stmt.getObject().toString().contains("favicon") && (stmt.getPredicate().toString().equals(XHTML_NS_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_ICON) || stmt.getPredicate().toString().equals(XHTML_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_MANIFEST) )) { removed = true; } //remove all non-documentBaseUri subjects from the model if (!removed && DOCBASE_ONLY && !stmt.getSubject().toString().equals(documentBaseUriStr)) { removed = true; } //we're not interested in blank nodes because they don't have a page as subject, so we might as well filter them out if (!removed && stmt.getSubject() instanceof BNode) { removed = true; } //we'll use this loop to whitespace-trim the values while we're at it //Note that this is a bit hacky. The more proper way would be to edit the com.beligum.blocks.rdf.importers.semargl.SesameSink.addPlainLiteral() // method, but that class is supposed to be part of the core Sesame library (only copied over to have RDFa support in Sesame4), so I opted to implement it here //Also note that this implementation doens't trim the non-plain literal values (like datetime). They are passed over via the @content attribute inside RDFa, // so it should be quite clean already. Also because the HTML input stream, coming from JSoup is minified before passed to Sesame. // But it can be easily supported (the part where the exception is thrown) if (!removed) { //these will hold possible modified pieces of the statement Resource newSubject = null; IRI newPredicate = null; Value newObject = null; //trim all "lang" params from the subject //This is an important change: // From time to time, the eg. ?lang=en part of an URI seeps through, even though we set every RDFa html tag with a clear @about attribute // eg. this is the case as subject of "http://www.w3.org/ns/rdfa#usesVocabulary" // Because we don't save the statements of a resource by language (the @lang tag makes sure it is added statement-per-statement for certain datatypes), // the subject of the resource needs to be cleared from all lang query params to avoid false doubles while querying the triplestore (eg. using SPARQL). // We group by subject-URI and double (or triple, or ..., depends on the amount of languages in the system) entries mess up the counts, iterations, group-by's, etc. // That's why we try hard here to avoid these during import. if (stmt.getSubject() instanceof IRI) { URI subject = URI.create(stmt.getSubject().stringValue()); MultivaluedMap<String, String> queryParams = StringFunctions.getQueryParameters(subject); if (queryParams != null && queryParams.containsKey(I18nFactory.LANG_QUERY_PARAM)) { URI noLangUri = UriBuilder.fromUri(subject).replaceQueryParam(I18nFactory.LANG_QUERY_PARAM).build(); newSubject = factory.createIRI(noLangUri.toString()); } } //if the object is a literal, check if it needs to be trimmed //BIG NOTE: XSD.anyURI is also an instance of a Literal!! if (stmt.getObject() instanceof Literal) { Literal literal = (Literal) stmt.getObject(); String objectValue = literal.getLabel(); //we like to use and save relative URIs as relative URIs because it means we don't need to //update them if the site domain changes. But the RDFa doc clearly states all relative URIs need //to be converted to absolute URIs: https://www.w3.org/TR/rdfa-core/#s_curieprocessing //However, when dealing with custom html tags (eg. <meta datatype="xsd:anyURI"> tags), this doesn't happen //automatically, so let's do it manually. if (literal.getDatatype().equals(XMLSchema.ANYURI)) { //this is important: blank URIs (and this happens; eg. a tag <meta property="sameAs" datatype="xsd:anyURI" /> will yield a blank value for "sameAs"!) // would get filled in without this check; eg. a "" value would become "http://localhost:8080/en/" by default and this is bad! (eg. for sameAs properties) if (!StringUtils.isBlank(objectValue)) { URI objectUri = URI.create(objectValue); if (!objectUri.isAbsolute()) { objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
NONSATD
true
} } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) {
} else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject();
//this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt;
21,985
16
// if the settings say so, validate the incoming (filtered) model
protected Model filterModel(Model model, URI documentBaseUri) throws IOException { final boolean IGNORE_STYLESHEETS = true; final boolean IGNORE_FAVICON = true; final boolean DOCBASE_ONLY = false; ValueFactory factory = SimpleValueFactory.getInstance(); String documentBaseUriStr = documentBaseUri.toString(); Iterator<Statement> iter = model.iterator(); //Note that the model has a "predictable iteration order", and since we get a ConcurrentModException while altering the model itself, // we choose to instance a new one, and add the valid filtered nodes in order to this new one Model filteredModel = new LinkedHashModel(); while (iter.hasNext()) { Statement stmt = iter.next(); //!!! Note !!! //The double (eg. both XHTML_NS_STYLESHEET and LOCAL_NS_STYLESHEET) checks below are the result of a bug: //Because we set the @vocab attribute on the <html> element, all the stylesheet-links are prefixed with that namespace, //so they're actually not real XHTML predicates, but changed into eg. http://www.mot.be/ontology/stylesheet //Because it's quite a hard fix to implement, we work around it here. //remove all the XHTML stylesheets predicates from the model boolean removed = false; if (!removed && IGNORE_STYLESHEETS && (stmt.getPredicate().toString().equals(XHTML_NS_STYLESHEET) || stmt.getPredicate().toString().equals(LOCAL_NS_STYLESHEET))) { removed = true; } //removes all favicon statements. Note that this last check isn't waterproof (we can use any name for our favicons), but it works 99% of the time if (!removed && IGNORE_FAVICON && stmt.getObject().toString().contains("favicon") && (stmt.getPredicate().toString().equals(XHTML_NS_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_ICON) || stmt.getPredicate().toString().equals(XHTML_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_MANIFEST) )) { removed = true; } //remove all non-documentBaseUri subjects from the model if (!removed && DOCBASE_ONLY && !stmt.getSubject().toString().equals(documentBaseUriStr)) { removed = true; } //we're not interested in blank nodes because they don't have a page as subject, so we might as well filter them out if (!removed && stmt.getSubject() instanceof BNode) { removed = true; } //we'll use this loop to whitespace-trim the values while we're at it //Note that this is a bit hacky. The more proper way would be to edit the com.beligum.blocks.rdf.importers.semargl.SesameSink.addPlainLiteral() // method, but that class is supposed to be part of the core Sesame library (only copied over to have RDFa support in Sesame4), so I opted to implement it here //Also note that this implementation doens't trim the non-plain literal values (like datetime). They are passed over via the @content attribute inside RDFa, // so it should be quite clean already. Also because the HTML input stream, coming from JSoup is minified before passed to Sesame. // But it can be easily supported (the part where the exception is thrown) if (!removed) { //these will hold possible modified pieces of the statement Resource newSubject = null; IRI newPredicate = null; Value newObject = null; //trim all "lang" params from the subject //This is an important change: // From time to time, the eg. ?lang=en part of an URI seeps through, even though we set every RDFa html tag with a clear @about attribute // eg. this is the case as subject of "http://www.w3.org/ns/rdfa#usesVocabulary" // Because we don't save the statements of a resource by language (the @lang tag makes sure it is added statement-per-statement for certain datatypes), // the subject of the resource needs to be cleared from all lang query params to avoid false doubles while querying the triplestore (eg. using SPARQL). // We group by subject-URI and double (or triple, or ..., depends on the amount of languages in the system) entries mess up the counts, iterations, group-by's, etc. // That's why we try hard here to avoid these during import. if (stmt.getSubject() instanceof IRI) { URI subject = URI.create(stmt.getSubject().stringValue()); MultivaluedMap<String, String> queryParams = StringFunctions.getQueryParameters(subject); if (queryParams != null && queryParams.containsKey(I18nFactory.LANG_QUERY_PARAM)) { URI noLangUri = UriBuilder.fromUri(subject).replaceQueryParam(I18nFactory.LANG_QUERY_PARAM).build(); newSubject = factory.createIRI(noLangUri.toString()); } } //if the object is a literal, check if it needs to be trimmed //BIG NOTE: XSD.anyURI is also an instance of a Literal!! if (stmt.getObject() instanceof Literal) { Literal literal = (Literal) stmt.getObject(); String objectValue = literal.getLabel(); //we like to use and save relative URIs as relative URIs because it means we don't need to //update them if the site domain changes. But the RDFa doc clearly states all relative URIs need //to be converted to absolute URIs: https://www.w3.org/TR/rdfa-core/#s_curieprocessing //However, when dealing with custom html tags (eg. <meta datatype="xsd:anyURI"> tags), this doesn't happen //automatically, so let's do it manually. if (literal.getDatatype().equals(XMLSchema.ANYURI)) { //this is important: blank URIs (and this happens; eg. a tag <meta property="sameAs" datatype="xsd:anyURI" /> will yield a blank value for "sameAs"!) // would get filled in without this check; eg. a "" value would become "http://localhost:8080/en/" by default and this is bad! (eg. for sameAs properties) if (!StringUtils.isBlank(objectValue)) { URI objectUri = URI.create(objectValue); if (!objectUri.isAbsolute()) { objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
NONSATD
true
} } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate();
else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
} if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
21,985
17
//DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);
protected Model filterModel(Model model, URI documentBaseUri) throws IOException { final boolean IGNORE_STYLESHEETS = true; final boolean IGNORE_FAVICON = true; final boolean DOCBASE_ONLY = false; ValueFactory factory = SimpleValueFactory.getInstance(); String documentBaseUriStr = documentBaseUri.toString(); Iterator<Statement> iter = model.iterator(); //Note that the model has a "predictable iteration order", and since we get a ConcurrentModException while altering the model itself, // we choose to instance a new one, and add the valid filtered nodes in order to this new one Model filteredModel = new LinkedHashModel(); while (iter.hasNext()) { Statement stmt = iter.next(); //!!! Note !!! //The double (eg. both XHTML_NS_STYLESHEET and LOCAL_NS_STYLESHEET) checks below are the result of a bug: //Because we set the @vocab attribute on the <html> element, all the stylesheet-links are prefixed with that namespace, //so they're actually not real XHTML predicates, but changed into eg. http://www.mot.be/ontology/stylesheet //Because it's quite a hard fix to implement, we work around it here. //remove all the XHTML stylesheets predicates from the model boolean removed = false; if (!removed && IGNORE_STYLESHEETS && (stmt.getPredicate().toString().equals(XHTML_NS_STYLESHEET) || stmt.getPredicate().toString().equals(LOCAL_NS_STYLESHEET))) { removed = true; } //removes all favicon statements. Note that this last check isn't waterproof (we can use any name for our favicons), but it works 99% of the time if (!removed && IGNORE_FAVICON && stmt.getObject().toString().contains("favicon") && (stmt.getPredicate().toString().equals(XHTML_NS_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_ICON) || stmt.getPredicate().toString().equals(XHTML_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_APPLE_TOUCH_ICON) || stmt.getPredicate().toString().equals(LOCAL_NS_MANIFEST) )) { removed = true; } //remove all non-documentBaseUri subjects from the model if (!removed && DOCBASE_ONLY && !stmt.getSubject().toString().equals(documentBaseUriStr)) { removed = true; } //we're not interested in blank nodes because they don't have a page as subject, so we might as well filter them out if (!removed && stmt.getSubject() instanceof BNode) { removed = true; } //we'll use this loop to whitespace-trim the values while we're at it //Note that this is a bit hacky. The more proper way would be to edit the com.beligum.blocks.rdf.importers.semargl.SesameSink.addPlainLiteral() // method, but that class is supposed to be part of the core Sesame library (only copied over to have RDFa support in Sesame4), so I opted to implement it here //Also note that this implementation doens't trim the non-plain literal values (like datetime). They are passed over via the @content attribute inside RDFa, // so it should be quite clean already. Also because the HTML input stream, coming from JSoup is minified before passed to Sesame. // But it can be easily supported (the part where the exception is thrown) if (!removed) { //these will hold possible modified pieces of the statement Resource newSubject = null; IRI newPredicate = null; Value newObject = null; //trim all "lang" params from the subject //This is an important change: // From time to time, the eg. ?lang=en part of an URI seeps through, even though we set every RDFa html tag with a clear @about attribute // eg. this is the case as subject of "http://www.w3.org/ns/rdfa#usesVocabulary" // Because we don't save the statements of a resource by language (the @lang tag makes sure it is added statement-per-statement for certain datatypes), // the subject of the resource needs to be cleared from all lang query params to avoid false doubles while querying the triplestore (eg. using SPARQL). // We group by subject-URI and double (or triple, or ..., depends on the amount of languages in the system) entries mess up the counts, iterations, group-by's, etc. // That's why we try hard here to avoid these during import. if (stmt.getSubject() instanceof IRI) { URI subject = URI.create(stmt.getSubject().stringValue()); MultivaluedMap<String, String> queryParams = StringFunctions.getQueryParameters(subject); if (queryParams != null && queryParams.containsKey(I18nFactory.LANG_QUERY_PARAM)) { URI noLangUri = UriBuilder.fromUri(subject).replaceQueryParam(I18nFactory.LANG_QUERY_PARAM).build(); newSubject = factory.createIRI(noLangUri.toString()); } } //if the object is a literal, check if it needs to be trimmed //BIG NOTE: XSD.anyURI is also an instance of a Literal!! if (stmt.getObject() instanceof Literal) { Literal literal = (Literal) stmt.getObject(); String objectValue = literal.getLabel(); //we like to use and save relative URIs as relative URIs because it means we don't need to //update them if the site domain changes. But the RDFa doc clearly states all relative URIs need //to be converted to absolute URIs: https://www.w3.org/TR/rdfa-core/#s_curieprocessing //However, when dealing with custom html tags (eg. <meta datatype="xsd:anyURI"> tags), this doesn't happen //automatically, so let's do it manually. if (literal.getDatatype().equals(XMLSchema.ANYURI)) { //this is important: blank URIs (and this happens; eg. a tag <meta property="sameAs" datatype="xsd:anyURI" /> will yield a blank value for "sameAs"!) // would get filled in without this check; eg. a "" value would become "http://localhost:8080/en/" by default and this is bad! (eg. for sameAs properties) if (!StringUtils.isBlank(objectValue)) { URI objectUri = URI.create(objectValue); if (!objectUri.isAbsolute()) { objectUri = documentBaseUri.resolve(objectUri); } //it makes sense to convert the data type to IRI as well newObject = factory.createIRI(objectUri.toString()); } } //this means it's a 'true' literal -> check if we can trim else { String objectValueTrimmed = StringUtils.strip(objectValue); if (!objectValue.equals(objectValueTrimmed)) { //Note: this makes sense: see SimpleLiteral(String label, IRI datatype) constructor code if (literal.getDatatype().equals(RDF.LANGSTRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getLanguage().get()); } else if (literal.getDatatype().equals(XMLSchema.STRING)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else if (literal.getDatatype().equals(RDF.HTML)) { newObject = factory.createLiteral(objectValueTrimmed, literal.getDatatype()); } else { throw new IOException("Encountered unsupported simple literal value, this shouldn't happen; " + literal.getDatatype() + " - " + objectValue); } } } } //After all the filtering above, check if we need to change the statement: remove it from the model and add it again later on Statement validStmt = null; if (newSubject != null || newObject != null || newPredicate != null) { if (newSubject == null) { newSubject = stmt.getSubject(); } if (newPredicate == null) { newPredicate = stmt.getPredicate(); } if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
NONSATD
true
new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
if (newObject == null) { newObject = stmt.getObject(); } if (stmt.getContext() == null) { validStmt = factory.createStatement(newSubject, newPredicate, newObject); } else { validStmt = factory.createStatement(newSubject, newPredicate, newObject, stmt.getContext()); } } else { validStmt = stmt; } filteredModel.add(validStmt); } } // if the settings say so, validate the incoming (filtered) model if (Settings.instance().getEnableRdfValidation()) { new RdfModelImpl(filteredModel).validate(); } //DEBUG //RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES); return filteredModel; }
30,177
0
//TODO: switch expression candidate!
@Messages({ "# {0} - variable name", "ERR_NeitherReadOrWritten=Variable {0} is neither read or written to", "# {0} - variable name", "ERR_NotWritten=Variable {0} is never written to", "# {0} - variable name", "ERR_NotRead=Variable {0} is never read", "# {0} - element name", "ERR_NotUsed={0} is never used", "ERR_NotUsedConstructor=Constructor is never used", }) private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) { //TODO: switch expression candidate! String name = ud.unusedElement.getSimpleName().toString(); String message; switch (ud.reason) { case NOT_WRITTEN_READ: message = Bundle.ERR_NeitherReadOrWritten(name); break; case NOT_WRITTEN: message = Bundle.ERR_NotWritten(name); break; case NOT_READ: message = Bundle.ERR_NotRead(name); break; case NOT_USED: if (ud.unusedElement.getKind() == ElementKind.CONSTRUCTOR) { message = Bundle.ERR_NotUsedConstructor(); } else { message = Bundle.ERR_NotUsed(name); } break; default: throw new IllegalStateException("Unknown unused type: " + ud.reason); } return ErrorDescriptionFactory.forName(ctx, ud.unusedElementPath, message); }
DESIGN
true
}) private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) { //TODO: switch expression candidate! String name = ud.unusedElement.getSimpleName().toString(); String message;
"ERR_NeitherReadOrWritten=Variable {0} is neither read or written to", "# {0} - variable name", "ERR_NotWritten=Variable {0} is never written to", "# {0} - variable name", "ERR_NotRead=Variable {0} is never read", "# {0} - element name", "ERR_NotUsed={0} is never used", "ERR_NotUsedConstructor=Constructor is never used", }) private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) { //TODO: switch expression candidate! String name = ud.unusedElement.getSimpleName().toString(); String message; switch (ud.reason) { case NOT_WRITTEN_READ: message = Bundle.ERR_NeitherReadOrWritten(name); break; case NOT_WRITTEN: message = Bundle.ERR_NotWritten(name); break; case NOT_READ: message = Bundle.ERR_NotRead(name); break; case NOT_USED: if (ud.unusedElement.getKind() == ElementKind.CONSTRUCTOR) { message = Bundle.ERR_NotUsedConstructor(); } else {
@Messages({ "# {0} - variable name", "ERR_NeitherReadOrWritten=Variable {0} is neither read or written to", "# {0} - variable name", "ERR_NotWritten=Variable {0} is never written to", "# {0} - variable name", "ERR_NotRead=Variable {0} is never read", "# {0} - element name", "ERR_NotUsed={0} is never used", "ERR_NotUsedConstructor=Constructor is never used", }) private static ErrorDescription convertUnused(HintContext ctx, UnusedDescription ud) { //TODO: switch expression candidate! String name = ud.unusedElement.getSimpleName().toString(); String message; switch (ud.reason) { case NOT_WRITTEN_READ: message = Bundle.ERR_NeitherReadOrWritten(name); break; case NOT_WRITTEN: message = Bundle.ERR_NotWritten(name); break; case NOT_READ: message = Bundle.ERR_NotRead(name); break; case NOT_USED: if (ud.unusedElement.getKind() == ElementKind.CONSTRUCTOR) { message = Bundle.ERR_NotUsedConstructor(); } else { message = Bundle.ERR_NotUsed(name); } break; default: throw new IllegalStateException("Unknown unused type: " + ud.reason); } return ErrorDescriptionFactory.forName(ctx, ud.unusedElementPath, message); }
30,178
0
//#if polish.midp || polish.usePolishGui /** * Wraps the given string so it fits on the specified lines. * First of al it is splitted at the line-breaks ('\n'), subsequently the substrings * are splitted when they do not fit on a single line. * * @param value the string which should be splitted * @param font the font which is used to display the font * @param firstLineWidth the allowed width for the first line * @param lineWidth the allowed width for all other lines, lineWidth >= firstLineWidth * @return the array containing the substrings * @deprecated please use wrap instead * @see #wrap(String, Font, int, int) */
public static String[] split( String value, Font font, int firstLineWidth, int lineWidth ) { return wrap(value, font, firstLineWidth, lineWidth); }
NONSATD
true
public static String[] split( String value, Font font, int firstLineWidth, int lineWidth ) { return wrap(value, font, firstLineWidth, lineWidth); }
public static String[] split( String value, Font font, int firstLineWidth, int lineWidth ) { return wrap(value, font, firstLineWidth, lineWidth); }
public static String[] split( String value, Font font, int firstLineWidth, int lineWidth ) { return wrap(value, font, firstLineWidth, lineWidth); }
13,815
0
/** * * @param standardValuesMap */
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
NONSATD
true
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
13,815
1
// since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
DESIGN
true
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0;
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //}
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
13,815
2
//getValidRawRatios();
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
NONSATD
true
// since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator();
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++;
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
13,815
3
// oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) {
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
NONSATD
true
DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //}
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
13,815
4
//}
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
NONSATD
true
//if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; }
//TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
public void updateRawRatioDataModelsWithPrimaryStandardValue(Double[] standardValuesMap) { // since ratios are sorted, we send in ordered array of corresponding standard values //TODO: make more robust SortedSet<DataModelInterface> ratiosSortedSet = getRatiosForFractionFitting();//getValidRawRatios(); int count = 0; Iterator<DataModelInterface> ratiosSortedSetIterator = ratiosSortedSet.iterator(); while (ratiosSortedSetIterator.hasNext()) { DataModelInterface ratio = ratiosSortedSetIterator.next(); ((RawRatioDataModel) ratio).setStandardValue(standardValuesMap[count]); // oct 2012 check for zero or missing standard ratio and remove ratio from fractination consideration //if ( standardValuesMap[count] == 0.0 ) { ((RawRatioDataModel) ratio).setUsedForFractionationCorrections(standardValuesMap[count] != 0.0); //} count++; } }
13,831
0
/** * Removes transitions to or from a missing activity, probably due to the activity not being imported. */
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
NONSATD
true
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
13,831
1
// Transitions from Boundary event timers should be included as well // todo: make generic
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
DESIGN
true
for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) {
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } }
private void removeDanglingTransitions(AbstractWorkflow workflow) { if (workflow.getTransitions() == null || workflow.getTransitions().isEmpty()) { return; } Set<String> activityIds = new HashSet<>(); for (Activity activity : workflow.getActivities()) { activityIds.add(activity.getId()); // Transitions from Boundary event timers should be included as well // todo: make generic List<Timer> activityTimers = activity.getTimers(); if (activityTimers != null) { for (Timer timer : activityTimers) { if (timer instanceof BoundaryEventTimer) { BoundaryEvent boundaryEvent = ((BoundaryEventTimer) timer).boundaryEvent; activityIds.add(boundaryEvent.getBoundaryId()); activityIds.addAll(boundaryEvent.getToTransitionIds()); } } } } ListIterator<Transition> transitionIterator = workflow.getTransitions().listIterator(); while(transitionIterator.hasNext()){ Transition transition = transitionIterator.next(); if (!activityIds.contains(transition.getFromId()) || !activityIds.contains(transition.getToId())) { transitionIterator.remove(); } } }
13,832
0
// TODO: use some sort of map instead
private void reloadItemsList() { documentPartsDataSource.ensureConnectionIsOpen(); List<DocumentCollectionItem> documentCollectionItems = new ArrayList<>(); Log.d("DocCollectionActivity", "Checking filetypes to add"); for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) { Log.d("DocCollectionActivity", "Checking filetype: " + fileType); // TODO: use some sort of map instead boolean isPresent = false; for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) { if (documentPart.getType().equals(fileType)) { DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_present_title), fileType, true); documentCollectionItems.add(docData); isPresent = true; break; } } if (!isPresent) { Log.d("DocCollectionActivity", "File type not found in documentparts, add as TO-DO"); DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_not_present_title), fileType, false); documentCollectionItems.add(docData); } } listView = (ListView) findViewById(R.id.documentlist); DocumentCollectionViewAdapter listViewAdapter = new DocumentCollectionViewAdapter(this, R.layout.fragment_document, documentCollectionItems); listView.setAdapter(listViewAdapter); }
DESIGN
true
for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) { Log.d("DocCollectionActivity", "Checking filetype: " + fileType); // TODO: use some sort of map instead boolean isPresent = false; for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) {
private void reloadItemsList() { documentPartsDataSource.ensureConnectionIsOpen(); List<DocumentCollectionItem> documentCollectionItems = new ArrayList<>(); Log.d("DocCollectionActivity", "Checking filetypes to add"); for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) { Log.d("DocCollectionActivity", "Checking filetype: " + fileType); // TODO: use some sort of map instead boolean isPresent = false; for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) { if (documentPart.getType().equals(fileType)) { DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_present_title), fileType, true); documentCollectionItems.add(docData); isPresent = true; break; } } if (!isPresent) {
private void reloadItemsList() { documentPartsDataSource.ensureConnectionIsOpen(); List<DocumentCollectionItem> documentCollectionItems = new ArrayList<>(); Log.d("DocCollectionActivity", "Checking filetypes to add"); for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) { Log.d("DocCollectionActivity", "Checking filetype: " + fileType); // TODO: use some sort of map instead boolean isPresent = false; for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) { if (documentPart.getType().equals(fileType)) { DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_present_title), fileType, true); documentCollectionItems.add(docData); isPresent = true; break; } } if (!isPresent) { Log.d("DocCollectionActivity", "File type not found in documentparts, add as TO-DO"); DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_not_present_title), fileType, false); documentCollectionItems.add(docData); } } listView = (ListView) findViewById(R.id.documentlist); DocumentCollectionViewAdapter listViewAdapter = new DocumentCollectionViewAdapter(this, R.layout.fragment_document, documentCollectionItems); listView.setAdapter(listViewAdapter); }
30,229
0
/** * @see ORUR01Handler#processMessage(Message) */
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
NONSATD
true
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
30,229
1
// the expected question for the obs in the hl7 message has to be coded
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
NONSATD
true
+ "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21));
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs;
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
30,229
2
// hacky way to get the newly added obs and make tests on it
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
DESIGN
true
Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null;
+ "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
30,244
0
/** * This method handle the keyboard input of the player. * It handles keeper moves. * @param code * @throws IOException * @throws ClassNotFoundException */
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
NONSATD
true
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
30,244
1
// TODO: implement something funny.
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
IMPLEMENTATION
true
break; default: // TODO: implement something funny. } if (isDebugActive()) {
case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
public void handleKey(KeyCode code) throws IOException, ClassNotFoundException { switch (code) { case UP: move(new Point(-1, 0),""); break; case RIGHT: move(new Point(0, 1),""); break; case DOWN: move(new Point(1, 0),""); break; case LEFT: move(new Point(0, -1),""); break; default: // TODO: implement something funny. } if (isDebugActive()) { System.out.println(code); } }
13,882
0
/** * Computes the average chaining distance, the average length of a path * through the given set of points to each target. The authors of COF decided * to approximate this value using a weighted mean that assumes every object * is reached from the previous point (but actually every point could be best * reachable from the first, in which case this does not make much sense.) * * TODO: can we accelerate this by using the kNN of the neighbors? * * @param knnq KNN query * @param dq Distance query * @param ids IDs to process * @param acds Storage for average chaining distances */
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
DESIGN
true
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
13,882
1
// Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order.
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k);
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.;
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist;
13,882
2
// Store the current lowest reachability.
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) {
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) {
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos);
13,882
3
// Find the minimum:
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN;
final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } }
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! }
13,882
4
// Both values could be NaN, deliberately.
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i;
for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0);
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } }
13,882
5
// Weighted sum, decreasing weights
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
} } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos);
int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2);
final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
13,882
6
// Update distances
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) {
double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; }
final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
13,882
7
// NaN = processed!
protected void computeAverageChainingDistances(KNNQuery<O> knnq, DistanceQuery<O> dq, DBIDs ids, WritableDoubleDataStore acds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances", ids.size(), LOG) : null; // Compute the chaining distances. // We do <i>not</i> bother to materialize the chaining order. for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { final KNNList neighbors = knnq.getKNNForDBID(iter, k); final int r = neighbors.size(); DoubleDBIDListIter it1 = neighbors.iter(), it2 = neighbors.iter(); // Store the current lowest reachability. final double[] mindists = new double[r]; for(int i = 0; it1.valid(); it1.advance(), ++i) { mindists[i] = DBIDUtil.equal(it1, iter) ? Double.NaN : it1.doubleValue(); } double acsum = 0.; for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
NONSATD
true
final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2);
} } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); }
for(int j = ((r < k) ? r : k) - 1; j > 0; --j) { // Find the minimum: int minpos = -1; double mindist = Double.NaN; for(int i = 0; i < mindists.length; ++i) { double curdist = mindists[i]; // Both values could be NaN, deliberately. if(curdist == curdist && !(curdist > mindist)) { minpos = i; mindist = curdist; } } acsum += mindist * j; // Weighted sum, decreasing weights mindists[minpos] = Double.NaN; it1.seek(minpos); // Update distances it2.seek(0); for(int i = 0; it2.valid(); it2.advance(), ++i) { final double curdist = mindists[i]; if(curdist != curdist) { continue; // NaN = processed! } double newdist = dq.distance(it1, it2); if(newdist < curdist) { mindists[i] = newdist; } } } acds.putDouble(iter, acsum / (r * 0.5 * (r - 1.))); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
13,884
0
//TODO: Replace this with your own logic
private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 5; }
DESIGN
true
private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 5; }
private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 5; }
private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 5; }
30,271
0
/** * Returns a list of clang flags used for all link and compile actions executed through clang. */
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
NONSATD
true
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
30,271
1
// TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version.
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
DESIGN
true
break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform));
switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR:
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); }
30,271
2
// TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version.
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
DESIGN
true
break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform));
switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR:
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); }
30,271
3
// TODO(bazel-team): Pass framework search paths to Xcodegen.
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
IMPLEMENTATION
true
.add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build();
break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
30,286
0
/** * configures the first algorithm responsible for : 1. discovering the * distinct values for the header 2. arranging the initial crosstab data * into rows for the second iteration 3. computing totals on the crosstab * data. * * @return the intermediate algorithm */
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
30,286
1
// initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep());
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep());
AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> {
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep());
30,286
2
// if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // }
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> {
.build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); }
30,286
3
// TODO: only when totals add the step below
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
DESIGN
true
return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug
// algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // }
if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> {
30,286
4
// only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
// TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep());
// algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); }
}else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep());
30,286
5
// only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // }
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
// TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug
// algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug
}else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm;
30,286
6
// only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
// TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep());
// algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); }
}else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep());
30,286
7
// }
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep()); if (getShowTotals() || getShowGrandTotal()) { algorithm.addMainStep(new IntermedTotalsCalculatorStep()); } // only for debug // algorithm.addMainStep(new DataRowsOutputStep()); // if( intermediateGroupCols.size() > 0){ algorithm.addMainStep(new IntermedPreviousRowManagerStep()); // } algorithm.addExitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).close(); return NO_RESULT; }); algorithm.addExitStep(new IntermedSetResultsExitStep()); return algorithm; }
NONSATD
true
// if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep());
algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep());
private Algorithm configIntermedAlgo(final boolean hasBeenPreviouslySorted) { AbstractMultiStepAlgo algorithm = null; Map<StepIOKeys, AlgoIOKeys> stepToAlgoKeysMapping = new StepAlgoKeyMapBuilder() .add(INTERMEDIATE_DISTINCT_VALUES_HOLDER, DISTINCT_VALUES_HOLDER) .add(INTERMEDIATE_SERIALIZED_FILE, INTERMEDIATE_OUTPUT_FILE) .build(); if(hasBeenPreviouslySorted){ algorithm = new MultipleSortedFilesInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); }else{ algorithm = new LoopThroughTableInputAlgo("Intermediate Algorithm", stepToAlgoKeysMapping); } // initial steps // algorithm.addInitStep(new ConfigIntermedColsInitStep()); algorithm.addInitStep(new ConstrIntermedDataColsInitStep()); algorithm.addInitStep(new ConstrIntermedGrpColsInitStep()); // if(!needsProgramaticSorting){ // algorithm.addInitStep(new ConfigIntermedIOInitStep()); // }else{ // algorithm.addInitStep(new // ConfigMultiExternalFilesInputForIntermReportInitStep()); // } algorithm.addInitStep(new ConfigIntermedReportOutputInitStep()); algorithm.addInitStep(stepInput -> { ((IntermediateCrosstabOutput) stepInput.getContextParam(INTERMEDIATE_CROSSTAB_OUTPUT)).open(); return NO_RESULT; }); // TODO: only when totals add the step below algorithm.addInitStep(new IntermedReportExtractTotalsDataInitStep()); // only for debug // algorithm.addInitStep(new ColumnHeaderOutputInitStep("Intermediate report")); // main steps algorithm.addMainStep(new DistinctValuesDetectorStep()); algorithm.addMainStep(new IntermedGroupLevelDetectorStep()); // only for debug // if( getShowTotals() || getShowGrandTotal()){ // algorithm.addMainStep(new FlatReportTotalsOutputStep()); // } algorithm.addMainStep(new IntermedRowMangerStep());
22,098
0
// User clicked OK button
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) {
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) {
22,098
1
//starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
// User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i);
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show();
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show();
22,098
2
//verify input
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try {
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; }
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; }
22,098
3
//validate results
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) {
int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) {
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); }
22,098
4
//save results //todo: save playerID with input field for better code quality
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
IMPLEMENTATION
true
return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) {
toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores();
toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); }
22,098
5
//if this entry is score, update views && activate next round
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap);
Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else {
int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
22,098
6
//change buttons
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
NONSATD
true
changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
13,922
0
/* TODO: clear previously-set field and avoid memory leak */
public void setSimpleTag() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.SIMPLE_TAG; }
IMPLEMENTATION
true
public void setSimpleTag() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.SIMPLE_TAG; }
public void setSimpleTag() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.SIMPLE_TAG; }
public void setSimpleTag() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.SIMPLE_TAG; }
22,202
0
// TODO: what about open and close inside strings ?
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
DESIGN
true
} char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src);
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++;
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
22,202
1
// code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close);
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
NONSATD
true
if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close)
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } }
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
22,202
2
//|| src[pos] == close)
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
NONSATD
true
// code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0)
while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++;
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
22,202
3
// TODO: optimize
public EasySource getInnerText(char open, char close) { StringBuffer code = new StringBuffer(); int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
DESIGN
true
} } code.append(c); // TODO: optimize pos++; }
} if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
int brace_counter = 0; while (true) { if (pos >= src.length) { return null; } char c = src[pos]; if (c == open) { // TODO: what about open and close inside strings ? brace_counter++; // code.appendInPlace(parse(rs, hook).src); // code.appendInPlace(close); } if (c == close) //|| src[pos] == close) { if (brace_counter > 0) brace_counter--; else { pos++; break; } } code.append(c); // TODO: optimize pos++; } return new EasySource(code.toString().toCharArray()); }
14,027
0
// TODO: Deal with potential runtime exceptions
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
IMPLEMENTATION
true
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
14,027
1
// TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start.
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
IMPLEMENTATION
true
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) {
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>();
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME);
14,027
2
// TODO: Fix nulls // Only process the session if it has associated events
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
DEFECT
true
sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>();
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail.
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId);
14,027
3
// FIXME: If we fail to parse the events, we'll need to bail.
public void finalizeReports(String currentSessionId) { // TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports(); }
DEFECT
true
events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME);
// Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId);
// TODO: Need to implement procedure to skip finalizing the current session when this is // called on app start, but keep the current session when called at crash time. Currently // this only works when called at app start. List<File> sessionDirectories = capAndGetOpenSessions(currentSessionId); for (File sessionDirectory : sessionDirectories) { final List<File> eventFiles = getFilesInDirectory( sessionDirectory, (f, name) -> name.startsWith(EVENT_FILE_NAME_PREFIX)); Collections.sort(eventFiles); // TODO: Fix nulls // Only process the session if it has associated events if (!eventFiles.isEmpty()) { final List<Event> events = new ArrayList<>(); boolean isHighPriorityReport = false; for (File eventFile : eventFiles) { final Event event = TRANSFORM.eventFromJson(readTextFile(eventFile)); isHighPriorityReport = isHighPriorityReport || isHighPriorityEventFile(eventFile.getName()); events.add(event); } // FIXME: If we fail to parse the events, we'll need to bail. String userId = null; final File userFile = new File(sessionDirectory, USER_FILE_NAME); if (userFile.exists()) { userId = readTextFile(userFile); } CrashlyticsReport report = TRANSFORM.reportFromJson(readTextFile(new File(sessionDirectory, REPORT_FILE_NAME))); final String sessionId = report.getSession().getIdentifier(); if (userId != null) { report = report.withUserId(userId); } final File outputDirectory = prepareDirectory(isHighPriorityReport ? priorityReportsDirectory : reportsDirectory); writeTextFile( new File(outputDirectory, sessionId), TRANSFORM.reportToJson(report.withEvents(ImmutableList.from(events)))); } recursiveDelete(sessionDirectory); } capFinalizedReports();
22,220
0
// System.out.println("Start");
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) {
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) {
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author
22,220
1
// System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size());
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString();
22,220
2
//System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo,
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) {
for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); }
22,220
3
//// this means the source has properties so it is likely to be the document with an author
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) {
if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); }
// System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document
22,220
4
// System.out.println("author source = " + author);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else {
if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data.
String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); }
22,220
5
//// it is not the document so a cited source
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
} } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/");
for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string
ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString();
22,220
6
/* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
DEFECT
true
cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); }
} // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else {
if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k);
22,220
7
// System.out.println("quote source = " + cite);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
} */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) {
/* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/");
} // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) {
22,220
8
// System.out.println("str = " + str);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) {
if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; }
cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else {
22,220
9
// System.out.println("myPerspective = " + myPerspective);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); }
if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } }
} } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
22,220
10
// System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI());
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
} } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } }
} ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } }
int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
22,220
11
// System.out.println("final author = " + author);
public static PerspectiveJsonObject getPerspectiveObjectForEvent(TrigTripleData trigTripleData, String mentionUri, String meta) { PerspectiveJsonObject perspectiveJsonObject = new PerspectiveJsonObject(); String author = ""; String cite = ""; // System.out.println("Start"); ArrayList<String> perspectives = new ArrayList<String>(); if (trigTripleData.tripleMapGrasp.containsKey(mentionUri)) { ArrayList<Statement> perspectiveTriples = trigTripleData.tripleMapGrasp.get(mentionUri); // System.out.println("perspectiveTriples.size() = " + perspectiveTriples.size()); for (int i = 0; i < perspectiveTriples.size(); i++) { Statement statement = perspectiveTriples.get(i); String subject = statement.getSubject().getURI(); String predicate = statement.getPredicate().getURI(); String object = statement.getObject().toString(); if (predicate.endsWith("#hasAttribution")) { if (trigTripleData.tripleMapGrasp.containsKey(object)) { ArrayList<Statement> perspectiveValues = trigTripleData.tripleMapGrasp.get(object); for (int j = 0; j < perspectiveValues.size(); j++) { Statement statement1 = perspectiveValues.get(j); //System.out.println("statement1.toString() = " + statement1.toString()); // System.out.println("statement1.getObject().toString() = " + statement1.getObject().toString()); //ttp://www.w3.org/ns/prov#wasAttributedTo, if (statement1.getPredicate().getURI().endsWith("#wasAttributedTo")) { if (trigTripleData.tripleMapGrasp.containsKey(statement1.getObject().toString())) { //// this means the source has properties so it is likely to be the document with an author ArrayList<Statement> provStatements = trigTripleData.tripleMapGrasp.get(statement1.getObject().toString()); for (int k = 0; k < provStatements.size(); k++) { Statement statement2 = provStatements.get(k); author = statement2.getObject().toString(); int idx = author.lastIndexOf("/"); if (idx > -1) { author = author.substring(idx + 1); } // System.out.println("author source = " + author); } } else { //// it is not the document so a cited source cite = statement1.getObject().toString(); int idx = cite.lastIndexOf("/"); if (idx > -1) { cite = cite.substring(idx + 1); } /* THIS DOES NOT WORK: PRONOUNS, RECEPTIONIST, ETC... //// There can be source documents without meta data. //// In that case, there are no triples for in tripleMapGrasp with this subject but it is still a document //// The next hack checks for upper case characters in the URI //// If they are present, we assume it is somebody otherwise we assume it is a document and we assign it to the meta string if (cite.toLowerCase().equals(cite)) { //// no uppercase characters cite = meta; } */ // System.out.println("quote source = " + cite); } } else if (statement1.getPredicate().getURI().endsWith("#value")) { String perspective = ""; String str = statement1.getObject().toString(); // System.out.println("str = " + str); int idx = str.lastIndexOf("#"); if (idx > -1) { perspective = str.substring(idx + 1); } else { idx = str.lastIndexOf("/"); if (idx > -1) { perspective = str.substring(idx + 1); } else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
NONSATD
true
} if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); }
} } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
} else { perspective = str; } } ArrayList<String> myPerspectives = PerspectiveJsonObject.normalizePerspectiveValue(perspective); for (int k = 0; k < myPerspectives.size(); k++) { String myPerspective = myPerspectives.get(k); if (!perspectives.contains(myPerspective)) { // System.out.println("myPerspective = " + myPerspective); perspectives.add(myPerspective); } } } else { // System.out.println("statement1.getPredicate().getURI() = " + statement1.getPredicate().getURI()); } } } } } if (perspectives.size() > 0) { // System.out.println("final author = " + author); perspectiveJsonObject = new PerspectiveJsonObject(perspectives, author, cite, "", "", "", mentionUri, null); } } return perspectiveJsonObject; }
14,028
0
//TODO: custom host and port
public String getHost() { return "localhost"; }
DESIGN
true
public String getHost() { return "localhost"; }
public String getHost() { return "localhost"; }
public String getHost() { return "localhost"; }
30,415
0
/** * Assign country codes for {@link Relation}s. This is assuming all {@link Way}s crossing * borders got cut and new {@link Way}s were generated to fill the polygon. All we need to do * here is group them by country and split the members. * * @param relation * The {@link Relation} to process. * @return All {@link Relation}s produced after splitting the given {@link Relation}. */
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
30,415
1
// Either the way is not sliced or way is outside of the supplied bound
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); }
final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled
final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else
30,415
2
// Check if we have the sub-relation in the store
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) {
} else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) {
switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) {
30,415
3
// Put the member back into the relation. Missing members will be handled // on a case by case basis
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break;
// Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else {
final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member,
30,415
4
// Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break;
members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country
{ logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else {
30,415
5
// Modified by way slicing or relation slicing
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); }
default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING;
{ members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else
30,415
6
// Group entities by country
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member ->
// PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else {
}); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; }
30,415
7
// One country code found, assign it
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next()));
memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity.
} } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty())
30,415
8
// Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity.
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
NONSATD
true
else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation);
} else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty())
} else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); }
30,415
9
// TODO Consider sharing CountryCode Tag objects
private Optional<List<Relation>> processDefaultRelation(final Relation relation, final List<Long> parents) { final List<Relation> createdRelations = new ArrayList<>(); final List<RelationMember> members = new ArrayList<>(); boolean isModified = false; for (final RelationMember member : relation.getMembers()) { switch (member.getMemberType()) { case Way: final List<Way> slicedWays = this.changeSet .getCreatedWays(member.getMemberId()); if (slicedWays != null && !slicedWays.isEmpty()) { isModified = true; slicedWays.forEach(way -> members .add(this.store.createRelationMember(member, way.getId()))); } else { // Either the way is not sliced or way is outside of the supplied bound members.add(member); } break; case Relation: parents.add(relation.getId()); final Relation subRelation = this.store.getRelation(member.getMemberId()); // Check if we have the sub-relation in the store if (subRelation == null) { // Put the member back into the relation. Missing members will be handled // on a case by case basis members.add(member); break; } final Optional<List<Relation>> slicedMembers; if (!parents.contains(subRelation.getId())) { slicedMembers = sliceRelation(subRelation, parents); } else { logger.error("Relation {} has a loop! Parent tree: {}", subRelation.getId(), parents); slicedMembers = Optional.empty(); } if (slicedMembers.isPresent()) { isModified = true; slicedMembers.get().forEach(slicedRelation -> { members.add(this.store.createRelationMember(member, slicedRelation.getId())); }); } else { members.add(member); } break; default: // Here we are not checking the bound, because we are assuming all data // outside of bound has already been filtered out and doesn't exist in the // PbfMemoryStore members.add(member); break; } } if (isModified) { // Modified by way slicing or relation slicing this.changeSet.addModifiedRelation(relation); } // Group entities by country final Map<String, List<RelationMember>> countryEntityMap = members.stream() .collect(Collectors.groupingBy(member -> { final Entity entity = this.store.getEntity(member); if (Objects.isNull(entity)) { return ISOCountryTag.COUNTRY_MISSING; } else { final Optional<Tag> countryCodeTag = entity.getTags().stream() .filter(tag -> tag.getKey().equals(ISOCountryTag.KEY)).findFirst(); if (countryCodeTag.isPresent()) { return countryCodeTag.get().getValue(); } else { return ISOCountryTag.COUNTRY_MISSING; } } })); final List<RelationMember> memberWithoutCountry; if (countryEntityMap.containsKey(ISOCountryTag.COUNTRY_MISSING)) { memberWithoutCountry = countryEntityMap.remove(ISOCountryTag.COUNTRY_MISSING); } else { memberWithoutCountry = Collections.emptyList(); } final int countryCount = countryEntityMap.size(); if (countryCount == 0) { relation.getTags().add(new Tag(ISOCountryTag.KEY, ISOCountryTag.COUNTRY_MISSING)); return Optional.empty(); } else if (countryCount == 1) { // One country code found, assign it relation.getTags() .add(new Tag(ISOCountryTag.KEY, countryEntityMap.keySet().iterator().next())); return Optional.empty(); } else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
DESIGN
true
final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd);
relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
} else { // Muliple country codes found, implies relation crosses countries. As a 2 dimensional // feature, relation sliced should not have more than one piece for each country. For // now, for features without a country code (nodes and feature not covered by any // boundary), we put a copy for every sliced piece to ensure integrity. RuntimeCounter.relationSliced(); this.changeSet.addDeletedRelation(relation); final CountrySlicingIdentifierFactory relationIdFactory = new CountrySlicingIdentifierFactory( relation.getId()); countryEntityMap.entrySet().forEach(entry -> { final List<RelationMember> candidateMembers = new ArrayList<>(); candidateMembers.addAll(entry.getValue()); candidateMembers.addAll(memberWithoutCountry); if (!candidateMembers.isEmpty()) { final Relation relationToAdd = this.store.createRelation(relation, relationIdFactory.nextIdentifier(), candidateMembers); // TODO Consider sharing CountryCode Tag objects relationToAdd.getTags().add(new Tag(ISOCountryTag.KEY, entry.getKey())); createdRelations.add(relationToAdd); this.changeSet.addCreatedRelation(relationToAdd); } }); } return Optional.of(createdRelations); }
22,238
0
// todo: support for tabs?
public static String replaceLeadingSpacesWithNbsps (String str) { // todo: support for tabs? Matcher m = _LeadingSpacesPattern.matcher(str); StringBuffer buf = new StringBuffer(); while (m.find()) { int spaceCount = m.group(1).length(); m.appendReplacement(buf, AWUtil.repeatedString("&nbsp;", spaceCount)); } m.appendTail(buf); return buf.toString(); }
IMPLEMENTATION
true
public static String replaceLeadingSpacesWithNbsps (String str) { // todo: support for tabs? Matcher m = _LeadingSpacesPattern.matcher(str); StringBuffer buf = new StringBuffer();
public static String replaceLeadingSpacesWithNbsps (String str) { // todo: support for tabs? Matcher m = _LeadingSpacesPattern.matcher(str); StringBuffer buf = new StringBuffer(); while (m.find()) { int spaceCount = m.group(1).length(); m.appendReplacement(buf, AWUtil.repeatedString("&nbsp;", spaceCount)); } m.appendTail(buf); return buf.toString(); }
public static String replaceLeadingSpacesWithNbsps (String str) { // todo: support for tabs? Matcher m = _LeadingSpacesPattern.matcher(str); StringBuffer buf = new StringBuffer(); while (m.find()) { int spaceCount = m.group(1).length(); m.appendReplacement(buf, AWUtil.repeatedString("&nbsp;", spaceCount)); } m.appendTail(buf); return buf.toString(); }
22,244
0
/** * Process a pending trash message command. * * @param remoteStore the remote store we're working in * @param newMailbox The local trash mailbox * @param oldMessage The message copy that was saved in the updates shadow table * @param newMessage The message that was moved to the mailbox */
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
22,244
1
// 0. No remote move if the message is local-only
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return;
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return;
22,244
2
// 1. Escape early if we can't find the local mailbox // TODO smaller projection here
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
DESIGN
true
return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) {
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; }
22,244
3
// can't find old mailbox, it may have been deleted. just return.
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; }
final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) {
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) {
22,244
4
// 2. We don't support delete-from-trash here
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return;
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE);
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; }
22,244
5
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) {
// TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it.
22,244
6
// 5. Find the remote original message
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) {
// 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it.
Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE);
22,244
7
// 6. Find the remote trash folder, and create it if not found
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) {
if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) {
if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
22,244
8
/* * If the remote trash folder doesn't exist we try to create it. */
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); }
} // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder
22,244
9
// 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /*
return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; }
} remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); }
22,244
10
/* * Because remoteTrashFolder may be new, we need to explicitly open it */
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); }
} // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder
22,244
11
// update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
@Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid);
remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override
* If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false);
22,244
12
/** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) {
remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge();
if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
22,244
13
// 8. Delete the message from the remote source folder
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge();
* deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
@Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
14,054
0
// Turn on Crunch runtime error catching. //TODO: allow configurable
@Override public void enableDebug() { // Turn on Crunch runtime error catching. //TODO: allow configurable getConfiguration().setBoolean("crunch.debug", true); }
DESIGN
true
@Override public void enableDebug() { // Turn on Crunch runtime error catching. //TODO: allow configurable getConfiguration().setBoolean("crunch.debug", true); }
@Override public void enableDebug() { // Turn on Crunch runtime error catching. //TODO: allow configurable getConfiguration().setBoolean("crunch.debug", true); }
@Override public void enableDebug() { // Turn on Crunch runtime error catching. //TODO: allow configurable getConfiguration().setBoolean("crunch.debug", true); }
30,445
0
//todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers()
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); } } producerExchanges.put(id, result); } } return result; }
IMPLEMENTATION
true
result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id);
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); } } producerExchanges.put(id, result); } } return result; }
30,445
1
// once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); } } producerExchanges.put(id, result); } } return result; }
DESIGN
true
//todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); }
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); }
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException { AMQProducerBrokerExchange result = producerExchanges.get(id); if (result == null) { synchronized (producerExchanges) { result = new AMQProducerBrokerExchange(); result.setConnectionContext(context); //todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194 //todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers() if (context.isReconnect() || (context.isNetworkConnection())) { // once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow // We have different semantics on Artemis Journal, but we could adapt something for this // TBD during the implemetnation of ARTEMIS-194 result.setLastStoredSequenceId(0); } SessionState ss = state.getSessionState(id.getParentId()); if (ss != null) { result.setProducerState(ss.getProducerState(id)); ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); } } producerExchanges.put(id, result); } } return result; }
14,066
0
/** GETTER * TODO: Write general description for this method */
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
DOCUMENTATION
true
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
@JsonGetter("accessToken") public String getAccessToken ( ) { return this.accessToken; }
14,067
0
/** SETTER * TODO: Write general description for this method */
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
DOCUMENTATION
true
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
@JsonSetter("accessToken") public void setAccessToken (String value) { this.accessToken = value; notifyObservers(this.accessToken); }
14,068
0
/** GETTER * TODO: Write general description for this method */
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }
DOCUMENTATION
true
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }
@JsonGetter("tokeType") public String getTokeType ( ) { return this.tokeType; }