HELP! Can not see other peers in group

"Wil" <[email protected]>
Newsgroups gmane.comp.java.jxta.user
Message-ID <000001c59455$278c3c00$74c8a8c0@cyberfusion>
Hi,

I have seen this subject recently on this list but it was never resolved
and I am having the same problem.

I have written an app that implements my own membership service,
searches for any of my groups that exist, joins them if so otherwise it
creates the group.

When I run two copies one copy creates the new group, the other joins
the existing group, but nether a peer discovery of the group nor a
rendezvous broadcast works.

In the code below I have removed my membership service and add the
password one, just to rule that out.

I know that there's quite a lot of code here but it's all just copied
from the programmer's guide.

Could someone PLEASE cast an eye over it and tell me if anything is
obviously wrong as I have now spent a working week looking at this with
no joy and may have to give up on it soon. BTW about a week ago I had
broadcasting working but I could not recreate this.

Much thanks in advance 

Wil 



package org.Sn0tters.b3ta.p2p;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.Sn0tters.b3ta.p2p.B3taMembershipService;
import net.jxta.impl.membership.passwd.PasswdMembershipService;
import net.jxta.credential.AuthenticationCredential;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.Element;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocument;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredTextDocument;
import net.jxta.document.TextElement;
import net.jxta.endpoint.*;
import net.jxta.exception.PeerGroupException;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.impl.protocol.*;
import net.jxta.membership.Authenticator;
import net.jxta.membership.MembershipService;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupFactory;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.platform.ModuleSpecID;
import net.jxta.protocol.ModuleImplAdvertisement;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.impl.peergroup.StdPeerGroupParamAdv ;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.rendezvous.RendezVousService;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PeerAdvertisement;
import net.jxta.rendezvous.RendezvousListener;
import net.jxta.rendezvous.RendezvousEvent;


public class b3ta_p2p  implements Runnable, DiscoveryListener {
	
	private PeerGroup  myNetPeerGroup=null,
b3taPeerGroup=null,discoveredb3taPeerGroup=null;
	private static PeerGroupID b3taPeerGroupID;
	private final static String GROUPID =
"jxta:uuid-967459379C3E4199BAB4EF605C6DEB4C02";
    private RendezVousService rdv;
	private DiscoveryService discovery;
	private String groupName="Wiltest";
    

    
    // Naughty naughty, globals, oh well
    PeerGroupAdvertisement globalGroupAd=null;
    

	
     
    /**
     * Convenience routine to allow other bits of code to issue a
request to other peers for a specific message
     * 
     * {@param} messageID message we are looking for
     **/
	public void issueMessageQuery( double messageID )
    {
               
        MessageIDQueryMsg equery =
            new MessageIDQueryMsg( messageID );
        
        if ( b3taPeerGroup != null )
        {
            String localPeerId = b3taPeerGroup.getPeerID().toString();
        
        
            ResolverQuery query = new ResolverQuery("MessageIDHandler",
                    null, localPeerId, equery.toString(), 0);
        }
           
    }
	
	public void run() {
		
		//TODO remove
		double i = 0;
		broadcaster b = broadcaster.getbroadcaster();
		


      
       while (true) {
        
            try {
            	
            	System.out.println("run - broadcast");
            	
            	if ( b != null )
                {
                    b.sendMessage(++i);
                }

// This is where I should discover other peers in the group
            	
 
discoveredb3taPeerGroup.getDiscoveryService().getRemoteAdvertisements(nu
ll,
                        DiscoveryService.PEER,
                        null, null, 100, this);
                       
               
                
                Thread.sleep(  10000);
            } catch(Exception e) {}
            
            
           
        }
		
    
       
        
		
		
		
	}
	
	 private static    b3ta_p2p session; // Our singleton
	 
	 public  static synchronized b3ta_p2p getb3ta_p2p () { 
		 
		 
		 
		 if ( session == null )
		 {
			 session = new b3ta_p2p();
		 }
		 
		 return session;
	 }
	 
	 
	 private b3ta_p2p() {
		 start_p2p();
	 }
	 
	 
	/** Creates new RootWS */
	public void start_p2p() {
		// Starts the JXTA Platform
		myNetPeerGroup=this.startJxta();
		
		
		if (myNetPeerGroup!=null) {
			System.out.println("JXTA platform Started ...");
		} else {
			System.err.println(" JXTA platform has failed to
start:  myNetPeerGroup is null");
			System.exit(1);
		}
		
		discovery = myNetPeerGroup.getDiscoveryService();
		
		rdv = myNetPeerGroup.getRendezVousService();
        
		rdv.setAutoStart(true);
		
//		Wait until we connect to a rendezvous peer
		System.out.println("Waiting to connect to
rendezvous...");
        
		while (! rdv.isConnectedToRendezVous()) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException ex) {
				ex.printStackTrace();
				
//				nothing, keep going
			}
		}

		
		
		System.out.println("Connected to Rendezvous ...");
		
        
//    Generate the parameters:
        // login, passwd, peer group name and peer group id
        // for creating the Peer Group
        String login="Sn0tters";
        String passwd="1nternet";
       
		
		
        
		// and finally peer group id
		// the peer group id is constant so that the same peer
group is
		//recreated each time.
        
        try {
            b3taPeerGroupID =
                (PeerGroupID) net.jxta.id.IDFactory.fromURI(new
java.net.URI(new java.net.URL("urn","",GROUPID).toExternalForm()));
        } catch (java.net.URISyntaxException e) {
            System.err.println(" Can't create b3taPeerGroupID:
URISyntaxException " +  GROUPID ) ;
            System.exit(1);
        }
        catch (java.net.MalformedURLException e) {
            System.err.println(" Can't create b3taPeerGroupID:
MalformedURLException " +  GROUPID ) ;
            System.exit(1);
        }
        
       
        
        // Find if group exists first 
 
discoveredb3taPeerGroup=this.discoverPeerGroup(myNetPeerGroup,b3taPeerGr
oupID);
        if (discoveredb3taPeerGroup!=null) {
        	
        	System.out.println(" Existing Peer Group Found ...");
        	this.joinPeerGroup(discoveredb3taPeerGroup, login,
passwd);
        	
        	
        	
        }
        else
        {
        	System.out.println(" Existing Peer Group Not Found
...");
//      	create The Passwd Authenticated Peer Group
        	b3taPeerGroup
=this.createPeerGroup(myNetPeerGroup,groupName,login,passwd);
        	
        	
        	
        	// join the b3taPeerGroup
        	if (b3taPeerGroup!=null) {
        		System.out.println(" Peer Group Created ...");
 
discoveredb3taPeerGroup=this.discoverPeerGroup(myNetPeerGroup,b3taPeerGr
oupID);
        		if (discoveredb3taPeerGroup!=null) {
        			System.out.println(" Peer Group Found
...");
 
this.joinPeerGroup(discoveredb3taPeerGroup, login, passwd);
        			
        			
        			
        			
        			
        		}
        		else
        		{
        			System.out.println( " Did not find group
......... ");
        		}
        	}
        	else
        	{
        		System.out.println( " Group create failed
......... ");
        	}
        	
        }
        
        /*
		 * Set our Propagate listener
		 */
		
		broadcaster.setPropagater(discoveredb3taPeerGroup, rdv);
		
		System.out.println(" Peer Group Joined ...");
		// Print the Peer Group Adverstisement on sdt out.
		this.printXmlAdvertisement("XML Advertisement for Peer
Group Advertisement",
	
discoveredb3taPeerGroup.getPeerGroupAdvertisement() );
		
		
		
	
	}
	
	private PeerGroup createPeerGroup( PeerGroup
rootPeerGroup,String groupName, String login, String passwd ) {
		// create the Peer Group by doing the following:
		// - Create a Peer Group Module Implementation
Advertisement and publish it
		// - Create a Peer Group Adv and publish it
		// - Create a Peer Group from the Peer Group Adv and
return this object
		PeerGroup b3taPeerGroup=null;
		PeerGroupAdvertisement b3taPeerGroupAdvertisement;
		
		// Create the PeerGroup Module Implementation Adv
		ModuleImplAdvertisement b3taMembershipModuleImplAdv ;
	
b3taMembershipModuleImplAdv=this.createB3taMembershipPeerGroupModuleImpl
Adv(rootPeerGroup);
		
		// Publish it in the parent peer group
		DiscoveryService rootPeerGroupDiscoveryService =
rootPeerGroup.getDiscoveryService();
		
		try {
			
	
rootPeerGroupDiscoveryService.publish(b3taMembershipModuleImplAdv,
					PeerGroup.DEFAULT_LIFETIME,
					PeerGroup.DEFAULT_EXPIRATION);
			
	
rootPeerGroupDiscoveryService.remotePublish(b3taMembershipModuleImplAdv,
					PeerGroup.DEFAULT_EXPIRATION);
			
		} catch (java.io.IOException e) {
			System.err.println("Can't Publish
passwdMembershipModuleImplAdv");
			System.exit(1);
		}
		
		
		
		
		// Now, Create the Peer Group Advertisement
		b3taPeerGroupAdvertisement=
	
this.createPeerGroupAdvertisement(b3taMembershipModuleImplAdv,groupName,
login,passwd);
		
		
		// Publish it in the parent peer group
		try {
			
	
rootPeerGroupDiscoveryService.publish(b3taPeerGroupAdvertisement,
					PeerGroup.DEFAULT_LIFETIME,
					PeerGroup.DEFAULT_EXPIRATION);
			
	
rootPeerGroupDiscoveryService.remotePublish(b3taPeerGroupAdvertisement,
					PeerGroup.DEFAULT_EXPIRATION);
			
			
		} catch (java.io.IOException e) {
			System.err.println("Can't Publish
b3taPeerGroupAdvertisement");
			System.exit(1);
		}
		
		
		// Finally Create the Peer Group
		if (b3taPeerGroupAdvertisement==null) {
			
			System.err.println("b3taPeerGroupAdvertisement
is null");
			
		}
		
		
		try {

	
b3taPeerGroup=rootPeerGroup.newGroup(b3taPeerGroupAdvertisement);
			
		} catch (net.jxta.exception.PeerGroupException e) {
			System.err.println("Can't create B3ta Peer Group
from Advertisement");
			e.printStackTrace();
			return null;
		}
		return b3taPeerGroup;
	}
	
	private PeerGroupAdvertisement
createPeerGroupAdvertisement(ModuleImplAdvertisement
passwdMembershipModuleImplAdv, String groupName, String login, String
passwd) {
		// Create a PeerGroupAdvertisement for the peer group
		PeerGroupAdvertisement  b3taPeerGroupAdvertisement=
(PeerGroupAdvertisement)
AdvertisementFactory.newAdvertisement(PeerGroupAdvertisement.getAdvertis
ementType());
		
		// Instead of creating a new group ID each time, by
using the line below
		//
b3taPeerGroupAdvertisement.setPeerGroupID(IDFactory.newPeerGroupID());
		// I use a fixed ID so that each time I start
SecurePeerGroup,
		// it creates the same Group
        
        System.out.println("Creating group " + b3taPeerGroupID);
	
b3taPeerGroupAdvertisement.setPeerGroupID(b3taPeerGroupID);
	
b3taPeerGroupAdvertisement.setModuleSpecID(passwdMembershipModuleImplAdv
.getModuleSpecID());
		b3taPeerGroupAdvertisement.setName(groupName);
		b3taPeerGroupAdvertisement.setDescription("Peer Group
using Password Authentication");
		
		
		
		return b3taPeerGroupAdvertisement;
	}
	
	
	
	private ModuleImplAdvertisement
createB3taMembershipPeerGroupModuleImplAdv2(PeerGroup rootPeerGroup) {
		
		ModuleImplAdvertisement moduleImplAdv =
(ModuleImplAdvertisement) 
		AdvertisementFactory.newAdvertisement(
	
ModuleImplAdvertisement.getAdvertisementType() );
		
		// TODO replace
moduleImplAdv.setCode(B3taMembershipService.class.getName());
	
moduleImplAdv.setCode(PasswdMembershipService.class.getName());
		//moduleImplAdv.setCompat();
		moduleImplAdv.setDescription("B3ta auth
implementation");
		try {
	
moduleImplAdv.setModuleSpecID(IDFactory.newModuleSpecID(rootPeerGroup.ge
tAllPurposePeerGroupImplAdvertisement().getModuleSpecID().getBaseClass()
));
		} catch (java.lang.Exception e) {
			System.err.println("Can't Execute:
getAllPurposePeerGroupImplAdvertisement();");
			System.exit(1);
		}
		moduleImplAdv.setProvider("Wil");
		
		return moduleImplAdv;
		
	}
	
	
	private ModuleImplAdvertisement
createB3taMembershipPeerGroupModuleImplAdv(PeerGroup rootPeerGroup) {
		// Create a ModuleImpl Advertisement for the Passwd
Membership Service
		// Take a allPurposePeerGroupImplAdv
ModuleImplAdvertisement parameter to
		// Clone some of its fields. It is easier than to
recreate everything
		// from scratch
		
		// Try to locate where the B3taMembership is within this
ModuleImplAdvertisement.
		// For a PeerGroup Module Impl, the list of the services
(including Membership)
		// are located in the Param section
		
		ModuleImplAdvertisement allPurposePeerGroupImplAdv=null;
		try {
	
allPurposePeerGroupImplAdv=rootPeerGroup.getAllPurposePeerGroupImplAdver
tisement();
		} catch (java.lang.Exception e) {
			System.err.println("Can't Execute:
getAllPurposePeerGroupImplAdvertisement();");
			System.exit(1);
		}
		
		ModuleImplAdvertisement
b3taMembershipPeerGroupModuleImplAdv=allPurposePeerGroupImplAdv;
		ModuleImplAdvertisement
b3taMembershipServiceModuleImplAdv=null;
		StdPeerGroupParamAdv
b3taMembershipPeerGroupParamAdv=null;
		
		try {
			
			b3taMembershipPeerGroupParamAdv =
				new
StdPeerGroupParamAdv(allPurposePeerGroupImplAdv.getParam());
			
		} catch (net.jxta.exception.PeerGroupException e) {
			System.err.println("Can't execute:
StdPeerGroupParamAdv passwdMembershipPeerGroupParamAdv = new
StdPeerGroupParamAdv (allPurposePeerGroupImplAdv.getParam());");
			System.exit(1);
		}
		
		Hashtable allPurposePeerGroupServicesHashtable =
b3taMembershipPeerGroupParamAdv.getServices();
		Enumeration allPurposePeerGroupServicesEnumeration =
allPurposePeerGroupServicesHashtable.keys();
		boolean membershipServiceFound=false;
		
		while ((!membershipServiceFound) &&
(allPurposePeerGroupServicesEnumeration.hasMoreElements())) {
			
			
			Object allPurposePeerGroupServiceID =
allPurposePeerGroupServicesEnumeration.nextElement();
			
			if
(allPurposePeerGroupServiceID.equals(PeerGroup.membershipClassID)) {
				
				//
allPurposePeerGroupMemershipServiceModuleImplAdv is the
				// all Purpose Mermbership Service for
the all purpose
				// Peer Group  Module Impl adv
				ModuleImplAdvertisement
allPurposePeerGroupMemershipServiceModuleImplAdv=
(ModuleImplAdvertisement)
allPurposePeerGroupServicesHashtable.get(allPurposePeerGroupServiceID);
				
				
				//Create the
passwdMembershipServiceModuleImplAdv
	
b3taMembershipServiceModuleImplAdv=this.createB3taMembershipServiceModul
eImplAdv(allPurposePeerGroupMemershipServiceModuleImplAdv);
				
				
				//Remove the All purpose Membership
Service implementation
	
allPurposePeerGroupServicesHashtable.remove(allPurposePeerGroupServiceID
);
				
				
				// And Replace it by the B3ta Membership
Service Implementation
				//System.out.println( "What is this
class --- " + PeerGroup.membershipClassID );
	
allPurposePeerGroupServicesHashtable.put(PeerGroup.membershipClassID,b3t
aMembershipServiceModuleImplAdv);
				membershipServiceFound=true;
				
				

				// Now the Service Advertisements are
complete
				// Let's update the
passwdMembershipPeerGroupModuleImplAdv by
				// Updating its param
	
b3taMembershipPeerGroupModuleImplAdv.setParam((Element)
b3taMembershipPeerGroupParamAdv.getDocument(MimeMediaType.XMLUTF8));
	
				
//				TODO this is new
	
b3taMembershipPeerGroupParamAdv.setServices(allPurposePeerGroupServicesH
ashtable);
				
				
				// Update its Spec ID
				// This comes from the Instant P2P
PeerGroupManager Code (Thanks !!!!)
				
				
				
				if
(!b3taMembershipPeerGroupModuleImplAdv.getModuleSpecID().equals(PeerGrou
p.allPurposePeerGroupSpecID)) {
				
	
b3taMembershipPeerGroupModuleImplAdv.setModuleSpecID(IDFactory.newModule
SpecID(b3taMembershipPeerGroupModuleImplAdv.getModuleSpecID().getBaseCla
ss()));
				
				} else {
				    ID passwdGrpModSpecID= ID.nullID;
				    try {

				        passwdGrpModSpecID =
IDFactory.fromURL(new URL("urn","","jxta:uuid-"+
"DeadBeefDeafBabaFeedBabe00000001" +"04" +"06"));
				        
				    } catch
(java.net.MalformedURLException e) {}
				    catch
(java.net.UnknownServiceException ee) {}
				    
	
b3taMembershipPeerGroupModuleImplAdv.setModuleSpecID((ModuleSpecID)
passwdGrpModSpecID);
				    
				} //End Else
				
				
				membershipServiceFound=true;
			} //end if
(allPurposePeerGroupServiceID.equals(PeerGroup.membershipClassID))
		}//end While
		
		return b3taMembershipPeerGroupModuleImplAdv;
	}
	
	
	
	private  ModuleImplAdvertisement
createB3taMembershipServiceModuleImplAdv( ModuleImplAdvertisement
allPurposePeerGroupMemershipServiceModuleImplAdv) {
		//Create a new ModuleImplAdvertisement for the
Membership Service
		ModuleImplAdvertisement
b3taMembershipServiceModuleImplAdv = (ModuleImplAdvertisement)
AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdverti
sementType());
		//TODO replace
b3taMembershipServiceModuleImplAdv.setModuleSpecID(B3taMembershipService
.B3taMembershipSpecID);
	
b3taMembershipServiceModuleImplAdv.setModuleSpecID(PasswdMembershipServi
ce.passwordMembershipSpecID);
		//TODO repalce
b3taMembershipServiceModuleImplAdv.setCode(B3taMembershipService.class.g
etName());
	
b3taMembershipServiceModuleImplAdv.setCode(PasswdMembershipService.class
.getName());
		b3taMembershipServiceModuleImplAdv.setDescription("
Module Impl Advertisement for the B3taMembership Service");
	
b3taMembershipServiceModuleImplAdv.setCompat(allPurposePeerGroupMemershi
pServiceModuleImplAdv.getCompat());
	
b3taMembershipServiceModuleImplAdv.setUri(allPurposePeerGroupMemershipSe
rviceModuleImplAdv.getUri());
	
b3taMembershipServiceModuleImplAdv.setProvider(allPurposePeerGroupMemers
hipServiceModuleImplAdv.getProvider());
		return b3taMembershipServiceModuleImplAdv;
	}
	
    

    /*
     * discoveryEvent is used here to find out b3ta group if it exists
     * 
     *  (non-Javadoc)
     * @see
net.jxta.discovery.DiscoveryListener#discoveryEvent(net.jxta.discovery.D
iscoveryEvent)
     */
    
    public void discoveryEvent(DiscoveryEvent ev) {
        DiscoveryResponseMsg res = ev.getResponse();
        String name = "unknown";
//      Get the responding peer's advertisement
        PeerAdvertisement peerAdv = res.getPeerAdvertisement();
//      some peers may not respond with their peerAdv
        if (peerAdv != null) {
            name = peerAdv.getName();
        }
        System.out.println("Got a Discovery Response [" +
                res.getResponseCount() +
                " elements] from peer: " +
                name);
        
        
        
//      printout each discovered peer
        
        Enumeration en = res.getAdvertisements();
        if (en != null ) {
            while (en.hasMoreElements()) {
                
                if (en != null ) {
                    while (en.hasMoreElements()) {
                        
                        
                        
                        Object ob =  en.nextElement();
                        
                        if ( ob instanceof PeerGroupAdvertisement )
                        {
                            PeerGroupAdvertisement  adv =
(PeerGroupAdvertisement ) ob;
                            System.out.println (" Peer group = " +
adv.getName() + " " + adv.getPeerGroupID() + " " + "urn:" + GROUPID );
                            
                            
                            if ( adv.getPeerGroupID().toString().equals(
"urn:" + GROUPID ) )                   
                            {
                                globalGroupAd = adv;
                                
                                synchronized(lock){
                                    lock.notifyAll();
                                }
                                
                                return;
                            }
                            
                        }
                        else
                        {
                            // Must be one of my erquests to find peers
                            // Could have used an inner class but I'm
lazy
                            
                            if ( ob instanceof PeerAdvertisement )
                            {
                                PeerAdvertisement  adv =
(PeerAdvertisement ) ob;
                                System.out.println (" Peer name = " +
adv.getName() + " " );
                                
                                
                            }
                            else
                            {
                                System.out.println( "Invalid discovery
event");
                            }
                            
                        }
                    }
                }
                
            }
        }
    }
    
    Object lock = new Object();
    
    
    private PeerGroup discoverPeerGroup(PeerGroup myNetPeerGroup,
PeerGroupID b3taPeerGroupID) {
        
        // Look for it locally, if that fails do a remote request
        
        System.out.println( "Looking for group  " + b3taPeerGroupID );
        
        
        PeerGroup b3taPeerGroup = null;
        DiscoveryService myNetPeerGroupDiscoveryService=null;
        if (myNetPeerGroup!=null) {
            myNetPeerGroupDiscoveryService =
myNetPeerGroup.getDiscoveryService();
        } else {
            System.err.println("Can't join  Peer Group since its parent
is null");
            System.exit(1);
        }
        
        
		
		Enumeration localPeerGroupAdvertisementEnumeration=null;
		PeerGroupAdvertisement b3taPeerGroupAdvertisement=null;
		
        /* TODO put back in 
        
		try {
		    localPeerGroupAdvertisementEnumeration =
	
myNetPeerGroupDiscoveryService.getLocalAdvertisements(DiscoveryService.G
ROUP,
		                "GID",
		                b3taPeerGroupID.toString());
		} catch (java.io.IOException e) {
		    System.out.println("Can't Discover Local Adv");
		}
		if (localPeerGroupAdvertisementEnumeration!=null) {
		    while
(localPeerGroupAdvertisementEnumeration.hasMoreElements()) {
		        PeerGroupAdvertisement pgAdv=null;
		        pgAdv=(PeerGroupAdvertisement)
localPeerGroupAdvertisementEnumeration.nextElement();
		        if
(pgAdv.getPeerGroupID().equals(b3taPeerGroupID)) {
		            b3taPeerGroupAdvertisement=pgAdv;
		            break ;
		        }
		    }
		}

*/
        if ( b3taPeerGroupAdvertisement == null )
        {
            
            
            
            //         Add ourselves as a DiscoveryListener for
            //         DiscoveryResponse events
            
            //         look for our peer group
            
            
            discovery.getRemoteAdvertisements(null,
                    DiscoveryService.GROUP,
                    "Name", groupName, 10, this);
            
            
            
            /*
             * Wait to see if we find our group
             */
            try
            {
                long t1 = System.currentTimeMillis();
                synchronized(lock){
                    
                    lock.wait(10000);
                }
                if ((System.currentTimeMillis() - t1) > 10000) {
                    
                    System.err.println("Timedout looking for our
group");

                    
                    return null;
                }
            } catch (InterruptedException e) {  
                System.err.println("Fucksaki Timedout looking for our
group");
                
                return null;
            }
            
            b3taPeerGroupAdvertisement = globalGroupAd;
            
        }
		
        if ( b3taPeerGroupAdvertisement != null )
        {
            try {
                
 
b3taPeerGroup=myNetPeerGroup.newGroup(b3taPeerGroupAdvertisement);
                
            } catch (net.jxta.exception.PeerGroupException e) {
                System.err.println("Can't create Peer Group from
Advertisement");
                e.printStackTrace();
                return null;
            }
        }
        else
        {
            System.out.println( "Did not find existing group");
        }
        
		return b3taPeerGroup;
	}
	
	private void joinPeerGroup(PeerGroup b3taPeerGroup,String
login,String passwd) {
	    // Get the Heavy Weight Paper for the resume
	    // Alias define the type of credential to be provided
	    StructuredDocument creds = null;
	    try {
	        // Create the resume to apply for the Job
	        // Alias generate the credentials for the Peer Group
			AuthenticationCredential authCred =new
AuthenticationCredential( b3taPeerGroup, null, creds );
			
			// Create the resume to apply for the Job
			// Alias generate the credentials for the Peer
Group
			MembershipService membershipService =
b3taPeerGroup.getMembershipService();
			
			// Send the resume and get the  Job application
form
			// Alias get the Authenticator from the
Authentication creds
			Authenticator auth = membershipService.apply(
authCred );
			
			// Fill in the Job Application Form
			// Alias complete the authentication
			completeAuth( auth, login, passwd );
			
			// Check if I got the Job
			// Alias Check if the authentication that was
submitted was
			//accepted.
			if( !auth.isReadyForJoin() ) {
				System.out.println( "Failure in
authentication.");
				System.out.println( "Group was not
joined. Does not know how to complete authenticator");
			}
			// I got the Job, Join the company
			// Alias I the authentication I completed was
accepted,
			// therefore join the Peer Group accepted.
			membershipService.join( auth );
		} catch (Exception e) {
			System.out.println("Failure in
authentication.");
			System.out.println("Group was not joined. Login
was incorrect.");
			e.printStackTrace();
		}
	}
	
	private  void completeAuth(Authenticator auth, String login,
String passwd) throws Exception {
		
		Method [] methods = auth.getClass().getMethods();
		Vector authMethods = new Vector();
		
		// Find out with fields of the application needs to be
filled
		// Alias Go through the methods of the Authenticator
class and copy
		// them sorted by name into a vector.
		for( int eachMethod = 0; eachMethod < methods.length;
eachMethod++ ) {
			if(
methods[eachMethod].getName().startsWith("setAuth") ) {
				if( Modifier.isPublic(
methods[eachMethod].getModifiers())) {
					
					// sorted insertion.
					for( int doInsert = 0; doInsert
<= authMethods.size();
					doInsert++ ) {
						int insertHere = -1;
						if( doInsert ==
authMethods.size() )
							insertHere =
doInsert;
						else {
	
if(methods[eachMethod].getName().compareTo(((Method)authMethods.elementA
t( doInsert )).getName()) <= 0 )
	
insertHere = doInsert;
						} // end else
						
						if(-1!= insertHere ) {
	
authMethods.insertElementAt(
	
methods[eachMethod],insertHere);
							break;
						} // end if ( -1 !=
insertHere)
					} // end for (int doInsert=0
				} // end if (modifier.isPublic
			} // end if (methods[eachMethod]
		} // end for (int eachMethod)
		
		
		Object [] AuthId = {login};
		Object [] AuthPasswd = {passwd};
		
		for( int
eachAuthMethod=0;eachAuthMethod<authMethods.size();
		eachAuthMethod++ ) {
			Method doingMethod = (Method)
authMethods.elementAt(eachAuthMethod);
			
			String authStepName =
doingMethod.getName().substring(7);
			if
(doingMethod.getName().equals("setAuth1Identity")) {
				// Found identity Method, providing
identity
				doingMethod.invoke( auth, AuthId);
				
			} else
				if
(doingMethod.getName().equals("setAuth2_Password")) {
					// Found Passwd Method,
providing passwd
					doingMethod.invoke( auth,
AuthPasswd );
				}
		}
	}
	
	public void printXmlAdvertisement( String title, Advertisement
adv) {
		// First, Let's print a "nice" Title
		String separator = "";
		for (int i=0 ; i<title.length()+4; i++) {
			separator=separator+"-";
		}
		System.out.println(separator);
		System.out.println("| " + title  +" |");
		System.out.println(separator);
		
		// Now let's print the Advertisement
		StringWriter outWriter = new StringWriter();
		StructuredTextDocument docAdv =
			(StructuredTextDocument)adv.getDocument(new
MimeMediaType("text/xml"));
		try {
			docAdv.sendToWriter(outWriter);
		} catch (java.io.IOException e) {
			System.err.println("Can't Execute:
docAdv.sendToWriter(outWriter);");
		}
		System.out.println(outWriter.toString());
		
		// Let's end up with a line
		System.out.println(separator);
	}
	
	/** Starts the jxta platform */
	private PeerGroup startJxta() {
		PeerGroup myNetPeerGroup  = null;
		try {
	
myNetPeerGroup=PeerGroupFactory.newNetPeerGroup();
		} catch ( PeerGroupException e) {
			// could not instantiate the group, print the
stack and exit
			System.out.println("fatal error : group creation
failure");
			e.printStackTrace();
			System.exit(1);
		}
		return myNetPeerGroup;
	}
	
  
    
    public Object clone()
    throws CloneNotSupportedException
    {
        throw new CloneNotSupportedException(); 
        // that'll teach 'em
    }
	
}


------------------------------------------------------------------------
-----

Thia code is just here to show other inner gubbins!

package org.Sn0tters.b3ta.p2p;

import org.Sn0tters.b3ta.b3ta;
/*TODO put backin 
 * import org.Sn0tters.b3ta.core.Session;
 */

import org.apache.log4j.*;
import net.jxta.document.XMLDocument;
import net.jxta.peergroup.PeerGroup;
import net.jxta.rendezvous.RendezVousService;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.endpoint.EndpointListener;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.document.TextElement;
import net.jxta.endpoint.TextDocumentMessageElement;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredTextDocument;
import net.jxta.document.Element;
import java.util.Enumeration;
import java.io.IOException;
import java.io.StringWriter;

/**
 * @author whadden
 *
 * B3ta broadcaster -
 * uses the rendezvous propagate message to send the latest message ID
to all other peers.
 * 
 *  It hijacks the propagte listener to update this clients notion of
the networks latest messages
 */

public class broadcaster implements EndpointListener{
    
    private static broadcaster singleton;
    
   
    private static final String BroadcasterName = "B3taBroadcasting";
    private String BroadcasterParam = null;
    private RendezVousService rdv = null;
    private PeerGroup peer;
    
    /**
     *  Log4J Logger
     **/
    private static  Logger LOG ;
    
    private broadcaster(){
    
    	
      
    }
    
    public static synchronized void   setPropagater( PeerGroup peer,
RendezVousService rdv ) {
    	
    	broadcaster localsingleton = getbroadcaster();
    	
    	
    	
    	localsingleton.peer = peer;
    	localsingleton.rdv = rdv;
    	localsingleton.BroadcasterParam =
peer.getPeerGroupID().getUniqueValue().toString();
    	
         if (LOG.isEnabledFor(Level.DEBUG)) {
             LOG.debug(" addPropagateListener " + BroadcasterName + " "
+  localsingleton.BroadcasterParam 
                     + " " + localsingleton );
         }
         
      
    	
    	if (  rdv.addPropagateListener( BroadcasterName,
    			localsingleton.BroadcasterParam ,
    			localsingleton ) == false )
    	{
    		
    		LOG.fatal("Cannot register Propagate Listener");
    		
    		
    		throw new IllegalStateException( "Cannot register
Propagate Listener" );
    	}
    
    	
    	
    }
    
    public static synchronized broadcaster getbroadcaster()
    {
        if (singleton == null)
        {
            // it's ok, we can call this constructor
            singleton = new broadcaster();
            
            LOG = Logger.getLogger(singleton.getClass().getName());
        }
        
        return singleton;
    }
    
    
    
    public void  sendMessage(Double latest){
        
        /*
         * If need be this can be extended to other types of message
         * 
         */
        
        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("Sending broadcast message " + latest );
        }
        
           
   
        
        
        StructuredTextDocument document = (StructuredTextDocument)
        StructuredDocumentFactory.newStructuredDocument( new
MimeMediaType("text/xml"),
        					"jxta:B3taBroadcast");
        
        
        Element element = document.createElement( "latestMessage",
Double.toString(latest));
        document.appendChild(element);
        
        Message propagateMsg = new Message();
        
        propagateMsg.addMessageElement("jxta",  
                new TextDocumentMessageElement(
singleton.BroadcasterParam,
                        document, null));
        
        
        
        /*
        
        // Now let's print the Advertisement
        StringWriter outWriter = new StringWriter();
        
        try {
            document.sendToWriter(outWriter);
        } catch (java.io.IOException e) {
            System.err.println("Can't Execute:
docAdv.sendToWriter(outWriter);");
        }
        System.out.println(outWriter.toString());
        */
        
        
        
        try {
        	
        	if ( rdv != null && singleton.BroadcasterParam != null
&&
        			rdv.isConnectedToRendezVous() == true )
        	{
        		// 7 is just an arbitrarty default, the TTL
count will go down from there
        		
        		// If rdv is null then is broadcast is just
dropped
        		
        		rdv.propagateInGroup(propagateMsg,
        				BroadcasterName,
        				singleton.BroadcasterParam,
        				7);
        		
        		if (LOG.isEnabledFor(Level.DEBUG)) {
        			
        			LOG.debug("Latest ID has been
broadcast");
        		}
        		
        	}
        	else
        	{
        		if (LOG.isEnabledFor(Level.WARN)) {
        			
        			LOG.warn("Rendezvous object is null, no
message sent, you may need to wait until it is setup");
        		}
        		
        		System.out.println("Oh shit");
        		
            }
            
          
            
        } catch (IOException e) {
            
            e.printStackTrace();
            
            if (LOG.isEnabledFor(Level.WARN)) {
                
                LOG.warn("Error during propagate", e);
            }
            
            System.out.println("Oh shitty shit");
        }
        
    }
    
    
    
    
    /***
     *  {@inheritDoc}
     **/
    public void processIncomingMessage(Message message, EndpointAddress
srcAddr, EndpointAddress dstAddr) {
        
        
    	
    	System.out.println( "Still don't believe it ");
    	
        if (LOG.isEnabledFor(Level.INFO)) {
            StringBuffer info = new StringBuffer( "Processing incoming
broadcast message"); 
            
            LOG.info(info);
        }
        
        if(singleton.rdv.isRendezVous()) {
            // possibly repropagate
            
            try {
                singleton.rdv.propagateInGroup(message, 
                        BroadcasterName, singleton.BroadcasterParam, 10,
null);
            }
            catch(IOException e)
            {
                // Don't really care it failed
                
                e.printStackTrace();
                
                if (LOG.isEnabledFor(Level.WARN)) {
                    
                    LOG.warn("Error during repropagate", e);
                }
            }
        }
        
        
        // Check if there is a B3ta broadcast header
        MessageElement elem = message.getMessageElement( "jxta",
singleton.BroadcasterParam );
        
        if(  elem != null ) {
            LOG.debug("Got latestID broadcast message - " +
elem.toString() );
            
            
            
            try{
                java.io.InputStream is = elem.getStream();
                net.jxta.document.StructuredTextDocument document =
(net.jxta.document.StructuredTextDocument)
 
net.jxta.document.StructuredDocumentFactory.newStructuredDocument(
                        new net.jxta.document.MimeMediaType("text/xml"),
is);
                
                Enumeration elements = document.getChildren();
                while (elements.hasMoreElements())
                {
                    TextElement element = (TextElement)
elements.nextElement();
                    if(element.getName().equals("latestMessage"))
                    {
                        /*
                         * So discover the latest known message we have
                         */
                        
                        double ourCurrentMessage = 0;
                        double latestBroadcastMessageID = 0;
                        
                        // Get our reference to session so we can record
the latest ID
                        
                      /*
                       * TODO put back in
                      
                        Session session = Session.getSession();
                        
                        if ( session != null )
                        {
                            ourCurrentMessage =
session.getLatestMessageID();
                            
                            try 
                            {
                                latestBroadcastMessageID =
Double.valueOf(element.getTextValue()).doubleValue();
                                
                            } catch (NumberFormatException e)
                            {
                                
                                
                                if (LOG.isEnabledFor(Level.ERROR))
                                {
                                    StringBuffer info = new
StringBuffer( "Teh Quo struck again, the latest message ID broadcast
here is crap " +element.getTextValue() ); 
                                    
                                    LOG.error(info);
                                    
                                    continue;
                                }
                            }
                            
                        }
                         */
                        
                        /*
                         * I am going to assume that once I have sent a
request that there is a good chance I will
                         * get a reply, the only other option to to
respond to all broadcasts of latestID, which
                         * could produce a multitude of requests here,
or to record and timeout request, which
                         * may be a job for another version ( tee hee )
                         * 
                         * I do this by setting the session's latest ID
                         */
                        
                        /* TODO put back in
                        session.setLatestMessageID(
latestBroadcastMessageID, false );
                        */
                        
                        
                        /*
                         * Now we fire off looking for the messages we
do not have
                         * 
                         * 
                         */
                        
                        if ( ourCurrentMessage != 0 )
                        {
                            /*
                             * Of course if ourCurrentMessage is 0 then
we never parsed the message board over
                             * the web, and we don't want every message
since the very first one
                             */ 
                            
                            
                             
                            
                            while ( ourCurrentMessage <=
latestBroadcastMessageID )
                            {
                                
                                if (LOG.isEnabledFor(Level.INFO))
                                {
                                    StringBuffer info = new
StringBuffer( "Looking for message ID " + ourCurrentMessage) ;
                                    
                                    LOG.info(info);
                                }
                                
                                
                                
                                
                                /*TODO put back in
                                 * Quickly make sure that the p2p object
is up and going, it's a good trick if it isn't
                               
                               b3ta_p2p p2p = b3ta_p2p.getb3ta();
                               
                                if ( p2p != null )
                                {
 
p2p.issueMessageQuery(ourCurrentMessage++);
                                }
                                  */
                                
                                try {
                                    Thread.sleep(1000);
                                } catch(Exception e) {
                                    
                                    if (LOG.isEnabledFor(Level.ERROR)) {
                                        StringBuffer info = new
StringBuffer( "Sleep in broadcast failed" );
                                        
                                        LOG.error(info);
                                    }
                                }
                                
                                
                                
                            }
                            
                            
                            
                        }
                    }
                    
                    
                    
                    continue;
                }// end while bit too much processing here, modularise
if mode functions added
                
            }catch(Exception e){System.err.println("Error demuxing"+e);}
            
            
        }
        
        
        
        
    }
    
    
    
    
    
    public Object clone()
    throws CloneNotSupportedException
    {
        throw new CloneNotSupportedException(); 
        // that'll teach 'em
    }
    
}

-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.338 / Virus Database: 267.9.4/57 - Release Date: 22/07/2005
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.