基于Burlap协议调用java方法

public interface TestService {
    public void test(String name);
}

 

public class TestServiceImpl implements TestService {
    @Override
    public void test(String name) {
        System.out.println("test:" + name);
    }
}

 

public class BurlapSkeletonTest {

	private static TestServiceImpl testService;

	private static BurlapSkeleton skeleton;

	@BeforeClass
	public static void initialize() {
		testService = new TestServiceImpl();

		skeleton = new BurlapSkeleton(testService, TestService.class);
	}
	
	private Document initBurlapRequest() throws BurlapException {
		DocumentBuilder domBuilder = null;
		try {
			domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new BurlapException(e);
		}
		return domBuilder.newDocument();
	}
	
	private InputStream getBurlapInputStream(Document doc) throws BurlapException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		Transformer transformer = null;
		try {
			TransformerFactory transFactory = TransformerFactory.newInstance();
			transformer = transFactory.newTransformer();
		} catch (Exception e) {
			throw new BurlapException(e);
		}
		
		transformer.setOutputProperty("encoding", "gb2312");
		transformer.setOutputProperty("indent", "yes");
		
		// omit xml declaration
		// <?xml version="1.0" encoding="GB2312" standalone="no"?>
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		
		
		DOMSource source = new DOMSource();
		source.setNode(doc);
		StreamResult result = new StreamResult();
		result.setOutputStream(bos);
		try {
			transformer.transform(source, result);
		} catch (Exception e) {
			throw new BurlapException(e);
		}
		
		System.out.println(new String(bos.toByteArray()));

		return new ByteArrayInputStream(bos.toByteArray());
	}

	/**
	 * <burlap:call>
	 *   <method>test</method>
	 *   <string>helloworld</string>
	 * </burlap:call>
	 * 
	 * @throws IOException
	 */
	@Test
	public void invoke() throws IOException {
		Document doc = null;
		try {
			doc = initBurlapRequest();
		} catch (BurlapException e) {
			throw new IOException(e);
		}
		
		Element root = doc.createElement("burlap:call");
		
		Element element = doc.createElement("method");
		element.setTextContent("test");
		root.appendChild(element);
		
		element = doc.createElement("string");
		element.setTextContent("helloworld");
		root.appendChild(element);
		
		doc.appendChild(root);


		InputStream isToUse;
		try {
			isToUse = getBurlapInputStream(doc);
		} catch (BurlapException e) {
			throw new IOException(e);
		}
		OutputStream osToUse = new ByteArrayOutputStream();

		BurlapInput in = new BurlapInput(isToUse);
		BurlapOutput out = new BurlapOutput(osToUse);
		try {
			skeleton.invoke(in, out);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(基于Burlap协议调用java方法)