org.openrdf.repository.RepositoryException Java Examples

The following examples show how to use org.openrdf.repository.RepositoryException. 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: TestRemoteGOM.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility to load statements from a resource
 */
private void load(final URL n3, final RDFFormat rdfFormat)
        throws IOException, RDFParseException, RepositoryException {
    final InputStream in = n3.openConnection().getInputStream();
    try {
        final Reader reader = new InputStreamReader(in);

        // FIXME: Loads into server directly, should change later to load
        // view ObjectManager
        final BigdataSailRepositoryConnection m_cxn = repo.getConnection();
        try {
            m_cxn.setAutoCommit(false);
            m_cxn.add(reader, "kb", rdfFormat);
            m_cxn.commit();
        } finally {
            m_cxn.close();
        }
    } finally {
        in.close();
    }
}
 
Example #2
Source File: ObjectParserTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testJSONLD() throws UpdateExecutionException {

    try {
        URL url = new URL("http://example.com/");

        ObjectParser objectParser = new ObjectParser();
        List<Annotation> annotations = objectParser.parse(JSONLD, url, RDFFormat.JSONLD, true);

        for(Annotation anno : annotations) {
            System.out.println(anno.toString());
        }

        assertEquals(1, annotations.size());

        objectParser.shutdown();
    } catch (RepositoryException | MalformedURLException | RepositoryConfigException e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Set<String> contextNames() {
    HashSet<String> names = new HashSet<>();
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> rs = conn.getContextIDs();
        while (rs.hasNext()) {
            names.add(rs.next().stringValue());
        }
        return names;
    } catch (RepositoryException x) {
        LOG.error("getting context names : {}", x.getMessage());
    } finally {
        closeConnection(conn, "Getting context names");
    }
    return names;
}
 
Example #4
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void write(DataSource ds, String contextName) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            if (context.stringValue().equals(contextName)) {
                write(ds, conn, context);
            }
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example #5
Source File: IdentifierBuilder.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if there is no suffix found in any other resource than the given one
 * that would possibly result into the same identifier name when processed by {@link #toJavaName(String)}.
 * @param resource The resource which suffix should be checked.
 * @return Returns true iff the no other possibly conflicting IRI is found in the repository.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private boolean isFileOrFragmentNameUnique(ResourceObject resource) throws RepositoryException {
    String fragment = getFileOrFragmentName(resource);
    // A conflicting label may be lead by a separator and some non-alphanumeric characters:
    StringBuilder regex = new StringBuilder("(.*)(:|/|#)([^a-zA-Z0-9])*");
    for(int i = 0; i < fragment.length(); i++) {
        char c = fragment.charAt(i);
        if(Character.isJavaIdentifierPart(c)) {
            regex.append(c);
        }
        // Between each char (and at the end) there may be non-alphanumeric chars (would be pruned out by name generation):
        regex.append("([^a-zA-Z0-9])*");
    }
    regex.append("$");

    try {
        return !connection.prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   ?s ?p ?o . " +
                        "   FILTER( ?s != <" + resource.getResourceAsString() + "> && REGEX(LCASE(str(?s)), \"" + regex + "\") )" +
                        "}"
        ).evaluate();
    } catch (MalformedQueryException | QueryEvaluationException | RepositoryException e) {
        throw new RepositoryException(e);
    }
}
 
Example #6
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void add(TripleStore source) {
    Objects.requireNonNull(source);
    Repository sourceRepository;
    if (source instanceof TripleStoreBlazegraph) {
        sourceRepository = ((TripleStoreBlazegraph) source).repo;
        RepositoryConnection sourceConn = null;
        try {
            sourceConn = sourceRepository.getConnection();
            copyFrom(sourceConn);
        } catch (RepositoryException e) {
            LOG.error("Connecting to the source repository : {}", e.getMessage());
        } finally {
            if (sourceConn != null) {
                closeConnection(sourceConn, "Copying from source");
            }
        }
    } else {
        throw new TripleStoreException(String.format("Add to %s from source %s is not supported",
            getImplementationName(), source.getImplementationName()));
    }
}
 
Example #7
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * Load data in specified graph (use default graph if contexts is null)
 * 
 * @param filePath
 * @param format
 * @param contexts
 * @throws RepositoryException
 * @throws IOException
 * @throws RDFParseException
 */
public void loadDataFromFile(String filePath, RDFFormat format,
		Resource... contexts) throws RepositoryException,
		RDFParseException, IOException {
	RepositoryConnection con = null;
	try {
		con = currentRepository.getConnection();
		// upload a file
		File f = new File(filePath);
		con.add(f, null, format, contexts);
	} finally {
		try {
			con.close();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}

}
 
Example #8
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Ends the locking status, committing all changed that have been made since
 * this RepositoryModel was locked and switching back to auto-commit mode.
 */
@Override
public synchronized void unlock() {
	if(!isLocked()) {
		return;
	}
	
	try {
		
		// commit all changes
		this.connection.commit();
		
		// unlock this model
		this.locked = false;
	} catch(RepositoryException e) {
		// TODO: a LockException would be more appropriate IMHO but this
		// requires a change to the RDF2Go API
		throw new ModelRuntimeException(e);
	}
}
 
Example #9
Source File: TestTicket1755.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	private void testQuery(final BigdataSailRepositoryConnection conn,
			final String query, final int expectedIVs) throws MalformedQueryException, RepositoryException, QueryEvaluationException {
		TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
		TupleQueryResult tqr = tq.evaluate();
		try {
			int cnt = 0;
			while (tqr.hasNext()) {
				tqr.next();
				cnt++;
			}
//			assertEquals("Expected 1 row in resultset", 1, cnt);
			QueryRoot queryRoot = ((BigdataSailTupleQuery)tq).getASTContainer().getOriginalAST();
			cnt = 0;
			for (Object filterNode: queryRoot.getWhereClause().getChildren(FilterNode.class)) {
				cnt += checkNode((BOp)filterNode);
			}
			assertEquals("Expected inlined IV for date literal", expectedIVs, cnt);
		} finally {
			tqr.close();
		}
	}
 
Example #10
Source File: SchemaSanitizingObjectSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the resource as the value of the inverse property for any value of a property of this
 * resource that has an inverse property.
 * @throws RepositoryException Thrown if an error occurs while updating the repository.
 */
private void sanitizeInverseProperties() throws RepositoryException {
    ObjectConnection connection = getObjectConnection();
    try {
        connection.prepareUpdate(QueryLanguage.SPARQL,
                "INSERT {" +
                        "   ?o ?inverse <" + getResourceAsString() + "> . " +
                        "} WHERE {" +
                        "   <" + getResourceAsString() + "> ?p ?o . " +
                        "   ?p owl:inverseOf ?inverse . " +
                        "}"
        ).execute();

    } catch (MalformedQueryException | UpdateExecutionException e) {
        throw new RepositoryException(e);
    }
}
 
Example #11
Source File: VarArgSetterSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
MethodSpec buildSignature(RDFSClazz domainClazz, OntGenerationConfig config) throws RepositoryException {
    if (getRanges() != null) {
        MethodSpec.Builder setter = buildParameterlessSetterSignature(domainClazz, config);

        // Get the vararg parameter type:
        TypeName paramType = ArrayTypeName.of(getParameterType(config, false));


        return setter.addParameter(paramType, "values")
                     .varargs()
                     .build();
    } else {
        return null;
    }
}
 
Example #12
Source File: RemotePropertySet.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public boolean removeAll(Collection<?> c) {
	ObjectConnection conn = getObjectConnection();
	boolean modified = false;
	try {
		boolean autoCommit = conn.isAutoCommit();
		if (autoCommit)
			conn.setAutoCommit(false);
		try {
			for (Object o : c)
				if (remove(o))
					modified = true;
			if (autoCommit)
				conn.setAutoCommit(true);
		} finally {
			if (autoCommit && !conn.isAutoCommit()) {
				conn.rollback();
				conn.setAutoCommit(true);
			}
		}
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
	refresh();
	refreshEntity();
	return modified;
}
 
Example #13
Source File: LiteralTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void testDay() throws Exception {
	TestConcept tester = manager.addDesignation(manager.getObjectFactory().createObject(), TestConcept.class);
	Resource bNode = (Resource) manager.addObject(tester);
	Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	cal.set(1970, 0, 1, 0, 0, 0);
	cal.set(Calendar.MILLISECOND, 0);
	Date date = cal.getTime();
	try {
		manager.add(bNode, dateURI, getValueFactory().createLiteral(
				"1970-01-01Z", XMLSchema.DATE));
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
	cal.setTime(tester.getADate());
	assertEquals(date, cal.getTime());
}
 
Example #14
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public void loadDataFromInputStream(InputStream is, RDFFormat format,
		Resource... contexts) throws RepositoryException,
		RDFParseException, IOException {
	RepositoryConnection con = null;
	try {
		con = currentRepository.getConnection();
		con.add(is, "http://geotriples.eu", format, contexts);
	} finally {
		try {
			con.close();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}

}
 
Example #15
Source File: BigdataSparqlTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
    protected Repository newRepository() throws RepositoryException {

        if (true) {
            final Properties props = getProperties();
            
            if (cannotInlineTests.contains(testURI)){
            	// The test can not be run using XSD inlining.
                props.setProperty(Options.INLINE_XSD_DATATYPE_LITERALS, "false");
            	props.setProperty(Options.INLINE_DATE_TIMES, "false");
            }
            
            if(unicodeStrengthIdentical.contains(testURI)) {
            	// Force identical Unicode comparisons.
            	props.setProperty(Options.COLLATOR, CollatorEnum.JDK.toString());
            	props.setProperty(Options.STRENGTH, StrengthEnum.Identical.toString());
            }
            
            final BigdataSail sail = new BigdataSail(props);
//            return new DatasetRepository(new BigdataSailRepository(sail));
            return new BigdataSailRepository(sail);
        } else {
            return new DatasetRepository(new SailRepository(new MemoryStore()));
        }
    }
 
Example #16
Source File: RDFSContainer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
public void add(int index, Object obj) {
	ObjectConnection conn = getObjectConnection();
	try {
		boolean autoCommit = conn.isAutoCommit();
		if (autoCommit)
			conn.setAutoCommit(false);
		try {
			for (int i = size() - 1; i >= index; i--) {
				replace(i + 1, get(i));
			}
			replace(index, obj);
			if (_size > UNKNOWN)
				_size++;
			if (autoCommit)
				conn.setAutoCommit(true);
		} finally {
			if (autoCommit && !conn.isAutoCommit()) {
				conn.rollback();
				conn.setAutoCommit(true);
			}
		}
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
}
 
Example #17
Source File: PathEqualityTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
public void persistTestData() throws RepositoryException, InstantiationException, IllegalAccessException {
    // Persisting some data
    Annotation annotation = anno4j.createObject(Annotation.class);
    FirstPathEqualityTestBody firstTestBody = anno4j.createObject(FirstPathEqualityTestBody.class);
    firstTestBody.setValue("First Value");
    firstTestBody.setAnotherValue("Another Value");
    annotation.addBody(firstTestBody);

    Annotation annotation1 = anno4j.createObject(Annotation.class);
    SecondPathEqualityTestBody secondTestBody = anno4j.createObject(SecondPathEqualityTestBody.class);
    secondTestBody.setValue("Second Value");
    secondTestBody.setAnotherValue("Another Value");
    annotation1.addBody(secondTestBody);

    Annotation annotation2 = anno4j.createObject(Annotation.class);
    FirstPathEqualityTestBody firstTestBody2 = anno4j.createObject(FirstPathEqualityTestBody.class);
    firstTestBody2.setValue("Second Value");
    annotation2.addBody(firstTestBody2);
}
 
Example #18
Source File: OWLSchemaPersistingManager.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Persists the information that a property is restricted to have a minimum number of values.
 * All properties with {@link MinCardinality} annotation are considered.
 * @param annotatedObjects The {@link Iri} annotated objects that should be considered.
 * @throws RepositoryException Thrown on error regarding the connected triplestore.
 */
private void persistMinCardinality(Collection<AccessibleObject> annotatedObjects) throws RepositoryException {
    // Get those methods and fields that have the @MinCardinality annotation:
    Collection<AccessibleObject> minCardinalityObjects = filterObjectsWithAnnotation(annotatedObjects, MinCardinality.class);

    for (AccessibleObject object : minCardinalityObjects) {
        for(MinCardinality minCardinalityAnnotation : unpackAnnotations(object, MinCardinality.class)) {
            int minCardinality = minCardinalityAnnotation.value();

            String onClazzIri = null;
            if(minCardinalityAnnotation.onClass() != OWLClazz.class) {
                onClazzIri = getIriFromObject(minCardinalityAnnotation.onClass());
            }

            // Add the cardinality to the restriction:
            Restriction restriction = buildRestrictionForProperty(object, onClazzIri);
            if(onClazzIri == null) {
                restriction.setMinCardinality(Sets.<Number>newHashSet(BigInteger.valueOf(minCardinality)));
            } else {
                restriction.setMinQualifiedCardinality(Sets.<Number>newHashSet(BigInteger.valueOf(minCardinality)));
            }
        }
    }
}
 
Example #19
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterator<org.ontoware.rdf2go.model.Statement> findStatements(
        ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object)
        throws ModelRuntimeException {
	assertModel();
	// convert parameters to OpenRDF data types
	org.openrdf.model.Resource openRdfSubject = (org.openrdf.model.Resource)ConversionUtil
	        .toOpenRDF(subject, this.valueFactory);
	org.openrdf.model.URI openRdfPredicate = (org.openrdf.model.URI)ConversionUtil.toOpenRDF(
	        predicate, this.valueFactory);
	Value openRdfObject = ConversionUtil.toOpenRDF(object, this.valueFactory);
	
	try {
		// find the matching statements
		CloseableIteration<? extends org.openrdf.model.Statement,? extends OpenRDFException> statements = this.connection
		        .getStatements(openRdfSubject, openRdfPredicate, openRdfObject, true,
		                this.openRdfContext);
		// wrap them in a StatementIterable
		return new StatementIterator(statements, this);
	} catch(RepositoryException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #20
Source File: IdentifierBuilder.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the RDFS label preferred by the given configuration.
 * @param resource The resource for which to get a label.
 * @param config The configuration object specifying the language preference.
 * @return Returns the RDFS label preferred or null if no label could be found.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private String getPreferredRDFSLabel(ResourceObject resource, OntGenerationConfig config) throws RepositoryException {
    try {
        RDFSSchemaResource schemaResource = connection.findObject(RDFSSchemaResource.class, resource.getResource());
        if(schemaResource != null) {
            CharSequence bestLabel = null;
            for (CharSequence label : schemaResource.getLabels()) {
                if (config.isPreferredForIdentifiers(label, bestLabel)) {
                    bestLabel = label;
                }
            }
            if (bestLabel != null) {
                return bestLabel.toString();
            } else {
                return null;
            }

        } else { // Something that is not a RDFS resource has no RDFS label:
            return null;
        }

    } catch (QueryEvaluationException | RepositoryException e) {
        throw new RepositoryException();
    }
}
 
Example #21
Source File: SesameTransformationInjectPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<SesamePosLengthInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI typeURI = vf.createURI(BASE_PREFIX + ModelConstants.LENGTH);
	final Literal zeroLiteral = vf.createLiteral(0);

	for (final SesamePosLengthInjectMatch match : matches) {
		final URI segment = match.getSegment();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(segment, typeURI, null, true);
		con.remove(statementsToRemove);

		con.add(segment, typeURI, zeroLiteral);
	}
}
 
Example #22
Source File: TestTicket632.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example #23
Source File: GraphHandler.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * Delete data from the graph.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return the EmptySuccessView if successes
 * @throws ClientHTTPException throws when there are errors in getting the name of the Graph
 * @throws ServerHTTPException throws when errors happens update the data
 */
private ModelAndView getDeleteDataResult(final Repository repository,
		final HttpServletRequest request, final HttpServletResponse response)
		throws ClientHTTPException, ServerHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	URI graph = getGraphName(request, vf);

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.clear(graph);
		}
		repositoryCon.close();
		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
	}
}
 
Example #24
Source File: PropertyBuildingSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the given resource in {@link BuildableRDFSClazz} type.
 * @param clazz The class resource which should be converted.
 * @return The class in the {@link BuildableRDFSClazz} type or null if there is no such class
 * in the repository.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private BuildableRDFSClazz asBuildableClazz(RDFSClazz clazz) throws RepositoryException {
    try {
        return getObjectConnection().findObject(BuildableRDFSClazz.class, clazz.getResource());
    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #25
Source File: Anno4j.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
public void clearContext(URI context) throws RepositoryException {
    Transaction transaction = createTransaction();
    transaction.clearContext(context);
    transaction.close();
}
 
Example #26
Source File: AdderSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public MethodSpec buildAdder(RDFSClazz domainClazz, OntGenerationConfig config) throws RepositoryException {
    // Add the abstract modifier to the signature, because there is no implementation in the interface:
    return buildSignature(domainClazz, config)
            .toBuilder()
            .addModifiers(Modifier.ABSTRACT)
            .build();
}
 
Example #27
Source File: ResourceObjectSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the resource object this support class belongs to has the given type,
 * i.e. a {@code rdf:type}-path exists from the resource to the given class.
 * @param type The type for which to check. This should be (but is not required to be) a RDFS/OWL class.
 * @return Returns true iff the resource has the specified {@code type}.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
protected boolean isInstance(Class<? extends ResourceObject> type) throws RepositoryException {
    // Get the types @Iri annotation:
    Iri annotation = type.getAnnotation(Iri.class);
    if(annotation != null) {
        return isInstance(new URIImpl(annotation.value()));

    } else {
        // If the type has no @Iri annotation it's not a class and thus this resource isn't an instance:
        return false;
    }
}
 
Example #28
Source File: OWLSchemaPersistingManager.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Persists the information that a property is transitive to the default graph of the connected triplestore.
 * All properties with {@link com.github.anno4j.annotations.Transitive} annotation are considered.
 * @param annotatedObjects The {@link Iri} annotated objects that should be considered.
 * @throws RepositoryException Thrown on error regarding the connected triplestore.
 * @throws UpdateExecutionException Thrown if an error occurred while executing the update.
 */
private void persistTransitive(Collection<AccessibleObject> annotatedObjects) throws RepositoryException, UpdateExecutionException {
    // Get those methods and fields that have the @Transitive annotation:
    Collection<AccessibleObject> transitiveObjects = filterObjectsWithAnnotation(annotatedObjects, Transitive.class);

    // Prepare the update query and execute it:
    try {
        Update update = buildInstanceUpdate(getIrisFromObjects(transitiveObjects), OWL.TRANSITIVE_PROPERTY);
        update.execute();
    } catch (MalformedQueryException e) {
        throw new UpdateExecutionException();
    }
}
 
Example #29
Source File: CachedPropertySet.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public void clear() {
	if (isCacheComplete() && !cache.isEmpty()) {
		ObjectConnection conn = getObjectConnection();
		try {
			boolean autoCommit = conn.isAutoCommit();
			if (autoCommit)
				conn.setAutoCommit(false);
			try {
				for (Object o : cache)
					remove(o);
				if (autoCommit)
					conn.setAutoCommit(true);
			} finally {
				if (autoCommit && !conn.isAutoCommit()) {
					conn.rollback();
					conn.setAutoCommit(true);
				}
			}
		} catch (RepositoryException e) {
			throw new ObjectPersistException(e);
		}
		refreshCache();
	} else if (!cached || !cache.isEmpty()) {
		super.clear();
		refreshCache();
	}
	cache = Collections.EMPTY_LIST;
	cached = true;
}
 
Example #30
Source File: CRUDTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all statements that are present in any context of a repository having the specified subject, predicate and/or object.
 * @param connection A connection to the repository to query.
 * @param subject The subject the returned triples should have or null for any subject.
 * @param predicate The predicate the returned triples should have or null for any predicate.
 * @param object The object the returned triples should have or null for any object.
 * @return Returns the set of all triples present in the repository having the desired spo-structure.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
private Collection<Statement> getStatements(RepositoryConnection connection, Resource subject, URI predicate, Value object) throws RepositoryException {
    // Query the repository:
    RepositoryResult<Statement> result = connection.getStatements(subject, predicate, object, false);

    // Fetch all statements from the result:
    Collection<Statement> statements = new HashSet<>();
    while (result.hasNext()) {
        statements.add(result.next());
    }
    return statements;
}