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

📄 workspaceutil.java

📁 基于jxta的局域网P2P文件共享,可以实现局域网中的文件p2p共享,实现文件快速传输及交流
💻 JAVA
字号:
package connex.core.WS;

import net.jxta.discovery.*;
import net.jxta.peergroup.*;
import net.jxta.document.*;
import net.jxta.impl.membership.*;
import net.jxta.protocol.*;
import net.jxta.id.*;
import java.util.*;
import java.io.*;
import net.jxta.impl.peergroup.*;
import java.net.*;
import net.jxta.impl.id.UUID.ModuleSpecID;
import net.jxta.exception.*;
import net.jxta.impl.membership.pse.PSEMembershipService;


import net.jxta.membership.*;
import net.jxta.membership.Authenticator;
import net.jxta.credential.*;

import net.jxta.impl.membership.PasswdMembershipService.*;
//import net.jxta.impl.membership.passwd.PasswdMembershipService.*;
import net.jxta.impl.membership.pse.StringAuthenticator;

public class WorkspaceUtil {
    public static final String MEMBERSHIP_ID = "ConneXuser";

    private static final long MILLISECONDS_IN_A_WEEK = 7 * 24 * 60 * 60 * 1000;

    /**
     * Create a new PeerGroupAdvertisment  from which a
     * new PeerGroup will be created.
     * <p>
     * See "Create a Secure Peer Group" in
     * <a href="http://www.jxta.org/docs/JxtaProgGuide_v2.pdf">Jxta
     *  Programmers Guide</a> for how to create a secure group. Most
     * of the code in this class is taken direcly from that chapter
     * @param name String
     * @param description String the description of the new PeerGroup
     * @param log String
     * @param password Stringthe password for the new Peergroup.
     *                 If it is null or an empty string this
     *                 peer group is not password protected

     * @param expiration long
     * @param id PeerGroupID
     * @return Workspace
     * @throws Exception
     * @return a new  Workspace
     */


    public static Workspace createWorkspace(String name,
                                            String description, String log,
                                            String password,
                                            long expiration, PeerGroupID id) throws
            Exception {
        PeerGroup pg = Boot.netPeerGroup;
        PeerGroupAdvertisement pga;
        ModuleImplAdvertisement mia;
        boolean passProt = (password != null &&
                            !password.trim().equals(""));

        // create the ModuleImplAdvertisement and publish it
        mia = pg.getAllPurposePeerGroupImplAdvertisement();

        if (passProt) {
            createPasswordModuleImpl(mia);
        }

        pg.getDiscoveryService().publish(mia);
        pg.getDiscoveryService().remotePublish(mia);

        // create the PeerGroupAdvertisment and publish it
        pga = (PeerGroupAdvertisement) AdvertisementFactory.newAdvertisement(
                PeerGroupAdvertisement.getAdvertisementType());
        pga.setPeerGroupID(id != null ? id : IDFactory.newPeerGroupID());
        pga.setName("ConneX: " + name);
        pga.setDescription(description);
        pga.setModuleSpecID(mia.getModuleSpecID());

        if (passProt) {
            StructuredTextDocument login =(StructuredTextDocument)
            StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, "Param");
            String loginString = log + ":" + PasswdMembershipService.makePsswd(password) + ":";
            TextElement loginElement = login.createElement("login", loginString);
            login.appendChild(loginElement);
            pga.putServiceParam(PeerGroup.membershipClassID, login);
        }

        DiscoveryService ds = pg.getDiscoveryService();

        ds.publish(pga, expiration != 0 ?
                   expiration : 2 * MILLISECONDS_IN_A_WEEK,
                   expiration != 0 ? expiration : 2 * MILLISECONDS_IN_A_WEEK);
        ds.remotePublish(pga, expiration != 0 ?
                         expiration : 2 * MILLISECONDS_IN_A_WEEK);
        PeerGroup ConneXPeerGroup = null;
        try {
            ConneXPeerGroup = pg.newGroup(pga);
        } catch (net.jxta.exception.PeerGroupException e) {
            System.err.println(
                    "Can't create ConneX Peer Group from Advertisement");
            e.printStackTrace();
            return null;
        }

        return new Workspace(ConneXPeerGroup);
    }


    /*********************************************************************************/
    /*  public static boolean joinWorkspace(Workspace ws,
                                          String login, String passwd) {
     MembershipService membership = (PSEMembershipService) ws.getPeerGroup().
                                         getMembershipService();
          StringAuthenticator auth = null;

          try {

              try {
                  AuthenticationCredential application = new
                          AuthenticationCredential(ws.getPeerGroup(),
     "StringAuthentication", null);
                  auth = (StringAuthenticator) membership.apply(application);
              } catch (ProtocolNotSupportedException noAuthenticator) {
                  throw new UndeclaredThrowableException(noAuthenticator,
                          "String authenticator not available!");
              }

              if (null != auth) {
                  auth.setAuth1_KeyStorePassword("test1");
                  auth.setAuth2Identity(login);
                  auth.setAuth3_IdentityPassword(passwd);
                  System.err.println("auth.isReadyForJoin() " +
                                     auth.isReadyForJoin());

                  // if (auth.isReadyForJoin()) {
                  membership.join(auth);
                  System.out.println("Authenticated");
                  //  }
              }

          } catch (Exception failed) {
              failed.printStackTrace();
              return false;
          }
          return true;
      }*/
    /********************************************************************************/
    /**
     *
     * @param ws Workspace
     * @param login String
     * @param passwd String
     * @return boolean
     */
    public static boolean joinWorkspace(Workspace ws,
                                        String login, String passwd) {

        AuthenticationCredential ac = new AuthenticationCredential(ws.
                getPeerGroup(), null, null);
        MembershipService ms = ws.getPeerGroup().getMembershipService();
        Authenticator auth = null;
        try {
            auth = ms.apply(ac);
        } catch (ProtocolNotSupportedException ex) {
        } catch (PeerGroupException ex) {
        }

        if (login != null && passwd != null) {
            ((PasswdAuthenticator) auth).setAuth1Identity(login);
            ((PasswdAuthenticator) auth).setAuth2_Password(passwd);
        }

        if (auth.isReadyForJoin()) {
            try {
                ms.join(auth);
            } catch (PeerGroupException ex1) {
            }
        }

        return isAuthenticated(ws);

    }


    public static void leaveGroup(Workspace myspace) {
        if (isAuthenticated(myspace)) {
            MembershipService myMembershipService =
                    myspace.getPeerGroup().getMembershipService();
            try {
                myMembershipService.resign();

            } catch (PeerGroupException e) {
                System.out.println("group not left" + e.getMessage());

            }

            // LogIn.prevGroup = LogIn.netPeerGroup;

            System.out.println(" Group has been left ");
        }

    }

    /************************************************************************/
    /**
     * remove local workspaces
     * @param pg PeerGroup
     */
    public static void flushLocalWorspaces(PeerGroup pg) {

        DiscoveryService disco = pg.getDiscoveryService();
        try {
            disco.flushAdvertisements(null, DiscoveryService.GROUP);
        } catch (IOException e) {

        }
    }

    /***********************************************************************************/
    /**
     *
     * @param ws Workspace
     * @return boolean
     */
    public static boolean isAuthenticated(Workspace ws) {

        boolean isAuthenticated = false;

        try {
            isAuthenticated =
                    (ws.getPeerGroup().getMembershipService().
                     getDefaultCredential() != null);

        } catch (PeerGroupException pge) {
            System.err.println(pge.getMessage());
        }

        return isAuthenticated;
    }

    /**
     *
     * @param name String
     * @return Collection
     */
    public static Collection getLocalWorkspaces(String name) {
        Vector p = new Vector();

        try {
            Enumeration gas = Boot.netPeerGroup.getDiscoveryService().
                              getLocalAdvertisements(DiscoveryService.GROUP,
                    name != null ? "Name" : null, name);
            while (gas.hasMoreElements()) {
                Object o = gas.nextElement();

                if (o instanceof PeerGroupAdvertisement) {
                    p.addElement(new Workspace((PeerGroupAdvertisement) o));
                }
            }
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
        //System.out.println(p.size());
        return p;
    }

    /**
     *
     * @param v Collection
     */

    public static void saveWorkspaces(Enumeration v) {
        flushLocalWorspaces(Boot.netPeerGroup);

        // for (int i = 0; i < v.size(); i++) {
        while (v.hasMoreElements()) {
            try {

                Boot.netPeerGroup.
                        getDiscoveryService().publish((PeerGroupAdvertisement)((Workspace)
                        v.nextElement()).getPeerGroup().getPeerGroupAdvertisement());
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * Updates the ModuleImplAdvertisement  of the PeerGroupAdvertisement
     * to reflect the fact that we want to use the PasswordService in order
     * to manage the membership in this group
     *
     * @param mia the ModuleImplAdvertisement  to update
     *  @throws Exception
     */

    private static void createPasswordModuleImpl(ModuleImplAdvertisement
                                                 mia) throws
            Exception {
        StdPeerGroupParamAdv stdPgParams = new StdPeerGroupParamAdv(mia.
                getParam());
        Map params = (Map) stdPgParams.getServices();
        // Enumeration en = params..keys();
        boolean found = false;

        // loop until the MembershipService is found


        //  if (serviceID.equals(PeerGroup.membershipClassID)) {
        if (params.containsKey(PeerGroup.membershipClassID)) {
            // get the  Advertisement for the MembershipService
            ModuleImplAdvertisement memServices =
                    (ModuleImplAdvertisement) params.get(PeerGroup.membershipClassID);

            // create a new Advertisement describing the password service
            ModuleImplAdvertisement newMemServices =
                    createPasswordServiceImpl(memServices);

            // update the services hashtable
            params.remove(PeerGroup.membershipClassID);
            params.put(PeerGroup.membershipClassID, newMemServices);
            found = true;

            // and update the Service parameters list for the
            // ModuleImplAdvertisement
            mia.setParam((Element) stdPgParams.getDocument(
                    MimeMediaType.XMLUTF8));

            // change the ModuleSpecID since this
            if (!mia.getModuleSpecID().equals(
                    PeerGroup.allPurposePeerGroupSpecID)) {
                mia.setModuleSpecID(IDFactory.newModuleSpecID(
                        mia.getModuleSpecID().getBaseClass()));
            } else {
                ID passID = ID.nullID;

                try {
                    passID = IDFactory.fromURI(new URI("urn",
                            "jxta:uuid-" +
                            "DeadBeefDeafBabaFeedBabe00000001" +
                            "04" + "06", null));
                } catch (URISyntaxException use) {
                    use.printStackTrace();
                }

                mia.setModuleSpecID((ModuleSpecID) passID);
            }
        }

    }

    /**
     * Create the ModuleImplAdvertisement that describes the
     * PasswordService that this group is going to use
     *
     *  @param template the previous ModuleImplAdvertisement that we use as
     *                   a template
     * @return the  ModuleImplAdvertisement that describes the
     *         PasswordService that this group is going to use
     */
    private static ModuleImplAdvertisement createPasswordServiceImpl(
            ModuleImplAdvertisement template) {
        ModuleImplAdvertisement passMember = (ModuleImplAdvertisement)
                                             AdvertisementFactory.
                                             newAdvertisement(
                ModuleImplAdvertisement.getAdvertisementType());

        passMember.setModuleSpecID(PasswdMembershipService.
                                   passwordMembershipSpecID);
        passMember.setCode(PasswdMembershipService.class.getName());
        passMember.setDescription("Membership Services for ConneX");
        passMember.setCompat(template.getCompat());
        passMember.setUri(template.getUri());
        passMember.setProvider(template.getProvider());

        return passMember;
    }
}

⌨️ 快捷键说明

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