package p2pEsPeTaC;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.Enumeration;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import net.jxta.credential.AuthenticationCredential;
import net.jxta.credential.Credential;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocument;
import net.jxta.document.StructuredTextDocument;
import net.jxta.exception.PeerGroupException;
import net.jxta.id.IDFactory;
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.protocol.ModuleImplAdvertisement;
import net.jxta.protocol.PeerGroupAdvertisement;
/**
* Esta classe serve para a inicialização dos grupos de peers e os lançarem dentro da rede JXTA
* para então usar seus seriços, podendo criar grupos
*
* @author pedrotanaka
*/
public class StartJXTA
{ //Class Variables
public JTextArea log;
private final static int TIMEOUT = 5*1000;
private PeerGroup netPeerGroup = null,
EsPeTaCGrupo =null;
DiscoveryService myDiscoveryService =null,
EsPeTaCGroupDiscoveryService =null;
PeerGroupAdvertisement EsPeTaCAdv =null;
//unique id for group, it is taken from JXTA services
private final String stringID = "jxta:uuid-4E0742B0E54F4D0ABAC6809BB82A311E02";
/** Creates a new instance of StartJXTA */
public StartJXTA(JTextArea txt)
{
this.log = txt;
launchJXTA();
getServices();
searchForGroup();
}
private void printOnLog(final String toPrint){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
log.append(toPrint);
}
});
}
private void launchJXTA()
{
printOnLog("[+]Lançando na rede JXTA ...\n");
try{
netPeerGroup = PeerGroupFactory.newNetPeerGroup();
}catch(PeerGroupException e){
printOnLog("[-]ERRO FATAL:" + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
}
private void getServices()
{
//Obtaining JXTA Services from JXTA Global group
printOnLog("[+]Obtendo o serviço de grupo de PEERS.\n");
myDiscoveryService = netPeerGroup.getDiscoveryService();
}
private void searchForGroup() //This method will Search for Group
{ //If group found it will be join into it otherwise it
Enumeration adv=null; //will create the group itself.
int count =0;
printOnLog("[+]Procurando por anuncios do EsPeTaCGrupos.\n");
while(count < 5){
try {
printOnLog("[+]Tentativa #: " + count +"\n");
//Searching for Group Advertisements , first from local cach if not
//found then search from remote peers
adv = myDiscoveryService.getLocalAdvertisements(DiscoveryService.GROUP,"Name","EsPeTaCGrupo");
if((adv != null) && adv.hasMoreElements()){
printOnLog("[+]EsPeTaCGrupo encontrado em anúncio.\n");
EsPeTaCAdv = (PeerGroupAdvertisement)adv.nextElement();
EsPeTaCGrupo = netPeerGroup.newGroup(EsPeTaCAdv);
joinToGroup(EsPeTaCGrupo);
break;
}else{
printOnLog("[-]Nenhum grupo encontrado em anúncio local.\n[+]Começando a procura remota...\n");
myDiscoveryService.getRemoteAdvertisements(null,DiscoveryService.GROUP,"Name","EsPeTaCGrupo",1);
}
Thread.sleep(TIMEOUT);
//if group not found after couple of tries it will create the group itself
if((count == 4) && (adv == null || !adv.hasMoreElements())){
printOnLog("[-]Nenhum grupo encontrado!!! - Criando grupo...\n");
EsPeTaCGrupo = createGroup();
joinToGroup(EsPeTaCGrupo);
break;
}
} catch (IOException ex) {
ex.printStackTrace();
}catch(PeerGroupException e){
printOnLog("[-]Erro Fatal:" + e.getMessage());
e.printStackTrace();
System.exit(-1);
}catch(InterruptedException e){
printOnLog("[-]Erro Fatal:" + e.getMessage());
e.printStackTrace();
}
count++;
}
}
private PeerGroup createGroup() //This method will Create SaEeD group :-)
{
printOnLog("[+]Criando novo grupo...\n");
PeerGroup myNewGroup = null;
try{
//specifying advertisement for group and configure group, then publish it
//Advertisement for remote peers
ModuleImplAdvertisement myMIA = netPeerGroup.getAllPurposePeerGroupImplAdvertisement();
myNewGroup = netPeerGroup.newGroup(getGID(),
myMIA,
"EsPeTaCGrupo",
"EsPeTaC P2P File Sharing Application");
EsPeTaCAdv = myNewGroup.getPeerGroupAdvertisement();
//publishing new group advertisements
myDiscoveryService.publish(EsPeTaCAdv);
myDiscoveryService.remotePublish(EsPeTaCAdv);
printOnLog("[+]Novo grupo de PEERS criado com sucesso:-)\n");
printOnLog("[+]Publicando novos anúncios de grupos de PEERS.\n");
printOnLog("[+]Informação do Grupo:\n");
printOnLog("[===========================]\n");
printOnLog("[+]Nome Grupo: " + EsPeTaCAdv.getName()+"\n");
printOnLog("[+]ID Grupo:" + EsPeTaCAdv.getPeerGroupID().toString()+"\n");
printOnLog("[+]Descrição do Grupo: " + EsPeTaCAdv.getDescription()+"\n");
printOnLog("[+]ID modulo Grupo: " + EsPeTaCAdv.getModuleSpecID().toString()+"\n");
printOnLog("[+]Tipo de anúncio: " + EsPeTaCAdv.getAdvertisementType()+"\n");
printOnLog("[===========================]\n");
}catch(Exception e){
printOnLog("[*]Erro Fatal:" + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
return myNewGroup;
}
//This method will return peerGroupID from given String ID
private PeerGroupID getGID() throws Exception{
return (PeerGroupID) IDFactory.fromURL(new URL("urn","",stringID));
}
private void joinToGroup(PeerGroup group) //This method will join to either found group or created group
{
StructuredDocument creds = null;
printOnLog("[===========================]\n");
printOnLog("[+]Juntando-se ao EsPeTaCGrupo.\n");
try{
//Athenticate and join to group
AuthenticationCredential authCred = new AuthenticationCredential(group,null,creds);
MembershipService membership = group.getMembershipService();
Authenticator auth = membership.apply(authCred);
if(auth.isReadyForJoin()){
Credential myCred = membership.join(auth);
printOnLog("[===== Detalhes do Grupo =====]");
StructuredTextDocument doc = (StructuredTextDocument)myCred.getDocument(new MimeMediaType("text/plain"));
StringWriter out = new StringWriter();
doc.sendToWriter(out);
printOnLog(out.toString());
printOnLog("[+]Nome do PEER: " + group.getPeerName() + " está online:-)\n");
printOnLog("[+]Obtendo serviços EsPeTaCGrupo.\n");
//Publishing Peer Advertisements.
EsPeTaCGroupDiscoveryService = group.getDiscoveryService();
printOnLog("[+]Publicando anúncio de PEER.\n");
EsPeTaCGroupDiscoveryService.publish(group.getPeerAdvertisement());
EsPeTaCGroupDiscoveryService.remotePublish(group.getPeerAdvertisement());
printOnLog("[===========================]\n");
}
else{
printOnLog("[!!]Erro Fatal! Não pode juntar ao grupo");
System.exit(-1);
}
}catch(Exception e){
printOnLog("[!]Erro Fatal: " + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
}
public PeerGroup getEsPeTaCGrupo() //This accessor will return group
{
return EsPeTaCGrupo;
}
public PeerGroupAdvertisement getEsPeTaCAdv(){//This accessor will return Advertisements
return EsPeTaCAdv;
}
}