문제

I have a string message from an AMQP message broker that consists of RDF statements. I want to covert it into a Jena model using Java and then merge the converted model with another one into single model. How can I do this?

도움이 되었습니까?

해결책

This can be divided into three logical steps. Some of these, you may have already done:

  1. Isolate the RDF statements from non-rdf text
  2. Identify the syntax used for the RDF (can be part of #1)
  3. Parse the resulting string into an Apache Jena Model.

As the first two are domain-specific, you will not likely find much help here unless you can provide some example input. Additionally, that would likely be considered a separate question (eg: 'how can I partition a string based on presence of RDF syntax?')

For the third, it's extremely quick and easy to do. Let us assume that you have a document in the N-Triples Format that you have extracted from the rest of your text. The following JUnit test demonstrates the ability to parse that and interact with its content.

final String nTriplesDoc = "<urn:ex:s> <urn:ex:p> <urn:ex:o> . ";

final Model model = ModelFactory.createDefaultModel();
try( final InputStream in = new ByteArrayInputStream(nTriplesDoc.getBytes("UTF-8")) ) {
    /* Naturally, you'd substitute the syntax of your actual
     * content here rather than use N-TRIPLE.
     */
    model.read(in, null, "N-TRIPLE");
}

final Resource s = ResourceFactory.createResource("urn:ex:s");
final Property p = ResourceFactory.createProperty("urn:ex:p");
final Resource o = ResourceFactory.createResource("urn:ex:o");
assertTrue( model.contains(s,p,o) );

Edit/Part II

After seeing your comment, I felt it prudent to add another note regarding the merging of models. In Jena, you can merge models by adding all of their triples together. This can create some leftover models that end up being garbage collected, which may not necessarily be the best scenario for your system.

final Model model0 = ModelFactory.create();
// Add things to model 0...
final Model model1 = ModelFactory.create();
// Add things to model 1...

final Model merger = ModelFactory.create();
merger.add(model0);
merger.add(model1);

In this example, the two source models now need collecting. It would be wise to either use one of the existing models as the destination for all the triples, or to create a model of the union of the two underlying graphs (resulting in both graphs being re-used):

final Model union = ModelFactory.createModelForGraph( new Union(model0.getGraph(), model1.getGraph()) );

I also leave an assumption in place that you are able to get String objects from your AMQP server, so that #3 from the first half of this answer is still relevant to your scenario.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top