org.openrdf.model.Graph Java Examples

The following examples show how to use org.openrdf.model.Graph. 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: QueryEvaluation.java    From CostFed with GNU Affero General Public License v3.0 7 votes vote down vote up
protected Graph parseConfig(File file) throws SailConfigException, IOException {

        RDFFormat format = Rio.getParserFormatForFileName(file.getAbsolutePath());
        if (format==null)
            throw new SailConfigException("Unsupported file format: " + file.getAbsolutePath());
        RDFParser parser = Rio.createParser(format);
        Graph model = new GraphImpl();
        parser.setRDFHandler(new StatementCollector(model));
        InputStream stream = new FileInputStream(file);

        try {
            parser.parse(stream, file.getAbsolutePath());
        } catch (Exception e) {
            throw new SailConfigException("Error parsing file!");
        }

        stream.close();
        return model;
    }
 
Example #2
Source File: BigdataRepositoryConfig.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void parse(Graph graph, Resource implNode)
	throws RepositoryConfigException
{
	super.parse(graph, implNode);

	try {
		Literal propertiesLit = GraphUtil.getOptionalObjectLiteral(
                   graph, implNode, BigdataConfigSchema.PROPERTIES);
		if (propertiesLit != null) {
			setPropertiesFile((propertiesLit).getLabel());
		} else {
               throw new RepositoryConfigException("Properties file required");
           }
	}
	catch (GraphUtilException e) {
		throw new RepositoryConfigException(e.getMessage(), e);
	}
}
 
Example #3
Source File: BigdataSailConfig.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void parse(Graph graph, Resource implNode)
	throws SailConfigException
{
	super.parse(graph, implNode);

	try {
		Literal propertiesLit = GraphUtil.getOptionalObjectLiteral(
                   graph, implNode, BigdataConfigSchema.PROPERTIES);
		if (propertiesLit != null) {
			setPropertiesFile((propertiesLit).getLabel());
		} else {
               throw new SailConfigException("Properties file required");
           }
	}
	catch (GraphUtilException e) {
		throw new SailConfigException(e.getMessage(), e);
	}
}
 
Example #4
Source File: EntityTypeSerializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private void serializePropertyTypes( final EntityDescriptor entityDescriptor,
                                     final Graph graph,
                                     final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();

    // Properties
    entityDescriptor.state().properties().forEach( persistentProperty -> {
        URI propertyURI = values.createURI( persistentProperty.qualifiedName().toURI() );
        graph.add( propertyURI, Rdfs.DOMAIN, entityTypeUri );
        graph.add( propertyURI, Rdfs.TYPE, Rdfs.PROPERTY );

        // TODO Support more types
        URI type = dataTypes.get( persistentProperty.valueType().primaryType().getName() );
        if( type != null )
        {
            graph.add( propertyURI, Rdfs.RANGE, type );
        }
    } );
}
 
Example #5
Source File: EntityTypeSerializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private void serializeAssociationTypes( final EntityDescriptor entityDescriptor,
                                        final Graph graph,
                                        final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();
    // Associations
    entityDescriptor.state().associations().forEach( associationType -> {
        URI associationURI = values.createURI( associationType.qualifiedName().toURI() );
        graph.add( associationURI, Rdfs.DOMAIN, entityTypeUri );
        graph.add( associationURI, Rdfs.TYPE, Rdfs.PROPERTY );

        URI associatedURI = values.createURI( Classes.toURI( Classes.RAW_CLASS.apply( associationType.type() ) ) );
        graph.add( associationURI, Rdfs.RANGE, associatedURI );
        graph.add( associationURI, Rdfs.RANGE, XMLSchema.ANYURI );
    } );
}
 
Example #6
Source File: EntityTypeSerializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private void serializeManyAssociationTypes( final EntityDescriptor entityDescriptor,
                                            final Graph graph,
                                            final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();
    // ManyAssociations
    entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> {
        URI associationURI = values.createURI( manyAssociationType.qualifiedName().toURI() );
        graph.add( associationURI, Rdfs.DOMAIN, entityTypeUri );

        graph.add( associationURI, Rdfs.TYPE, Rdfs.SEQ );

        URI associatedURI = values.createURI( manyAssociationType.qualifiedName().toURI() );
        graph.add( associationURI, Rdfs.RANGE, associatedURI );
        graph.add( associationURI, Rdfs.RANGE, XMLSchema.ANYURI );
    } );
}
 
Example #7
Source File: EntityTypeSerializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public Iterable<Statement> serialize( final EntityDescriptor entityDescriptor )
{
    Graph graph = new GraphImpl();
    ValueFactory values = graph.getValueFactory();
    URI entityTypeUri = values.createURI( Classes.toURI( entityDescriptor.types().findFirst().orElse( null ) ) );

    graph.add( entityTypeUri, Rdfs.TYPE, Rdfs.CLASS );
    graph.add( entityTypeUri, Rdfs.TYPE, OWL.CLASS );

    graph.add( entityTypeUri,
               PolygeneEntityType.TYPE,
               values.createLiteral( entityDescriptor.types().findFirst().get().toString() )
    );
    graph.add( entityTypeUri, PolygeneEntityType.QUERYABLE, values.createLiteral( entityDescriptor.queryable() ) );

    serializeMixinTypes( entityDescriptor, graph, entityTypeUri );

    serializePropertyTypes( entityDescriptor, graph, entityTypeUri );
    serializeAssociationTypes( entityDescriptor, graph, entityTypeUri );
    serializeManyAssociationTypes( entityDescriptor, graph, entityTypeUri );

    return graph;
}
 
Example #8
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
* Sets up a simple data set on the server.
* 
* @throws Exception
*/
protected void setupDataOnServer() throws Exception {
    
    final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
    final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
    final URI person = new URIImpl(BD.NAMESPACE + "Person");
    final URI likes = new URIImpl(BD.NAMESPACE + "likes");
    final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
    final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");
    final Literal label1 = new LiteralImpl("Mike");
    final Literal label2 = new LiteralImpl("Bryan");

  {
     final Graph g = new LinkedHashModel();
     g.add(mike, RDF.TYPE, person);
     g.add(mike, likes, rdf);
     g.add(mike, RDFS.LABEL, label1);
     g.add(bryan, RDF.TYPE, person);
     g.add(bryan, likes, rdfs);
     g.add(bryan, RDFS.LABEL, label2);

     m_repo.add(new AddOp(g));
  }

}
 
Example #9
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
  protected void doInsertWithBodyTest(final String method, final int ntriples,
          /*final String servlet,*/ final RDFFormat format) throws Exception {

      final Graph g = genNTRIPLES2(ntriples);
      cxn.add(g);
      assertEquals(ntriples, getExactSize());
      
// Verify the expected #of statements in the store.
{
	final String queryStr = "select * where {?s ?p ?o}";
	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	assertEquals(ntriples, countResults(query.evaluate()));
}

  }
 
Example #10
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void test_INSERT_triples_with_BODY_and_defaultContext()
        throws Exception {

    if(TestMode.quads != getTestMode())
        return;

    final String resource = packagePath
            + "insert_triples_with_defaultContext.ttl";

    final Graph g = loadGraphFromResource(resource);

    // Load the resource into the KB.
    doInsertByBody("POST", RDFFormat.TURTLE, g, new URIImpl(
            "http://example.org"));
    
    // Verify that the data were inserted into the appropriate context.
    {
    	final String queryStr = "select * { GRAPH <http://example.org> {?s ?p ?p} }";
    	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		assertEquals(7, countResults(query.evaluate()));
    }

}
 
Example #11
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private void serializeProperties( EntityState entityState,
                                  Graph graph, Resource subject,
                                  EntityDescriptor entityType,
                                  boolean includeNonQueryable )
{
    // Properties
    entityType.state().properties().forEach(
        persistentProperty ->
        {
            Object property = entityState.propertyValueOf( persistentProperty.qualifiedName() );
            if( property != null )
            {
                serializeProperty( persistentProperty, property, subject, graph, includeNonQueryable );
            }
        } );
}
 
Example #12
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
     * Reads a resource and sends it using an INSERT with BODY request to be
     * loaded into the database.
     * 
     * @param method
     * @param servlet
     * @param resource
     * @return
     * @throws Exception
     */
    protected long doInsertByBody(final String method,
            /*final String servlet,*/ final RDFFormat rdfFormat, final Graph g,
            final URI defaultContext) throws Exception {

        final byte[] wireData = writeOnBuffer(rdfFormat, g);

//        final RemoteRepository repo = new RemoteRepository(m_serviceURL);
        final AddOp add = new AddOp(wireData, rdfFormat);
        if (defaultContext != null)
        	add.setContext(defaultContext);
        return m_repo.add(add);

    }
 
Example #13
Source File: ApplicationSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public Graph serialize( Application app )
{
    Graph graph = new GraphImpl();
    SerializerContext context = new SerializerContext( graph );
    ApplicationVisitor applicationVisitor = new ApplicationVisitor( context );
    app.descriptor().accept( applicationVisitor );
    return graph;
}
 
Example #14
Source File: EntityTypeSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void serializeMixinTypes( final EntityDescriptor entityDescriptor,
                                  final Graph graph,
                                  final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();

    entityDescriptor.mixinTypes().forEach( mixinType -> {
        graph.add( entityTypeUri, Rdfs.SUB_CLASS_OF, values.createURI( Classes.toURI( mixinType ) ) );
    } );
}
 
Example #15
Source File: BigdataRepositoryConfig.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource export(Graph graph)
{
	Resource implNode = super.export(graph);

	if (propertiesFile != null) {
		graph.add(implNode, BigdataConfigSchema.PROPERTIES, 
                   graph.getValueFactory().createLiteral(propertiesFile));
	}

	return implNode;
}
 
Example #16
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void serializeAssociations( final EntityState entityState,
                                    final Graph graph, URI entityUri,
                                    final Stream<? extends AssociationDescriptor> associations,
                                    final boolean includeNonQueryable
)
{
    ValueFactory values = graph.getValueFactory();

    // Associations
    associations.filter( type -> includeNonQueryable || type.queryable() ).forEach(
        associationType ->
        {
            EntityReference associatedId
                = entityState
                .associationValueOf(
                    associationType
                        .qualifiedName() );
            if( associatedId != null )
            {
                URI assocURI = values
                    .createURI(
                        associationType
                            .qualifiedName()
                            .toURI() );
                URI assocEntityURI
                    = values.createURI(
                    associatedId
                        .toURI() );
                graph.add( entityUri,
                           assocURI,
                           assocEntityURI );
            }
        } );
}
 
Example #17
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void serializeProperty( PropertyDescriptor persistentProperty, Object property,
                                Resource subject, Graph graph,
                                boolean includeNonQueryable )
{
    if( !( includeNonQueryable || persistentProperty.queryable() ) )
    {
        return; // Skip non-queryable
    }

    ValueType valueType = persistentProperty.valueType();

    final ValueFactory valueFactory = graph.getValueFactory();

    String propertyURI = persistentProperty.qualifiedName().toURI();
    URI predicate = valueFactory.createURI( propertyURI );
    String baseURI = propertyURI.substring( 0, propertyURI.indexOf( '#' ) ) + "/";

    if( valueType instanceof ValueCompositeType )
    {
        serializeValueComposite( subject, predicate, (ValueComposite) property, valueType,
                                 graph, baseURI, includeNonQueryable );
    }
    else
    {
        String stringProperty = serializer.serialize( Serializer.Options.NO_TYPE_INFO, property );
        final Literal object = valueFactory.createLiteral( stringProperty );
        graph.add( subject, predicate, object );
    }
}
 
Example #18
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public void serialize( final EntityState entityState,
                       final boolean includeNonQueryable,
                       final Graph graph
)
{
    ValueFactory values = graph.getValueFactory();
    EntityReference reference = entityState.entityReference();
    URI entityUri = createEntityURI( values, reference );

    graph.add( entityUri,
               Rdfs.TYPE,
               values.createURI(
                   Classes.toURI( entityState.entityDescriptor().types().findFirst().orElse( null ) ) ) );

    serializeProperties( entityState,
                         graph,
                         entityUri,
                         entityState.entityDescriptor(),
                         includeNonQueryable );

    serializeAssociations( entityState,
                           graph,
                           entityUri,
                           entityState.entityDescriptor().state().associations(),
                           includeNonQueryable );

    serializeManyAssociations( entityState,
                               graph,
                               entityUri,
                               entityState.entityDescriptor().state().manyAssociations(),
                               includeNonQueryable );
}
 
Example #19
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public Iterable<Statement> serialize( final EntityState entityState,
                                      final boolean includeNonQueryable
)
{
    Graph graph = new GraphImpl();
    serialize( entityState, includeNonQueryable, graph );
    return graph;
}
 
Example #20
Source File: RdfIndexerService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void indexEntityState( final EntityState entityState,
                               final RepositoryConnection connection
)
    throws RepositoryException
{
    if( entityState.entityDescriptor().queryable() )
    {
        EntityReference reference = entityState.entityReference();
        final URI entityURI = stateSerializer.createEntityURI( getValueFactory(), reference);
        Graph graph = new GraphImpl();
        stateSerializer.serialize( entityState, false, graph );
        connection.add( graph, entityURI );
    }
}
 
Example #21
Source File: Test_REST_ServiceDescription.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
	 * Request the SPARQL SERVICE DESCRIPTION for the end point.
	 */
	public void test_SERVICE_DESCRIPTION() throws Exception {

		final Graph g = RemoteRepository
				.asGraph(m_repo.getServiceDescription());

		final ValueFactory f = g.getValueFactory();

		// Verify the end point is disclosed.
		assertEquals(
				1,
				countMatches(g, null/* service */, SD.endpoint,
						f.createURI(m_repo.getSparqlEndPoint())));
//		            f.createURI(m_serviceURL + "/sparql")));

		// Verify description includes supported query and update languages.
		assertEquals(
				1,
				countMatches(g, null/* service */, SD.supportedLanguage,
						SD.SPARQL10Query));
		assertEquals(
				1,
				countMatches(g, null/* service */, SD.supportedLanguage,
						SD.SPARQL11Query));
		assertEquals(
				1,
				countMatches(g, null/* service */, SD.supportedLanguage,
						SD.SPARQL11Update));

		// Verify support for Basic Federated Query is disclosed.
		assertEquals(
				1,
				countMatches(g, null/* service */, SD.feature,
						SD.BasicFederatedQuery));

	}
 
Example #22
Source File: BigdataSailConfig.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource export(Graph graph)
{
	Resource implNode = super.export(graph);

	if (propertiesFile != null) {
		graph.add(implNode, BigdataConfigSchema.PROPERTIES, 
                   graph.getValueFactory().createLiteral(propertiesFile));
	}

	return implNode;
}
 
Example #23
Source File: ObjectRepositoryConfig.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private void exportAssocation(Resource subj, Map<Class<?>, List<URI>> assocation,
		URI relation, Graph model) {
	ValueFactory vf = ValueFactoryImpl.getInstance();
	for (Map.Entry<Class<?>, List<URI>> e : assocation.entrySet()) {
		URI name = vf.createURI(JAVA_NS, e.getKey().getName());
		model.add(subj, relation, name);
		if (e.getValue() != null) {
			for (URI value : e.getValue()) {
				model.add(name, KNOWN_AS, value);
			}
		}
	}
}
 
Example #24
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void doConstructTest(final String method, final RDFFormat format)
            throws Exception {
        
        setupDataOnServer();
        final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
        final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
        final URI person = new URIImpl(BD.NAMESPACE + "Person");

        // The expected results.
        final Graph expected = new LinkedHashModel();
        {
//            expected.add(new StatementImpl(mike, likes, rdf));
            expected.add(new StatementImpl(mike, RDF.TYPE, person));
            expected.add(new StatementImpl(bryan, RDF.TYPE, person));
//            expected.add(new StatementImpl(mike, RDFS.LABEL, label1));
        }
        
        // Run the query and verify the results.
        {

            final String queryStr =
                "prefix bd: <"+BD.NAMESPACE+"> " +//
                "prefix rdf: <"+RDF.NAMESPACE+"> " +//
                "prefix rdfs: <"+RDFS.NAMESPACE+"> " +//
                "CONSTRUCT { ?x rdf:type bd:Person }" +//
                "WHERE { " +//
                "  ?x rdf:type bd:Person . " +//
//                "  ?x bd:likes bd:RDF " +//
                "}";

            final IPreparedGraphQuery query = m_repo.prepareGraphQuery(queryStr);

//            final Graph actual = asGraph(query.evaluate());

            assertSameGraph(expected, query);
            
        }
    
    }
 
Example #25
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test of insert and retrieval of a large literal.
 */
public void test_INSERT_veryLargeLiteral() throws Exception {

    final Graph g = new LinkedHashModel();
    
    final URI s = new URIImpl("http://www.bigdata.com/");
    final URI p = RDFS.LABEL;
    final Literal o = getVeryLargeLiteral();
    final Statement stmt = new StatementImpl(s, p, o);
    g.add(stmt);
    
    // Load the resource into the KB.
    assertEquals(
            1L,
            doInsertByBody("POST", RDFFormat.RDFXML, g, null/* defaultContext */));

    // Read back the data into a graph.
    final Graph g2;
    {
        final String queryStr = "DESCRIBE <" + s.stringValue() + ">";
        final GraphQuery query = cxn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
        g2 = asGraph(query.evaluate());
        
    }
    
    assertEquals(1, g2.size());
    
    assertTrue(g2.match(s, p, o).hasNext());
    
}
 
Example #26
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets up a simple data set on the server.
* @throws Exception 
 */
protected void setupQuadsDataOnServer() throws Exception {
    
    final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
    final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
    final URI person = new URIImpl(BD.NAMESPACE + "Person");
    final URI likes = new URIImpl(BD.NAMESPACE + "likes");
    final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
    final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");
    final URI c1 = new URIImpl(BD.NAMESPACE + "c1");
    final URI c2 = new URIImpl(BD.NAMESPACE + "c2");
    final URI c3 = new URIImpl(BD.NAMESPACE + "c3");
    final Literal label1 = new LiteralImpl("Mike");
    final Literal label2 = new LiteralImpl("Bryan");

  {
     final Graph g = new LinkedHashModel();
     g.add(mike, RDF.TYPE, person, c1, c2, c3);
     g.add(mike, likes, rdf, c1, c2, c3);
     g.add(mike, RDFS.LABEL, label1, c1, c2, c3);
     g.add(bryan, RDF.TYPE, person, c1, c2, c3);
     g.add(bryan, likes, rdfs, c1, c2, c3);
     g.add(bryan, RDFS.LABEL, label2, c1, c2, c3);
     m_repo.add(new AddOp(g));
  }

}
 
Example #27
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return the statements matching the triple pattern.
 */
static protected Statement[] getMatches(final Graph g, final Resource s,
        final URI p, final Value o) {

    final List<Statement> out = new LinkedList<Statement>();

    final Iterator<Statement> itr = g.match(s, p, o);

    while (itr.hasNext()) {

        out.add(itr.next());

    }

    return out.toArray(new Statement[out.size()]);

}
 
Example #28
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
protected Graph genNTRIPLES2(final int ntriples)
		throws RDFHandlerException {

	final Graph g = new LinkedHashModel();

	final ValueFactory f = new ValueFactoryImpl();

	final URI s = f.createURI("http://www.bigdata.org/b");

	final URI rdfType = f
			.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");

	for (int i = 0; i < ntriples; i++) {

		final URI o = f.createURI("http://www.bigdata.org/c#" + i);

		g.add(s, rdfType, o);

	}
	
	return g;

}
 
Example #29
Source File: BigdataRDFServlet.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Send an RDF Graph as a response using content negotiation.
     * 
     * @param req
     * @param resp
     */
    static public void sendGraph(final HttpServletRequest req,
            final HttpServletResponse resp, final Graph g) throws IOException {
        /*
         * CONNEG for the MIME type.
         */
        final List<String> acceptHeaders = Collections.list(req.getHeaders("Accept"));
		final String acceptStr = ConnegUtil.getMimeTypeForQueryParameterQueryRequest(req
				.getParameter(BigdataRDFServlet.OUTPUT_FORMAT_QUERY_PARAMETER),
				acceptHeaders.toArray(new String[acceptHeaders.size()])); 
		
        final ConnegUtil util = new ConnegUtil(acceptStr);

        // The best RDFFormat for that Accept header.
        RDFFormat format = util.getRDFFormat();

        if (format == null)
            format = RDFFormat.RDFXML;

		RDFWriterFactory writerFactory = RDFWriterRegistry.getInstance().get(
				format);

		if (writerFactory == null) {

			if (log.isDebugEnabled()) {
				log.debug("No writer for format: format=" + format
						+ ", Accept=\"" + acceptStr + "\"");
			}

			format = RDFFormat.RDFXML;
			
			writerFactory = RDFWriterRegistry.getInstance().get(format);
			
		}

//        if (writerFactory == null) {
//
//			buildResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
//					"No writer for format: Accept=\"" + acceptStr
//							+ "\", format=" + format);
//			
//			return;
//
//		}
		
        resp.setStatus(HTTP_OK);

        resp.setContentType(format.getDefaultMIMEType());

        final OutputStream os = resp.getOutputStream();
        try {
            final RDFWriter writer = writerFactory.getWriter(os);
            writer.startRDF();
            final Iterator<Statement> itr = g.iterator();
            while (itr.hasNext()) {
                final Statement stmt = itr.next();
                writer.handleStatement(stmt);
            }
            writer.endRDF();
            os.flush();
        } catch (RDFHandlerException e) {
        	// wrap and rethrow. will be handled by launderThrowable().
            throw new IOException(e);
        } finally {
            os.close();
        }
    }
 
Example #30
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @deprecated by {@link #asGraph(IPreparedGraphQuery)} which can ensure that
 *             the {@link GraphQueryResult} is closed.
 */
static protected Graph asGraph(final GraphQueryResult result) throws Exception {

   try {
      final Graph g = new LinkedHashModel();

      while (result.hasNext()) {

         g.add(result.next());

      }

      return g;
   } finally {
      result.close();
   }

}