⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jxtapeer.java

📁 javaP2P技术内幕课程19-20的源代码
💻 JAVA
字号:
/*
 * We customized our SOAP-over-P2P implementation 
 * by using different examples provided at JXTA.org. 
 * That's the reason for copying the license information here.
 *
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *
 */


package ch20.peer;


import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Enumeration;
import java.net.URL;

import java.net.MalformedURLException;
import net.jxta.pipe.PipeID;
import net.jxta.document.TextElement;
import net.jxta.platform.Application;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredTextDocument;
import net.jxta.document.StructuredDocument;
import net.jxta.document.MimeMediaType;
import net.jxta.document.Element;
import net.jxta.document.StructuredDocumentUtils;
import net.jxta.endpoint.Message;
import net.jxta.pipe.PipeService;
import net.jxta.id.IDFactory;
import net.jxta.pipe.OutputPipe;
import net.jxta.pipe.InputPipe;
import net.jxta.id.ID;
import net.jxta.platform.ModuleClassID;
import net.jxta.pipe.InputPipe;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.protocol.ModuleSpecAdvertisement;
import net.jxta.protocol.ModuleClassAdvertisement;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.discovery.DiscoveryService;
import net.jxta.exception.PeerGroupException;
import net.jxta.impl.peergroup.Platform;
import net.jxta.impl.peergroup.GenericPeerGroup;

import net.jxta.pipe.PipeMsgListener;
import net.jxta.pipe.PipeMsgEvent;

import javax.swing.*;


public class JXTAPeer implements PipeMsgListener{

	protected static PeerGroup group = null;
	protected PeerGroupAdvertisement groupAdvertisement = null;
	protected DiscoveryService disco;
	protected PipeService pipes;
	protected Message msg;      

	private static int objectCount = 0;

	private PipeMsgListener listener;

	protected JTextArea receiver;


	public JXTAPeer(){
		if (group==null)
		{
			try {
				// Create the default NetPeerGroup.
				group = PeerGroupFactory.newNetPeerGroup();
			} catch (Exception e) {
				System.out.println("fatal error : group creation failure");
				e.printStackTrace();
			}//catch
			objectCount++;
		}//if (!objectCount)
		startJXTA();
	}//constructor


	protected void startJXTA() {
		
		// Obtain the group advertisement
		groupAdvertisement = group.getPeerGroupAdvertisement();

		// get the discovery, and pipe service
		disco = group.getDiscoveryService();
		pipes = group.getPipeService();
	}//startJXTA()


	public InputPipe publishServiceOverJXTAPipe(
			String ServiceName,//Name of service being published.
			String ServiceVersion,//Version of the service.
			String ServiceDescription,//Description of the service.
			String ServiceCreator,//Creator of the service.
			String SpecURI,//URI of the service apecification.
			String PipeAdvFile//Name of service XML advertisement.
	){

		receiver.setText(receiver.getText()+
			"Starting to create input pipe service to receive messages:\n");
		
		try {
			// Shortform class advertisement.
			ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement)
			AdvertisementFactory.newAdvertisement(
			ModuleClassAdvertisement.getAdvertisementType());
			mcadv.setName("JXTAMOD:"+ServiceName);
			mcadv.setDescription(ServiceDescription);
			ModuleClassID mcID = IDFactory.newModuleClassID();
			mcadv.setModuleClassID(mcID);
	
			// Publsih the shortform class advertisement.
			disco.publish(mcadv, DiscoveryService.ADV);
			disco.remotePublish(mcadv, DiscoveryService.ADV);

			// Now create the detailed module advertisement.
			ModuleSpecAdvertisement mdadv = 
		     	(ModuleSpecAdvertisement)AdvertisementFactory.newAdvertisement(
			ModuleSpecAdvertisement.getAdvertisementType());
			mdadv.setName("JXTASPEC:"+ServiceName);
			mdadv.setVersion(ServiceVersion);
			mdadv.setCreator(ServiceCreator);
			mdadv.setDescription(ServiceDescription);
			mdadv.setModuleSpecID(IDFactory.newModuleSpecID(mcID));
			mdadv.setSpecURI(SpecURI);

			// Now create the pipe advertismeent.
			// We will later copy the pipe advert
			// into the module spec advert.
			PipeAdvertisement pipeadv = null;
			try {
				FileInputStream is = 
					new FileInputStream(PipeAdvFile);
				pipeadv = (PipeAdvertisement)
					AdvertisementFactory.newAdvertisement(
					new MimeMediaType("text/xml"), is);
				is.close();
			} catch (Exception e) {
				receiver.setText(receiver.getText()+"\n"+
				"Error reading advert file "+ PipeAdvFile);
				return null;
			}//catch

			// Now copy the pipe advert
			// into the module spec advert.
			StructuredTextDocument paramDoc =
				(StructuredTextDocument) 
				StructuredDocumentFactory.newStructuredDocument
				(new MimeMediaType("text/xml"),"Parm");

			StructuredDocumentUtils.copyElements(
				paramDoc, 
				paramDoc, 
				(Element)pipeadv.getDocument(
					new MimeMediaType("text/xml"))
				);
			mdadv.setParam((StructuredDocument) paramDoc);

			// Publish the module spec advert.
			disco.publish(mdadv, DiscoveryService.ADV);
			disco.remotePublish(mdadv, DiscoveryService.ADV);

			// We are now all set to create our input pipe.
			InputPipe ip = pipes.createInputPipe(pipeadv, 
				((listener==null)?this:listener));

			receiver.setText(receiver.getText()+
				"Input Pipe service created.\n");
		
			return ip;
		} catch (Exception ex) {
			receiver.setText(receiver.getText()+
				"Error in publishing.\n");
			return null;

		}//catch
	}//publishServiceOverJXTAPipe()


	public void createOutputPipeAndSendMessage(
			String ServiceName,//Name of output pipe service.
			String resBody//Message to be sent.
								){
		

		OutputPipe myOutPipe;
		Message msg = null;      // pipe message received
	
		Enumeration enum = null;

		// Find the module spec advertisement.
		while (true) {
			try {
				receiver.setText(receiver.getText()+
					"\nLooking for the pipe advertisement: "+
					ServiceName+" .........\n");
				enum = disco.getLocalAdvertisements(DiscoveryService.ADV
						     , "Name"
						     , "JXTASPEC:"+ServiceName);
				if ((enum != null) && enum.hasMoreElements()) break;

				disco.getRemoteAdvertisements(null, 
								DiscoveryService.ADV,
								"Name",
								"JXTASPEC:"+ServiceName,											1, 
								null);
	
				try { Thread.sleep(2000);} catch (Exception e){}
	    		} catch (Exception e){   }
		} // while (true)
   
		// Now extract the pipe advert from module spec advert.
		ModuleSpecAdvertisement mdsadv = 
			(ModuleSpecAdvertisement) enum.nextElement();
		try {
			StructuredTextDocument paramDoc = 
				(StructuredTextDocument)  mdsadv.getParam();

			String pID = null;
			String pType = null;

		    	Enumeration elements = paramDoc.getChildren("jxta:PipeAdvertisement");

			elements = ((TextElement) elements.nextElement()).getChildren();

			while (elements.hasMoreElements()) {
				TextElement elem = (TextElement) elements.nextElement();
				String nm = elem.getName();

				if(nm.equals("Id")) {
			    		pID = elem.getTextValue();
					continue;
			 	}

			 	if(nm.equals("Type")) {
			    		pType = elem.getTextValue();
			    		continue;
			 	}
			} // while

		    	PipeAdvertisement pipeadv = (PipeAdvertisement) 
				AdvertisementFactory.newAdvertisement(
				PipeAdvertisement.getAdvertisementType());
	    
			try {
	            	URL pipeID = new URL(pID );
	            	pipeadv.setPipeID( (PipeID) IDFactory.fromURL( pipeID ) );
				pipeadv.setType(pType);
			} catch ( MalformedURLException badID ) {
		   		badID.printStackTrace();
	            	throw new IllegalArgumentException( 
					"Bad pipe ID in advertisement" );
			}//catch
	    
			myOutPipe = pipes.createOutputPipe(pipeadv, 11000);
	    	
			// Create a new message.
			msg = pipes.createMessage();

			msg.setString("ServiceName", ServiceName);
 			msg.setString("SOAPResponse", resBody);

			myOutPipe.send (msg);

		}catch (Exception ex) {
			receiver.setText(receiver.getText()+
				"Error in sending the message.\n");
		}//catch
	} // getNewAdvmtAndSendResponse(String resBody)


	public void setInputPipeMessageListener(PipeMsgListener msgListener)
	{
		listener = msgListener;

	}//private setInputPipeMessageListener()




	public void pipeMsgEvent ( PipeMsgEvent event ){
		receiver.setText(receiver.getText()+
			"Message received.\n");
	}//pipeMsgEvent

	public void setMessageReceiver(JTextArea msgReceiver){
		receiver = msgReceiver;
	}//setMessageReceiver

}//JXTAPeer

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -