第六章 基础知识
这一章根据手册中描述的编程实例所需的编译、运行的相关步骤讨论了JXTA开发的相关开发环境。
- 1.开始
- 系统要求
- 访问在线文档
- 下载JXTA项目的二进制文件
- 编译JXTA技术的代码
- 运行JXTA技术的应用
- 配置JXTA技术的相关环境
- 2.创建各种ID类型
- 3.创建新的广告信息
- 4.创建一个信息和信息元素
开始
系统要求
当前的JXSE实现需要5.0版或更高的JRE和SDK。JRE和JDK当前对于Solaris系统、Moicrosoft Windows、Linux、Mac OS X和其它部分操作系统都是可用的。你可以为这些系统从甲骨文的网站下载所对应的JDK版本。
访问在线文档
你可以访问JXTA JXSE API的在线文档。(没找到……)
下载二进制文件
从官方站点下载JXSE的配套编程手册(不知道是不是SUN被收购的原因,我没找到JXSE的手册项目,听了吗?可以在这找些JXSE的资源)。这个压缩文档中包含了教程的源码和二进制发布。
你可以从网站下载JXTA的当前版本。这个站点提供了JXTA的几个版本:
- 发布版——JXTA JXSE的经过测试的稳定版。这个版本是JXTA初学者的最好的选择。
- 每日更新版——JXTA还在进行中的最新版。这个版本用于开发者的测试且并不保证运行的正确性。
通常下载的JXTA的源码同样允许你自己编译。你可以从下载源代码,用来编译你自己的JXTA二进制文件。
编译JXTA代码
例子中的HelloWorld程序在编译时需要jxta.jar文件包。当你运行Java编译程序(javac)时,你需要使用-classpath参数来指定jxta.jar文件的位置。你将需要提供jxta.jar文件在你系统上的具体位置。
编译命令的例子(Windows systems):
C:>javac -classpath .\lib\jxta.jar IDTutorial.java
运行JXTA程序
当你输入java命令运行程序的时候,你需要使用-classpath参数指定所需的jar文件的位置。你将需要提供所需的.jar文件的具体位置。
程序运行命令例子(Windows systems):
C:>java -classpath .\lib\jxta.jar;.\lib\bcprov-jdk14.jar;. IDTutorial
- 注意——你会发现通过创建一个脚本或批处理文件来运行你的程序是非常简单的。这就消除了你每次都是用非常长的命令来运行你的程序的需要。
JXSE包含一个简单的用户界面的配置。多数情况下这种默认的配种会被使用编程性的平台配置替代,例如作为NetworkConfigurator类或通过使用NetworkManager类,需要进行的预先的概要配置:
- Ad-Hoc:这种节点在点对点网络中是典型的部署。这个节点不会使用基础设施节点(集合节点或中继节点)。
- 边缘节点——除了支持Ad-Hoc的行为,一个边缘节点还会依附于一个基础设施节点(集合节点、中继节点或这两者)。
- 集合节点——支持网络初期引导服务,例如发现,管道解析等。
- 中继节点——提供信息中继服务,使其能穿越防火墙。
- 代理节点——为J2ME代理服务提供JXME JXTA。
- 超级节点——提供集合节点、中继节点、代理节点的所有功能。
强烈推荐JXTA节点通过NetworkManager或NetworkConfigurator类的静态静态方法进行节点配置,被期望使用的方法例如newEdgeConfiguration(storeHome)。一旦配置被创建,它可能会符合程序的要求。
NetworkConfigurator可以使用一个给定的URI载入配置的能力也是值得注意的。它的一个特点是为提供节点的PeerID和节点证书提供了系统的方法。例如,load("");
“公共JXTA网络”配置参数
在一些例子中可能会用到JXTA开发网络,以用来支持初始示例程序和教程。它们并不打算在生产网络中被使用。这个配置是用来对运行在本地多子网、防火墙、NATs环境中的JXTA程序进行测试。
JXTA和HTTP代理
为了能让JXTA节点穿过防火墙进行连接,JXTA支持使用HTTP代理。它们是被web浏览器所使用的代理相同的代理。一些代理被配置为需要认证。大多数情况下,Java程序在安装的时候JXTA会使用系统HTTP代理配置参数或者是使用提供的配置。你也可以通过Java控制台调整HTTP代理设置。
我需要代理吗?
如果你的web浏览器需要使用HTTP代理,那么你的JXTA很可能也需要代理。大多数服务器都有一个包含代理信息的首选项页面。在一些自动浏览器的代理机制中,确定是否使用了代理是很困难的。在这种情况下,要问一问本地的专家或IT部员工。
在Java代码行中配置HTTP代理
如果你通过直接运行Java来启动你的程序,你可以把HTTP代理参数作为java命令行的一部分。HTTP代理通过Java系统性能定义。例如:
% java -Dhttp.proxyHost=proxy.mycompany.com Dhttp.proxyPort=8080...
这个设定将会配置Java使用proxy.mycompany.com为代理服务器,端口为8080。你需要使用你从web服务器模仿的值。
JXTA和代理人证
当HTTP需要认证的时候,以下Java系统性质需要被设定:
% java -Djxta.proxy.user=usr -Djxta.proxy.password=pwd...
配置信息被保存在安全信息文件中(用户名和密码),存储位置./.cache/example_name/PlatfornConfig;(./.cache/example_name/cm)。程序下次运行的时候,这些信息被用来配置你的节点。
- 注意——指定一个默认配置信息存储位置的代替位置(比使用默认的./.jxta子目录更好),使用:
java -DJXTA_HOME="alternate dir" ...
创建多种ID
节点、节点组、管道和其它的JXTA资源需要被唯一的标识出来。一个JXTA ID唯一的标识了一个资源和服务。当前有六种JXTA实体定义了JXTA ID:节点、节点组、管道、内容、模块类和模块规范。URNs被用来描述JXTA IDs。URNs是一种URI的格式“... are intended to serve as persistent, location-independent, resource identifiers”。就像是其它的URI结构,JXTA使用字符串来提供。
一个JXTA节点ID的例子:
urn:jxta:uuid-59616261646162614A78746150325033F3BC76FF13C2414CBC0AB663666DA53903
一个JXTA管道的例子:
urn:jxta:uuid-59616261646162614E504720503250338E3E786229EA460DADC1A176B69B731504
每一个JXTA ID都有一个ID格式。这个格式描述了ID怎样被创建和怎样被程序操作。(后边这一段与前边重复了,怎么这么罗嗦……)
下边的例子阐述了各种类型的JXTA表示是怎么构建的:
ID教程源码:
- package tutorial.id;
-
import net.jxta.id.IDFactory;
-
import net.jxta.peer.PeerID;
-
import net.jxta.peergroup.PeerGroupID;
-
import net.jxta.pipe.PipeID;
-
import java.io.UnsupportedEncodingException;
-
import java.security.MessageDigest;
-
import java.security.NoSuchAlgorithmException;
-
import java.text.MessageFormat;
-
/**
-
* A simple and re-usable example of creating various JXTA IDs
-
*
-
* This is a two part tutorial :
-
*
-
*
- Illustrates the creation of predictable ID's based upon the hash of a
-
* provided string. This method provides an independent and deterministic
-
* method for generating IDs. However using this method does require care
-
* in the choice of the seed expression in order to prevent ID collisions
-
* (duplicate IDs).
-
*
-
*
- New random ID's encoded with a specific GroupID.
-
*
-
*/
-
public class IDTutorial {
-
private static final String SEED = "IDTuorial";
-
/**
-
* Returns a SHA1 hash of string.
-
*
-
* @param expression to hash
-
* @return a SHA1 hash of string or {@code null} if the expression could
-
* not be hashed.
-
*/
-
private static byte[] hash(final String expression) {
-
byte[] result;
-
MessageDigest digest;
-
if (expression == null) {
-
throw new IllegalArgumentException("Invalid null expression");
-
}
-
try {
-
digest = MessageDigest.getInstance("SHA1");
-
} catch (NoSuchAlgorithmException failed) {
-
failed.printStackTrace(System.err);
-
RuntimeException failure = new IllegalStateException("Could not get
-
SHA-1 Message");
-
failure.initCause(failed);
-
throw failure;
-
}
-
try {
-
byte[] expressionBytes = expression.getBytes("UTF-8");
-
result = digest.digest(expressionBytes);
-
} catch (UnsupportedEncodingException impossible) {
-
RuntimeException failure =
-
new IllegalStateException("Could not encode expression as UTF8");
-
failure.initCause(impossible);
-
throw failure;
-
}
-
return result;
-
}
-
/**
-
* Given a pipe name, it returns a PipeID who's value is chosen based upon that name.
-
*
-
* @param pipeName instance name
-
* @param pgID the group ID encoding
-
* @return The pipeID value
-
*/
-
public static PipeID createPipeID(PeerGroupID pgID, String pipeName) {
-
String seed = pipeName + SEED;
-
return IDFactory.newPipeID(pgID, hash(seed.toLowerCase()));
-
}
-
/**
-
* Creates group encoded random PipeID.
-
*
-
* @param pgID the group ID encoding
-
* @return The pipeID value
-
*/
-
public static PipeID createNewPipeID(PeerGroupID pgID) {
-
return IDFactory.newPipeID(pgID);
-
}
-
/**
-
* Creates group encoded random PeerID.
-
*
-
* @param pgID the group ID encoding
-
* @return The PeerID value
-
*/
-
public static PeerID createNewPeerID(PeerGroupID pgID) {
-
return IDFactory.newPeerID(pgID);
-
}
-
/**
-
* Given a peer name generates a Peer ID who's value is chosen based upon that name.
-
*
-
* @param peerName instance name
-
* @param pgID the group ID encoding
-
* @return The PeerID value
-
*/
-
public static PeerID createPeerID(PeerGroupID pgID, String peerName) {
-
String seed = peerName + SEED;
-
return IDFactory.newPeerID(pgID, hash(seed.toLowerCase()));
-
}
-
/**
-
* Creates group encoded random PeerGroupID.
-
*
-
* @param pgID the group ID encoding
-
* @return The PeerGroupID value
-
*/
-
public static PeerGroupID createNewPeerGroupID(PeerGroupID pgID) {
-
return IDFactory.newPeerGroupID(pgID);
-
}
-
/**
-
* Given a group name generates a Peer Group ID who's value is chosen based
-
* upon that name.
-
*
-
* @param groupName group name encoding value
-
* @return The PeerGroupID value
-
*/
-
public static PeerGroupID createPeerGroupID(final String groupName) {
-
//Use lower case to avoid any locale conversion inconsistencies
-
return IDFactory.newPeerGroupID(PeerGroupID.defaultNetPeerGroupID,
-
hash(SEED + groupName.toLowerCase()));
-
}
-
/**
-
* Contructs and returns an string encoded Infrastructure PeerGroupID.
-
*
-
* @param groupName the string encoding
-
* @return The infraPeerGroupID PeerGroupID
-
*/
-
public static PeerGroupID createInfraPeerGroupID(String groupName) {
-
return createPeerGroupID(groupName);
-
}
-
/**
-
* Main method
-
*
-
* @param args command line arguments. None defined
-
*/
-
public static void main(String args[]) {
-
PeerGroupID infra = createInfraPeerGroupID("infra");
-
PeerID peerID = createPeerID(infra, "peer");
-
PipeID pipeID = createPipeID(PeerGroupID.defaultNetPeerGroupID, "pipe");
-
System.out.println(MessageFormat.format(
-
"\n\nAn infrastucture PeerGroupID: {0}", infra.toString()));
-
System.out.println(MessageFormat.format(
-
"PeerID with the above infra ID encoding: {0}", peerID.toString()));
-
System.out.println(MessageFormat.format("PipeID with the default
-
defaultNetPeerGroupID encoding: {0}", pipeID.toString()));
-
peerID = createNewPeerID(PeerGroupID.defaultNetPeerGroupID);
-
pipeID = createNewPipeID(PeerGroupID.defaultNetPeerGroupID);
-
PeerGroupID pgid = createNewPeerGroupID(PeerGroupID.defaultNetPeerGroupID);
-
System.out.println(
-
MessageFormat.format("\n\nNew PeerID created : {0}", peerID.toString()));
-
System.out.println(
-
MessageFormat.format("New PipeID created : {0}", pipeID.toString()));
-
System.out.println(
-
MessageFormat.format("New PeerGroupID created : {0}", pgid.toString()));
-
}
-
}
广告
广告是JXTA项目的核心内容,它用来广告节点、节点组、服务、管道和其它的JXTA资源。广告为JXTA资源提供了一种平***立地表示,使得两个不同的平台实现之间可以交换信息(Java、C等)。
每一个广告都带有一个可以描述此广告的文档。广告通常被描述为XML文档。方法Advertisement.getDocument(MimeMediaType)用来生成广告的描述。不同的描述通过mime类型的选择后是有效的。典型的mime类型是“text/xml”或“text/plain”,它们能够生成广告的文本表示。使用AdvertisementFactory构造广告实例比使用Advertisement类构造广告实例更常用。所有的在net.jxta.protocol中定义的公共广告都是抽象类。对于每一个抽象公共广告,它们都有一个包含文档创建和解析方法的私有实现。私有的实现使用AdvertisementFactory注册。新的广告类型必须用下边阐述所示的方式进行注册或者是使用META-INF/services/net.jxta.document.Advertisement扩展。
下边的实例阐述了新的广告类型的创建方法,还有通过广告工厂对其进行注册的方法:
AdvertisementFactory.registerAdvertisementInstance(
AdvertisementTutorial.getAdvertisementType(),new AdvertisementTutorial.Instantiator());
广告教程代码
- package tutorial.advertisement;
-
import net.jxta.document.*;
-
import net.jxta.id.ID;
-
import net.jxta.id.IDFactory;
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.io.Serializable;
-
import java.net.InetAddress;
-
import java.net.URI;
-
import java.net.URISyntaxException;
-
import java.net.UnknownHostException;
-
import java.util.Enumeration;
-
import java.util.logging.Logger;
-
/**
-
* Simple Advertisement Tutorial creates a advertisment describing a system
-
*
-
*
-
* <?xml version="1.0"?>
-
* <!DOCTYPE jxta:System>
-
* <jxta:System xmlns:jxta="">
-
* <id>id</id>
-
* <name>Device Name</name>
-
* <ip>ip address</ip>
-
* <hwarch>x86</hwarch>
-
* <hwvendor>Sun MicroSystems</hwvendor>
-
* <OSName></OSName>
-
* <OSVer></OSVer>
-
* <osarch></osarch>
-
* <sw></sw>
-
* </jxta:System>
-
*
-
*/
-
public class AdvertisementTutorial extends Advertisement
-
implements Comparable, Cloneable, Serializable {
-
private String hwarch;
-
private String hwvendor;
-
private ID id = ID.nullID;
-
private String ip;
-
private String name;
-
private String osname;
-
private String osversion;
-
private String osarch;
-
private String inventory;
-
private final static Logger LOG =
-
Logger.getLogger(AdvertisementTutorial.class.getName());
-
private final static String OSNameTag = "OSName";
-
private final static String OSVersionTag = "OSVer";
-
private final static String OSarchTag = "osarch";
-
private final static String hwarchTag = "hwarch";
-
private final static String hwvendorTag = "hwvendor";
-
private final static String idTag = "ID";
-
private final static String ipTag = "ip";
-
private final static String nameTag = "name";
-
private final static String swTag = "sw";
-
/**
-
* Indexable fields. Advertisements must define the indexables, in order
-
* to properly index and retrieve these advertisements locally and on the
-
* network
-
*/
-
private final static String[] fields = {idTag, nameTag, hwarchTag};
-
/**
-
* Default Constructor
-
*/
-
public AdvertisementTutorial() {
-
}
-
/**
-
* Construct from a StructuredDocument
-
*
-
* @param root Root element
-
*/
-
public AdvertisementTutorial(Element root) {
-
TextElement doc = (TextElement) root;
-
if (!getAdvertisementType().equals(doc.getName())) {
-
throw new IllegalArgumentException("Could not construct : " +
-
getClass().getName() + "from doc containing a " +
-
doc.getName());
-
}
-
initialize(doc);
-
}
-
/**
-
* Construct a doc from InputStream
-
*
-
* @param stream the underlying input stream.
-
* @throws IOException if an I/O error occurs.
-
*/
-
public AdvertisementTutorial(InputStream stream) throws IOException {
-
StructuredTextDocument doc = (StructuredTextDocument)
-
StructuredDocumentFactory
-
.newStructuredDocument(MimeMediaType.XMLUTF8, stream);
-
initialize(doc);
-
}
-
/**
-
* Sets the hWArch attribute of the AdvertisementTutorial object
-
*
-
* @param hwarch The new hWArch value
-
*/
-
public void setHWArch(String hwarch) {
-
this.hwarch = hwarch;
-
}
-
/**
-
* Sets the OSArch attribute of the AdvertisementTutorial object
-
*
-
* @param osarch The new hWArch value
-
*/
-
public void setOSArch(String osarch) {
-
this.osarch = osarch;
-
}
-
/**
-
* Sets the hWVendor attribute of the AdvertisementTutorial object
-
*
-
* @param hwvendor The new hWVendor value
-
*/
-
public void setHWVendor(String hwvendor) {
-
this.hwvendor = hwvendor;
-
}
-
/**
-
* sets the unique id
-
*
-
* @param id The id
-
*/
-
public void setID(ID id) {
-
this.id = (id == null ? null : id);
-
}
-
/**
-
* Sets the iP attribute of the AdvertisementTutorial object
-
*
-
* @param ip The new iP value
-
*/
-
public void setIP(String ip) {
-
this.ip = ip;
-
}
-
/**
-
* Sets the name attribute of the AdvertisementTutorial object
-
*
-
* @param name The new name value
-
*/
-
public void setName(String name) {
-
this.name = name;
-
}
-
/**
-
* Sets the oSName attribute of the AdvertisementTutorial object
-
*
-
* @param osname The new oSName value
-
*/
-
public void setOSName(String osname) {
-
this.osname = osname;
-
}
-
/**
-
* Sets the oSVersion attribute of the AdvertisementTutorial object
-
*
-
* @param osversion The new oSVersion value
-
*/
-
public void setOSVersion(String osversion) {
-
this.osversion = osversion;
-
}
-
/**
-
* Sets the SWInventory attribute of the AdvertisementTutorial object
-
*
-
* @param inventory the software inventory of the system
-
*/
-
public void setSWInventory(String inventory) {
-
this.inventory = inventory;
-
}
-
/**
-
* {@inheritDoc}
-
*
-
* @param asMimeType Document encoding
-
* @return The document value
-
*/
-
@Override
-
public Document getDocument(MimeMediaType asMimeType) {
-
StructuredDocument adv =
-
StructuredDocumentFactory.newStructuredDocument(asMimeType,
-
getAdvertisementType());
-
if (adv instanceof Attributable) {
-
((Attributable) adv).addAttribute("xmlns:jxta", "");
-
}
-
Element e;
-
e = adv.createElement(idTag, getID().toString());
-
adv.appendChild(e);
-
e = adv.createElement(nameTag, getName().trim());
-
adv.appendChild(e);
-
e = adv.createElement(OSNameTag, getOSName().trim());
-
adv.appendChild(e);
-
e = adv.createElement(OSVersionTag, getOSVersion().trim());
-
adv.appendChild(e);
-
e = adv.createElement(OSarchTag, getOSArch().trim());
-
adv.appendChild(e);
-
e = adv.createElement(ipTag, getIP().trim());
-
adv.appendChild(e);
-
e = adv.createElement(hwarchTag, getHWArch().trim());
-
adv.appendChild(e);
-
e = adv.createElement(hwvendorTag, getHWVendor().trim());
-
adv.appendChild(e);
-
e = adv.createElement(swTag, getSWInventory().trim());
-
adv.appendChild(e);
-
return adv;
-
}
-
/**
-
* Gets the hWArch attribute of the AdvertisementTutorial object
-
*
-
* @return The hWArch value
-
*/
-
public String getHWArch() {
-
return hwarch;
-
}
-
/**
-
* Gets the OSArch attribute of the AdvertisementTutorial object
-
*
-
* @return The OSArch value
-
*/
-
public String getOSArch() {
-
return osarch;
-
}
-
/**
-
* Gets the hWVendor attribute of the AdvertisementTutorial object
-
*
-
* @return The hWVendor value
-
*/
-
public String getHWVendor() {
-
return hwvendor;
-
}
-
/**
-
* returns the id of the device
-
*
-
* @return ID the device id
-
*/
-
@Override
-
public ID getID() {
-
return (id == null ? null : id);
-
}
-
/**
-
* Gets the IP attribute of the AdvertisementTutorial object
-
*
-
* @return The IP value
-
*/
-
public String getIP() {
-
return ip;
-
}
-
/**
-
* Gets the name attribute of the AdvertisementTutorial object
-
*
-
* @return The name value
-
*/
-
public String getName() {
-
return name;
-
}
-
/**
-
* Gets the OSName attribute of the AdvertisementTutorial object
-
*
-
* @return The OSName value
-
*/
-
public String getOSName() {
-
return osname;
-
}
-
/**
-
* Gets the Software Inventory text element
-
*
-
* @return The Inventory value
-
*/
-
public String getSWInventory() {
-
if (inventory == null) {
-
inventory = "";
-
}
-
return inventory;
-
}
-
/**
-
* Gets the OSVersion attribute of the AdvertisementTutorial object
-
*
-
* @return The OSVersion value
-
*/
-
public String getOSVersion() {
-
return osversion;
-
}
-
/**
-
* Process an individual element from the document.
-
*
-
* @param elem the element to be processed.
-
* @return true if the element was recognized, otherwise false.
-
*/
-
protected boolean handleElement(TextElement elem) {
-
if (elem.getName().equals(idTag)) {
-
try {
-
URI id = new URI(elem.getTextValue());
-
setID(IDFactory.fromURI(id));
-
} catch (URISyntaxException badID) {
-
throw new IllegalArgumentException("unknown ID format in
-
advertisement: " +
-
elem.getTextValue());
-
}
-
catch (ClassCastException badID) {
-
throw new IllegalArgumentException("Id is not a known id type: " +
-
elem.getTextValue());
-
}
-
return true;
-
}
-
if (elem.getName().equals(nameTag)) {
-
setName(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(OSNameTag)) {
-
setOSName(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(OSVersionTag)) {
-
setOSVersion(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(OSarchTag)) {
-
setOSArch(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(ipTag)) {
-
setIP(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(hwarchTag)) {
-
setHWArch(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(hwvendorTag)) {
-
setHWVendor(elem.getTextValue());
-
return true;
-
}
-
if (elem.getName().equals(swTag)) {
-
setSWInventory(elem.getTextValue());
-
return true;
-
}
-
// element was not handled
-
return false;
-
}
-
/**
-
* Intialize a System advertisement from a portion of a structured document.
-
*
-
* @param root document root
-
*/
-
protected void initialize(Element root) {
-
if (!TextElement.class.isInstance(root)) {
-
throw new IllegalArgumentException(getClass().getName() +
-
" only supports TextElement");
-
}
-
TextElement doc = (TextElement) root;
-
if (!doc.getName().equals(getAdvertisementType())) {
-
throw new IllegalArgumentException("Could not construct : "
-
+ getClass().getName() + "from doc containing a " +
-
doc.getName());
-
}
-
Enumeration elements = doc.getChildren();
-
while (elements.hasMoreElements()) {
-
TextElement elem = (TextElement) elements.nextElement();
-
if (!handleElement(elem)) {
-
LOG.warning("Unhandleded element \'" + elem.getName() + "\' in " +
-
doc.getName());
-
}
-
}
-
}
-
/**
-
* {@inheritDoc}
-
*/
-
@Override
-
public final String[] getIndexFields() {
-
return fields;
-
}
-
/**
-
* {@inheritDoc}
-
*/
-
@Override
-
public boolean equals(Object obj) {
-
if (this == obj) {
-
return true;
-
}
-
if (obj instanceof AdvertisementTutorial) {
-
AdvertisementTutorial adv = (AdvertisementTutorial) obj;
-
return getID().equals(adv.getID());
-
}
-
return false;
-
}
-
/**
-
* {@inheritDoc}
-
*/
-
public int compareTo(Object other) {
-
return getID().toString().compareTo(other.toString());
-
}
-
/**
-
* All messages have a type (in xml this is !doctype) which
-
* identifies the message
-
*
-
* @return String "jxta:AdvertisementTutorial"
-
*/
-
public static String getAdvertisementType() {
-
return "jxta:AdvertisementTutorial";
-
}
-
/**
-
* Instantiator
-
*/
-
public static class Instantiator implements AdvertisementFactory.Instantiator {
-
/**
-
* Returns the identifying type of this Advertisement.
-
*
-
* @return String the type of advertisement
-
*/
-
public String getAdvertisementType() {
-
return AdvertisementTutorial.getAdvertisementType();
-
}
-
/**
-
* Constructs an instance of
Advertisement
matching the
-
* type specified by the
advertisementType
parameter.
-
*
-
* @return The instance of
Advertisement
or null if it
-
* could not be created.
-
*/
-
public Advertisement newInstance() {
-
return new AdvertisementTutorial();
-
}
-
/**
-
* Constructs an instance of
Advertisement
matching the
-
* type specified by the
advertisementType
parameter.
-
*
-
* @param root Specifies a portion of a StructuredDocument which will
-
* be converted into an Advertisement.
-
* @return The instance of
Advertisement
or null if it
-
* could not be created.
-
*/
-
public Advertisement newInstance(net.jxta.document.Element root) {
-
return new AdvertisementTutorial(root);
-
}
-
}
-
/**
-
* Main method
-
*
-
* @param args command line arguments. None defined
-
*/
-
public static void main(String args[]) {
-
// The following step is required and only need to be done once,
-
// without this step the AdvertisementFactory has no means of
-
// associating an advertisement name space with the proper obect
-
// in this cast the AdvertisementTutorial
-
AdvertisementFactory.registerAdvertisementInstance(
-
AdvertisementTutorial.getAdvertisementType(),
-
new AdvertisementTutorial.Instantiator());
-
AdvertisementTutorial advTutorial = new AdvertisementTutorial();
-
advTutorial.setID(ID.nullID);
-
advTutorial.setName("AdvertisementTutorial");
-
try {
-
advTutorial.setIP(InetAddress.getLocalHost().getHostAddress());
-
} catch (UnknownHostException ignored) {
-
//ignored
-
}
-
advTutorial.setOSName(System.getProperty("os.name"));
-
advTutorial.setOSVersion(System.getProperty("os.version"));
-
advTutorial.setOSArch(System.getProperty("os.arch"));
-
advTutorial.setHWArch(System.getProperty("HOSTTYPE",
-
System.getProperty("os.arch")));
-
advTutorial.setHWVendor(System.getProperty("java.vm.vendor"));
-
System.out.println(advTutorial.toString());
-
}
-
}
信息和信息元素
一个JXTA信息是一个协议信息和内容的容器。每一个信息都由一系列的信息元素组成。信息元素包含信息的协议信息和内容。每一个元素都包含信息的一部分。元素的目标和内容是由信息协议定义所定义的。按照信息协议,信息元素可以包含所需的多种类型的数据。
JXTA信息包含一个含有0个或多个信息元素的有序列表。相同的信息元素可能会随时出现在信息中。信息中的每一个信息元素都与一个名字空间相联系。名字空间允许在一个信息中使用多个协议层,而避免了它们信息元素的冲突。例如,所有的JXTA核心协议都把它们的信息存储到保留的名字空间‘jxta’中。默认的命名空间对程序和服务来说是保留的。应用总会为它们的信息元素定义自己的命名空间,但是要避免使用‘jxta’和在模块规则ID中定义的命名空间,除了它们自己的MSID。
一个JXTA信息元素可以用来存储多种类型的数据。JXTA JSE API支持多种信息元素,而附加的信息类型可能被定义。所提供的元素类允许你从一个字符串、字节数组、文档、输入流等创建信息元素。为了将数据作为信息的一部分传输,则元素的数据在发送之前必须被分成原始的字节流。有多种信息元素的“调料”用来方便而有效地进行原始比特的转换。所有的元素类只是将元素数据转换为二进制数据的简单代理。
在使用信息元素的开发中,你不用在创建之后考虑信息元素的原始类型。比起StringMessageElement elem = new StringMessageElement("foo","bar",null);我们更常使用MessageElement elem = new StringMessageElement("foo","bar",null);。通过使用MessageElement类加强每一个信息元素的通用性——所有的数据都以字节的形式发送和接受。每一个信息元素都分为四部分:
- 一个可选的名字可以是任何字符串。没有命名的元素假定有“”的名字(空字符串)。
- 一个可选的MIME媒体类型。如果没有指定类型,MIME媒体类型会被假设为“Applacation/Octet-Stream”,二进制数据的默认类型。
- 信息元素的内容,一个字节序列。为了能将信息元素的内容作为信息的一部分进行传输,信息元素必须在发送前被分成原始字节。信息元素可以从各种各样的数据类型转化而来,其中有字符串、字节数组、文档、二进制数据等。在各种情况下,不管数据的数据源,结果信息元素都是一个数组队列的容器。所有信息元素都会以原始比特的方式进行发送和接受。 有多种信息元素的“调料”用来方便而有效地进行原始比特的转换。
- 一个可选的签名:每个信息元素都可以与一个额外的信息元素相联系,这个元素中可能包含经过加密的这个元素的签名或哈希值。
为JXTA信息设计节点
- 每一个信息元素你大约会加入50个字节的传输开销。如果可能,避免协议设计使用太多的小元素。
- 命名空间只与将信息元素作为元素加入一个信息有联系。命名空间在信息中动态的与信息元素相关联,因为对于元素来说适当的命名空间往往是基于上下文发生改变的。
- 有四种简单的方法让程序和服务使用信息命名空间:
- 只是用默认的命名空间。因为这个命名空间是为要创建信息的程序和服务保留的,所以它是最容易,也是最通常的选择。
- 使用一个习惯性的硬编码命名空间,如“myApplication”。这种方法在JXTA程序中是很常用的,它使得程序可以按照需求定义尽可能多的命名空间。尽管不太可能,当使用硬编码命名空间是有一个小问题,就是两个单独的编码之间可能会有冲突。如果方便的话,程序和服务需要使用它们的MSID代替它们的命名空间。
- 它们的MSID是它们常用的命名空间。基于MSID的命名空间是为那些实现了某些模块规范的程序和服务而预定义的。例如,标准JXTA集合节点服务的MSID是urn:jxta:uuid-deadbeefdeafbabafeedbabe000000060106.则命名空间 urn:jxta:uuid-deadbeefdeafbabafeedbabe000000060106.可能只会被实现了相应规范的JXTA集合节点所使用。
- 使用一个唯一的随即命名空间。MessageElement类为创建的基于UUIDs的唯一的随即名字提供了工具。这些随机的名字可以用于程序和服务的单一信息或序列信息。程序也可以产生它们自己的随即命名空间的名字,只要所选的名字是唯一的。通常这意味着要使用UUIDs或安全信息摘要(SHA1、MD5等)作为命名空间的名字。
- 信息可以被重用或非常方便的克隆。在许多程序中,在信息发送前创建一个预定义的、可被克隆的信息模板比每次都直接创建一个新的信息要更方便。
- 来自一个单一线程的信息并不是同步的,而且只能可靠的使用。这在信息发送的时候经常被套用。直到信息发送成功它都不会被其它程序使用。
为信息元素设计节点
- 信息元素是不变的,同时它作为信息的一部分被重复使用。这个特点常常用在不变的值,例如地址数据,或者是缓存的信息,例如节点广告。
- 包含在MessageElement中的数据有四种方法访问:
- 作为一个 java.io.InputStream
- 发数据发给一个 java.io.OutputStream
- 作为一个 java.lang.String
- 作为一个字节数组
信息和信息元素教程源码
- 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();
-
}
-
}
阅读(1238) | 评论(0) | 转发(0) |