java jxta_JXTA Java Standard Edition v2.5 Programmers Guide中文翻译(二)

这是一个关于使用Java处理JXTA消息的教程,包括添加和读取字符串、整数、长整型、字节数组以及Java对象到消息中。此外,还展示了如何使用GZIP进行消息元素内容的压缩。示例涵盖了基本的消息操作和对象序列化。
摘要由CSDN通过智能技术生成

package tutorial.message;

import net.jxta.document.AdvertisementFactory;

import net.jxta.document.MimeMediaType;

import net.jxta.document.StructuredDocumentFactory;

import net.jxta.document.XMLDocument;

import net.jxta.endpoint.ByteArrayMessageElement;

import net.jxta.endpoint.Message;

import net.jxta.endpoint.Message.ElementIterator;

import net.jxta.endpoint.MessageElement;

import net.jxta.endpoint.StringMessageElement;

import net.jxta.endpoint.TextDocumentMessageElement;

import net.jxta.endpoint.WireFormatMessage;

import net.jxta.endpoint.WireFormatMessageFactory;

import net.jxta.id.IDFactory;

import net.jxta.peergroup.PeerGroupID;

import net.jxta.pipe.PipeService;

import net.jxta.protocol.PipeAdvertisement;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.RandomAccessFile;

import java.util.zip.GZIPInputStream;

import java.util.zip.GZIPOutputStream;

/**

* A simple and re-usable example of manipulating JXATA Messages. Included in

* this tutorial are:

*

*

*

Adding and reading {@code String}, {@code int} and {@code long} with Message elements

*

Adding and reading Java {@code Object} with Message Elements.

*

Adding and reading byte arrays with Message Elements.

*

Adding and reading JXTA Advertisements with Message Elements.

*

Compressing message element content with gzip.

*

*/

public class MessageTutorial {

private final static MimeMediaType GZIP_MEDIA_TYPE =

new MimeMediaType("application/gzip").intern();

/**

* Adds a String to a Message as a StringMessageElement

*

* @param message The message to add to

* @param nameSpace The namespace of the element to add. a null value assumes

default namespace.

* @param elemName Name of the Element.

* @param string The string to add

*/

public static void addStringToMessage(Message message,

String nameSpace, String elemName, String string) {

message.addMessageElement(nameSpace,

new StringMessageElement(elemName,

string,

null));

}

/**

* Adds a long to a message

*

* @param message The message to add to

* @param nameSpace The namespace of the element to add. a null value assumes

default namespace.

* @param elemName Name of the Element.

* @param data The feature to be added to the LongToMessage attribute

*/

public static void addLongToMessage(Message message,

String nameSpace, String elemName, long data) {

message.addMessageElement(nameSpace,

new StringMessageElement(elemName,

Long.toString(data),

null));

}

/**

* Adds a int to a message

*

* @param message The message to add to

* @param nameSpace The namespace of the element to add. a null value assumes

default namespace.

* @param elemName Name of the Element.

* @param data The feature to be added to the IntegerToMessage attribute

*/

public static void addIntegerToMessage(Message message, String nameSpace,

String elemName, int data) {

message.addMessageElement(nameSpace,

new StringMessageElement(elemName,

Integer.toString(data),

null));

}

/**

* Adds an byte array to a message

*

* @param message The message to add to

* @param nameSpace The namespace of the element to add. a null value assumes

default namespace.

* @param elemName Name of the Element.

* @param data the byte array

* @param compress indicates whether to use GZIP compression

* @throws IOException if an io error occurs

*/

public static void addByteArrayToMessage(Message message, String nameSpace,

String elemName, byte[] data, boolean compress) throws IOException {

byte[] buffer = data;

MimeMediaType mimeType = MimeMediaType.AOS;

if (compress) {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

GZIPOutputStream gos = new GZIPOutputStream(outStream);

gos.write(data, 0, data.length);

gos.finish();

gos.close();

buffer = outStream.toByteArray();

mimeType = GZIP_MEDIA_TYPE;

}

message.addMessageElement(nameSpace,

new ByteArrayMessageElement(elemName,

mimeType,

buffer,

null));

}

/**

* Adds an Object to message within the specified name space and with the

specified element name

* @param message the message to add the object to

* @param nameSpace the name space to add the object under

* @param elemName the given element name

* @param object the object

* @throws IOException if an io error occurs

*/

public static void addObjectToMessage(Message message, String nameSpace,

String elemName, Object object) throws IOException {

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(bos);

oos.writeObject(object);

oos.close();

bos.close();

addByteArrayToMessage(message, nameSpace, elemName, bos.toByteArray(), false);

}

/**

* Returns a String from a message

*

* @param message The message to retrieve from

* @param nameSpace The namespace of the element to get.

* @param elemName Name of the Element.

* @return The string value or {@code null} if there was no element matching

the specified name.

*/

public static String getStringFromMessage(Message message,

String nameSpace, String elemName) {

MessageElement me = message.getMessageElement(nameSpace, elemName);

if (null != me) {

return me.toString();

} else {

return null;

}

}

/**

* Returns an long from a message

*

* @param message The message to retrieve from

* @param nameSpace The namespace of the element to get.

* @param elemName Name of the Element.

* @return The long value

* @throws NumberFormatException If the String does not contain a parsable int.

*/

public static long getLongFromMessage(Message message,

String nameSpace, String elemName) throws NumberFormatException {

String longStr = getStringFromMessage(message, nameSpace, elemName);

if (null != longStr) {

return Long.parseLong(longStr);

} else {

throw new NumberFormatException("No such Message Element.");

}

}

/**

* Returns an int from a message

*

* @param message The message to retrieve from

* @param nameSpace The namespace of the element to get.

* @param elemName Name of the Element.

* @return The int value

* @throws NumberFormatException If the String does not contain a parsable long.

*/

public static int getIntegerFromMessage(Message message, String nameSpace,

String elemName) throws NumberFormatException {

String intStr = getStringFromMessage(message, nameSpace, elemName);

if (null != intStr) {

return Integer.parseInt(intStr);

} else {

throw new NumberFormatException("No such Message Element.");

}

}

/**

* Returns an InputStream for a byte array

*

* @param message The message to retrieve from

* @param nameSpace The namespace of the element to get.

* @param elemName Name of the Element.

* @return The {@code InputStream} or {@code null} if the message has no such

element, String elemName) throws IOException {

* @throws IOException if an io error occurs

*/

public static InputStream getInputStreamFromMessage(Message message,

String nameSpace, String elemName) throws IOException {

InputStream result = null;

MessageElement element = message.getMessageElement(nameSpace, elemName);

if (null == element) {

return null;

}

if (element.getMimeType().equals(GZIP_MEDIA_TYPE)) {

result = new GZIPInputStream(element.getStream());

} else if (element.getMimeType().equals(MimeMediaType.AOS)) {

result = element.getStream();

}

return result;

}

/**

* Reads a single Java Object from a Message.

*

* @param message The message containing the object.

* @param nameSpace The name space of the element containing the object.

* @param elemName The name of the element containing the object.

* @return The Object or {@code null} if the Message contained no such element.

* @throws IOException if an io error occurs

* @throws ClassNotFoundException if an object could not constructed from the message

element

*/

public static Object getObjectFromMessage(Message message, String nameSpace,

String elemName) throws IOException, ClassNotFoundException {

InputStream is = getInputStreamFromMessage(message, nameSpace, elemName);

if (null == is) {

return null;

}

ObjectInputStream ois = new ObjectInputStream(is);

return ois.readObject();

}

/**

* Prints message element names and content and some stats

*

* @param msg message to print

* @param verbose indicates whether to print elment content

*/

public static void printMessageStats(Message msg, boolean verbose) {

try {

System.out.println("------------------Begin Message---------------------");

WireFormatMessage serialed = WireFormatMessageFactory.toWire(

msg,

new MimeMediaType("application/x-jxta-msg"), null);

System.out.println("Message Size :" + serialed.getByteLength());

ElementIterator it = msg.getMessageElements();

while (it.hasNext()) {

MessageElement el = it.next();

System.out.println("Element : " + it.getNamespace() + " :: " +

el.getElementName());

if (verbose) {

System.out.println("[" + el + "]");

}

}

System.out.println("-------------------End Message----------------------");

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* Illustrates adding and retrieving a String to and from a Message

*/

public static void stringExample() {

Message message = new Message();

addStringToMessage(message, "TutorialNameSpace", "String Test", "This is a test");

printMessageStats(message, true);

System.out.println("String Value :" +

getStringFromMessage(message, "TutorialNameSpace", "String Test"));

}

/**

* Illustrates adding and retrieving a long to and from a Message

*/

public static void longExample() {

Message message = new Message();

addLongToMessage(message, "TutorialNameSpace", "long test", Long.MAX_VALUE);

printMessageStats(message, true);

System.out.println("long Value :" +

getLongFromMessage(message, "TutorialNameSpace", "long test"));

}

/**

* Illustrates adding and retrieving an integer to and from a Message

*/

public static void intExample() {

Message message = new Message();

addIntegerToMessage(message, "TutorialNameSpace", "int test", Integer.MAX_VALUE);

printMessageStats(message, true);

System.out.println("int Value :" +

getIntegerFromMessage(message, "TutorialNameSpace", "int test"));

}

/**

* Illustrates adding and retrieving byte-array to and from a Message

*/

public static void byteArrayExample() {

Message message = new Message();

try {

File file = new File("message.tst");

file.createNewFile();

RandomAccessFile raf = new RandomAccessFile(file, "rw");

raf.setLength(1024 * 4);

int size = 4096;

byte[] buf = new byte[size];

raf.read(buf, 0, size);

addByteArrayToMessage(message, "TutorialNameSpace", "byte test", buf, true);

printMessageStats(message, true);

InputStream is = getInputStreamFromMessage(message,

"TutorialNameSpace", "byte test");

int count = 0;

while (is.read() != -1) {

count++;

}

System.out.println("Read " + count + " byte back");

} catch (IOException io) {

io.printStackTrace();

}

}

/**

* Illustrates adding and retrieving advertisements to and from a Message

*/

public static void xmlDocumentExample() {

Message message = new Message();

PipeAdvertisement pipeAdv = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(

PipeAdvertisement.getAdvertisementType());

pipeAdv.setPipeID(IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID));

pipeAdv.setType(PipeService.UnicastType);

message.addMessageElement("MESSAGETUT", new

TextDocumentMessageElement("MESSAGETUT",

(XMLDocument) pipeAdv.getDocument(MimeMediaType.XMLUTF8), null));

MessageElement msgElement = message.getMessageElement("MESSAGETUT", "MESSAGETUT");

try {

XMLDocument asDoc = (XMLDocument)

StructuredDocumentFactory.newStructuredDocument(msgElement.getMimeType(),

msgElement.getStream());

PipeAdvertisement newPipeAdv = (PipeAdvertisement)

AdvertisementFactory.newAdvertisement(asDoc);

System.out.println(newPipeAdv.toString());

} catch (IOException e) {

// This is thrown if the message element could not be read.

e.printStackTrace();

} catch (IllegalArgumentException e) {

// This is thrown if the document or advertisement is invalid (illegal

// values, missing tags, etc.)

e.printStackTrace();

}

}

/**

* Main method

*

* @param args command line arguments. None defined

*/

public static void main(String args[]) {

stringExample();

longExample();

intExample();

byteArrayExample();

xmlDocumentExample();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值