Java Code Examples for org.apache.jena.rdf.model.Model#remove()

The following examples show how to use org.apache.jena.rdf.model.Model#remove() . 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: Exporter.java    From fcrepo-import-export with Apache License 2.0 6 votes vote down vote up
private Set<URI> filterInboundReferences(final URI uri, final Model model) {
    final String withSlash = withSlash(uri).toString();
    final String withoutSlash = withoutSlash(uri).toString();
    final Set<URI> inboundMembers = new HashSet<>();
    final List<Statement> removeList = new ArrayList<>();
    for (final StmtIterator inbound = model.listStatements(); inbound.hasNext(); ) {
        final Statement s = inbound.next();
        final String subject = s.getSubject().toString();
        if (!subject.equals(withSlash) && !subject.equals(withoutSlash)) {
            removeList.add(s);
            logger.trace("Filtering inbound reference: {}", s);
            inboundMembers.add(URI.create(subject));
        }
    }

    model.remove(removeList);
    return inboundMembers;
}
 
Example 2
Source File: Exporter.java    From fcrepo-import-export with Apache License 2.0 6 votes vote down vote up
/**
 * Filter out the binary resource references from the model
 * @param uri the URI for the resource
 * @param model the RDF Model of the resource
 * @return the RDF model with no binary references
 * @throws FcrepoOperationFailedException
 * @throws IOException
 */
private void filterBinaryReferences(final URI uri, final Model model) throws IOException,
        FcrepoOperationFailedException {

    final List<Statement> removeList = new ArrayList<>();
    for (final StmtIterator it = model.listStatements(); it.hasNext();) {
        final Statement s = it.nextStatement();

        final RDFNode obj = s.getObject();
        if (obj.isResource() && obj.toString().startsWith(repositoryRoot.toString())
                && !s.getPredicate().toString().equals(REPOSITORY_NAMESPACE + "hasTransactionProvider")) {
            try (final FcrepoResponse resp = client().head(URI.create(obj.toString())).disableRedirects()
                    .perform()) {
                checkValidResponse(resp, URI.create(obj.toString()), config.getUsername());
                final List<URI> linkHeaders = resp.getLinkHeaders("type");
                if (linkHeaders.contains(binaryURI)) {
                    removeList.add(s);
                }
            }
        }
    }

    model.remove(removeList);
}
 
Example 3
Source File: Importer.java    From fcrepo-import-export with Apache License 2.0 6 votes vote down vote up
/**
 * Removes statements from the provided model that affect triples that need not be (and indeed
 * cannot be) modified directly through PUT, POST or PATCH requests to fedora.
 *
 * Certain triples included in a resource from fedora cannot be explicitly stored, but because
 * they're derived from other content that *can* be stored will still appear identical when the
 * other RDF and content is ingested.  Examples include those properties that reflect innate
 * characteristics of binary resources like file size and message digest,  Or triples that
 * represent characteristics of rdf resources like the number of children, whether it has
 * versions and some of the types.
 *
 * @param model the RDF statements about an exported resource
 * @return the provided model updated to omit statements that may not be updated directly through
 *         the fedora API
 * @throws IOException
 * @throws FcrepoOperationFailedException
 */
private Model sanitize(final Model model) throws IOException, FcrepoOperationFailedException {
    final List<Statement> remove = new ArrayList<>();
    for (final StmtIterator it = model.listStatements(); it.hasNext(); ) {
        final Statement s = it.nextStatement();

        if ((s.getPredicate().getNameSpace().equals(REPOSITORY_NAMESPACE) && !relaxedPredicate(s.getPredicate()))
                || s.getSubject().getURI().endsWith("fcr:export?format=jcr/xml")
                || s.getSubject().getURI().equals(REPOSITORY_NAMESPACE + "jcr/xml")
                || s.getPredicate().equals(DESCRIBEDBY)
                || s.getPredicate().equals(CONTAINS)
                || s.getPredicate().equals(HAS_MESSAGE_DIGEST)
                || (s.getPredicate().equals(RDF_TYPE) && forbiddenType(s.getResource()))) {
            remove.add(s);
        } else if (s.getObject().isResource()) {
            // make sure that referenced repository objects exist
            final String obj = s.getResource().toString();
            if (obj.startsWith(repositoryRoot.toString())) {
                ensureExists(URI.create(obj));
            }
        }
    }
    return model.remove(remove);
}
 
Example 4
Source File: JenaTransformationRepairPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@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 5
Source File: JenaTransformationInjectPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<JenaPosLengthInjectMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property lengthProperty = model.getProperty(BASE_PREFIX + LENGTH);

	for (final JenaPosLengthInjectMatch match : matches) {
		final Resource segment = match.getSegment();
		final Selector selector = new SimpleSelector(segment, lengthProperty, (RDFNode) null);
		final StmtIterator oldStatements = model.listStatements(selector);
		if (!oldStatements.hasNext()) {
			continue;

		}
		final Statement oldStatement = oldStatements.next();
		model.remove(oldStatement);
		final Statement newStatement = model.createLiteralStatement(segment, lengthProperty, 0);
		model.add(newStatement);
	}
}
 
Example 6
Source File: JenaTransformationRepairConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaConnectedSegmentsMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property connectsToProperty = model.getProperty(BASE_PREFIX + ModelConstants.LENGTH);

	for (final JenaConnectedSegmentsMatch match : matches) {
		final Resource segment2 = match.getSegment2();

		// delete segment2 by removing all (segment2, _, _) and (_, _, segment2) triples
		final Collection<Statement> statementsToRemove = new ArrayList<>();

		final Selector selectorOutgoingEdges = new SimpleSelector(segment2, null, (RDFNode) null);
		final StmtIterator statementsOutgoingEdges = model.listStatements(selectorOutgoingEdges);
		while (statementsOutgoingEdges.hasNext()) {
			statementsToRemove.add(statementsOutgoingEdges.next());
		}
		final Selector selectorIncomingEdges = new SimpleSelector(null, null, segment2);
		final StmtIterator statementsIncomingEdges = model.listStatements(selectorIncomingEdges);
		while (statementsIncomingEdges.hasNext()) {
			statementsToRemove.add(statementsIncomingEdges.next());
		}
		for (final Statement statement : statementsToRemove) {
			model.remove(statement);
		}

		// insert (segment1)-[:connectsTo]->(segment3) edge
		model.add(model.createStatement(match.getSegment1(), connectsToProperty, match.getSegment3()));
	}
}
 
Example 7
Source File: JenaTransformationRepairSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaSwitchSetMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property currentPositionProperty = model.getProperty(BASE_PREFIX + CURRENTPOSITION);

	for (final JenaSwitchSetMatch match : matches) {
		final Resource sw = match.getSw();

		model.remove(sw, currentPositionProperty, match.getCurrentPosition());
		model.add(sw, currentPositionProperty, match.getPosition());
	}
}
 
Example 8
Source File: JenaTransformationInjectSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaSwitchSetInjectMatch> matches) {
	final Model model = driver.getModel();
	final Property currentPositionProperty = model.getProperty(BASE_PREFIX + CURRENTPOSITION);

	for (final JenaSwitchSetInjectMatch match : matches) {
		final Resource sw = match.getSw();
		
		final Selector selector = new SimpleSelector(sw, currentPositionProperty, (RDFNode) null);
		final StmtIterator statementsToRemove = model.listStatements(selector);
		if (!statementsToRemove.hasNext()) {
			continue;

		}

		// delete old statement
		final Statement oldStatement = statementsToRemove.next();
		model.remove(oldStatement);

		// get next enum value
		final Resource currentPositionResource = oldStatement.getObject().asResource();
		final String currentPositionRDFString = currentPositionResource.getLocalName();
		final String currentPositionString = RdfHelper.removePrefix(Position.class, currentPositionRDFString);
		final Position currentPosition = Position.valueOf(currentPositionString);
		final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length];
		final String newCurrentPositionString = RdfHelper.addEnumPrefix(newCurrentPosition);
		final Resource newCurrentPositionResource = model.createResource(BASE_PREFIX + newCurrentPositionString);

		// set new value
		final Statement newStatement = model.createLiteralStatement(sw, currentPositionProperty, newCurrentPositionResource);
		model.add(newStatement);

	}
}
 
Example 9
Source File: JenaTransformationInjectConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaConnectedSegmentsInjectMatch> matches) throws Exception {
	final Model model = driver.getModel();

	final Property length = model.getProperty(BASE_PREFIX + ModelConstants.LENGTH);
	final Property connectsTo = model.getProperty(BASE_PREFIX + ModelConstants.CONNECTS_TO);
	final Property monitoredBy = model.getProperty(BASE_PREFIX + ModelConstants.MONITORED_BY);
	final Property segmentType = model.getProperty(BASE_PREFIX + ModelConstants.SEGMENT);

	for (final JenaConnectedSegmentsInjectMatch match : matches) {
		// create (segment2) node
		final Long newVertexId = driver.generateNewVertexId();
		final Resource segment2 = model.createResource(BASE_PREFIX + ID_PREFIX + newVertexId);
		model.add(model.createStatement(segment2, RDF.type, segmentType));
		model.add(model.createLiteralStatement(segment2, length, TrainBenchmarkConstants.DEFAULT_SEGMENT_LENGTH));

		// (segment1)-[:connectsTo]->(segment2)
		model.add(match.getSegment1(), connectsTo, segment2);
		// (segment2)-[:connectsTo]->(segment3)
		model.add(segment2, connectsTo, match.getSegment3());
		// (segment2)-[:monitoredBy]->(sensor)
		model.add(segment2, monitoredBy, match.getSensor());

		// remove (segment1)-[:connectsTo]->(segment3)
		model.remove(match.getSegment1(), connectsTo, match.getSegment3());
	}
}
 
Example 10
Source File: JenaTransformationInjectSemaphoreNeighbor.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaSemaphoreNeighborInjectMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property entry = model.getProperty(RdfConstants.BASE_PREFIX + ModelConstants.ENTRY);
	for (JenaSemaphoreNeighborInjectMatch match : matches) {
		model.remove(match.getRoute(), entry, match.getSemaphore());
	}
}
 
Example 11
Source File: JenaTransformationInjectRouteSensor.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaRouteSensorInjectMatch> routeSensorInjectMatchsMatches) throws IOException {
	final Model model = driver.getModel();
	final Property requires = model.getProperty(BASE_PREFIX + ModelConstants.REQUIRES);
	
	for (final JenaRouteSensorInjectMatch rsim : routeSensorInjectMatchsMatches) {
		model.remove(rsim.getRoute(), requires, rsim.getSensor()); 
	}

}
 
Example 12
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();



    HGQLConfig externalConfig = fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}
 
Example 13
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();

    HGQLConfig externalConfig = HGQLConfig.fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = HGQLConfig.fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}