eXistDB简单通讯08(HTTP_REST)

  • 保存文件
  • 取回文件
  • 查询

1、GetFileHTTP.java

package com.neohope.existdb.test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class GetFileHTTP {
    public static void GetXML(String fileId) throws IOException {
        URL url = new URL("http://localhost:8080/exist/rest/db/CDA/" + fileId);
        System.out.println("GET file from " + url.toString());

        HttpURLConnection connect = (HttpURLConnection) url.openConnection();
        connect.setRequestMethod("GET");
        connect.connect();
        System.out.println("Result:");

        BufferedReader bis = new BufferedReader(new InputStreamReader(connect.getInputStream()));
        String line;
        while ((line = bis.readLine()) != null) {
            System.out.println(line);
        }
    }

    public static void main(String[] args) throws IOException {
        GetXML("入院患者护理评估单01.xml");
    }
}

eXistDB简单通讯07(HTTP_REST)

  • 保存文件
  • 取回文件
  • 查询

1、SaveFileHTTP.java

package com.neohope.existdb.test;

//apache的base64会多一个换行符
//import org.apache.ws.commons.util.Base64;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.sun.xml.internal.messaging.saaj.util.Base64;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SaveFileHTTP {
    public static void SaveXML(String inFileName, String fileId) throws IOException {
        URL url = new URL("http://localhost:8080/exist/rest/db/CDA/" + fileId);
        System.out.println("Save file to " + url.toString());

        HttpURLConnection connect = (HttpURLConnection) url.openConnection();
        connect.setRequestMethod("PUT");
        connect.setDoOutput(true);
        connect.setRequestProperty("Content-Type", "application/xml");
        String userCredentials = "neotest:neotest";
        String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
        System.out.println(basicAuth);
        connect.setRequestProperty ("Authorization", basicAuth);

        File file = new File(inFileName);
        InputStream is = new FileInputStream(file);
        OutputStream os = connect.getOutputStream();

        byte[] buf = new byte[1024];
        int c;
        while ((c = is.read(buf)) > -1) {
            os.write(buf, 0, c);
        }
        os.flush();
        os.close();
        System.out.println("Statuscode " + connect.getResponseCode()
                + " (" + connect.getResponseMessage() + ")");
    }

    public static void main(String[] args) throws IOException {
        SaveXML("D:\\MyProjects\\IDEA14\\TestExistDB\\XMLFiles\\医惠\\入院患者护理评估单01.xml", "入院患者护理评估单01.xml");
    }
}

eXistDB简单通讯06(RPC)

  • 保存文件
  • 取回文件

1、GetFileRPC.java

package com.neohope.existdb.test;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;

public class GetFileRPC {
    public static void GetXML(String documentId, String user, String pwd) throws Exception {
        String uri = "http://localhost:8080/exist/xmlrpc";
        XmlRpcClient client = new XmlRpcClient();
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL(uri));
        config.setBasicUserName(user);
        config.setBasicPassword(pwd);
        client.setConfig(config);

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("indent", "yes");
        options.put("encoding", "UTF-8");
        options.put("expand-xincludes", "yes");
        options.put("process-xsl-pi", "no");

        Vector<Object> params = new Vector<Object>();
        params.addElement(documentId);
        params.addElement(options);
        String xml = (String)
                client.execute("getDocumentAsString", params);
        System.out.println(xml);
    }

    public static void GetXMLChuncked(String documentId, String outPath, String user, String pwd) throws IOException, XmlRpcException {
        String url = "http://localhost:8080/exist/xmlrpc";

        XmlRpcClient client = new XmlRpcClient();
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL(url));
        config.setBasicUserName(user);
        config.setBasicPassword(pwd);
        client.setConfig(config);

        Hashtable<String, String> options = new Hashtable<String, String>();
        options.put("indent", "no");
        options.put("encoding", "UTF-8");

        Vector<Object> params = new Vector<Object>();
        params.addElement(documentId);
        params.addElement(options);

        FileOutputStream fos = new FileOutputStream(outPath);
        HashMap<?, ?> ht = (HashMap<?, ?>) client.execute("getDocumentData", params);
        int offset = ((Integer) ht.get("offset")).intValue();
        byte[] data = (byte[]) ht.get("data");
        String handle = (String) ht.get("handle");
        fos.write(data);

        while (offset != 0) {
            params.clear();
            params.addElement(handle);
            params.addElement(new Integer(offset));

            ht = (HashMap<?, ?>) client.execute("getNextChunk", params);
            data = (byte[]) ht.get("data");
            offset = ((Integer) ht.get("offset")).intValue();
            fos.write(data);
        }
        fos.close();
    }

    public static void main(String args[]) throws Exception {
        String user = "neotest";
        String pwd = "neotest";
        //GetXML("/db/CDA/入院患者护理评估单05.xml", user, pwd);
        GetXMLChuncked("/db/PNG/兔子.png","兔子1.png", user, pwd);
    }
}

eXistDB简单通讯05(RPC)

  • 保存文件
  • 取回文件

1、SaveFileRPC.java

package com.neohope.existdb.test;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.URL;
import java.util.Vector;

public class SaveFileRPC {
    public static void SaveXML(String xmlFilePath, String user, String pw) throws Exception {
        String url = "http://localhost:8080/exist/xmlrpc";
        String path = "/db/CDA/入院患者护理评估单05.xml";

        XmlRpcClient client = new XmlRpcClient();
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL(url));
        config.setBasicUserName(user);
        config.setBasicPassword(pw);
        client.setConfig(config);

        BufferedReader f = new BufferedReader(new FileReader(xmlFilePath));
        String line;
        StringBuffer xml = new StringBuffer();
        while ((line = f.readLine()) != null)
            xml.append(line);
        f.close();

        Vector<Object> params = new Vector<Object>();
        params.addElement(xml.toString());
        params.addElement(path);
        params.addElement(new Integer(0));
        Boolean result = (Boolean) client.execute("parse", params);

        if (result.booleanValue())
            System.out.println("document stored.");
        else
            System.out.println("could not store document.");
    }

    public static void SaveXMLChuncked(String xmlFilePath, String user, String pwd) throws Exception {
        String url = "http://localhost:8080/exist/xmlrpc";
        String path = "/db/PNG/兔子.png";

        XmlRpcClient client = new XmlRpcClient();
        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
        config.setServerURL(new URL(url));
        config.setBasicUserName(user);
        config.setBasicPassword(pwd);
        client.setConfig(config);

        Vector<Object> params = new Vector<Object>();
        String handle = null;
        InputStream fis = new FileInputStream(xmlFilePath);
        byte[] buf = new byte[4096];
        int len;
        while ((len = fis.read(buf)) > 0) {
            params.clear();
            if (handle != null) {
                params.addElement(handle);
            }
            params.addElement(buf);
            params.addElement(new Integer(len));
            handle = (String) client.execute("upload", params);
        }
        fis.close();

        params.clear();
        params.addElement(handle);
        params.addElement(path);
        params.addElement(new Boolean(true));
        params.addElement("image/png");
        Boolean result = (Boolean) client.execute("parseLocal", params); // exceptions

        if (result.booleanValue())
            System.out.println("document stored.");
        else
            System.out.println("could not store document.");
    }

    public static void main(String args[]) throws Exception {
        String user = "neotest";
        String pwd = "neotest";
        SaveXML("PATH_TO_FILE\\入院患者护理评估单05.xml", user, pwd);
        //SaveXMLChuncked("D:\\MyProjects\\IDEA14\\TestExistDB\\XMLFiles\\兔子.png", user, pwd);
    }
}

eXistDB简单通讯04

  • 保存文件
  • 取回文件
  • 查询
  • 嵌套查询

1、Base.java

package com.neohope.existdb.test;

import org.exist.util.serializer.SAXSerializer;
import org.exist.util.serializer.SerializerPool;

import javax.xml.transform.OutputKeys;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class Base {
    protected final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
    protected final static String driver = "org.exist.xmldb.DatabaseImpl";
    protected static  Class<?> cl = null;

    static{
        try {
            cl = Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected static SAXSerializer getSAXSerializer()
    {
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.INDENT, "yes");
        SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        serializer.setOutput(new OutputStreamWriter(System.out), outputProperties);
        return serializer;
    }

    protected static void releaseSAXSerializer(SAXSerializer serializer) {
        SerializerPool.getInstance().returnObject(serializer);
    }
}

Continue reading eXistDB简单通讯04

eXistDB简单通讯03

  • 保存文件
  • 取回文件
  • 查询
  • 嵌套查询

1、Base.java

package com.neohope.existdb.test;

import org.exist.util.serializer.SAXSerializer;
import org.exist.util.serializer.SerializerPool;

import javax.xml.transform.OutputKeys;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class Base {
    protected final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
    protected final static String driver = "org.exist.xmldb.DatabaseImpl";
    protected static  Class<?> cl = null;

    static{
        try {
            cl = Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected static SAXSerializer getSAXSerializer()
    {
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.INDENT, "yes");
        SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        serializer.setOutput(new OutputStreamWriter(System.out), outputProperties);
        return serializer;
    }

    protected static void releaseSAXSerializer(SAXSerializer serializer) {
        SerializerPool.getInstance().returnObject(serializer);
    }
}

Continue reading eXistDB简单通讯03

eXistDB简单通讯02

  • 保存文件
  • 取回文件
  • 查询
  • 嵌套查询

1、Base.java

package com.neohope.existdb.test;

import org.exist.util.serializer.SAXSerializer;
import org.exist.util.serializer.SerializerPool;

import javax.xml.transform.OutputKeys;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class Base {
    protected final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
    protected final static String driver = "org.exist.xmldb.DatabaseImpl";
    protected static  Class<?> cl = null;

    static{
        try {
            cl = Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected static SAXSerializer getSAXSerializer()
    {
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.INDENT, "yes");
        SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        serializer.setOutput(new OutputStreamWriter(System.out), outputProperties);
        return serializer;
    }

    protected static void releaseSAXSerializer(SAXSerializer serializer) {
        SerializerPool.getInstance().returnObject(serializer);
    }
}

Continue reading eXistDB简单通讯02

eXistDB简单通讯01

  • 保存文件
  • 取回文件
  • 查询
  • 嵌套查询

1、Base.java

package com.neohope.existdb.test;

import org.exist.util.serializer.SAXSerializer;
import org.exist.util.serializer.SerializerPool;

import javax.xml.transform.OutputKeys;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class Base {
    protected final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
    protected final static String driver = "org.exist.xmldb.DatabaseImpl";
    protected static  Class<?> cl = null;

    static{
        try {
            cl = Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected static SAXSerializer getSAXSerializer()
    {
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.INDENT, "yes");
        SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        serializer.setOutput(new OutputStreamWriter(System.out), outputProperties);
        return serializer;
    }

    protected static void releaseSAXSerializer(SAXSerializer serializer) {
        SerializerPool.getInstance().returnObject(serializer);
    }
}

Continue reading eXistDB简单通讯01

Java实现CORBA静态绑定(七)

本文主要内容涉及:

  • CORBA基本架构
  • IDL文件编写
  • POA示例实现
  • POA+TIE示例实现
  • ImplBase示例实现
  • ImplBase+TIE示例实现
  • Persistent示例实现

HiPersistent.idl

module HiCorba
{
	interface HiPersistent
	{
		string sayHiTo(in string someone);
		long add(in long numa, in long numb);
		oneway void shutdown();
	};
};

JDK提供了工具,可以直接生成stubs及skeletons接口代码:

idlj -fall HiPersistent.idl

编写server端代码:

import java.util.Properties;
import org.omg.CORBA.Object;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CORBA.Policy;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.*;
import org.omg.PortableServer.Servant;
import HiCorba.*;

class HiPersistentImpl extends HiPersistentPOA {
	private ORB orb;
	public void setORB(ORB orb_val) {
		orb = orb_val;
	}
	// implement sayHiTo() method
	public String sayHiTo(String someone) {
		return "\nHi, "+someone+" !"+"\n";
	}
	// implement add() method
	public int add(int numa, int numb) {
		return numa+numb;
	}
	// implement shutdown() method
	public void shutdown() {
		orb.shutdown(false);
	}
}

public class HiPersistentServer {
	public static void main( String args[] ) {
		try {
			// Step 1: Instantiate the ORB
			ORB orb = ORB.init(args, null);

			// Step 2: Instantiate the servant
			HiPersistentImpl impl = new HiPersistentImpl();
		        impl.setORB(orb);

			// Step 3 : Create a POA with Persistent Policy
			// Step 3-1: Get the rootPOA 
			POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			// Step 3-2: Create the Persistent Policy
			Policy[] persistentPolicy = new Policy[1];
			persistentPolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT);
			// Step 3-3: Create a POA by passing the Persistent Policy
			POA persistentPOA = rootPOA.create_POA("childPOA", null, persistentPolicy ); 
			// Step 3-4: Activate HiPersistentPOA's POAManager, Without this
			// All calls to HiPersistent Server will hang because POAManager
			// will be in the 'HOLD' state.
			persistentPOA.the_POAManager().activate( );
			
			// Step 4: Associate the servant with HiPersistentPOA
			persistentPOA.activate_object( impl );

			// Step 5: Resolve RootNaming context and bind a name for the
			// servant.
			// NOTE: If the Server is persistent in nature then using Persistent
			// Name Service is a good choice. Even if ORBD is restarted the Name
			// Bindings will be intact. To use Persistent Name Service use
			// 'NameService' as the key for resolve_initial_references() when
			// ORBD is running.
			org.omg.CORBA.Object obj = orb.resolve_initial_references( "NameService" );
			NamingContextExt rootContext = NamingContextExtHelper.narrow( obj );

			NameComponent[] nc = rootContext.to_name( "HiPersistent" );
			rootContext.rebind( nc, persistentPOA.servant_to_reference( impl ) );

			// Step 6: We are ready to receive client requests
			orb.run();
		} catch ( Exception e ) {
			System.err.println( "Exception in Persistent Server Startup " + e );
		}
	}
}

编写client端代码:

import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.CORBA.OBJ_ADAPTER;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NameComponent;
import org.omg.PortableServer.POA;
import HiCorba.*;

public class HiPersistentClient {
	public static void main(String args[]) {
		try {
			// Step 1: Instantiate the ORB
			ORB orb = ORB.init(args, null);

			// Step 2: Resolve the PersistentHelloServant by using INS's
			// corbaname url. The URL locates the NameService running on
			// localhost and listening on 1900 and resolve 
			// 'PersistentServerTutorial' from that NameService
			org.omg.CORBA.Object obj = orb.string_to_object("corbaname::localhost:1900#HiPersistent");
			HiPersistent hiPersistent = HiPersistentHelper.narrow( obj );

			// Step 3: Call the sayHello() method every 60 seconds and shutdown
			// the server. Next call from the client will restart the server,
			// because it is persistent in nature.
			while( true ) {
				System.out.println( "Calling HiPersisten Server.." );
				System.out.println("Message From HiPersisten Server: " + hiPersistent.sayHiTo("neohope") );
				System.out.println("70 + 80 = " + hiPersistent.add(70, 80) );
				System.out.println( "Shutting down HiPersistent Server.." );
				hiPersistent.shutdown( );
				Thread.sleep(2000);
			}
		} catch ( Exception e ) {
			System.err.println( "Exception in HiPersistentClient.java..." + e );
			e.printStackTrace( );
		}
	}
}

编译代码:

javac *.java HiCorba/*.java

测试,在三个shell或cmd窗口中依次运行:

#shell01
orbd -ORBInitialPort 1900 -serverPollingTime 200
#shell02
servertool -ORBInitialPort 1900
>>欢迎使用 Java IDL 服务器工具
>>请在提示处输入命令
> register -server HiPersistentServer -applicationName s1 -classpath .
#shell03
java HiPersistentClient
>>Calling HiPersisten Server..
>>Message From HiPersisten Server:
>>Hi, neohope !
>>70 + 80 = 150
>>Shutting down HiPersistent Server..
>>
>>Calling HiPersisten Server..
>>Message From HiPersisten Server:
>>Hi, neohope !
>>70 + 80 = 150
>>Shutting down HiPersistent Server..