Java Code Examples for org.apache.jena.rdf.model.Resource#addProperty()

The following examples show how to use org.apache.jena.rdf.model.Resource#addProperty() . 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: SPDXFile.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param artifactOf the artifactOf to set
 */
public void setArtifactOf(DOAPProject[] artifactOf) {
	this.artifactOf = artifactOf;
	if (this.model != null && this.name != null) {
		Resource fileResource = model.createResource(node.getURI());
		Property p = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_ARTIFACTOF);
		model.removeAll(fileResource, p, null);
		p = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_ARTIFACTOF);
		for (int i = 0; i < artifactOf.length; i++) {
			// we need to check on these if it already exists
			Resource projectResource = null;
			String uri = artifactOf[i].getProjectUri();
			if (uri != null) {
				projectResource = model.createResource(uri);
			} else {
				projectResource = artifactOf[i].createResource(model);
			}
			fileResource.addProperty(p, projectResource);
		}
	}

}
 
Example 2
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 6 votes vote down vote up
/**
 * Test of build method, of class Skolemizer.
 */
@Test
public void testBuild_Model()
{
    Model expected = ModelFactory.createDefaultModel();
    Resource expAbsolute = expected.createResource(baseUriBuilder.clone().path(absoluteId).build().toString()).
            addProperty(RDF.type, absolutePathClass).
            addLiteral(DCTerms.identifier, absoluteId);
    Resource expRelative = expected.createResource(absolutePathBuilder.clone().path(relativeId).build().toString()).
            addProperty(RDF.type, relativePathClass).
            addLiteral(DCTerms.identifier, relativeId);
    Resource expThing = expected.createResource(absolutePathBuilder.clone().path(thingTitle).fragment(thingFragment).build().toString()).
            addProperty(RDF.type, thingClass).
            addLiteral(DCTerms.title, thingTitle);
    Resource expImported = expected.createResource(absolutePathBuilder.clone().path(thingTitle).fragment(thingFragment).build().toString()).
            addProperty(RDF.type, importedClass).
            addLiteral(DCTerms.title, thingTitle);
    Resource expRestricted = expected.createResource(UriBuilder.fromUri(restrictionValue).clone().path(restrictedId).build().toString()).
            addProperty(RDF.type, restrictedClass).
            addLiteral(DCTerms.identifier, restrictedId);        
    expRelative.addProperty(FOAF.primaryTopic, expThing);
    expThing.addProperty(FOAF.isPrimaryTopicOf, expRelative);
    
    Model result = skolemizer.build(input);
    assertTrue(result.isIsomorphicWith(expected));
}
 
Example 3
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param files the files to set
 * @throws InvalidSPDXAnalysisException
 */
public void setFiles(SPDXFile[] files) throws InvalidSPDXAnalysisException {
	removeProperties(node, PROP_PACKAGE_FILE);
	Resource s = getResource(this.node);
	Property p = model.createProperty(SPDX_NAMESPACE, PROP_PACKAGE_FILE);
	Resource docResource = getResource(getSpdxDocNode());
	Property docP = model.createProperty(SPDX_NAMESPACE, PROP_SPDX_FILE);
	for (int i = 0; i < files.length; i++) {
		Resource file = files[i].createResource(model);
		s.addProperty(p, file);
		docResource.addProperty(docP, file);
	}
}
 
Example 4
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
public void setLicenseInfoFromFiles(AnyLicenseInfo[] licenseInfo) throws InvalidSPDXAnalysisException {
	removeProperties(node, PROP_PACKAGE_LICENSE_INFO_FROM_FILES);
	if (licenseInfo != null) {
		Resource s = getResource(this.node);
		Property p = model.createProperty(SPDX_NAMESPACE, PROP_PACKAGE_LICENSE_INFO_FROM_FILES);
		for (int i = 0; i < licenseInfo.length; i++) {
			Resource lic = licenseInfo[i].createResource(this.enclosingSpdxDocument);
			s.addProperty(p, lic);
		}
	}
}
 
Example 5
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param files the files to set
 * @throws InvalidSPDXAnalysisException 
 */
public void setFiles(SPDXFile[] files) throws InvalidSPDXAnalysisException {
	// Delete all existing files
	List<Node> alFileNodes = Lists.newArrayList();
	Node n = model.getProperty(SPDX_NAMESPACE, PROP_PACKAGE_FILE).asNode();
	Triple m = Triple.createMatch(this.node, n, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		alFileNodes.add(t.getObject());
	}
	removeProperties(node, PROP_PACKAGE_FILE);
	removeProperties(getSpdxDocNode(), PROP_SPDX_FILE_REFERENCE);	// NOTE: In version 2.0, we will need to remove just the files which were in the package

	for (Node fileNode : alFileNodes) {
		model.removeAll(getResource(fileNode), null, null);
	}
	
	if (files != null) {
		Resource s = getResource(this.node);
		Property p = model.createProperty(SPDX_NAMESPACE, PROP_PACKAGE_FILE);
		Resource docResource = getResource(getSpdxDocNode());
		Property docP = model.createProperty(SPDX_NAMESPACE, PROP_SPDX_FILE_REFERENCE);
		for (int i = 0; i < files.length; i++) {				
			Resource file = files[i].createResource(getDocument(), getDocumentNamespace() + getNextSpdxElementRef());
			s.addProperty(p, file);
			docResource.addProperty(docP, file);
		}
	}
}
 
Example 6
Source File: AbstractSPARQLExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static void addDetails(Resource parentResult, Model nestedResults) {
	if(!nestedResults.isEmpty()) {
		parentResult.getModel().add(nestedResults);
		for(Resource type : SHACLUtil.RESULT_TYPES) {
			for(Resource nestedResult : nestedResults.listSubjectsWithProperty(RDF.type, type).toList()) {
				if(!parentResult.getModel().contains(null, SH.detail, nestedResult)) {
					parentResult.addProperty(SH.detail, nestedResult);
				}
			}
		}
	}
}
 
Example 7
Source File: ExceptionMapperBase.java    From Processor with Apache License 2.0 5 votes vote down vote up
public Resource toResource(Exception ex, Response.StatusType status, Resource statusResource)
{
    if (ex == null) throw new IllegalArgumentException("Exception cannot be null");
    if (status == null) throw new IllegalArgumentException("Response.Status cannot be null");

    Resource resource = ModelFactory.createDefaultModel().createResource().
            addProperty(RDF.type, HTTP.Response).
            addLiteral(HTTP.statusCodeValue, status.getStatusCode()).
            addLiteral(HTTP.reasonPhrase, status.getReasonPhrase());

    if (statusResource != null) resource.addProperty(HTTP.sc, statusResource);
    if (ex.getMessage() != null) resource.addLiteral(DCTerms.title, ex.getMessage());
    
    return resource;
}
 
Example 8
Source File: DataIDGenerator.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
public void addToModel(Model model, List<ExperimentTaskStatus> results, String eID) {
    if (results.size() == 0) {
        return;
    }

    Resource experiment = createExperimentResource(model, eID);

    boolean first = true;
    Iterator<ExperimentTaskStatus> resultIterator = results.iterator();
    ExperimentTaskStatus result;
    // iterating over the experiments
    while (resultIterator.hasNext()) {
        result = resultIterator.next();
        // If this is the first experiment result, use it to get further
        // properties of the experiment (matching, ...)
        if (first) {
            Resource r = GERBIL.getExperimentTypeResource(result.type);
            if (r != null) {
                experiment.addProperty(GERBIL.experimentType, r);
            }
            r = GERBIL.getMatchingResource(result.matching);
            if (r != null) {
                experiment.addProperty(GERBIL.matching, r);
            }
            first = false;
        }
        // create experiment task
        addExperimentTask(model, result, experiment);
    }
}
 
Example 9
Source File: HypermediaFilter.java    From Processor with Apache License 2.0 5 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response)
{
    if (request == null) throw new IllegalArgumentException("ContainerRequest cannot be null");
    if (response == null) throw new IllegalArgumentException("ContainerResponse cannot be null");
    
    // do not process hypermedia if the response is a redirect or 201 Created or 404 Not Found
    if (response.getStatusType().getFamily().equals(REDIRECTION) || response.getStatusType().equals(CREATED) ||
            response.getStatusType().equals(NOT_FOUND) || response.getStatusType().equals(INTERNAL_SERVER_ERROR) || 
            response.getEntity() == null || (!(response.getEntity() instanceof Dataset)))
        return response;
    
    TemplateCall templateCall = getTemplateCall();
    if (templateCall == null) return response;
    
    Resource state = templateCall.build();
    Resource absolutePath = state.getModel().createResource(request.getAbsolutePath().toString());
    if (!state.equals(absolutePath)) state.addProperty(C.stateOf, absolutePath);

    Resource requestUri = state.getModel().createResource(request.getRequestUri().toString());
    if (!state.equals(requestUri)) // add hypermedia if there are query parameters
        state.addProperty(C.viewOf, requestUri). // needed to lookup response state by request URI without redirection
            addProperty(RDF.type, C.View);

    if (log.isDebugEnabled()) log.debug("Added Number of HATEOAS statements added: {}", state.getModel().size());
    Dataset newEntity = ((Dataset)response.getEntity());
    newEntity.getDefaultModel().add(state.getModel());
    response.setEntity(newEntity);
    
    return response;
}
 
Example 10
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param reviewers the reviewers to set
 * @throws InvalidSPDXAnalysisException
 */
public void setReviewers(SPDXReview[] reviewers) throws InvalidSPDXAnalysisException {
	if (reviewers.length > 0) {
		ArrayList<String> errors = new ArrayList<String>();
		for (int i = 0;i < reviewers.length; i++) {
			errors.addAll(reviewers[i].verify());
		}
		if (errors.size() > 0) {
			StringBuilder sb = new StringBuilder("Invalid reviewers due to the following errors in validation:\n");
			for (int i = 0; i < errors.size(); i++) {
				sb.append(errors.get(i));
				sb.append('\n');
			}
			throw(new InvalidSPDXAnalysisException(sb.toString()));
		}
	}
	Node spdxDocNode = getSpdxDocNode();
	if (spdxDocNode == null) {
		throw(new InvalidSPDXAnalysisException("Must have an SPDX document to set reviewers"));
	}
	// delete any previous created
	Property p = model.getProperty(SPDX_NAMESPACE, PROP_SPDX_REVIEWED_BY);
	Resource s = getResource(spdxDocNode);
	model.removeAll(s, p, null);
	// add the property
	for (int i = 0; i < reviewers.length; i++) {
		p = model.createProperty(SPDX_NAMESPACE, PROP_SPDX_REVIEWED_BY);
		s.addProperty(p, reviewers[i].createResource(model));
	}
}
 
Example 11
Source File: CtlEarlReporter.java    From teamengine with Apache License 2.0 5 votes vote down vote up
private Resource createEarlRequest( Model earl, Element reqElement ) {
    Element requestNode = getElementByTagName( reqElement, "http://www.occamlab.com/ctl", "request" );
    if ( requestNode != null ) {
        String httpMethod = parseTextContent( requestNode, "http://www.occamlab.com/ctl", "method" );
        String url = parseTextContent( requestNode, "http://www.occamlab.com/ctl", "url" );
        Resource earlRequest = earl.createResource( HTTP.Request );
        if ( "GET".equalsIgnoreCase( httpMethod ) ) {
            Map<String, String> parameters = parseParameters( requestNode );
            String urlWithQueryString = createUrlWithQueryString( url, parameters );
            earlRequest.addProperty( HTTP.methodName, httpMethod );
            earlRequest.addProperty( HTTP.requestURI, urlWithQueryString );
            return earlRequest;
        }
        if ( "POST".equalsIgnoreCase( httpMethod ) ) {
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty( OutputKeys.INDENT, "yes" );

                StreamResult result = new StreamResult( new StringWriter() );
                DOMSource source = new DOMSource( requestNode );
                transformer.transform( source, result );

                String xmlString = result.getWriter().toString();
                result.getWriter().close();

                Resource reqContent = earl.createResource( CONTENT.ContentAsXML );

                reqContent.addProperty( CONTENT.rest, xmlString );
                earlRequest.addProperty( HTTP.body, reqContent );
                return earlRequest;
            } catch ( Exception e ) {
                new RuntimeException( "Request content is not well-formatted. " + e.getMessage() );
            }
        }
    }
    return null;
}
 
Example 12
Source File: ContactPoint.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Override
public Resource addToResource(Model model, Resource parent) {
    addNsPrefix(model);
    for (VCardOrganization organization : getOrganizations()) {
        parent.addProperty(getProperty(), organization.createResource(model, parent));
        return parent;
    }
    return super.addToResource(model, parent);
}
 
Example 13
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param reviewers the reviewers to set
 * @throws InvalidSPDXAnalysisException 
 */
public void setReviewers(SPDXReview[] reviewers) throws InvalidSPDXAnalysisException {
	if (reviewers.length > 0) {
		List<String> errors = Lists.newArrayList();
		for (int i = 0;i < reviewers.length; i++) {
			errors.addAll(reviewers[i].verify());
		}
		if (errors.size() > 0) {
			StringBuilder sb = new StringBuilder("Invalid reviewers due to the following errors in validation:\n");
			for (int i = 0; i < errors.size(); i++) {
				sb.append(errors.get(i));
				sb.append('\n');
			}
			throw(new InvalidSPDXAnalysisException(sb.toString()));
		}
	}
	Node spdxDocNode = getSpdxDocNode();
	if (spdxDocNode == null) {
		throw(new InvalidSPDXAnalysisException("Must have an SPDX document to set reviewers"));
	}
	// delete any previous created
	Property p = model.getProperty(SPDX_NAMESPACE, PROP_SPDX_REVIEWED_BY);
	Resource s = getResource(spdxDocNode);
	model.removeAll(s, p, null);
	// add the property
	for (int i = 0; i < reviewers.length; i++) {
		p = model.createProperty(SPDX_NAMESPACE, PROP_SPDX_REVIEWED_BY);
		s.addProperty(p, reviewers[i].createResource(model));
	}
}
 
Example 14
Source File: SPDXChecksum.java    From tools with Apache License 2.0 5 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;
	try {
		r = findSpdxChecksum(model, this);
	} catch (InvalidSPDXAnalysisException e) {
		// if we run into an error finding the checksum, we'll just create a new one
		r = null;
	}		// prevent duplicate checksum objects
	if (r == null) {
		r = model.createResource(type);
	}
	if (algorithm != null) {
		Property algProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, 
				SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM);
		Resource algResource = model.createResource(ALGORITHM_TO_URI.get(algorithm));
		r.addProperty(algProperty, algResource);
	}
	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 15
Source File: CtlEarlReporter.java    From teamengine with Apache License 2.0 5 votes vote down vote up
private void processRequest( Resource earlResult, Model earl, Element reqElement ) {
    Resource httpReq = createEarlRequest( earl, reqElement );
    if ( httpReq == null )
        return;
    String response = parseNodeAsString( reqElement, "response" );
    if ( response != null ) {
        Resource httpRsp = earl.createResource( HTTP.Response );
        Resource rspContent = earl.createResource( CONTENT.ContentAsXML );
        rspContent.addProperty( CONTENT.rest, response );
        httpRsp.addProperty( HTTP.body, rspContent );
        httpReq.addProperty( HTTP.resp, httpRsp );
    }
    earlResult.addProperty( CITE.message, httpReq );
}
 
Example 16
Source File: PrefixUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Resource addNamespace(Resource ontology, String prefix, String namespace) {
	Resource declaration = ontology.getModel().createResource(namespace + SH.PrefixDeclaration.getLocalName(), SH.PrefixDeclaration);
	ontology.addProperty(SH.declare, declaration);
	declaration.addProperty(SH.prefix, prefix);
	declaration.addProperty(SH.namespace, ResourceFactory.createTypedLiteral(namespace, XSDDatatype.XSDanyURI));
	return declaration;
}
 
Example 17
Source File: Dataset.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
@Override
public Resource addToResource(Model model, Resource parent) {
    addNsPrefix(model);
    Resource dataset = model.createResource(DCAT.Dataset);
    addTitleAndDescription(model, dataset);

    for (Identifier identifier : getIdentifiers()) {
        identifier.addToResource(model, dataset);
    }

    for (Keyword keyword : getKeywords()) {
        keyword.addToResource(model, dataset);
    }

    if (getAccrualPeriodicity() != null) {
        getAccrualPeriodicity().addToResource(model, dataset);
    }

    for (Theme theme : getThemes()) {
        theme.addToResource(model, dataset);
    }

    if (getPublisher() != null) {
        getPublisher().addToResource(model, dataset);
    }

    for (Language language : getLanguages()) {
        language.addToResource(model, dataset);
    }

    if (getIssued() != null) {
        getIssued().addToResource(model, dataset);
    }

    for (ThemeTaxonomy themeTaxonomy : getThemeTaxonomies()) {
        themeTaxonomy.addToResource(model, dataset);
    }

    if (getModified() != null) {
        getModified().addToResource(model, dataset);
    }

    for (ContactPoint contactPoint : getContactPoints()) {
        contactPoint.addToResource(model, dataset);
    }

    if (getAccessRights() != null) {
        getAccessRights().addToResource(model, dataset);
    }

    for (LandingPage landingPage : getLandingPages()) {
        landingPage.addToResource(model, dataset);
    }

    for (DistributionProperty distribution : getDistributions()) {
        distribution.addToResource(model, dataset);
    }

    for (Spatial spatial : getSpatials()) {
        spatial.addToResource(model, dataset);
    }

    parent.addProperty(DCAT.dataset, dataset);
    return parent;
}
 
Example 18
Source File: CtlEarlReporter.java    From teamengine with Apache License 2.0 4 votes vote down vote up
private void processTestResults( Model earl, Element logElement, NodeList logList, String conformanceClass,
                                 Resource parentTestCase )
                        throws UnsupportedEncodingException {
    NodeList childtestcallList = logElement.getElementsByTagName( "testcall" );

    for ( int l = 0; l < childtestcallList.getLength(); l++ ) {
        Element childtestcallElement = (Element) childtestcallList.item( l );
        String testcallPath = childtestcallElement.getAttribute( "path" );

        Element childlogElement = findMatchingLogElement( logList, testcallPath );

        if ( childlogElement == null )
            throw new NullPointerException( "Failed to get Test-Info due to null log element." );
        TestInfo testDetails = getTestinfo( childlogElement );

        // create earl:Assertion
        GregorianCalendar calTime = new GregorianCalendar( TimeZone.getDefault() );
        Resource assertion = earl.createResource( "assert-" + ++this.resultCount, EARL.Assertion );
        assertion.addProperty( EARL.mode, EARL.AutomaticMode );
        assertion.addProperty( EARL.assertedBy, this.assertor );
        assertion.addProperty( EARL.subject, this.testSubject );
        // link earl:TestResult to earl:Assertion
        Resource earlResult = earl.createResource( "result-" + this.resultCount, EARL.TestResult );
        earlResult.addProperty( DCTerms.date, earl.createTypedLiteral( calTime ) );

        processTestResult( childlogElement, testDetails, earlResult );
        processRequests( earlResult, childlogElement, earl );

        assertion.addProperty( EARL.result, earlResult );
        // link earl:TestCase to earl:Assertion and earl:TestRequirement
        String testName = testDetails.testName;
        StringBuilder testCaseId = new StringBuilder( testcallPath );
        testCaseId.append( '#' ).append( testName );
        Resource testCase = earl.createResource( testCaseId.toString(), EARL.TestCase );
        testCase.addProperty( DCTerms.title, testName );
        testCase.addProperty( DCTerms.description, testDetails.assertion );
        assertion.addProperty( EARL.test, testCase );

        if ( parentTestCase != null )
            parentTestCase.addProperty( DCTerms.hasPart, testCase );
        else
            earl.createResource( conformanceClass ).addProperty( DCTerms.hasPart, testCase );
        processTestResults( earl, childlogElement, logList, conformanceClass, testCase );
    }
}
 
Example 19
Source File: Distribution.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public Resource getResource(Model model) {
    Resource distribution = DCAT.NAMESPACE;
    distribution.addProperty(RDF.type, DCAT.Distribution);
    addValues(model, distribution);
    return addValues(model, distribution);
}
 
Example 20
Source File: DataIDGenerator.java    From gerbil with GNU Affero General Public License v3.0 4 votes vote down vote up
public void createExperimentTask(Model model, ExperimentTaskStatus result, Resource superExpTask,
        List<Resource> experimentTasks) {
    // create Resource
    Resource experimentTask = model.createResource(generateExperimentTaskUri(result.idInDb));
    experimentTasks.add(experimentTask);
    if (model.containsResource(experimentTask)) {
        return;
    }
    experimentTask.addProperty(RDF.type, CUBE.Observation);

    // add annotator and dataset
    experimentTask.addProperty(GERBIL.annotator,
            gerbilURL + ANNOTATOR_DATAID + DataIDUtils.treatsNames(result.dataset) + DATAID_EXTENSION);
    experimentTask.addProperty(GERBIL.dataset,
            gerbilURL + DATASET_DATAID + DataIDUtils.treatsNames(result.annotator) + DATAID_EXTENSION);

    // set the status of this task
    model.add(experimentTask, GERBIL.statusCode, model.createTypedLiteral(result.state));

    if (superExpTask != null) {
        model.add(experimentTask, GERBIL.subExperimentOf, superExpTask);
    }

    // If this task has been finished
    if (ExperimentTaskStateHelper.taskFinished(result)) {
        // creating and setting literals for the current experiment
        Map<String, TaskResult> resMap = result.getResultsMap();
        String propertyUri;
        for(String resName: resMap.keySet()) {
        	 propertyUri = GERBIL.getURI() + resName.replace(" ", "_");
        	 model.add(experimentTask, model.createProperty(propertyUri), model.createTypedLiteral(
                     String.valueOf(resMap.get(resName).getResValue()), XSDDatatype.XSDdecimal));
        }
        if (result.hasSubTasks()) {
            for (ExperimentTaskStatus subResult : result.getSubTasks()) {
                createExperimentTask(model, subResult, experimentTask, experimentTasks);
            }
        }
    }

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(result.timestamp);
    model.add(experimentTask, GERBIL.timestamp, model.createTypedLiteral(cal));
}