Java Code Examples for com.hp.hpl.jena.rdf.model.Model#getResource()

The following examples show how to use com.hp.hpl.jena.rdf.model.Model#getResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassMapServlet.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	if (request.getPathInfo() == null) {
		new ModelResponse(classMapListModel(), request, response).serve();
		return;
	}
	String classMapName = request.getPathInfo().substring(1);
	Model resourceList = server.getMapping().getResourceCollection(classMapName).getInventoryModel();
	if (resourceList == null) {
		response.sendError(404, "Sorry, class map '" + classMapName + "' not found.");
		return;
	}
   	Resource classMap = resourceList.getResource(server.baseURI() + "all/" + classMapName);
   	Resource directory = resourceList.createResource(server.baseURI() + "all");
   	classMap.addProperty(RDFS.seeAlso, directory);
   	classMap.addProperty(RDFS.label, "List of all instances: " + classMapName);
   	directory.addProperty(RDFS.label, "D2R Server contents");
   	server.addDocumentMetadata(resourceList, classMap);
	new ModelResponse(resourceList, request, response).serve();
}
 
Example 2
Source File: RdfGeneratorTest2.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Test
    // Run test_discoverMapping_fb_XBRL to generate the mapping file before running
    // this test.
    public void test_generateRdfs_fb_XBRL() throws SAXException, IOException, ParserConfigurationException {
        // Setup deserializer
        mappingDeserialization = new XmlBasedMappingDeserialization(
                new FileInputStream("output/fb-20121231-mapping.xml"), parser);

        Document dataDocument = parser.parse(RdfGeneratorTest2.class.getResourceAsStream(
                "/secxbrls/data/fb-20121231.xml"), -1);
        rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

        // Add steps
        rdfGenerator.addStep(mappingDeserialization);
        rdfGenerator.addStep(rdfGeneration);

        // Generate
        rdfGenerator.generateRdfs();

        // Verify
        Model model = TDBFactory.createModel(testTdbDir);
        Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

        Resource r = model.getResource("http://example.org/resource/class/unitNumerator");
        // Failing, investigate
        Assert.assertTrue(r.hasProperty(model.getProperty("http://example.org/resource/property/measure")));

//    ResIterator iter = model.listResourcesWithProperty(RDF.type);
//    while (iter.hasNext()) {
//      Resource resource = iter.nextResource();
//      System.out.println(resource.getLocalName());
//      StmtIterator iterStm = resource.listProperties();
//      while (iterStm.hasNext()) {
//        System.out.println(iterStm.nextStatement().toString());
//      }
//    }
    }
 
Example 3
Source File: RdfGeneratorTest2.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Test
    // Run test_discoverMapping_XBRL_msft to generate the mapping file before running
    // this test.
    public void test_generateRdfs_msft_XBRL() throws SAXException, IOException, ParserConfigurationException {
        // Setup deserializer
        mappingDeserialization = new XmlBasedMappingDeserialization(
                new FileInputStream("output/msft-20130630-mapping.xml"), parser);

        Document dataDocument = parser.parse(RdfGeneratorTest2.class.getResourceAsStream(
                "/secxbrls/data/msft-20130630.xml"), -1);
        rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

        // Add steps
        rdfGenerator.addStep(mappingDeserialization);
        rdfGenerator.addStep(rdfGeneration);

        // Generate
        rdfGenerator.generateRdfs();

        // Verify
        Model model = TDBFactory.createModel(testTdbDir);
        Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

        Resource r = model.getResource("http://example.org/resource/class/unitNumerator");
        // Failing, investigate
        Assert.assertTrue(r.hasProperty(model.getProperty("http://example.org/resource/property/measure")));

//    ResIterator iter = model.listResourcesWithProperty(RDF.type);
//    while (iter.hasNext()) {
//      Resource resource = iter.nextResource();
//      System.out.println(resource.getLocalName());
//      StmtIterator iterStm = resource.listProperties();
//      while (iterStm.hasNext()) {
//        System.out.println(iterStm.nextStatement().toString());
//      }
//    }
    }
 
Example 4
Source File: RdfGeneratorTest.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Test
    // Run test_discoverMapping_fb_XBRL to generate the mapping file before running
    // this test.
    public void test_generateRdfs_fb_XBRL() throws SAXException, IOException, ParserConfigurationException {
        // Setup deserializer
        mappingDeserialization = new XmlBasedMappingDeserialization(
                new FileInputStream("output/fb-20121231-mapping.xml"), parser);

        Document dataDocument = parser.parse(RdfGeneratorTest.class.getResourceAsStream(
                "/secxbrls/data/fb-20121231.xml"), -1);
        rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

        // Add steps
        rdfGenerator.addStep(mappingDeserialization);
        rdfGenerator.addStep(rdfGeneration);

        // Generate
        rdfGenerator.generateRdfs();

        // Verify
        Model model = TDBFactory.createModel(testTdbDir);
        Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

        Resource r = model.getResource("http://example.org/resource/class/unitNumerator");
        // Failing, investigate
        Assert.assertTrue(r.hasProperty(model.getProperty("http://example.org/resource/property/measure")));

//    ResIterator iter = model.listResourcesWithProperty(RDF.type);
//    while (iter.hasNext()) {
//      Resource resource = iter.nextResource();
//      System.out.println(resource.getLocalName());
//      StmtIterator iterStm = resource.listProperties();
//      while (iterStm.hasNext()) {
//        System.out.println(iterStm.nextStatement().toString());
//      }
//    }
    }
 
Example 5
Source File: RdfGeneratorTest.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Test
    // Run test_discoverMapping_XBRL_msft to generate the mapping file before running
    // this test.
    public void test_generateRdfs_msft_XBRL() throws SAXException, IOException, ParserConfigurationException {
        // Setup deserializer
        mappingDeserialization = new XmlBasedMappingDeserialization(
                new FileInputStream("output/msft-20130630-mapping.xml"), parser);

        Document dataDocument = parser.parse(RdfGeneratorTest.class.getResourceAsStream(
                "/secxbrls/data/msft-20130630.xml"), -1);
        rdfGenerator = new RdfGenerator(new DataDocument(dataDocument), new XmlBasedMapping());

        // Add steps
        rdfGenerator.addStep(mappingDeserialization);
        rdfGenerator.addStep(rdfGeneration);

        // Generate
        rdfGenerator.generateRdfs();

        // Verify
        Model model = TDBFactory.createModel(testTdbDir);
        Assert.assertFalse("No RDF was generated. TDB directory: " + testTdbDir, model.isEmpty());

        Resource r = model.getResource("http://example.org/resource/class/unitNumerator");
        // Failing, investigate
        Assert.assertTrue(r.hasProperty(model.getProperty("http://example.org/resource/property/measure")));

//    ResIterator iter = model.listResourcesWithProperty(RDF.type);
//    while (iter.hasNext()) {
//      Resource resource = iter.nextResource();
//      System.out.println(resource.getLocalName());
//      StmtIterator iterStm = resource.listProperties();
//      while (iterStm.hasNext()) {
//        System.out.println(iterStm.nextStatement().toString());
//      }
//    }
    }
 
Example 6
Source File: PageServlet.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	String relativeResourceURI = request.getRequestURI().substring(
			request.getContextPath().length()
					+ request.getServletPath().length());
	// Some servlet containers keep the leading slash, some don't
	if (!"".equals(relativeResourceURI)
			&& "/".equals(relativeResourceURI.substring(0, 1))) {
		relativeResourceURI = relativeResourceURI.substring(1);
	}
	if (request.getQueryString() != null) {
		relativeResourceURI = relativeResourceURI + "?"
				+ request.getQueryString();
	}

	/* Determine service stem, i.e. vocab/ in /[vocab/]page */
	int servicePos;
	if (-1 == (servicePos = request.getServletPath().indexOf(
			"/" + D2RServer.getPageServiceName())))
		throw new ServletException("Expected to find service path /"
				+ D2RServer.getPageServiceName());
	String serviceStem = request.getServletPath().substring(1,
			servicePos + 1);

	String resourceURI = server.resourceBaseURI(serviceStem)
			+ relativeResourceURI;
	String documentURL = server.dataURL(serviceStem, relativeResourceURI);
	String pageURL = server.pageURL(serviceStem, relativeResourceURI);

	VelocityWrapper velocity = new VelocityWrapper(this, request, response);
	Context context = velocity.getContext();
	context.put("uri", resourceURI);

	// Build resource description
	Resource resource = ResourceFactory.createResource(resourceURI);
	boolean outgoingTriplesOnly = server.isVocabularyResource(resource)
			&& !server.getConfig().getVocabularyIncludeInstances();
	int limit = server.getConfig().getLimitPerPropertyBridge();
	Model description = null;
	try {
		ResourceDescriber describer = new ResourceDescriber(
				server.getMapping(), resource.asNode(), outgoingTriplesOnly,
				limit, Math.round(server.getConfig().getPageTimeout() * 1000));
		description = ModelFactory.createModelForGraph(describer.description());
	} catch (QueryCancelledException ex) {
		velocity.reportError(
				504, "504 Gateway Timeout", "The operation timed out.");
		return;
	}
	if (description.size() == 0) {
		velocity.reportError(404, "404 Not Found", "No resource with this identifier exists in the database.");
		return;
	}
	// Get a Resource that is attached to the description model
	resource = description.getResource(resourceURI);

	this.prefixes = server.getPrefixes(); // model();

	if (server.getConfig().serveMetadata()) {
		// create and add metadata to context
		MetadataCreator resourceMetadataCreator = new MetadataCreator(
				server, server.getConfig().getResourceMetadataTemplate(
						server, getServletContext()));

		Model metadata = resourceMetadataCreator.addMetadataFromTemplate(
				resourceURI, documentURL, pageURL);
		if (!metadata.isEmpty()) {
			List<Statement> mList = metadata.getResource(documentURL)
					.listProperties().toList();
			Collections.sort(mList, MetadataCreator.subjectSorter);
			context.put("metadata", mList);

			context.put("metadataroot", metadata.getResource(documentURL));

			// add prefixes to context
			Map<String, String> nsSet = metadata.getNsPrefixMap();
			nsSet.putAll(description.getNsPrefixMap());

			context.put("prefixes", nsSet.entrySet());
			context.put("renderedNodesMap",
					new HashMap<Resource, Boolean>());

			// add a empty map for keeping track of blank nodes aliases
			context.put("blankNodesMap", new HashMap<Resource, String>());
		} else {
			context.put("metadata", Boolean.FALSE);
		}
	} else {
		context.put("metadata", Boolean.FALSE);
	}

	context.put("rdf_link", documentURL);
	context.put("label", getBestLabel(resource));
	context.put("properties", collectProperties(description, resource));
	context.put("classmap_links", classmapLinks(resource));
	context.put("limit_per_property_bridge", limit > 0 ? limit : null);
	velocity.mergeTemplateXHTML("resource_page.vm");
}
 
Example 7
Source File: ResourceDescriptionServlet.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	String relativeResourceURI = request.getRequestURI().substring(
			request.getContextPath().length()
					+ request.getServletPath().length());
	// Some servlet containers keep the leading slash, some don't
	if (!"".equals(relativeResourceURI)
			&& "/".equals(relativeResourceURI.substring(0, 1))) {
		relativeResourceURI = relativeResourceURI.substring(1);
	}
	if (request.getQueryString() != null) {
		relativeResourceURI = relativeResourceURI + "?"
				+ request.getQueryString();
	}

	/* Determine service stem, i.e. vocab/ in /[vocab/]data */
	int servicePos;
	if (-1 == (servicePos = request.getServletPath().indexOf(
			"/" + D2RServer.getDataServiceName())))
		throw new ServletException("Expected to find service path /"
				+ D2RServer.getDataServiceName());
	String serviceStem = request.getServletPath().substring(1,
			servicePos + 1);

	String resourceURI = RequestParamHandler
			.removeOutputRequestParam(server.resourceBaseURI(serviceStem)
					+ relativeResourceURI);
	String documentURL = server.dataURL(serviceStem, relativeResourceURI);

	String pageURL = server.pageURL(serviceStem, relativeResourceURI);

	String sparqlQuery = "DESCRIBE <" + resourceURI + ">";
	QueryExecution qe = QueryExecutionFactory.create(sparqlQuery,
			server.dataset());
	if (server.getConfig().getPageTimeout() > 0) {
		qe.setTimeout(Math.round(server.getConfig().getPageTimeout() * 1000));
	}
	Model description = qe.execDescribe();
	qe.close();
	
	if (description.size() == 0) {
		response.sendError(404);
	}
	if (description.qnameFor(FOAF.primaryTopic.getURI()) == null
			&& description.getNsPrefixURI("foaf") == null) {
		description.setNsPrefix("foaf", FOAF.NS);
	}
	Resource resource = description.getResource(resourceURI);

	Resource document = description.getResource(documentURL);
	document.addProperty(FOAF.primaryTopic, resource);

	Statement label = resource.getProperty(RDFS.label);
	if (label != null) {
		document.addProperty(RDFS.label,
				"RDF Description of " + label.getString());
	}
	server.addDocumentMetadata(description, document);
	if (server.getConfig().serveMetadata()) {
		// add document metadata from template
		Model resourceMetadataTemplate = server.getConfig().getResourceMetadataTemplate(
				server, getServletContext());
		MetadataCreator resourceMetadataCreator = new MetadataCreator(
				server, resourceMetadataTemplate);
		description.add(resourceMetadataCreator.addMetadataFromTemplate(
				resourceURI, documentURL, pageURL));
		
		Map<String, String> descPrefixes = description.getNsPrefixMap();
		descPrefixes.putAll(resourceMetadataTemplate.getNsPrefixMap());
		description.setNsPrefixes(descPrefixes);
	}
	// TODO: Add a Content-Location header
	new ModelResponse(description, request, response).serve();
}