📄 digconnection.java
字号:
/*****************************************************************************
* Source code information
* -----------------------
* Original author Ian Dickinson, HP Labs Bristol
* Author email ian.dickinson@hp.com
* Package Jena 2
* Web http://sourceforge.net/projects/jena/
* Created 11-Sep-2003
* Filename $RCSfile: DIGConnection.java,v $
* Revision $Revision: 1.15 $
* Release status $State: Exp $
*
* Last modified on $Date: 2007/01/02 11:49:27 $
* by $Author: andy_seaborne $
*
* (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
* [See end of file]
*****************************************************************************/
// Package
///////////////
package com.hp.hpl.jena.reasoner.dig;
// Imports
///////////////
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xml.serialize.*;
import org.w3c.dom.*;
import com.hp.hpl.jena.util.FileUtils;
/**
* <p>
* Encapsulates the connection to a DIG reasoner.
* </p>
*
* @author Ian Dickinson, HP Labs (<a href="mailto:Ian.Dickinson@hp.com">email</a>)
* @version Release @release@ ($Id: DIGConnection.java,v 1.15 2007/01/02 11:49:27 andy_seaborne Exp $)
*/
public class DIGConnection {
// Constants
//////////////////////////////////
/** Default URL for connecting to a local DIG reasoner on port 8081 */
public static final String DEFAULT_REASONER_URL = "http://localhost:8081";
/** Namespace for XSI */
public static final String XSI = "http://www.w3.org/2001/XMLSchema-instance";
// Static variables
//////////////////////////////////
private static Log log = LogFactory.getLog( DIGConnection.class );
// Instance variables
//////////////////////////////////
/** The URL to connect to, initialised to the default URL */
protected String m_extReasonerURL = DEFAULT_REASONER_URL;
/** URI of current KB */
private String m_kbURI;
/** The XML document builder we are using */
protected DocumentBuilderFactory m_factory = DocumentBuilderFactory.newInstance();
/** List of most recent warnings */
private List m_warnings = new ArrayList();
/** Flag to control whether we log incoming and outgoing messages */
protected boolean m_logCommunications = true;
// Constructors
//////////////////////////////////
// External signature methods
//////////////////////////////////
/**
* <p>Send a verb to the attached DIG reasoner and answer the result. The verb is encoded as an XML
* document object.</p>
* @param digVerb A DIG verb (information request, ask or tell) as an XML document
* @return The resulting XML document formed from the response from the reasoner
* @exception DigReasonerException for any errors in XML encoding or HTTP transmission
*/
public Document sendDigVerb( Document digVerb, DIGProfile profile ) {
try {
// make sure we set the KB uri
Element verb = digVerb.getDocumentElement();
if (!verb.hasAttribute( DIGProfile.URI )) {
verb.setAttribute( DIGProfile.URI, m_kbURI );
}
// first open the connection
URL url = new URL( m_extReasonerURL );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// pre-serialise the content so we can set the Content-Length field correctly
StringWriter out = new StringWriter();
serialiseDocument( digVerb, out );
conn.setDoOutput( true );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Length", Integer.toString( out.getBuffer().length() ) );
// different varaints on the protocol make different choices here
conn.setRequestProperty( "Content-Type", profile.getContentType() );
// log
logMessage( true, digVerb );
// send
conn.connect();
PrintWriter pw = FileUtils.asPrintWriterUTF8( conn.getOutputStream() );
pw.print( out.getBuffer() );
pw.flush();
pw.close();
// and receive
Document response = getDigResponse( conn );
// log
logMessage( false, response );
errorCheck( response, profile );
return response;
}
catch (IOException e) {
throw new DIGWrappedException( e );
}
}
/**
* <p>Serialise the given document to the given output writer.</p>
* @param doc An XML document to serialise
* @param out A writer that will consume the seralised form of the document
*/
public void serialiseDocument( Document doc, Writer out ) {
try {
// write the given document to the string buffer
XMLSerializer serializer = new XMLSerializer ( out, createXMLFormatter( doc ) );
serializer.asDOMSerializer();
serializer.serialize( doc );
}
catch (IOException e) {
throw new DIGWrappedException( e );
}
}
/**
* <p>Bind a DIG KB to this adapter, by requesting a KB URI through the newKB
* verb. If there is already a binding, do nothing unless rebind is true.
* @param rebind If true, any existing KB will be released before binding
* to a new KB
*/
public void bindKB( boolean rebind, DIGProfile profile ) {
// delete the old KB
if (rebind && m_kbURI != null) {
Document release = createDigVerb( DIGProfile.RELEASEKB, profile );
Document response = sendDigVerb( release, profile );
errorCheck( response, profile );
if (warningCheck(response)) {
log.warn( "DIG reasoner warning: " + getWarnings().next() );
}
m_kbURI = null;
}
// allocate a new KB
if (m_kbURI == null) {
// request a whole new KB
Document response = sendDigVerb( createDigVerb( DIGProfile.NEWKB, profile ), profile );
errorCheck( response, profile );
// extract the new KB URI
Element kb = (Element) response.getDocumentElement()
.getElementsByTagName( DIGProfile.KB )
.item( 0 );
if (kb == null) {
throw new DIGReasonerException( "Could not locate DIG KB identifier in return value from newKB" );
}
else {
m_kbURI = kb.getAttribute( DIGProfile.URI );
}
}
}
/**
* <p>Check the response from the DIG server to see if there is an error code,
* and raise an excption if so.</p>
* @param response The response from the DIG server
*/
public void errorCheck( Document response, DIGProfile profile ) {
Element root = response.getDocumentElement();
NodeList errs = root.getElementsByTagName( DIGProfile.ERROR );
if (errs != null && errs.getLength() > 0) {
Element error = (Element) errs.item( 0 );
String errCode = error.getAttribute( DIGProfile.CODE );
int code = (errCode == null || errCode.length() == 0) ? 0 : Integer.parseInt( errCode );
String msgAttr = error.getAttribute( DIGProfile.MESSAGE );
NodeList messages = error.getChildNodes();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -