Java Code Examples for org.apache.jena.rdf.model.Model

The following examples show how to use org.apache.jena.rdf.model.Model. These examples are extracted from open source projects. 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 Project: RDFUnit   Source File: ComponentParameterWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource = ElementWriter.copyElementResourceInModel(componentParameter, model);

    // rdf:type sh:ComponentParameter
    resource.addProperty(RDF.type, SHACL.ParameterCls);

    // sh:path sh:argX
    resource.addProperty(SHACL.path, componentParameter.getPredicate()) ;

    //Optional
    if (componentParameter.isOptional()) {
        resource.addProperty(SHACL.optional, ResourceFactory.createTypedLiteral("true", XSDDatatype.XSDboolean)) ;
    }
    return resource;
}
 
Example 2
Source Project: tools   Source File: SPDXChecksum.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a resource from this SPDX Checksum
 * @param model
 * @return
 */
public Resource createResource(Model model) {
	this.model = model;
	Resource type = model.createResource(SpdxRdfConstants.SPDX_NAMESPACE +
			SpdxRdfConstants.CLASS_SPDX_CHECKSUM);
	Resource r = model.createResource(type);
	if (algorithm != null) {
		Property algProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE,
				SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM);
		r.addProperty(algProperty, this.algorithm);
	}
	if (this.value != null) {
		Property valueProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE);
		r.addProperty(valueProperty, this.value);
	}
	this.checksumNode = r.asNode();
	this.checksumResource = r;
	return r;
}
 
Example 3
Source Project: tools   Source File: TestSPDXDocument.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.spdx.rdfparser.SPDXDocument#setDocumentComment(java.lang.String)}.
 * @throws InvalidSPDXAnalysisException 
 * @throws IOException 
 */
@Test
public void testSetDocumentComment() throws InvalidSPDXAnalysisException, IOException {
	Model model = ModelFactory.createDefaultModel();
	SPDXDocument doc = new SPDXDocument(model);
	String testUri = "https://olex.openlogic.com/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&package_version_id=1082";
	doc.createSpdxAnalysis(testUri);
	String beforeComment = doc.getDocumentComment();
	if (beforeComment != null) {
		fail("Comment should not exist");
	}
	String COMMENT_STRING = "This is a comment";
	doc.setDocumentComment(COMMENT_STRING);
	String afterComment = doc.getDocumentComment();
	assertEquals(COMMENT_STRING, afterComment);
}
 
Example 4
Source Project: hypergraphql   Source File: SPARQLEndpointService.java    License: Apache License 2.0 6 votes vote down vote up
void iterateFutureResults (
        final Set<Future<SPARQLExecutionResult>> futureSPARQLResults,
        final Model unionModel,
        Map<String, Set<String>> resultSet
) {

    for (Future<SPARQLExecutionResult> futureExecutionResult : futureSPARQLResults) {
        try {
            SPARQLExecutionResult result = futureExecutionResult.get();
            unionModel.add(result.getModel());
            resultSet.putAll(result.getResultSet());
        } catch (InterruptedException
                | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
 
Example 5
Source Project: tools   Source File: TestSPDXDocument.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDataLicense() throws InvalidSPDXAnalysisException, InvalidLicenseStringException {
	Model model = ModelFactory.createDefaultModel();
	SPDXDocument doc = new SPDXDocument(model);
	String testDocUri = "https://olex.openlogic.com/spdxdoc/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&amp;package_version_id=1082";
	doc.createSpdxAnalysis(testDocUri);
	// check default
	SpdxListedLicense dataLicense = doc.getDataLicense();
	assertEquals(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID, dataLicense.getLicenseId());
	// check set correct license
	AnyLicenseInfo cc0License = LicenseInfoFactory.parseSPDXLicenseString(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID);
	doc.setDataLicense((SpdxListedLicense)cc0License);
	dataLicense = doc.getDataLicense();
	assertEquals(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID, dataLicense.getLicenseId());
	// check error when setting wrong license
	AnyLicenseInfo ngplLicense = LicenseInfoFactory.parseSPDXLicenseString("NGPL");
	try {
		doc.setDataLicense((SpdxListedLicense)ngplLicense);
		fail("Incorrect license allowed to be set for data license");
	} catch(InvalidSPDXAnalysisException e) {
		// expected - do nothing
	}
}
 
Example 6
Source Project: hypergraphql   Source File: SPARQLExecutionResultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void toString_should_produce_intelligible_results() {

    final Model model = ModelFactory.createDefaultModel();
    model.add(
            model.createStatement(
                    model.createResource("http://data.hypergraphql.org/resources/123456"),
                    model.createProperty("http://data.hypergraphql.org/ontology/", "name"),
                    model.createLiteral("Test", "en")
            )
    );

    final SPARQLExecutionResult result = new SPARQLExecutionResult(generateSimpleResultSet(), model);
    final String toString = result.toString();

    final String expectedToS = "RESULTS\nModel : \n" +
            "<ModelCom   {http://data.hypergraphql.org/resources/123456 " +
            "@http://data.hypergraphql.org/ontology/name \"Test\"@en} |  " +
            "[http://data.hypergraphql.org/resources/123456, http://data.hypergraphql.org/ontology/name, \"Test\"@en]>\n" +
            "ResultSet : \n{one=[1]}";

    assertEquals(expectedToS, toString);
}
 
Example 7
Source Project: Processor   Source File: SkolemizerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of getResource method, of class Skolemizer.
 */
@Test
public void testGetResource()
{
    Model model = ModelFactory.createDefaultModel();

    Resource second = model.createResource().
            addLiteral(DCTerms.title, "Second");
    Resource first = model.createResource().
            addLiteral(DCTerms.title, "First").
            addProperty(FOAF.primaryTopic, second);
    
    Resource secondResult = skolemizer.getResource(first, "primaryTopic");
    assertEquals(second, secondResult);
    Resource resultFail1 = skolemizer.getResource(first, "title");
    assertNull(resultFail1); // title is a literal, not a resource
    Resource resultFail2 = skolemizer.getResource(first, "primaryTopic.title");
    assertNull(resultFail2); // title is a literal, not a resource
    Resource resultFail3 = skolemizer.getResource(first, "whatever");
    assertNull(resultFail3); // no such property
}
 
Example 8
Source Project: data-transfer-project   Source File: SolidContactsExport.java    License: Apache License 2.0 6 votes vote down vote up
private List<VCard> parseAddressBook(Resource selfResource, SolidUtilities utilities)
    throws IOException {

  String peopleUri = selfResource.getProperty(NAME_EMAIL_INDEX_PROPERTY).getResource().getURI();
  Model peopleModel = utilities.getModel(peopleUri);
  List<VCard> vcards = new ArrayList<>();
  ResIterator subjects = peopleModel.listSubjects();
  while (subjects.hasNext()) {
    Resource subject = subjects.nextResource();
    Model personModel = utilities.getModel(subject.getURI());
    Resource personResource = SolidUtilities.getResource(subject.getURI(), personModel);
    if (personResource == null) {
      throw new IllegalStateException(subject.getURI() + " not found in " + subject.toString());
    }
    vcards.add(parsePerson(personResource));
  }
  return vcards;
}
 
Example 9
Source Project: tools   Source File: SPDXCreatorInformation.java    License: Apache License 2.0 6 votes vote down vote up
public Resource createResource(Model model) {
	this.model = model;
	Resource type = model.createResource(SpdxRdfConstants.SPDX_NAMESPACE +
			SpdxRdfConstants.CLASS_SPDX_CREATION_INFO);
	Resource r = model.createResource(type);
	if (creators != null && creators.length > 0) {
		Property nameProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE,
				SpdxRdfConstants.PROP_CREATION_CREATOR);
		for (int i = 0; i < creators.length; i++) {
			r.addProperty(nameProperty, this.creators[i]);
		}
	}
	if (this.comment != null) {
		Property commentProperty = model.createProperty(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT);
		r.addProperty(commentProperty, this.comment);
	}
	// creation date
	if (this.createdDate != null) {
		Property createdDateProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CREATION_CREATED);
		r.addProperty(createdDateProperty, this.createdDate);
	}
	this.creatorNode = r.asNode();
	this.creatorResource = r;
	return r;
}
 
Example 10
Source Project: shacl   Source File: ARQFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Query from a partial query (possibly lacking
 * PREFIX declarations), using the ARQ syntax specified by <code>getSyntax</code>.
 * @param model  the Model to operate on
 * @param partialQuery  the (partial) query string
 * @return the Query
 */
public Query createQuery(Model model, String partialQuery) {
	PrefixMapping pm = new PrefixMappingImpl();
    String defaultNamespace = JenaUtil.getNsPrefixURI(model, "");
    if(defaultNamespace != null) {
        pm.setNsPrefix("", defaultNamespace);
    }
    Map<String,String> extraPrefixes = ExtraPrefixes.getExtraPrefixes();
    for(String prefix : extraPrefixes.keySet()) {
    	String ns = extraPrefixes.get(prefix);
    	if(ns != null && pm.getNsPrefixURI(prefix) == null) {
    		pm.setNsPrefix(prefix, ns);
    	}
    }

    // Get all the prefixes from the model at once.
    Map<String, String> map = model.getNsPrefixMap();
    map.remove("");
    pm.setNsPrefixes(map);
    
	return doCreateQuery(partialQuery, pm);
}
 
Example 11
Source Project: tools   Source File: TestRdfModelObject.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAnyLicenseInfos() throws InvalidSPDXAnalysisException {
	final Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	Resource r = model.createResource();
	EmptyRdfModelObject empty = new EmptyRdfModelObject(modelContainer, r.asNode());
	AnyLicenseInfo[] result = empty.findAnyLicenseInfoPropertyValues(TEST_NAMESPACE, TEST_PROPNAME1);
	assertEquals(0, result.length);
	SpdxListedLicense lic1 = LicenseInfoFactory.getListedLicenseById(STANDARD_LICENSE_ID1);
	String licId2 = "LicRef-2";
	String licenseText2 = "License text 2";
	ExtractedLicenseInfo lic2 = new ExtractedLicenseInfo(licId2, licenseText2);
	empty.addPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1, lic1);
	result = empty.findAnyLicenseInfoPropertyValues(TEST_NAMESPACE, TEST_PROPNAME1);
	assertEquals(1, result.length);
	assertEquals(lic1, result[0]);
	empty.addPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1, lic2);
	result = empty.findAnyLicenseInfoPropertyValues(TEST_NAMESPACE, TEST_PROPNAME1);
	assertEquals(2, result.length);
	assertTrue(UnitTestHelper.isArraysEqual(new AnyLicenseInfo[] {lic1, lic2},
			result));
}
 
Example 12
Source Project: tools   Source File: LicenseException.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Searches the model for a exception with the ID
 * @param model
 * @param id
 * @return Node containing the exception or Null if none found
 */
public static Node findException(Model model, String id) {
	Property idProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, 
			SpdxRdfConstants.PROP_LICENSE_EXCEPTION_ID);
	Property typeProperty = model.getProperty(SpdxRdfConstants.RDF_NAMESPACE, 
			SpdxRdfConstants.RDF_PROP_TYPE);
	Property exceptionTypeProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE,
			SpdxRdfConstants.CLASS_SPDX_LICENSE_EXCEPTION);
	Triple m = Triple.createMatch(null, idProperty.asNode(), null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		if (t.getObject().toString(false).equals(id)) {
			Triple typeMatch = Triple.createMatch(t.getSubject(), typeProperty.asNode(), exceptionTypeProperty.asNode());
			ExtendedIterator<Triple> typeTripleIter = model.getGraph().find(typeMatch);
			if (typeTripleIter.hasNext()) {
				return t.getSubject();
			}
		}
	}
	return null;
}
 
Example 13
Source Project: tools   Source File: TestAnnotation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.spdx.rdfparser.model.Annotation#setAnnotationDate(java.lang.String)}.
 * @throws InvalidSPDXAnalysisException
 */
@Test
public void testSetDate() throws InvalidSPDXAnalysisException {
	Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1);
	assertEquals(ANNOTATOR1, a.getAnnotator());
	assertEquals(OTHER_ANNOTATION, a.getAnnotationType());
	assertEquals(date, a.getAnnotationDate());
	assertEquals(COMMENT1, a.getComment());
	final Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	Resource r = a.createResource(modelContainer);
	a.setAnnotationDate(oldDate);
	assertEquals(oldDate, a.getAnnotationDate());
	Annotation copy = new Annotation(modelContainer, r.asNode());
	assertEquals(oldDate, copy.getAnnotationDate());
}
 
Example 14
Source Project: shacl   Source File: SHACLPaths.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to parse a given string into a Jena Path.
 * Throws an Exception if the string cannot be parsed.
 * @param string  the string to parse
 * @param model  the Model to operate on (for prefixes)
 * @return a Path or a Resource if this is a URI
 */
public static Object getJenaPath(String string, Model model) throws QueryParseException {
	Query query = ARQFactory.get().createQuery(model, "ASK { ?a \n" + string + "\n ?b }");
	Element element = query.getQueryPattern();
	if(element instanceof ElementGroup) {
		Element e = ((ElementGroup)element).getElements().get(0);
		if(e instanceof ElementPathBlock) {
			Path path = ((ElementPathBlock) e).getPattern().get(0).getPath();
			if(path instanceof P_Link && ((P_Link)path).isForward()) {
				return model.asRDFNode(((P_Link)path).getNode());
			}
			else {
				return path;
			}
		}
		else if(e instanceof ElementTriplesBlock) {
			return model.asRDFNode(((ElementTriplesBlock) e).getPattern().get(0).getPredicate());
		}
	}
	throw new QueryParseException("Not a SPARQL 1.1 Path expression", 2, 1);
}
 
Example 15
@Override
public void activate(final Collection<JenaPosLengthMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property lengthProperty = model.getProperty(BASE_PREFIX + LENGTH);

	for (final JenaPosLengthMatch match : matches) {
		final Resource segment = match.getSegment();
		final int length = match.getLength().getInt();
		final int newLength = -length + 1;

		final Selector selector = new SimpleSelector(segment, lengthProperty, (RDFNode) null);
		final StmtIterator statementsToRemove = model.listStatements(selector);
		if (statementsToRemove.hasNext()) {
			final Statement oldStatement = statementsToRemove.next();
			model.remove(oldStatement);
		}
		
		final Statement newStatement = model.createLiteralStatement(segment, lengthProperty, newLength);
		model.add(newStatement);
	}
}
 
Example 16
Source Project: ontopia   Source File: RDFToTopicMapConverter.java    License: Apache License 2.0 5 votes vote down vote up
private RDFToTopicMapConverter(Model model, TopicMapIF topicmap)
  throws JenaException, MalformedURLException {

  this.topicmap = topicmap;
  this.builder = topicmap.getBuilder();

  buildMappings(model);
}
 
Example 17
Source Project: sparql-generate   Source File: RootPlan.java    License: Apache License 2.0 5 votes vote down vote up
private void execSelectPlan(final List<Var> variables, final List<Binding> values, final Context context) {
	if (selectPlan == null) {
		if (query.isSelectType()) {
			final List<String> listVar = variables.stream().map(Var::getVarName).collect(Collectors.toList());
			final Model model = ContextUtils.getDataset(context).getDefaultModel();
			final ResultSet resultSet = new ResultSetStream(listVar, model, values.iterator());
			ContextUtils.getSelectOutput(context).accept(resultSet);
		} else if(query.isGenerateType()) {
			generatePlan.exec(variables, values, context);
		} else if(query.isTemplateType()) {
			templatePlan.exec(variables, values, context);
		}
	} else {
		selectPlan.exec(variables, values, context, resultSet -> {
			if (query.isSelectType()) {
				ContextUtils.getSelectOutput(context).accept(resultSet);
			} else {
				final List<Var> newVariables = new ArrayList<>();
				newVariables.addAll(variables); // can we delete this?
				newVariables.addAll(selectPlan.getVars());
				final List<Binding> newValues = new ArrayList<>();
				while (resultSet.hasNext()) {
					final Binding p = EvalUtils.createBinding(resultSet.next());
					newValues.add(p);
				}
				if(query.isGenerateType()) {
					generatePlan.exec(newVariables, newValues, context);
				} else if(query.isTemplateType()) {
					templatePlan.exec(newVariables, newValues, context);
				}
			}
		});
	}
}
 
Example 18
Source Project: tools   Source File: SPDXStandardLicense.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Resource _createResource(Model model) {
	Resource type = model.createResource(SpdxRdfConstants.SPDX_NAMESPACE+SpdxRdfConstants.CLASS_SPDX_STANDARD_LICENSE);
	String uri = this.createStdLicenseUri(this.id);
	Resource r = super._createResource(model, type, uri);
	//TODO: Implement additional properties
	return r;
}
 
Example 19
Source Project: hypergraphql   Source File: Service.java    License: Apache License 2.0 5 votes vote down vote up
Map<String, Set<String>> getResultset(Model model, JsonNode query, Set<String> input, Set<String> markers, HGQLSchema schema) {

        Map<String, Set<String>> resultset = new HashMap<>();
        JsonNode node;

        if (query.isArray()) {
            node = query; // TODO - in this situation, we should iterate over the array
        } else {
            node = query.get("fields");
            if (markers.contains(query.get("nodeId").asText())){
                resultset.put(query.get("nodeId").asText(),findRootIdentifiers(model,schema.getTypes().get(query.get("targetName").asText())));
            }
        }
        Set<LinkedList<QueryNode>> paths = new HashSet<>();
        if (node != null && !node.isNull()) {
            paths = getQueryPaths(node, schema);
        }

        paths.forEach(path -> {
            if (hasMarkerLeaf(path, markers)) {
                Set<String> identifiers = findIdentifiers(model, input, path);
                String marker = getLeafMarker(path);
                resultset.put(marker, identifiers);
            }
        });

        // TODO query happens to be an array sometimes - then the following line fails.

        return resultset;
    }
 
Example 20
Source Project: tools   Source File: DOAPProject.java    License: Apache License 2.0 5 votes vote down vote up
public Resource createResource(Model model) {
	Resource type = model.createResource(SpdxRdfConstants.DOAP_NAMESPACE + SpdxRdfConstants.CLASS_DOAP_PROJECT);
	Resource retval;
	if (uri != null && !uri.isEmpty() && !uri.equals(UNKNOWN_URI)) {
		retval = model.createResource(uri, type);
	} else {
		retval = model.createResource(type);
	}
	populateModel(model, retval);
	return retval;
}
 
Example 21
Source Project: SDA   Source File: OneM2MContainerDTO.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
		String sample = "{     \"_id\" : ObjectId(\"561f27831ee8202c5e307d37\"),     \"rn\" : \"CONTAINER_268\",     \"ty\" : 3,     \"ri\" : \"CONTAINER_268\",     \"pi\" : \"SAE_0\",     \"lbl\" : [          \"switch\",          \"key1\",          \"key2\"     ],     \"et\" : \"20151203T122321\",     \"cr\" : \"//onem2m.herit.net/herit-cse/SAE_5\",     \"mni\" : 100,     \"mbs\" : 1.024e+006,     \"mia\" : 36000,     \"cni\" : 1,     \"cbs\" : 2,     \"_uri\" : \"/herit-in/herit-cse/SAE_0/CONTAINER_268\",     \"ct\" : \"20151015T131147\",     \"lt\" : \"20151015T131147\", \"or\":\"http://www.pineone.com/m2m/SwitchStatusSensor\" }";
		Gson gson = new Gson();
		OneM2MContainerDTO cont = gson.fromJson(sample, OneM2MContainerDTO.class);


		System.out.println(cont);
		
		OneM2MContainerMapper mapper = new OneM2MContainerMapper(cont);
		Model model = ModelFactory.createDefaultModel();
		model.add(mapper.from());
		
		//스트링 변환부분
		RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);

		//스트링 변환부분
//		String serviceURI = "http://219.248.137.7:13030/icbms";
//
//		DatasetAccessor	accessor = DatasetAccessorFactory.createHTTP(serviceURI);
//		accessor.deleteDefault();
//		accessor.add(model);
//		
//		
//		QueryExecution q = QueryExecutionFactory.sparqlService(serviceURI	,"select * {?s ?p ?o}"	);
//		ResultSet rs = q.execSelect();
//		ResultSetFormatter.out(rs);;
		
//		model = DatasetAccessorFactory.createHTTP(serviceURI).getModel();
//		System.out.println(model.size());

	}
 
Example 22
Source Project: shacl   Source File: ValidationEngine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets a Set of all Shapes that should be evaluated for a given resource.
 * @param focusNode  the resource to get the shapes for
 * @param dataset  the Dataset containing the resource
 * @param shapesModel  the shapes Model
 * @return a Set of shape resources
 */
private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) {

	Set<Resource> shapes = new HashSet<>();
	
	for(Shape rootShape : shapesGraph.getRootShapes()) {
		for(Target target : rootShape.getTargets()) {
			if(!(target instanceof InstancesTarget)) {
				if(target.contains(dataset, focusNode)) {
					shapes.add(rootShape.getShapeResource());
				}
			}
		}
	}
	
	// rdf:type / sh:targetClass
	if(focusNode instanceof Resource) {
		for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) {
			if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) {
				shapes.add(type);
			}
			for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) {
				shapes.add(s.getSubject());
			}
		}
	}
	
	return shapes;
}
 
Example 23
public static void main(String[] args) {
//		String sample = "{     \"_id\" : ObjectId(\"560c9d741ee8203c53a63569\"),     \"rn\" : \"CONTENT_INST_5\",     \"ty\" : 4,     \"ri\" : \"CONTENT_INST_5\",     \"pi\" : \"CONTAINER_37\",     \"lbl\" : [          \"cnt-switch\"     ],     \"cr\" : \"C_AE-D-GASLOCK1004\",     \"cnf\" : \"text/plain:0\",     \"cs\" : 3,     \"con\" : \"Off\",     \"_uri\" : \"/herit-in/herit-cse/ae-gaslock1004/cnt-switch/CONTENT_INST_5\",     \"ct\" : \"20151001T114156\",     \"lt\" : \"20151001T114156\" , \"or\":\"http://www.pineone.com/campus/StateCondition\" }";
		String sample = 
				"{ "+
				"	    \"_id\" : ObjectId(\"560c9b1e1ee8203c53a63554\"),"+
				"	    \"rn\" : \"CONTENT_INST_0\","+
				"	    \"ty\" : 4,"+
				"	    \"ri\" : \"CONTENT_INST_0\","+
				"	    \"pi\" : \"CONTAINER_15\","+
				"	    \"lbl\" : [ "+
				"	        \"cnt-temperature\""+
				"	    ],"+
				"	    \"cr\" : \"C_AE-D-GASLOCK1001\","+
				"	    \"cnf\" : \"text/plain:0\","+
				"	    \"cs\" : 2,"+
				"	    \"con\" : \"13\","+
				"	    \"_uri\" : \"/herit-in/herit-cse/ae-gaslock1001/cnt-temperature/CONTENT_INST_0\","+
				"	    \"ct\" : \"20151001T113158\","+
				"	    \"lt\" : \"20151001T113158\" "+
				"	} " ;
		Gson gson = new Gson();
		OneM2MContentInstanceDTO cont = gson.fromJson(sample, OneM2MContentInstanceDTO.class);
		System.out.println(cont);


		OneM2MContentInstanceMapper mapper = new OneM2MContentInstanceMapper(cont);
		mapper = new OneM2MContentInstanceMapper(cont);
		Model model = ModelFactory.createDefaultModel();
		model.add(mapper.from());

		// 스트링 변환부분
		RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);
	}
 
Example 24
protected void copyClassHierarchy(Model readModel, Model model, Set<Resource> classes) {
    StmtIterator stmtIterator = readModel.listStatements();
    Statement s;
    while (stmtIterator.hasNext()) {
        s = stmtIterator.next();
        if (classes.contains(s.getSubject()) && ALLOWED_PROPERTIES.contains(s.getPredicate())
                && (!s.getObject().isAnon())) {
            model.add(s);
        }
    }
}
 
Example 25
public Resource createExperimentResource(Model model, String eID) {
    // create experiment resource
    Resource experiment = model.createResource(gerbilURL + EXPERIMENT_PREFIX + eID);
    experiment.addProperty(RDF.type, CUBE.Dataset);
    experiment.addProperty(RDF.type, GERBIL.Experiment);

    model.add(experiment, RDFS.label, "Experiment " + eID);
    model.add(experiment, CUBE.structure, GERBIL.DSD);

    return experiment;
}
 
Example 26
Source Project: shacl   Source File: ARQFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static void perhapsAppend(StringBuffer queryString, String prefix, String namespace, Model model) {
	if(model.getNsPrefixURI(prefix) == null && namespace != null) {
    	queryString.append("PREFIX ");
    	queryString.append(prefix);
    	queryString.append(": <");
    	queryString.append(namespace);
    	queryString.append(">\n");
	}
}
 
Example 27
Source Project: Server.Java   Source File: TriplePatternFragmentImpl.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new Triple Pattern Fragment.
 * @param triples the triples (possibly partial)
 * @param totalSize the total size
 * @param fragmentURL
 * @param datasetURL
 * @param isLastPage
 * @param pageNumber
 */
public TriplePatternFragmentImpl( final Model triples,
                                  long totalSize,
                                  final String fragmentURL,
                                  final String datasetURL,
                                  final long pageNumber,
                                  final boolean isLastPage ) {
    super( totalSize, fragmentURL, datasetURL, pageNumber, isLastPage );
    this.triples = triples;
}
 
Example 28
Source Project: RDFUnit   Source File: BatchShapeTargetReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRead() throws RdfReaderException {

    Model shapesModel = RdfReaderFactory.createResourceReader(shapeResource).read();

    Resource r1 = shapesModel.getResource("http://example.org/MyShape");
    Set<ShapeTarget> targets1 = BatchShapeTargetReader.create().read(r1);
    assertThat(targets1)
            .hasSize(2);
}
 
Example 29
Source Project: shacl   Source File: FunctionTestCaseType.java    License: Apache License 2.0 5 votes vote down vote up
private Graph parseGraph(RDFNode node) {
	Model model = JenaUtil.createDefaultModel();
	if(node.isLiteral()) {
		String str = node.asLiteral().getLexicalForm();
		model.read(new ByteArrayInputStream(str.getBytes()), "urn:x:dummy", FileUtils.langTurtle);
	}
	return model.getGraph();
}
 
Example 30
Source Project: teamengine   Source File: EarlReporter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates EARL statements for the entire collection of test suite results.
 * Each test subset is defined by a {@literal <test>} tag in the suite
 * definition; these correspond to earl:TestRequirement resources in the
 * model.
 * 
 * @param model
 *            An RDF Model containing EARL statements.
 * @param results
 *            A Map containing the actual test results, where the key is the
 *            name of a test subset (conformance class).
 */
void processSuiteResults(Model model, Map<String, ISuiteResult> results) {
    for (Map.Entry<String, ISuiteResult> entry : results.entrySet()) {
        String testName = entry.getKey();
        String testReqName = testName.replaceAll("\\s", "-");
        // can return existing resource in model
        Resource testReq = model.createResource(testReqName);
        ITestContext testContext = entry.getValue().getTestContext();
        int nPassed = testContext.getPassedTests().size();
        int nSkipped = testContext.getSkippedTests().size();
        int nFailed = testContext.getFailedTests().size();
        testReq.addLiteral(CITE.testsPassed, new Integer(nPassed));
        testReq.addLiteral(CITE.testsFailed, new Integer(nFailed));
        testReq.addLiteral(CITE.testsSkipped, new Integer(nSkipped));
        if (nPassed + nFailed == 0) {
            testReq.addProperty(DCTerms.description,
                    "A precondition was not met. All tests in this set were skipped.");
        }
        if(isBasicConformanceClass(testName)){
          if(nFailed > 0){
            areCoreConformanceClassesPassed = false;
          }              
        }
        processTestResults(model, testContext.getFailedTests());
        processTestResults(model, testContext.getSkippedTests());
        processTestResults(model, testContext.getPassedTests());
    }
}