📄 httprepository.java
字号:
_adminPost(_dataMergeURL, postParams, listener); } /* (non-Javadoc) * @see org.openrdf.sesame.repository.SesameRepository#addGraph(org.openrdf.sesame.constants.QueryLanguage, java.lang.String) */ public void addGraph(QueryLanguage language, String query) throws IOException, AccessDeniedException { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("query", query); postParams.put("queryLanguage", language.toString()); postParams.put("resultFormat", AdminResultFormat.XML.toString()); AdminMsgCollector listener = new AdminMsgCollector(); _adminPost(_mergeGraphQueryURL, postParams, listener); } public void addGraph(Graph graph, boolean joinBlankNodes) throws IOException, AccessDeniedException { if (!joinBlankNodes) { String turtleDoc = _graph2TurtleDoc(graph); AdminMsgCollector listener = new AdminMsgCollector(); addData(turtleDoc, null, RDFFormat.TURTLE, false, listener); if (listener.hasErrors()) { // FIXME what to do with errors during upload? } } else { addGraph(graph); } } // SesameRepository.addGraph(QueryLanguage, String) public void addGraph(QueryLanguage language, String query, boolean joinBlankNodes) throws IOException, AccessDeniedException { if (!joinBlankNodes) { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("query", query); postParams.put("queryLanguage", language.toString()); postParams.put("resultFormat", AdminResultFormat.XML.toString()); AdminMsgCollector listener = new AdminMsgCollector(); _adminPost(_addGraphQueryURL, postParams, listener); } else { addGraph(language, query); } } // implements SesameRepository.extractData(RDFFormat, boolean, boolean, boolean, boolean) public InputStream extractRDF(RDFFormat serialization, boolean schema, boolean data, boolean explicitOnly, boolean niceOutput) throws IOException, AccessDeniedException { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("serialization", serialization.toString()); if (schema) { postParams.put("schema", "on"); } if (data) { postParams.put("data", "on"); } if (explicitOnly) { postParams.put("explicitOnly", "on"); } if (niceOutput) { postParams.put("niceOutput", "on"); } try { return _sendPostRequest(_extractURL, postParams); } catch (MalformedQueryException e) { // Never thrown in this context _throwIOException(e); } catch (QueryEvaluationException e) { // Never thrown in this context _throwIOException(e); } // Statement never reached but needed to keep the compiler happy. return null; } // implements SesameRepository.removeStatements(Resource, URI, Value, AdminListener) public void removeStatements(Resource subject, URI predicate, Value object, AdminListener listener) throws IOException, AccessDeniedException { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("resultFormat", AdminResultFormat.XML.toString()); if (subject != null) { postParams.put("subject", NTriplesUtil.toNTriplesString(subject)); } if (predicate != null) { postParams.put("predicate", NTriplesUtil.toNTriplesString(predicate)); } if (object != null) { postParams.put("object", NTriplesUtil.toNTriplesString(object)); } _adminPost(_removeStatsURL, postParams, listener); } // implements SesameRepository.removeGraph(Graph) public void removeGraph(Graph graph) throws IOException, AccessDeniedException { String turtleDoc = _graph2TurtleDoc(graph); // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("dataFormat", RDFFormat.TURTLE.toString()); postParams.put("resultFormat", AdminResultFormat.XML.toString()); postParams.put("data", turtleDoc); AdminMsgCollector listener = new AdminMsgCollector(); _adminPost(_removeStatsURL, postParams, listener); if (listener.hasErrors()) { // FIXME what to do with errors during upload? } } // SesameRepository.removeGraph(QueryLanguage, String) public void removeGraph(QueryLanguage language, String query) throws IOException, AccessDeniedException { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("query", query); postParams.put("queryLanguage", language.toString()); postParams.put("resultFormat", AdminResultFormat.XML.toString()); AdminMsgCollector listener = new AdminMsgCollector(); _adminPost(_removeGraphQueryURL, postParams, listener); } // implements SesameRepository.clear(AdminListener) public void clear(AdminListener listener) throws IOException, AccessDeniedException { // Build the query string Map postParams = new HashMap(); postParams.put("repository", _repositoryId); postParams.put("resultFormat", AdminResultFormat.XML.toString()); _adminPost(_clearURL, postParams, listener); } public String getRepositoryId() { return _repositoryId; } /** * Generates a Turtle document from the supplied graph. **/ private String _graph2TurtleDoc(Graph graph) throws IOException { StringWriter stringWriter = new StringWriter(8192); TurtleWriter turtleWriter = new TurtleWriter(stringWriter); turtleWriter.startDocument(); StatementIterator statIter = graph.getStatements(); while (statIter.hasNext()) { Statement st = statIter.next(); turtleWriter.writeStatement(st.getSubject(), st.getPredicate(), st.getObject()); } statIter.close(); turtleWriter.endDocument(); return stringWriter.toString(); } /** * Sends an HTTP-POST request with the supplied postData to the supplied * URL. Status, warning and error messages will be reported to the supplied * AdminListener. */ private void _adminPost(URL url, Map postParams, AdminListener listener) throws IOException, AccessDeniedException { InputStream responseStream = null; try { responseStream = _sendPostRequest(url, postParams); } catch (MalformedQueryException e) { // Never thrown in this context _throwIOException(e); } catch (QueryEvaluationException e) { // Never thrown in this context _throwIOException(e); } // Parse the response try { XmlAdminMsgReader reader = new XmlAdminMsgReader(XMLReaderFactory.createXMLReader()); reader.read(responseStream, listener); } catch (SAXException e) { String msg; // Nested exception? Exception ne = e.getException(); if (ne != null) { msg = ne.getMessage(); } else { msg = e.getMessage(); } _throwIOException("Unable to handle request: " + msg, e); } finally { responseStream.close(); } } /** * Sends an HTTP-POST request with the supplied postData to the supplied * URL. The server's response is checked, throwing an exception when it * indicates an error. Otherwise, the data returned by the server is * returned as an InputStream. * * @param url The URL to post the data to. * @param postParams The parameters for the POST request. * @return An input stream containing the data that was returned by the server. * @exception AccessDeniedException In case one does not have access to the * specified resource. * @exception MalformedQueryException In case the server was unable to parse * the query that was sent to it. * @exception QueryEvaluationException In case the server failed to evaluate * the query that was sent to it. * @exception IOException In case of an error in the request or in the * processing of it by the server. */ private InputStream _sendPostRequest(URL url, Map postParams) throws IOException, AccessDeniedException, MalformedQueryException, QueryEvaluationException { // Set up request HttpURLConnection conn = (HttpURLConnection) url.openConnection(); _cookieManager.setCookies(conn); HttpClientUtil.setAcceptGZIPEncoding(conn); try { HttpClientUtil.prepareMultipartPostRequest(conn, postParams, "UTF-8"); } catch (UnsupportedEncodingException e) { // UTF-8 must be supported by all compliant JVM's, this exception should never be thrown. throw new RuntimeException("UTF-8 character encoding not supported on this platform"); } // Send the request conn.connect(); // Check whether the server reported any errors _checkResponse(conn); // Get buffered input stream (HttpClientUtil takes care of any gzip compression) return new BufferedInputStream(HttpClientUtil.getInputStream(conn), 2048); } private void _checkResponse(HttpURLConnection conn) throws IOException, AccessDeniedException, MalformedQueryException, QueryEvaluationException { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return; } String responseMsg = conn.getResponseMessage(); //System.out.println("Got error code: " + responseCode + " " + responseMsg); if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new AccessDeniedException(responseMsg); } else if (responseCode == HttpURLConnection.HTTP_BAD_REQUEST && responseMsg != null) { int colonIdx = responseMsg.indexOf(':'); if (colonIdx > 0) { HTTPErrorType errType = HTTPErrorType.forValue(responseMsg.substring(0, colonIdx)); if (errType == HTTPErrorType.UNKNOWN_REPOSITORY) { // Repository removed on server? throw new IOException(responseMsg.substring(colonIdx + 2)); } else if (errType == HTTPErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(responseMsg.substring(colonIdx + 2)); } else if (errType == HTTPErrorType.QUERY_EVALUATION_ERROR) { throw new QueryEvaluationException(responseMsg.substring(colonIdx + 2)); } } else { throw new IOException(responseMsg); } } else { throw new IOException(responseMsg); } } private void _throwIOException(Exception e) throws IOException { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } private void _throwIOException(String msg, Exception e) throws IOException { IOException ioe = new IOException(msg); ioe.initCause(e); throw ioe; }/*------------------------------+| Inner class RDFParserListener |+------------------------------*/ /** * A listener for various events from an RDF parser that reports these * events to a GraphQueryResultListener. */ static class RDFParserListener implements StatementHandler, ParseErrorListener, NamespaceListener { /** * The listener to report events to. */ private GraphQueryResultListener _listener; /** * Flag indicating whether the start of the query result has already * been reported to the listener. */ private boolean _queryResultStarted; /** * Creates an RDFParserListener that reports events to the supplied * listener. */ public RDFParserListener(GraphQueryResultListener listener) { _listener = listener; _queryResultStarted = false; } // Calling startGraphQueryResult() is deferred until all namespaces have // been reported private void _ensureQueryResultStarted() throws IOException { if (!_queryResultStarted) { _listener.startGraphQueryResult(); _queryResultStarted = true; } } // Implements StatementHandler.handleStatement(...) public void handleStatement(Resource subject, URI predicate, Value object) throws StatementHandlerException { try { _ensureQueryResultStarted(); _listener.triple(subject, predicate, object); } catch (IOException e) { throw new StatementHandlerException(e); } } // Implements ParseErrorListener.warning(...) public void warning(String msg, int lineNo, int colNo) { // ignore } // Implements ParseErrorListener.error(...) public void error(String msg, int lineNo, int colNo) { try { _ensureQueryResultStarted(); _listener.reportError(msg); } catch (Exception e) { // FIXME ignore for now. } } // Implements ParseErrorListener.fatalError(...) public void fatalError(String msg, int lineNo, int colNo) { try { _ensureQueryResultStarted(); _listener.reportError(msg); } catch (Exception e) { // FIXME ignore for now. } } // Implements NamespaceListener.handleNamespace(String, String) public void handleNamespace(String prefix, String uri) { try { _listener.namespace(prefix, uri); } catch (IOException e) { // ignore } } /** * Reports the end of the graph query result to the * GraphQueryResultListener. This method should be called when the RDF * parser has finished parsing. */ public void finishGraphQueryResult() { try { _ensureQueryResultStarted(); _listener.endGraphQueryResult(); } catch (IOException e) { // FIXME ignore for now } } } // end inner class}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -