private static void addTypeToAll(Resource type, Set<Resource> candidates) { List<Resource> types = equivalentTypes(type); for (Resource element : candidates) { Resource resource = element; for (int i = 0; i < types.size(); i += 1) resource.addProperty(RDF.type, types.get(i)); } }
public static String RenderTemplatePage(Bindings b, String templateName) throws IOException { MediaType mt = MediaType.TEXT_HTML; Resource config = model.createResource("eh:/root"); Mode prefixMode = Mode.PreferPrefixes; ShortnameService sns = new StandardShortnameService(); List<Resource> noResults = CollectionUtils.list(root.inModel(model)); Graph resultGraph = graphModel.getGraph(); resultGraph.getPrefixMapping().setNsPrefix("api", API.NS); resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode())); APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL); VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns); VelocityRendering vx = new VelocityRendering(b, rs, vr); VelocityEngine ve = vx.createVelocityEngine(); VelocityContext vc = vx.createVelocityContext(b); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(bos, "UTF-8"); Template t = ve.getTemplate(templateName); t.merge(vc, w); w.close(); return bos.toString(); }
public Resource rowColRef(int col, Model pmlModel) { Resource epa = pmlModel.createResource(Ontology.EPA.NS + "EPA"); Resource source = pmlModel.createResource(pmlModel.createResource(Ontology.PMLP.SourceUsage)); Resource frag = pmlModel.createResource(pmlModel.createResource(Ontology.PMLP.DocumentFragmentByRowCol)); Resource document = pmlModel.createResource(src, pmlModel.createResource(Ontology.PMLP.Dataset)); Property prop; // Relate source to fragment prop = pmlModel.createProperty(Ontology.PMLP.hasSource); source.addProperty(prop, frag); // Relate row/col information prop = pmlModel.createProperty(Ontology.PMLP.hasFromCol); frag.addLiteral(prop, col); prop = pmlModel.createProperty(Ontology.PMLP.hasToCol); frag.addLiteral(prop, col); prop = pmlModel.createProperty(Ontology.PMLP.hasFromRow); frag.addLiteral(prop, row); prop = pmlModel.createProperty(Ontology.PMLP.hasToRow); frag.addLiteral(prop, row); // Relate fragment to document prop = pmlModel.createProperty(Ontology.PMLP.hasDocument); frag.addProperty(prop, document); // Relate document to publisher prop = pmlModel.createProperty(Ontology.PMLP.hasPublisher); document.addProperty(prop, epa); return source; }
private void addTriplePatterns(Property predicate, Set<TriplePattern> results) { StmtIterator it = getModel().listStatements(null, predicate, this); while (it.hasNext()) { Resource subject = it.nextStatement().getSubject(); results.add((TriplePattern) subject.as(TriplePattern.class)); } }
private void updateAddRemoveDataGetterStatements( OntModel displayModel, Model removeStatements, Model addStatements, Resource oldType, Resource newType) { log.debug("Old type: " + oldType.getURI() + " - newType: " + newType.getURI()); removeStatements.add(displayModel.listStatements(null, RDF.type, oldType)); StmtIterator oldStatements = displayModel.listStatements(null, RDF.type, oldType); while (oldStatements.hasNext()) { Statement stmt = oldStatements.nextStatement(); addStatements.add(stmt.getSubject(), RDF.type, newType); } // Print out remove and add statements here StringWriter sw = new StringWriter(); try { log.debug( "Adding statements with old data getter types to remove statements, remove statements is now"); removeStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); sw = new StringWriter(); log.debug( "Adding statements with new data getter types to add statements, add statements is now"); addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in writing out remove and statements for data getter types", ex); } }
public static Method create(QuerySolution qs) throws Exception { Resource id = (Resource) qs.get("x"); Literal fullPath = (Literal) qs.get("fullPath"); Literal name = (Literal) qs.get("name"); Literal accessModifier = (Literal) qs.get("accessModifier"); Literal lineStart = (Literal) qs.get("line_start"); Literal lineEnd = (Literal) qs.get("line_end"); Resource returnType = (Resource) qs.get("returnType"); Resource hasParameter = (Resource) qs.get("hasParameter"); Resource throwsException = (Resource) qs.get("throwsException"); Resource belongsTo = (Resource) qs.get("belongsTo"); Method meth = new Method(id.toString(), name.getValue().toString()); meth.setAccessModifier(accessModifier.getValue().toString()); meth.setFullPath(fullPath.getValue().toString()); meth.setLineStart(lineStart.getInt()); meth.setLineEnd(lineEnd.getInt()); meth.setReturnType(returnType.toString()); if (hasParameter != null) { meth.setHasParameter(hasParameter.toString()); } if (throwsException != null) { meth.setThrowsException(throwsException.toString()); } meth.setBelongsTo(belongsTo.toString()); return meth; }
public List<ReMSerialisation> getReMSerialisations() throws OREException { try { List<ReMSerialisation> serialisations = new ArrayList<ReMSerialisation>(); StmtIterator itr = res.listProperties(ORE.isDescribedBy); while (itr.hasNext()) { Statement statement = itr.nextStatement(); Resource resource = (Resource) statement.getObject(); StmtIterator itr2 = resource.listProperties(DC.format); StmtIterator itr3 = resource.listProperties(OREX.isAuthoritativeFor); String mime = "application/octet-stream"; if (itr2.hasNext()) { Statement stmt = itr2.nextStatement(); mime = ((Literal) stmt.getObject()).getLexicalForm(); } boolean authoritative = false; if (itr3.hasNext()) { authoritative = true; } ReMSerialisation serialisation = new ReMSerialisation(mime, new URI(resource.getURI())); serialisation.setAuthoritative(authoritative); serialisations.add(serialisation); } return serialisations; } catch (URISyntaxException e) { throw new OREException(e); } }
public Resource getRDFResource() { OntModel vocab = OntologyFactory.getTalenticaOntology(); Resource price = vocab.createResource(getUri()); price.addProperty(vocab.getProperty(AMNT_URI), String.valueOf(this.amount)); price.addProperty(vocab.getProperty(CURRENCY_URI), this.currency); return price; }
public Resource createGLIFinstance(String bp_type, String id, AttribGroupSet ags) { Resource r = rdfModel.createResource(KB_NS_PREFIX + "GLIF3_5_BitPathways_Class_" + classIndex); classIndex++; String type = getGLIFtype(bp_type); Resource r_type = rdfModel.createResource(GLIF_Factory.KB_NS_PREFIX + type); r.addProperty(RDF.type, r_type); String label = ags.getSpecialValue("label")[0].toString(); if (label == null) label = ""; r.addProperty(RDFS.label, label); r.addProperty(rdfModel.createProperty(KB_NS_PREFIX + "name"), label); if (type.equalsIgnoreCase("Patient_State")) { r.addProperty(rdfModel.createProperty(KB_NS_PREFIX + "display_name"), label); } if (bp_type.equalsIgnoreCase("TASK")) { addTaskProperties(r, ags); } else if (bp_type.equalsIgnoreCase("DECISION")) { addDecisionProperties(r, ags); } else if (bp_type.equalsIgnoreCase("START")) { addStartProperties(r, ags); } else if (bp_type.equalsIgnoreCase("END")) { addEndProperties(r, ags); } else if (bp_type.equalsIgnoreCase("SUBPATH")) { addSubpathProperties(r, ags); } stepSet.put(id, r); return r; }
/** @todo Add Documentation. */ @Override public boolean isFedoraGraphSubject(Resource subject) { checkArgument(subject != null, "null cannot be a Fedora object!"); assert (subject != null); return subject.isURIResource() && subject.getURI().startsWith("info:fedora/"); }
/** * Returns reflection of the given resource <code>r</code> into given domain <code>mDomain</code>. * * @param uri uri of the resource to be reflected * @param mDB is model, which contains statements about resource <code>uri</code> * @param mDomain domain model describing classes * @return < * <UL> * <LI><code>uri</code> if resource with this <code>uri</code> , i.e. this resource occurs * as a subject of a any statement in <code>mDomain</code>. * <LI>URI of <code>C</code>, if resource with this <code>uri</code> does NOT belong do * <code>mDomain</code> and instance of resource (class) C, belonging do <code>mDomain * </code>. * <LI><code>null</code> -- otherwise. * </UL> */ public static Resource getReflection(Resource r, OntModel mDB, OntModel mDomain) { // TODO The idea of reflexion becomes illogical when the individual as // an instance of more then one type (class). if (mDomain.containsResource(r)) // Associate resource with mDomain return (Resource) r.inModel(mDomain); // Check whether ontr is instance (individual) of some class... // Associate it for the test with mDB model r = (Resource) r.inModel(mDB); for (StmtIterator it = r.listProperties(RDF.type); it.hasNext(); ) { Resource clazz = it.nextStatement().getResource(); // ...and this class belongs to domain ontology if (mDomain.containsResource(clazz)) { // Since clazz is object of rdf:type predicate, than it is // rdfs:Resource. // Associate it with mDomain. return (Resource) clazz.inModel(mDomain); } } // The value is undefined return null; }
@Test public void shouldSortTriplesForDisplay() { final Model model = createDefaultModel(); model.setNsPrefix("prefix", "namespace"); final Property propertyA = model.createProperty("namespace", "a"); final Property propertyB = model.createProperty("namespace", "b"); final Property propertyC = model.createProperty("c"); final Literal literalA = model.createLiteral("a"); final Literal literalB = model.createLiteral("b"); final Resource resourceB = model.createResource("b"); model.add(resourceB, propertyA, literalA); final Resource a = model.createResource("a"); model.add(a, propertyC, literalA); model.add(a, propertyB, literalA); model.add(a, propertyA, literalA); model.add(a, propertyA, literalB); final Iterator<Quad> iterator = DatasetFactory.create(model).asDatasetGraph().find(); final List<Quad> sortedTriples = testObj.getSortedTriples(model, iterator); sortedTriples.get(0).matches(ANY, a.asNode(), propertyA.asNode(), literalA.asNode()); sortedTriples.get(1).matches(ANY, a.asNode(), propertyA.asNode(), literalB.asNode()); sortedTriples.get(2).matches(ANY, a.asNode(), propertyB.asNode(), literalA.asNode()); sortedTriples.get(3).matches(ANY, a.asNode(), propertyC.asNode(), literalA.asNode()); sortedTriples.get(4).matches(ANY, resourceB.asNode(), propertyC.asNode(), literalA.asNode()); }
public MappedResource getIndexResource() { if (!config.hasProperty(CONF.indexResource)) { return null; } return getMappedResourceFromDatasetURI( config.getProperty(CONF.indexResource).getResource().getURI()); }
private static Set<Property> getPermissions(String userPrefix, String username, String uri) { Set<Property> permissions = new HashSet<Property>(); Resource resource = configModel.createResource(uri); Resource user; if (username == null) user = PERM.Public; else user = configModel.createResource(userPrefix + username); StmtIterator stmts = configModel.listStatements(user, null, resource); while (stmts.hasNext()) permissions.add(stmts.next().getPredicate()); String queryString = ""; queryString += "PREFIX perm: <http://vocab.ox.ac.uk/perm#>\n"; queryString += "SELECT ?perm ?regex WHERE {\n"; queryString += " <" + user.getURI() + "> ?perm ?rm ."; queryString += " ?rm a perm:ResourceMatch ;"; queryString += " perm:matchExpression ?regex }"; com.hp.hpl.jena.query.Query query = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.create(query, configModel); ResultSet results = qexec.execSelect(); while (results.hasNext()) { QuerySolution sol = results.next(); if (uri.matches(((Literal) sol.get("regex")).getLexicalForm())) permissions.add(configModel.createProperty(((Resource) sol.get("perm")).getURI())); } if (username != null) permissions.addAll(getPermissions(userPrefix, null, uri)); return permissions; }
protected String jcrMixinNameFromRdfResource(final Resource mixinResource) throws RepositoryException { final String namespace = getJcrNamespaceForRDFNamespace(mixinResource.getNameSpace()); String namespacePrefix = null; final Map<String, String> streamNSMap = checkNotNull(stream().namespaces(), "Use an empty map of namespaces, not null!"); if (streamNSMap.containsValue(namespace)) { LOGGER.debug("Found namespace: {} in stream namespace mapping.", namespace); for (final Map.Entry<String, String> entry : streamNSMap.entrySet()) { final String streamNamespace = entry.getValue(); if (namespace.equals(streamNamespace)) { LOGGER.debug( "Found namespace: {} in stream namespace mapping with prefix: {}.", namespace, namespacePrefix); namespacePrefix = entry.getKey(); } } } else { try { namespacePrefix = session().getNamespacePrefix(namespace); LOGGER.debug( "Found namespace: {} in repository namespace mapping with prefix: {}.", namespace, namespacePrefix); } catch (final NamespaceException e) { throw new MalformedRdfException( "Unable to resolve registered namespace for resource " + mixinResource.toString(), e); } } final String mixinName = namespacePrefix + ":" + mixinResource.getLocalName(); LOGGER.debug("Constructed JCR mixin name: {}", mixinName); return mixinName; }
public void testCreateAnonResourceWithNull() { final Resource r = model.createResource((String) null); Assert.assertTrue(r.isAnon()); Assert.assertNull(r.getURI()); Assert.assertNull(r.getNameSpace()); Assert.assertNull(r.getLocalName()); }
@Override public void processInput(Resource input, Resource output) { final Model model = ModelFactory.createDefaultModel(); final List<Statement> tipURIs = input.listProperties(Vocab.has).toList(); final SublistIterator<Statement> tipsIterator = new SublistIterator<Statement>(tipURIs, QUERY_CHUNK_SIZE); while (tipsIterator.hasNext()) { final List<String> ancestorQueryBlocks = new ArrayList<String>(); final List<String> parentQueryBlocks = new ArrayList<String>(); final List<Statement> tips = tipsIterator.next(); for (Statement statement : tips) { final String tipURI = statement.getResource().getProperty(DC.subject).getResource().getURI(); ancestorQueryBlocks.add(String.format(ancestorQueryBody, tipURI)); parentQueryBlocks.add(String.format(parentQueryBody, tipURI)); } final String ancestorQuery = String.format(ancestorQueryHead, StringUtils.join(ancestorQueryBlocks, " UNION ")); final String parentQuery = String.format(parentQueryHead, StringUtils.join(parentQueryBlocks, ", ")); QueryEngineHTTP ancestorQE = new QueryEngineHTTP(endpoint, ancestorQuery); QueryEngineHTTP parentQE = new QueryEngineHTTP(endpoint, parentQuery); ancestorQE.execConstruct(model); ancestorQE.close(); parentQE.execConstruct(model); parentQE.close(); } this.processNode(Vocab.TaxonomyRoot, model, output.getModel(), null, output); output.getModel().setNsPrefix("cdao", "http://www.evolutionaryontology.org/cdao/1.0/cdao.owl#"); }
public static Offering addServiceFeatures(Resource service, Offering offering) { ArrayList<QualitativeFeature> qualFeatures = offering.getQualitativeFeatures(); ArrayList<QuantitativeFeature> quantFeatures = offering.getQuantitativeFeatures(); /*//adding the offering provider if(service.hasProperty(hasProvider)){ Resource provider = service.getPropertyResourceValue(hasProvider); if(provider.hasProperty(page)) offering.setURL(provider.getProperty(page).getString()); }*/ // get qualitativeFeatures StmtIterator iter = service.listProperties(qualitativeProductOrServiceProperty); // System.out.println(iter.toList().size()); while (iter.hasNext()) { Resource feature = iter.next().getObject().asResource(); qualFeatures.addAll(convertQualitativeFeatures(feature)); } // get quantitative StmtIterator iter2 = service.listProperties(quantitativeProductOrServiceProperty); // System.out.println(iter.toList().size()); while (iter2.hasNext()) { Resource feature = iter2.next().getObject().asResource(); quantFeatures.addAll(convertQuantitativeFeatures(feature)); } return offering; }
@Test public void testPresentTotalCount() throws URISyntaxException { Integer totalResults = new Integer(17); Resource thisMetaPage = createMetadata(true, totalResults); Literal tr = thisMetaPage.getModel().createTypedLiteral(totalResults); assertTrue(thisMetaPage.hasProperty(OpenSearch.totalResults, tr)); }
private static boolean hasPermission( String userPrefix, String username, String uri, Property[] permissions) { Set<Property> permissionSet = new HashSet<Property>(); Resource resource = configModel.createResource(uri); Resource user; if (username == null) user = PERM.Public; else user = configModel.createResource(userPrefix + username); for (Property permission : permissions) { if (configModel.contains(user, permission, resource)) return true; permissionSet.add(permission); } StmtIterator stmts = user.listProperties(); while (stmts.hasNext()) { Statement stmt = stmts.next(); if (!permissionSet.contains(stmt.getPredicate())) continue; RDFNode resourceMatch = stmt.getObject(); if (!(resourceMatch.isResource() && configModel.contains((Resource) resourceMatch, RDF.type, PERM.ResourceMatch))) continue; RDFNode matchRegex = ((Resource) resourceMatch).getProperty(PERM.matchExpression).getObject(); if (matchRegex == null || !matchRegex.isLiteral()) continue; try { if (uri.matches(((Literal) matchRegex).getString())) return true; } catch (PatternSyntaxException e) { } } if (username != null) return hasPermission(userPrefix, null, uri, permissions); else return false; }
private static void extractList(List<String> output, Resource head) { if (head.hasProperty(RDF.first)) output.add(head.getProperty(RDF.first).getObject().asLiteral().getString()); if (head.hasProperty(RDF.rest)) extractList(output, head.getProperty(RDF.rest).getObject().asResource()); }
public Property getRelationshipProperty(Resource relationship) { if (_model.contains(relationship, Vertere.property)) { Resource resource = _model.getProperty(relationship, Vertere.property).getResource(); return ResourceFactory.createProperty(resource.getURI()); } else { return null; } }
private static QualitativeFeature convertQualitativeFeature(Resource r, String attributeType) { QualitativeFeature qf = new QualitativeFeature(); qf.setType(QUAL_FEATURE.get(attributeType)); if (r.hasProperty(comment)) qf.setDescription(r.getProperty(comment).getString()); if (r.hasProperty(name)) qf.setName(r.getProperty(name).getString()); return qf; }
/** Adds a random Observable to any Activities that are missing Observables */ public void fillInObservables() { for (Resource r : process.getActivities()) { if (process.getObservables(r).size() < 1) { String obsUri = String.format("%1$s_OBSERVABLE", r.getURI()); addObservable(r, createObservable(obsUri)); } } }
public static Resource createFigure(OntModel model, Resource creator, String title) { // Anonymous figure node Resource figure = model.createResource(); figure.addProperty(RDF.type, QualiPSoDOC.Figure); figure.addProperty(QualiPSoDOC.title, title); figure.addProperty(QualiPSoDOC.creator, creator); return figure; }
/** * Index all the resources in a Jena Model to ES * * @param model the model to index * @param bulkRequest a BulkRequestBuilder * @param getPropLabel if set to true all URI property values will be indexed as their label. The * label is taken as the value of one of the properties set in {@link #uriDescriptionList}. */ private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) { long startTime = System.currentTimeMillis(); long bulkLength = 0; HashSet<Property> properties = new HashSet<Property>(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement st = it.nextStatement(); Property prop = st.getPredicate(); String property = prop.toString(); if (rdfPropList.isEmpty() || (isWhitePropList && rdfPropList.contains(property)) || (!isWhitePropList && !rdfPropList.contains(property)) || (normalizeProp.containsKey(property))) { properties.add(prop); } } ResIterator resIt = model.listSubjects(); while (resIt.hasNext()) { Resource rs = resIt.nextResource(); Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel); bulkRequest.add( client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap))); bulkLength++; // We want to execute the bulk for every DEFAULT_BULK_SIZE requests if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) { BulkResponse bulkResponse = bulkRequest.execute().actionGet(); // After executing, flush the BulkRequestBuilder. bulkRequest = client.prepareBulk(); if (bulkResponse.hasFailures()) { processBulkResponseFailure(bulkResponse); } } } // Execute remaining requests if (bulkRequest.numberOfActions() > 0) { BulkResponse response = bulkRequest.execute().actionGet(); // Handle failure by iterating through each bulk response item if (response.hasFailures()) { processBulkResponseFailure(response); } } // Show time taken to index the documents logger.info( "Indexed {} documents on {}/{} in {} seconds", bulkLength, indexName, typeName, (System.currentTimeMillis() - startTime) / 1000.0); }
@Test public void testSave() throws BadRequestException { folderResourceMap.save(); Model model = ModelFactory.createDefaultModel(); model.read(folderResourceMap.getGraphAsInputStream(RDFFormat.RDFXML), null); Resource r = model.getResource(folderResourceMap.getUri().toString()); Assert.assertTrue(r.hasProperty(ORE.describes, model.getResource(folder.getUri().toString()))); Assert.assertTrue(r.hasProperty(RDF.type, ORE.ResourceMap)); }
/** * Returns the main rdf:type of the given Thing. * * @param t is thing object * @return URI reference of value for rdf:type property */ public static String getClosestRDFType(Thing t) { try { Class clazz = t.getClass(); Resource r = (Resource) clazz.getField("TYPE").get(t); return r.getURI(); } catch (Exception e) { throw new RuntimeException(e); } }
public RDFDatatype getDatatype(Resource attribute) { if (_model.contains(attribute, Vertere.datatype)) { Resource resource = _model.getProperty(attribute, Vertere.datatype).getResource(); RDFDatatype datatype = new BaseDatatype(resource.getURI()); return datatype; } else { return null; } }
/** * Create a new RDF folder resource * * @param model * @param uri * @param title * @param description * @param creator * @return the new created resource */ public static Resource createFolder( OntModel model, String uri, String title, String description, Resource creator) { Resource folder = model.createResource(uri); folder.addProperty(RDF.type, QualiPSoDOC.Folder); folder.addProperty(QualiPSoDOC.title, title); folder.addProperty(QualiPSoDOC.description, description); folder.addProperty(QualiPSoDOC.creator, creator); return folder; }