org.eclipse.rdf4j.RDF4JException Java Examples

The following examples show how to use org.eclipse.rdf4j.RDF4JException. 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: QueryStorage.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Save a query. UNSAFE from an injection point of view. It is the responsibility of the calling code to call
 * checkAccess() with the full credentials first.
 *
 * @param repository    the repository the query is associated with
 * @param queryName     the name for the query
 * @param userName      the user saving the query
 * @param shared        whether the query is to be shared with other users
 * @param queryLanguage the language, SeRQL or SPARQL, of the query
 * @param queryText     the actual query text
 * @param infer
 * @param rowsPerPage   rows to display per page, may be 0 (all), 10, 50, 100, or 200)
 * @throws RDF4JException
 */
public void saveQuery(final HTTPRepository repository, final String queryName, final String userName,
		final boolean shared, final QueryLanguage queryLanguage, final String queryText, final boolean infer,
		final int rowsPerPage) throws RDF4JException {
	if (QueryLanguage.SPARQL != queryLanguage && QueryLanguage.SERQL != queryLanguage) {
		throw new RepositoryException("May only save SPARQL or SeRQL queries, not" + queryLanguage.toString());
	}
	if (0 != rowsPerPage && 10 != rowsPerPage && 20 != rowsPerPage && 50 != rowsPerPage && 100 != rowsPerPage
			&& 200 != rowsPerPage) {
		throw new RepositoryException("Illegal value for rows per page: " + rowsPerPage);
	}
	this.checkQueryText(queryText);
	final QueryStringBuilder save = new QueryStringBuilder(SAVE);
	save.replaceURI(REPOSITORY, repository.getRepositoryURL());
	save.replaceURI(QUERY, "urn:uuid:" + UUID.randomUUID());
	save.replaceQuote(QUERY_NAME, queryName);
	this.replaceUpdateFields(save, userName, shared, queryLanguage, queryText, infer, rowsPerPage);
	updateQueryRepository(save.toString());
}
 
Example #2
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void visitInsertData(Resource query) throws RDF4JException {
	SingletonSet stub = new SingletonSet();
	tupleRoot = new QueryRoot(stub);
	tupleNode = stub;
	TupleExpr insertExpr;
	Value insert = TripleSources.singleValue(query, SP.DATA_PROPERTY, store);
	if (!(insert instanceof Resource)) {
		throw new MalformedSpinException(String.format("Value of %s is not a resource", SP.DATA_PROPERTY));
	}
	visitInsert((Resource) insert);
	insertExpr = tupleNode;
	insertExpr.setParentNode(null);

	DataVisitor visitor = new DataVisitor();
	insertExpr.visit(visitor);
	updateRoot = new InsertData(visitor.getData());
}
 
Example #3
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInsertDelete() throws RDF4JException {
	final Statement stmt = vf.createStatement(vf.createIRI(URN_TEST_S1), vf.createIRI(URN_TEST_P1),
			vf.createIRI(URN_TEST_O1));
	testCon.begin();
	testCon.prepareUpdate(QueryLanguage.SPARQL,
			"INSERT DATA {<" + URN_TEST_S1 + "> <" + URN_TEST_P1 + "> <" + URN_TEST_O1 + ">}").execute();
	testCon.prepareUpdate(QueryLanguage.SPARQL,
			"DELETE DATA {<" + URN_TEST_S1 + "> <" + URN_TEST_P1 + "> <" + URN_TEST_O1 + ">}").execute();
	testCon.commit();

	testCon.exportStatements(null, null, null, false, new AbstractRDFHandler() {

		@Override
		public void handleStatement(Statement st) throws RDFHandlerException {
			assertThat(st).isNotEqualTo(stmt);
		}
	});
}
 
Example #4
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testAddRemove() throws RDF4JException {
	final Statement stmt = vf.createStatement(vf.createIRI(URN_TEST_S1), vf.createIRI(URN_TEST_P1),
			vf.createIRI(URN_TEST_O1));
	testCon.begin();
	testCon.add(stmt);
	testCon.remove(stmt);
	testCon.commit();

	testCon.exportStatements(null, null, null, false, new AbstractRDFHandler() {

		@Override
		public void handleStatement(Statement st) throws RDFHandlerException {
			assertThat(st).isNotEqualTo(stmt);
		}
	});
}
 
Example #5
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Var getVar(Value v) throws RDF4JException {
	Var var = null;
	if (v instanceof Resource) {
		String varName = getVarName((Resource) v);
		if (varName != null) {
			var = createVar(varName);
		}
	}

	if (var == null) {
		// it must be a constant then
		var = TupleExprs.createConstVar(v);
	}

	return var;
}
 
Example #6
Source File: RepositoryManagerFederator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Adds a new repository to the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}, which is a
 * federation of the given repository id's, which must also refer to repositories already managed by the
 * {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}.
 *
 * @param fedID       the desired identifier for the new federation repository
 * @param description the desired description for the new federation repository
 * @param members     the identifiers of the repositories to federate, which must already exist and be managed by
 *                    the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager}
 * @param readonly    whether the federation is read-only
 * @param distinct    whether the federation enforces distinct results from its members
 * @throws MalformedURLException if the {@link org.eclipse.rdf4j.repository.manager.RepositoryManager} has a
 *                               malformed location
 * @throws RDF4JException        if a problem otherwise occurs while creating the federation
 */
public void addFed(String fedID, String description, Collection<String> members, boolean readonly, boolean distinct)
		throws MalformedURLException, RDF4JException {
	if (members.contains(fedID)) {
		throw new RepositoryConfigException("A federation member may not have the same ID as the federation.");
	}
	Model graph = new LinkedHashModel();
	BNode fedRepoNode = valueFactory.createBNode();
	LOGGER.debug("Federation repository root node: {}", fedRepoNode);
	addToGraph(graph, fedRepoNode, RDF.TYPE, RepositoryConfigSchema.REPOSITORY);
	addToGraph(graph, fedRepoNode, RepositoryConfigSchema.REPOSITORYID, valueFactory.createLiteral(fedID));
	addToGraph(graph, fedRepoNode, RDFS.LABEL, valueFactory.createLiteral(description));
	addImplementation(members, graph, fedRepoNode, readonly, distinct);
	RepositoryConfig fedConfig = RepositoryConfig.create(graph, fedRepoNode);
	fedConfig.validate();
	manager.addRepositoryConfig(fedConfig);
}
 
Example #7
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int getMaxIterationCount(Resource ruleProp, TripleSource store) throws RDF4JException {
	Value v = TripleSources.singleValue(ruleProp, SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY, store);
	if (v == null) {
		return -1;
	} else if (v instanceof Literal) {
		try {
			return ((Literal) v).intValue();
		} catch (NumberFormatException e) {
			throw new MalformedSpinException("Value for " + SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY
					+ " must be of datatype " + XMLSchema.INTEGER + ": " + ruleProp);
		}
	} else {
		throw new MalformedSpinException(
				"Non-literal value for " + SPIN.RULE_PROPERTY_MAX_ITERATION_COUNT_PROPERTY + ": " + ruleProp);
	}
}
 
Example #8
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Projection visitResultNodes(Resource resultNodes) throws RDF4JException {
	ProjectionElemList projElemList = new ProjectionElemList();
	Iteration<Resource, QueryEvaluationException> iter = TripleSources.listResources(resultNodes,
			store);
	while (iter.hasNext()) {
		Resource r = iter.next();
		ProjectionElem projElem = visitResultNode(r);
		projElemList.addElement(projElem);
	}

	Projection proj = new Projection();
	proj.setProjectionElemList(projElemList);

	tupleRoot = new DescribeOperator(proj);
	return proj;
}
 
Example #9
Source File: TestProxyRepositoryFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public final void testGetRepository() throws RDF4JException, IOException {
	Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE,
			RDFFormat.TURTLE);
	RepositoryConfig config = RepositoryConfig.create(graph,
			Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
					.orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config")));
	config.validate();
	assertThat(config.getID()).isEqualTo("proxy");
	assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'");
	RepositoryImplConfig implConfig = config.getRepositoryImplConfig();
	assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository");
	assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class);
	assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory");

	// Factory just needs a resolver instance to proceed with construction.
	// It doesn't actually invoke the resolver until the repository is
	// accessed. Normally LocalRepositoryManager is the caller of
	// getRepository(), and will have called this setter itself.
	ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig);
	repository.setRepositoryResolver(mock(RepositoryResolver.class));
	assertThat(repository).isInstanceOf(ProxyRepository.class);
}
 
Example #10
Source File: AbstractCommandTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/***
 * Add a new repository to the manager.
 *
 * @param configStream input stream of the repository configuration
 * @return ID of the repository as string
 * @throws IOException
 * @throws RDF4JException
 */
protected String addRepository(InputStream configStream) throws IOException, RDF4JException {
	RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, SimpleValueFactory.getInstance());

	Model graph = new LinkedHashModel();
	rdfParser.setRDFHandler(new StatementCollector(graph));
	rdfParser.parse(
			new StringReader(IOUtil.readString(new InputStreamReader(configStream, StandardCharsets.UTF_8))),
			RepositoryConfigSchema.NAMESPACE);
	configStream.close();

	Resource repositoryNode = Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY))
			.orElseThrow(() -> new RepositoryConfigException("could not find subject resource"));

	RepositoryConfig repoConfig = RepositoryConfig.create(graph, repositoryNode);
	repoConfig.validate();
	manager.addRepositoryConfig(repoConfig);

	String repId = Models.objectLiteral(graph.filter(repositoryNode, RepositoryConfigSchema.REPOSITORYID, null))
			.orElseThrow(() -> new RepositoryConfigException("missing repository id"))
			.stringValue();

	return repId;
}
 
Example #11
Source File: RDFSailInserter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void addStatement(Resource subj, IRI pred, Value obj, Resource ctxt) throws RDF4JException {
	if (enforcesContext()) {
		addStatement(uc, subj, pred, obj, contexts);
	} else {
		if (uc != null && ctxt == null) {
			final IRI insertGraph = uc.getDataset().getDefaultInsertGraph();
			if (insertGraph != null) {
				addStatement(uc, subj, pred, obj, insertGraph);
			} else {
				addStatement(uc, subj, pred, obj);
			}
		} else {
			addStatement(uc, subj, pred, obj, ctxt);
		}
	}
}
 
Example #12
Source File: CustomGraphQueryInferencerFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Sail getSail(SailImplConfig config) throws SailConfigException {
	if (!SAIL_TYPE.equals(config.getType())) {
		throw new SailConfigException("Invalid Sail type: " + config.getType());
	}
	CustomGraphQueryInferencer sail = new CustomGraphQueryInferencer();
	if (config instanceof CustomGraphQueryInferencerConfig) {
		CustomGraphQueryInferencerConfig customConfig = (CustomGraphQueryInferencerConfig) config;
		try {
			sail.setFields(customConfig.getQueryLanguage(), customConfig.getRuleQuery(),
					customConfig.getMatcherQuery());
		} catch (RDF4JException e) {
			throw new SailConfigException("Problem occured parsing rule or matcher query text.", e);
		}
	}
	return sail;
}
 
Example #13
Source File: ExploreServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void service(final WorkbenchRequest req, final HttpServletResponse resp, final TupleResultBuilder builder,
		final RepositoryConnection con) throws BadRequestException, RDF4JException {
	final Value value = req.getValue("resource");
	logger.debug("resource = {}", value);

	// At worst, malicious parameter value could cause inaccurate
	// reporting of count in page.
	int count = req.getInt("know_total");
	if (count == 0) {
		count = this.processResource(con, builder, value, 0, Integer.MAX_VALUE, false).getTotalResultCount();
	}
	this.cookies.addTotalResultCountCookie(req, resp, (int) count);
	final int offset = req.getInt("offset");
	int limit = LIMIT_DEFAULT;
	if (req.isParameterPresent(LIMIT)) {
		limit = req.getInt(LIMIT);
		if (0 == limit) {
			limit = Integer.MAX_VALUE;
		}
	}
	this.processResource(con, builder, value, offset, limit, true);
}
 
Example #14
Source File: ExploreServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Query the repository for all instances of the given value, optionally writing the results into the HTTP response.
 *
 * @param con     the connection to the repository
 * @param builder used for writing to the HTTP response
 * @param value   the value to query the repository for
 * @param offset  The result at which to start rendering results.
 * @param limit   The limit on the number of results to render.
 * @param render  If false, suppresses output to the HTTP response.
 * @throws RDF4JException if there is an issue iterating through results
 * @return The count of all triples in the repository using the given value.
 */
protected ResultCursor processResource(final RepositoryConnection con, final TupleResultBuilder builder,
		final Value value, final int offset, final int limit, final boolean render) throws RDF4JException {
	final ResultCursor cursor = new ResultCursor(offset, limit, render);
	boolean resource = value instanceof Resource;
	if (resource) {
		export(con, builder, cursor, (Resource) value, null, null);
		logger.debug("After subject, total = {}", cursor.getTotalResultCount());
	}
	if (value instanceof IRI) {
		export(con, builder, cursor, null, (IRI) value, null);
		logger.debug("After predicate, total = {}", cursor.getTotalResultCount());
	}
	if (value != null) {
		export(con, builder, cursor, null, null, value);
		logger.debug("After object, total = {}", cursor.getTotalResultCount());
	}
	if (resource) {
		export(con, builder, cursor, null, null, null, (Resource) value);
		logger.debug("After context, total = {}", cursor.getTotalResultCount());
	}
	return cursor;
}
 
Example #15
Source File: SavedQueriesServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void doPost(final WorkbenchRequest wreq, final HttpServletResponse resp, final String xslPath)
		throws BadRequestException, IOException, RDF4JException {
	final String urn = wreq.getParameter("delete");
	if (null == urn || urn.isEmpty()) {
		throw new BadRequestException("Expected POST to contain a 'delete=' parameter.");
	}
	final boolean accessible = storage.checkAccess((HTTPRepository) this.repository);
	if (accessible) {
		String userName = wreq.getParameter(SERVER_USER);
		if (null == userName) {
			userName = "";
		}
		final IRI queryURI = SimpleValueFactory.getInstance().createIRI(urn);
		if (storage.canChange(queryURI, userName)) {
			storage.deleteQuery(queryURI, userName);
		} else {
			throw new BadRequestException("User '" + userName + "' may not delete query id " + urn);
		}
	}
	this.service(wreq, resp, xslPath);
}
 
Example #16
Source File: QueryStorage.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Retrieves the specified query text. No security checks are done here. If the saved query exists, its text is
 * returned.
 *
 * @param repository Repository that the saved query is associated with.
 * @param owner      The user that saved the query.
 * @param queryName  The name given to the saved query.
 * @return the text of the saved query, if it exists
 * @throws RDF4JException      if a problem occurs accessing storage
 * @throws BadRequestException if the specified query doesn't exist
 */
public String getQueryText(final HTTPRepository repository, final String owner, final String queryName)
		throws RDF4JException, BadRequestException {
	final QueryStringBuilder select = new QueryStringBuilder(SELECT_TEXT);
	select.replaceQuote(QueryStorage.USER_NAME, owner);
	select.replaceURI(REPOSITORY, repository.getRepositoryURL());
	select.replaceQuote(QUERY_NAME, queryName);
	try (RepositoryConnection connection = this.queries.getConnection()) {
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, select.toString());
		try (TupleQueryResult result = query.evaluate()) {
			if (result.hasNext()) {
				return result.next().getValue("queryText").stringValue();
			} else {
				throw new BadRequestException("Could not find query entry in storage.");
			}
		}

	}
}
 
Example #17
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public TupleFunction parseMagicProperty(IRI propUri, TripleSource store) throws RDF4JException {
	for (TupleFunctionParser tupleFunctionParser : tupleFunctionParsers) {
		TupleFunction tupleFunction = tupleFunctionParser.parse(propUri, store);
		if (tupleFunction != null) {
			return tupleFunction;
		}
	}
	logger.warn("No TupleFunctionParser for magic property: {}", propUri);
	throw new MalformedSpinException(String.format("No TupleFunctionParser for magic property: %s", propUri));
}
 
Example #18
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitDescribe(Resource describe) throws RDF4JException {
	Value resultNodes = TripleSources.singleValue(describe, SP.RESULT_NODES_PROPERTY, store);
	if (!(resultNodes instanceof Resource)) {
		throw new MalformedSpinException(
				String.format("Value of %s is not a resource", SP.RESULT_NODES_PROPERTY));
	}

	projElems = new LinkedHashMap<>();
	Projection projection = visitResultNodes((Resource) resultNodes);
	TupleExpr whereExpr = visitWhere(describe);
	projection.setArg(whereExpr);
	addSourceExpressions(projection, projElems.values());
}
 
Example #19
Source File: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSpinRenderer() throws IOException, RDF4JException {
	StatementCollector expected = new StatementCollector();
	RDFParser parser = Rio.createParser(RDFFormat.TURTLE);
	parser.setRDFHandler(expected);
	try (InputStream rdfStream = testURL.openStream()) {
		parser.parse(rdfStream, testURL.toString());
	}

	// get query from sp:text
	String query = null;
	for (Statement stmt : expected.getStatements()) {
		if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) {
			query = stmt.getObject().stringValue();
			break;
		}
	}
	assertNotNull(query);

	ParsedOperation parsedOp = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, testURL.toString());

	StatementCollector actual = new StatementCollector();
	renderer.render(parsedOp, actual);

	Object operation = (parsedOp instanceof ParsedQuery) ? ((ParsedQuery) parsedOp).getTupleExpr()
			: ((ParsedUpdate) parsedOp).getUpdateExprs();
	assertTrue("Operation was\n" + operation + "\nExpected\n" + toRDF(expected) + "\nbut was\n" + toRDF(actual),
			Models.isomorphic(actual.getStatements(), expected.getStatements()));
}
 
Example #20
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void executeNoContent(HttpUriRequest method) throws IOException, RDF4JException {
	HttpResponse response = execute(method);
	try {
		if (response.getStatusLine().getStatusCode() >= 300) {
			throw new RepositoryException("Failed to get server protocol; no such resource on this server: "
					+ method.getURI().toString());
		}
	} finally {
		EntityUtils.consume(response.getEntity());
	}
}
 
Example #21
Source File: TestQueryServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetQueryTextUnrecognizedRef() throws BadRequestException, RDF4JException {
	WorkbenchRequest request = mock(WorkbenchRequest.class);
	when(request.isParameterPresent(QueryServlet.QUERY)).thenReturn(true);
	when(request.getParameter(QueryServlet.QUERY)).thenReturn(SHORT_QUERY);
	when(request.isParameterPresent(QueryServlet.REF)).thenReturn(true);
	when(request.getParameter(QueryServlet.REF)).thenReturn("junk");
	assertThat(servlet.getQueryText(request)).isEqualTo(SHORT_QUERY);
}
 
Example #22
Source File: TestExploreServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public final void testSES1723regression() throws RDF4JException {
	addToFooContext(":foo :foo :foo");
	connection.add(foo, foo, foo);
	assertStatementCount(foo, 2, 2);
	verify(builder).result(foo, foo, foo, foo);
	verify(builder).result(foo, foo, foo, null);
}
 
Example #23
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public synchronized void rollbackTransaction() throws RDF4JException, IOException, UnauthorizedException {
	checkRepositoryURL();

	if (transactionURL == null) {
		throw new IllegalStateException("Transaction URL has not been set");
	}

	String requestURL = transactionURL;
	HttpDelete method = applyAdditionalHeaders(new HttpDelete(requestURL));

	try {
		final HttpResponse response = execute(method);
		try {
			int code = response.getStatusLine().getStatusCode();
			if (code == HttpURLConnection.HTTP_NO_CONTENT) {
				// we're done.
				transactionURL = null;
				if (ping != null) {
					ping.cancel(false);
				}
			} else {
				throw new RepositoryException("unable to rollback transaction. HTTP error code " + code);
			}
		} finally {
			EntityUtils.consumeQuietly(response.getEntity());
		}
	} finally {
		method.reset();
	}
}
 
Example #24
Source File: SailUpdate.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void execute() throws UpdateExecutionException {
	ParsedUpdate parsedUpdate = getParsedUpdate();
	List<UpdateExpr> updateExprs = parsedUpdate.getUpdateExprs();
	Map<UpdateExpr, Dataset> datasetMapping = parsedUpdate.getDatasetMapping();

	SailUpdateExecutor executor = new SailUpdateExecutor(con.getSailConnection(), con.getValueFactory(),
			con.getParserConfig());

	boolean localTransaction = false;
	try {
		if (!getConnection().isActive()) {
			localTransaction = true;
			beginLocalTransaction();
		}
		for (UpdateExpr updateExpr : updateExprs) {

			Dataset activeDataset = getMergedDataset(datasetMapping.get(updateExpr));

			try {
				executor.executeUpdate(updateExpr, activeDataset, getBindings(), getIncludeInferred(),
						getMaxExecutionTime());
			} catch (RDF4JException | IOException e) {
				logger.warn("exception during update execution: ", e);
				if (!updateExpr.isSilent()) {
					throw new UpdateExecutionException(e);
				}
			}
		}

		if (localTransaction) {
			commitLocalTransaction();
			localTransaction = false;
		}
	} finally {
		if (localTransaction) {
			rollbackLocalTransaction();
		}
	}
}
 
Example #25
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private HttpResponse sendBooleanQueryViaHttp(HttpUriRequest method, Set<QueryResultFormat> booleanFormats)
		throws IOException, RDF4JException {

	final List<String> acceptValues = new ArrayList<>(booleanFormats.size());

	for (QueryResultFormat format : booleanFormats) {
		// Determine a q-value that reflects the user specified preference
		int qValue = 10;

		if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) {
			// Prefer specified format over other formats
			qValue -= 2;
		}

		for (String mimeType : format.getMIMETypes()) {
			String acceptParam = mimeType;

			if (qValue < 10) {
				acceptParam += ";q=0." + qValue;
			}

			acceptValues.add(acceptParam);
		}
	}

	method.addHeader(ACCEPT_PARAM_NAME, String.join(", ", acceptValues));

	return executeOK(method);
}
 
Example #26
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TupleExpr visitHaving(Resource having) throws RDF4JException {
	UnaryTupleOperator op = (UnaryTupleOperator) group.getParentNode();
	op.setArg(new Extension(group));
	Iteration<Resource, QueryEvaluationException> iter = TripleSources.listResources(having, store);
	while (iter.hasNext()) {
		Resource r = iter.next();
		ValueExpr havingExpr = visitExpression(r);
		Filter filter = new Filter(op.getArg(), havingExpr);
		op.setArg(filter);
		op = filter;
	}
	return op;
}
 
Example #27
Source File: QueryEvaluator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Evaluates the query submitted with the given request.
 *
 * @param builder   used to build the response
 * @param resp      the response object
 * @param out       the output writer
 * @param xslPath   style sheet path
 * @param con       connection to repository
 * @param queryText the query text, having been pulled using
 *                  {@link org.eclipse.rdf4j.workbench.commands.QueryServlet} from one of three request parameters:
 *                  "query", "queryhash" or "saved"
 * @param req       the request object
 * @param cookies   used to deal with browser cookies
 * @throws BadRequestException if there's a problem getting request parameters or issuing the repository query
 * @throws RDF4JException      if there's a problem preparing the query
 */
public void extractQueryAndEvaluate(final TupleResultBuilder builder, final HttpServletResponse resp,
		final OutputStream out, final String xslPath, final RepositoryConnection con, String queryText,
		final WorkbenchRequest req, final CookieHandler cookies) throws BadRequestException, RDF4JException {
	final QueryLanguage queryLn = QueryLanguage.valueOf(req.getParameter("queryLn"));
	Query query = QueryFactory.prepareQuery(con, queryLn, queryText);
	boolean evaluateCookie = false;
	int offset = req.getInt("offset");
	int limit = req.getInt("limit_query");
	boolean paged = limit > 0;
	if (query instanceof GraphQuery || query instanceof TupleQuery) {
		final int know_total = req.getInt("know_total");
		evaluateCookie = know_total <= 0;
		if (!evaluateCookie) {
			cookies.addTotalResultCountCookie(req, resp, know_total);
		}
		if (paged) {
			PagedQuery pagedQuery = new PagedQuery(queryText, queryLn, limit, offset);
			if (pagedQuery.isPaged()) {
				offset = pagedQuery.getOffset();
				limit = pagedQuery.getLimit();
			}
			if (!evaluateCookie) {
				query = QueryFactory.prepareQuery(con, queryLn, pagedQuery.toString());
			}
		}
	}
	if (req.isParameterPresent("infer")) {
		final boolean infer = Boolean.parseBoolean(req.getParameter("infer"));
		query.setIncludeInferred(infer);
	}
	this.evaluate(builder, out, xslPath, req, resp, cookies, query, evaluateCookie, paged, offset, limit);
}
 
Example #28
Source File: SpinSailConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void checkConstraint(Resource subj, Resource constraint)
		throws RDF4JException {
	logger.trace("checking constraint {} on resoure {}", constraint, subj);
	ConstraintViolation violation = SpinInferencing.checkConstraint(subj, constraint, queryPreparer,
			parser);
	if (violation != null) {
		handleConstraintViolation(violation);
	} else {
		logger.trace("no violation detected for resource {}", subj);
	}
}
 
Example #29
Source File: QueryFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Query prepareQuery(final RepositoryConnection con, final QueryLanguage queryLn, final String query)
		throws RDF4JException {
	Query rval = null;
	try {
		rval = con.prepareQuery(queryLn, query);
	} catch (UnsupportedOperationException exc) {
		// TODO must be an HTTP repository
		try {
			con.prepareTupleQuery(queryLn, query).evaluate().close();
			rval = con.prepareTupleQuery(queryLn, query);
		} catch (Exception e1) {
			// guess its not a tuple query
			try {
				con.prepareGraphQuery(queryLn, query).evaluate().close();
				rval = con.prepareGraphQuery(queryLn, query);
			} catch (Exception e2) {
				// guess its not a graph query
				try {
					con.prepareBooleanQuery(queryLn, query).evaluate();
					rval = con.prepareBooleanQuery(queryLn, query);
				} catch (Exception e3) {
					// guess its not a boolean query
					// let's assume it is an malformed tuple query
					rval = con.prepareTupleQuery(queryLn, query);
				}
			}
		}
	}
	return rval;
}
 
Example #30
Source File: TestQueryServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetQueryTextRefHash() throws BadRequestException, RDF4JException {
	WorkbenchRequest request = mock(WorkbenchRequest.class);
	when(request.isParameterPresent(QueryServlet.QUERY)).thenReturn(true);
	String hash = String.valueOf(longQuery.hashCode());
	when(request.getParameter(QueryServlet.QUERY)).thenReturn(hash);
	when(request.isParameterPresent(QueryServlet.REF)).thenReturn(true);
	when(request.getParameter(QueryServlet.REF)).thenReturn("hash");
	QueryServlet.substituteQueryCache(Collections.singletonMap(hash, longQuery));
	assertThat(servlet.getQueryText(request)).isEqualTo(longQuery);
}