Пример #1
0
  /**
   * {@inheritDoc}
   *
   * @param raw Description of the Parameter
   * @return Description of the Return Value
   */
  protected boolean handleElement(Element raw) {

    if (super.handleElement(raw)) {
      return true;
    }

    XMLElement elem = (XMLElement) raw;

    if (DEST_PID_TAG.equals(elem.getName())) {
      try {
        URI pID = new URI(elem.getTextValue());

        setDestPeerID((PeerID) IDFactory.fromURI(pID));
      } catch (URISyntaxException badID) {
        throw new IllegalArgumentException("Bad PeerID in advertisement");
      } catch (ClassCastException badID) {
        throw new IllegalArgumentException("ID in advertisement is not a peer id");
      }
      return true;
    }

    if (elem.getName().equals("Dst")) {
      for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements(); ) {
        TextElement aXpt = (TextElement) eachXpt.nextElement();

        AccessPointAdvertisement xptAdv =
            (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement(aXpt);

        setDest(xptAdv);
      }
      return true;
    }

    if (elem.getName().equals("Hops")) {
      Vector hops = new Vector();

      for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements(); ) {
        TextElement aXpt = (TextElement) eachXpt.nextElement();

        AccessPointAdvertisement xptAdv =
            (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement(aXpt);

        hops.addElement(xptAdv);
      }
      setHops(hops);
      return true;
    }

    return false;
  }
Пример #2
0
  /**
   * Use this form for a fully populated advert.
   *
   * @param msid -- the module spec id, "urn:jxta:uuid-[the big hex string]"
   * @param moduleSpecName -- something like "JXTASPEC:JXTA-WIRE-MyNewThing-SPEC"
   * @param moduleSpecDescription -- something like "JXTA-WIRE MyNewThing Specification"
   * @param creator -- something like "jxta.org"
   * @param version -- something like "Version 2.0"
   * @param specURI -- where to locate the formal specs, e.g. "http://www.jxta.org/MyNewThing"
   * @param pipeAdv -- to make the module useable remotely (see {@link ModuleSpecAdvertisement})
   * @param proxySpecID -- sometimes required for remote use (see {@link ModuleSpecAdvertisement})
   * @param authorizationSpecID -- sometimes required for remote use (see {@link
   *     ModuleSpecAdvertisement})
   * @param param -- anything else
   * @return -- a fully populated advert specifying remote access to module services.
   */
  public static ModuleSpecAdvertisement buildModuleSpecAdvertisement(
      ModuleSpecID msid,
      String moduleSpecName,
      String moduleSpecDescription,
      String creator,
      String version,
      String specURI,
      PipeAdvertisement pipeAdv,
      ModuleSpecID proxySpecID,
      ModuleSpecID authorizationSpecID,
      StructuredDocument param) {
    ModuleSpecAdvertisement msadv =
        (ModuleSpecAdvertisement)
            AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType());

    msadv.setModuleSpecID(msid);
    msadv.setName(moduleSpecName);
    msadv.setDescription(moduleSpecDescription);
    msadv.setCreator(creator == null ? "jxta.org" : creator);
    msadv.setVersion(version == null ? "Version 2.0" : version);
    msadv.setSpecURI(specURI == null ? "http://www.jxta.org/" + moduleSpecName : specURI);
    if (pipeAdv != null) {
      msadv.setPipeAdvertisement(pipeAdv);
    }
    if (proxySpecID != null) {
      msadv.setProxySpecID(proxySpecID);
    }
    if (authorizationSpecID != null) {
      msadv.setAuthSpecID(authorizationSpecID);
    }
    if (param != null) {
      msadv.setParam(param);
    }
    return msadv;
  }
 /**
  * Gets the pipeAdvertisement attribute of the PipeResolverMessage object
  *
  * @return The pipeAdvertisement value
  */
 public PipeAdvertisement getPipeAdvertisement() {
   if (pipeAdv == null && (getPipeID().equals(ID.nullID) && getPipeType() != null)) {
     pipeAdv =
         (PipeAdvertisement)
             AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());
     pipeAdv.setPipeID(getPipeID());
     pipeAdv.setType(getPipeType());
   }
   return pipeAdv;
 }
Пример #4
0
  /**
   * The module class advertisement is to simply advertise the existence of a module.
   *
   * @param mcid -- the module class id
   * @param serviceName -- something like "JXTAMOD:JXTA-WIRE-MyNewThing"
   * @param serviceDescription -- something like "JXTA-WIRE MyNewThing Module"
   * @return an appropriate ModuleClassAdvertisement
   */
  public static ModuleClassAdvertisement buildModuleClassAdvertisement(
      ModuleClassID mcid, String serviceName, String serviceDescription) {
    ModuleClassAdvertisement mcadv =
        (ModuleClassAdvertisement)
            AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType());

    mcadv.setName(serviceName);
    mcadv.setDescription(serviceDescription);
    mcadv.setModuleClassID(mcid);
    return mcadv;
  }
Пример #5
0
  /**
   * A ModuleImplAdvertisement represents one of any number of published implementations of a given
   * specification. Use this form with for a development boilerplate. Use buildCompat() for a compat
   * boilerplate. (See {@link ModuleImplAdvertisement}.)
   *
   * @param msid -- the module spec id
   * @param code -- the module's fully qualified classname, "net.jxta.impl.wire.MyNewThing"
   * @param compat -- a compatibility statement. Use buildCompat() for a boilerplate.
   * @return -- a development boilerplate with custom compatibility.
   */
  public static ModuleImplAdvertisement buildModuleImplAdvertisement(
      ModuleSpecID msid, String code, Element compat) {
    ModuleImplAdvertisement miadv =
        (ModuleImplAdvertisement)
            AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType());

    miadv.setCompat(compat);
    miadv.setModuleSpecID(msid);
    miadv.setCode(code);
    miadv.setDescription(code + " Module, J2SE Implementation");
    miadv.setProvider("jxta.org");
    miadv.setUri("http://download.jxta.org");
    return miadv;
  }
Пример #6
0
  /**
   * Process an individual element from the document during parse. Normally, implementations will
   * allow the base advertisments a chance to handle the element before attempting ot handle the
   * element themselves. ie.
   *
   * <p>
   *
   * <p>
   *
   * <pre><code>
   *  protected boolean handleElement(Element elem) {
   * <p/>
   *      if (super.handleElement()) {
   *           // it's been handled.
   *           return true;
   *           }
   * <p/>
   *      <i>... handle elements here ...</i>
   * <p/>
   *      // we don't know how to handle the element
   *      return false;
   *      }
   *  </code></pre>
   *
   * @param elem the element to be processed.
   * @return true if the element was recognized, otherwise false.
   */
  protected boolean handleElement(XMLElement elem) {

    String value = elem.getTextValue();

    if (null == value) {
      return false;
    }

    value = value.trim();

    if (0 == value.length()) {
      return false;
    }

    if (elem.getName().equals(typeTag)) {
      setDiscoveryType(Integer.parseInt(value));
      return true;
    }
    if (elem.getName().equals(thresholdTag)) {
      setThreshold(Integer.parseInt(value));
      return true;
    }
    if (elem.getName().equals(peerAdvTag)) {
      try {
        XMLDocument asDoc =
            (XMLDocument)
                StructuredDocumentFactory.newStructuredDocument(
                    MimeMediaType.XMLUTF8, new StringReader(value));
        PeerAdvertisement adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc);
        setPeerAdvertisement(adv);
        return true;
      } catch (IOException failed) {
        IllegalArgumentException failure = new IllegalArgumentException("Bad Peer Advertisement");
        failure.initCause(failed);

        throw failure;
      }
    }
    if (elem.getName().equals(queryAttrTag)) {
      setAttr(value);
      return true;
    }
    if (elem.getName().equals(queryValueTag)) {
      setValue(value);
      return true;
    }

    // element was not handled
    return false;
  }
Пример #7
0
  /**
   * Process the Query, and generate response
   *
   * @param query the query to process
   */
  public int processQuery(ResolverQueryMsg query) {

    if (!useRouteResolver) { // Route resolver disabled
      return ResolverService.OK;
    }

    if (LOG.isEnabledFor(Level.DEBUG)) {
      LOG.debug("processQuery starts");
    }

    RouteQuery routeQuery = null;
    Reader ip = null;

    try {
      ip = new StringReader(query.getQuery());

      StructuredTextDocument asDoc =
          (StructuredTextDocument)
              StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, ip);

      routeQuery = new RouteQuery(asDoc);

    } catch (Throwable e) {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("Malformed Route query ", e);
      }
      return ResolverService.OK;
    } finally {
      try {
        if (null != ip) {
          ip.close();
          ip = null;
        }
      } catch (Throwable ignored) {;
      }
    }

    PeerID pId = routeQuery.getDestPeerID();

    if (LOG.isEnabledFor(Level.DEBUG)) {
      LOG.debug("processQuery: looking for route to " + pId);
    }

    RouteAdvertisement srcRoute = routeQuery.getSrcRoute();
    List badHops = routeQuery.getBadHops();

    if (LOG.isEnabledFor(Level.DEBUG)) {
      if (badHops != null) {
        LOG.debug("processQuery: bad Hops");
        for (int i = 0; i < badHops.size(); i++) {
          LOG.debug("processQuery:   :" + ((PeerID) badHops.get(i)).toString());
        }
      }
    }
    // if our source route is not null, then publish it
    if (srcRoute != null) {
      if (!(srcRoute.getDestPeerID()).equals(localPeerId)) {
        // This is not our own peer adv so we must not keep it
        // longer than its expiration time.
        try {
          if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("processQuery: publishing sender route info " + srcRoute.getDestPeerID());
          }

          // we only need to publish this route if
          // we don't know about it yet
          // XXX: here is where we could be more conservative and use isNormallyReachable() instead,
          // thus excluding
          // incoming messengers.
          if ((!router.isLocalRoute(router.pid2addr(srcRoute.getDestPeerID())))
              && (!router.isRoutedRoute(router.pid2addr(srcRoute.getDestPeerID())))) {
            routeCM.publishRoute(srcRoute);
          }
        } catch (Exception e) {
          if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("Could not publish Route Adv from query - discard", e);
          }
          return ResolverService.OK;
        }
      }
    } else {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("No src Route in route query - discard ");
      }
      return ResolverService.OK;
    }

    if (pId == null) {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("Malformed route query request, no PeerId - discard");
      }
      return ResolverService.OK;
    }

    // We have more luck with that one because, since it is part of OUR
    // message, and not part of the resolver protocol, it is in OUR
    // format.
    EndpointAddress qReqAddr = router.pid2addr(pId);

    RouteAdvertisement route = null;

    // check if this peer has a route to the destination
    // requested
    boolean found = false;

    if (qReqAddr.equals(localPeerAddr)) {
      found = true;
      // return the route that is my local route
      route = router.getMyLocalRoute();
    } else {
      // only rendezvous can respond to route requests
      // if not we are generating too much traffic
      // XXX: here is where we could be more conservative and use isNormallyReachable() instead,
      // thus excluding
      // incoming messengers.
      if (router.isLocalRoute(qReqAddr)) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
          LOG.debug("processQuery: peer has direct route to destination ");
        }
        // we should set the route to something  :-)

        found = true;

        // this peer has a direct route to the destination
        // return the short route advertisement we know for this peer
        // (For us it is zero hop, and we advertise ourself as the routing
        // peer in the response. The stiching is done by whoever gets that
        // response). May be there are more than one hop advertised in-there...
        // alternate routing peers...should we leave them ?
        // For now, we keep the full dest, but wack the hops.

        route =
            (RouteAdvertisement)
                AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

        AccessPointAdvertisement ap =
            (AccessPointAdvertisement)
                AdvertisementFactory.newAdvertisement(
                    AccessPointAdvertisement.getAdvertisementType());

        ap.setPeerID(pId);
        route.setDest(ap);

      } else {

        route = router.getRoute(qReqAddr, false);
        if (route != null) {
          found = true;
          // check if we were given some bad hops info
          // and see if the found route contains
          // any of these bad hops. In that case, we need
          // to mark this route as bad
          for (int i = 0; i < badHops.size(); i++) {

            // destination is known to be bad
            if (router.addr2pid(qReqAddr).equals(((PeerID) badHops.get(i)))) {
              processBadRoute((PeerID) badHops.get(i), route);
              found = false;
              break;
            }

            if (route.containsHop((PeerID) badHops.get(i))) {
              if (LOG.isEnabledFor(Level.DEBUG)) {
                LOG.debug(
                    "processQuery: peer has bad route due to "
                        + ((PeerID) badHops.get(i)).toString());
              }
              processBadRoute((PeerID) badHops.get(i), route);
              found = false;
              break;
            }
          }
        }
      }
    }

    if (!found) {
      // discard the request if we are not a rendezvous
      // else forward to the next peers
      if (!group.isRendezvous()) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
          LOG.debug("discard query forwarding as not a rendezvous");
        }
        return ResolverService.OK;
      }

      // did not find a route, check our srdi cache
      // make sure we protect against out of sync
      // SRDI index

      // srdi forwarding is only involved once the Index entry has
      // been found and we forwarded the resolver query. Afterward a
      // normal walk proceeds from the initial SRDI index pointing
      // rdv. This is done to protect against potential loopback
      // entries in the SRDI cache index due to out of sync peerview
      // and index.
      if (query.getHopCount() < 2) {

        // check local SRDI cache to see if we have the entry
        // we look for 10 entries, will pickup one randomly
        Vector results = srdiIndex.query("route", "DstPID", pId.toString(), 10);

        if (results.size() > 0) {
          if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("processQuery srdiIndex lookup match :" + results.size());
          }

          // remove any non-rdv peers to avoid sending
          // to a non-rdv peers and garbage collect the SRDI
          // index in the process
          Vector clean = cleanupAnyEdges(query.getSrc(), results);

          if (clean.size() > 0) {

            if (LOG.isEnabledFor(Level.DEBUG)) {
              LOG.debug("found an srdi entry forwarding query to SRDI peer");
            }

            // The purpose of incrementing the hopcount
            // when an SRDI index match is found (we got a
            // pointer to a rdv that should have the route) is to
            // restrict any further forwarding. The increment
            // count is only done when a matching SRDI index is
            // found. Not when the replica is selected as we
            // still need to forward the query.  This restriction
            // is purposelly done to avoid too many longjumps
            // within a walk.
            query.incrementHopCount();

            // Note: this forwards the query to 1 peer randomly
            // selected from the result
            srdi.forwardQuery(clean, query, 1);

            // tell the resolver no further action is needed.
            return ResolverService.OK;
          }
        }
      }

      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("did not find a route or SRDI index");
      }

      // force a walk
      return ResolverService.Repropagate;
    }

    // we found a route send the response
    try {
      if (route == null) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
          LOG.debug("we should have had a route at this point");
        }
        return ResolverService.OK;
      }

      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("processQuery: we have a route build route response" + route.display());
      }

      RouteAdvertisement myRoute = router.getMyLocalRoute();

      // make sure we initialized our local
      // route info as we will need it to respond. We may
      // not have our route if we are still
      // waiting for a relay connection.
      if (myRoute == null) {
        return ResolverService.OK;
      }

      RouteResponse routeResponse = new RouteResponse();

      routeResponse.setDestRoute(route);
      routeResponse.setSrcRoute(myRoute);

      if (routeResponse == null) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
          LOG.debug("error creating route response");
        }
        return ResolverService.OK;
      }

      // construct a response from the query
      ResolverResponseMsg res = query.makeResponse();

      res.setCredential(credentialDoc);
      res.setResponse(routeResponse.toString());

      resolver.sendResponse(query.getSrc(), res);
      return ResolverService.OK;

    } catch (Exception ee) {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("processQuery: error while processing query ", ee);
      }
      return ResolverService.OK;
    }
  }
Пример #8
0
  /**
   * Return a route error in case a route was found to be invalid as the current hop cannot find a
   * way to forward the message to the destination or any other hops in the forward part of the
   * route. In that case a negative route response is forwarded to the orginal source of the
   * message. Now of course we do not have any way to guarantee that the NACK message will be
   * received by the sender, but the best we can do is to try :-)
   *
   * <p>we send a query ID to NACKROUTE_QUERYID to indicate this is a bad Route
   *
   * @param src original source of the message
   * @param dest original destination of the message
   */
  protected void generateNACKRoute(PeerID src, PeerID dest, Vector origHops) {

    // As long as the group is partially initialized, do not bother
    // trying to send NACKS. We can't: it just causes NPEs.
    if (resolver == null) {
      return;
    }

    if (LOG.isEnabledFor(Level.DEBUG)) {
      LOG.debug("generate NACK Route response " + src);
    }

    // check first, if we are not already in process of looking for a
    // route to the destination peer of the NACK. We should not try to
    // send a NACK to that destination at that point as this will block
    // our incoming processing thread while it is looking for a route to
    // that destination. If there a no pending route requests to that
    // destination then we can go ahead an attempt to send the NACK. At
    // the maximum we should have only one thread block while looking for
    // a specific destination. When we find a route to the destination,
    // the next NACK processing will be sent.

    if (router.isPendingRouteQuery(router.pid2addr(src))) {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("drop NACK due to pending route discovery " + src);
      }
      return;
    }

    // Generate a route response
    RouteAdvertisement route =
        (RouteAdvertisement)
            AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

    AccessPointAdvertisement ap =
        (AccessPointAdvertisement)
            AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType());

    ap.setPeerID(dest);
    route.setDest(ap);
    route.setHops(origHops);

    // set the the route of the peer that
    // detected the bad route
    RouteAdvertisement routeSrc =
        (RouteAdvertisement)
            AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType());

    AccessPointAdvertisement apSrc =
        (AccessPointAdvertisement)
            AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType());

    apSrc.setPeerID((PeerID) localPeerId);
    routeSrc.setDest(apSrc);

    RouteResponse routeResponse = new RouteResponse();

    routeResponse.setDestRoute(route);
    routeResponse.setSrcRoute(routeSrc);

    if (routeResponse == null) {
      if (LOG.isEnabledFor(Level.DEBUG)) {
        LOG.debug("error creating route NACKresponse");
      }
      return;
    }

    ResolverResponse res =
        new ResolverResponse(
            routerSName,
            credentialDoc,
            NACKROUTE_QUERYID, // mean NACKRoute
            routeResponse.toString());

    // send the NACK response back to the originator
    resolver.sendResponse(src.toString(), res);
  }
Пример #9
0
  private 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(paramTag))
      throw new IllegalArgumentException(
          "Could not construct : "
              + getClass().getName()
              + "from doc containing a "
              + doc.getName());

    // set defaults
    servicesTable = new Hashtable();
    protosTable = new Hashtable();
    appsTable = new Hashtable();

    int appCount = 0;
    Enumeration modules = doc.getChildren();
    while (modules.hasMoreElements()) {
      Hashtable theTable;

      TextElement module = (TextElement) modules.nextElement();
      String tagName = module.getName();
      if (tagName.equals(svcTag)) {
        theTable = servicesTable;
      } else if (tagName.equals(appTag)) {
        theTable = appsTable;
      } else if (tagName.equals(protoTag)) {
        theTable = protosTable;
      } else continue;

      ModuleSpecID specID = null;
      ModuleClassID classID = null;
      ModuleImplAdvertisement inLineAdv = null;

      try {
        if (module.getTextValue() != null) {
          specID = (ModuleSpecID) IDFactory.fromURL(IDFactory.jxtaURL(module.getTextValue()));
        }

        // Check for children anyway.
        Enumeration fields = module.getChildren();
        while (fields.hasMoreElements()) {
          TextElement field = (TextElement) fields.nextElement();
          if (field.getName().equals(mcidTag)) {
            classID = (ModuleClassID) IDFactory.fromURL(IDFactory.jxtaURL(field.getTextValue()));
            continue;
          }
          if (field.getName().equals(msidTag)) {
            specID = (ModuleSpecID) IDFactory.fromURL(IDFactory.jxtaURL(field.getTextValue()));
            continue;
          }
          if (field.getName().equals(miaTag)) {
            inLineAdv = (ModuleImplAdvertisement) AdvertisementFactory.newAdvertisement(field);
            continue;
          }
        }
      } catch (Exception any) {
        if (LOG.isEnabledFor(Level.WARN)) LOG.warn("Broken entry; skipping", any);
        continue;
      }

      if (inLineAdv == null && specID == null) {
        if (LOG.isEnabledFor(Level.WARN)) LOG.warn("Insufficent entry; skipping");
        continue;
      }

      Object theValue;
      if (inLineAdv == null) {
        theValue = specID;
      } else {
        specID = inLineAdv.getModuleSpecID();
        theValue = inLineAdv;
      }
      if (classID == null) {
        classID = specID.getBaseClass();
      }

      // For applications, the role does not matter. We just create
      // a unique role ID on the fly.
      // When outputing the add we get rid of it to save space.

      if (theTable == appsTable) {
        // Only the first (or only) one may use the base class.
        if (appCount++ != 0) {
          classID = IDFactory.newModuleClassID(classID);
        }
      }
      theTable.put(classID, theValue);
    }
  }
Пример #10
0
  /**
   * {@inheritDoc}
   *
   * @param encodeAs Description of the Parameter
   * @return The document value
   */
  public Document getDocument(MimeMediaType encodeAs) {
    StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs);

    if (hasALoop()) {
      throw new IllegalStateException("I won't write a doc for a route with a loop");
    }

    PeerID pid = getDestPeerID();
    AccessPointAdvertisement dest = getDest();

    if ((null != pid) && (null != dest) && (null != dest.getPeerID())) {
      if (!pid.equals(dest.getPeerID())) {
        throw new IllegalStateException(
            "Destination peer id and destination access point adv don't refer to the same peer");
      }
    }

    // HACK Backwards Compatibility
    if ((null == pid) && (null != dest)) {
      pid = dest.getPeerID();
    }

    if (pid != null) {
      Element e0 = adv.createElement(DEST_PID_TAG, pid.toString());

      adv.appendChild(e0);
    }

    if (dest != null) {
      // create the copy without the PID
      AccessPointAdvertisement ap =
          (AccessPointAdvertisement)
              AdvertisementFactory.newAdvertisement(
                  AccessPointAdvertisement.getAdvertisementType());

      ap.setEndpointAddresses(dest.getVectorEndpointAddresses());

      StructuredTextDocument xptDoc = (StructuredTextDocument) ap.getDocument(encodeAs);

      Element e1 = adv.createElement("Dst");

      adv.appendChild(e1);
      StructuredDocumentUtils.copyElements(adv, e1, xptDoc);
    }

    // only include hops if we have some
    if (getHops().hasMoreElements()) {

      Element e2 = adv.createElement("Hops");

      adv.appendChild(e2);

      for (Enumeration e = getHops(); e.hasMoreElements(); ) {
        AccessPointAdvertisement hop = (AccessPointAdvertisement) e.nextElement();

        if (hop != null) {
          StructuredTextDocument xptDoc = (StructuredTextDocument) hop.getDocument(encodeAs);

          StructuredDocumentUtils.copyElements(adv, e2, xptDoc);
        }
      }
    }

    return adv;
  }
Пример #11
0
  /** @see net.jxta.discovery.DiscoveryListener#discoveryEvent(DiscoveryEvent) */
  public void discoveryEvent(DiscoveryEvent event) {
    // copied from JXTA Examples - PeerDiscovery
    System.out.println("Process discovery event...");

    DiscoveryResponseMsg response = event.getResponse();

    // Get the responding peer's advertisement as a string
    String responderAdvString = response.getPeerAdv();

    InputStream is = null;

    try {
      // create a peer advertisement
      is = new ByteArrayInputStream(responderAdvString.getBytes());

      PeerAdvertisement responderAdv =
          (PeerAdvertisement) AdvertisementFactory.newAdvertisement(XML_MIME_TYPE, is);
      System.out.println(
          " [  Got a Discovery Response ["
              + response.getResponseCount()
              + " elements] from peer: "
              + responderAdv.getName()
              + " ]");
    } catch (java.io.IOException e) {
      // bogus peer, skip this message alltogether.
      System.out.println("Warning: cannot parse remote peer's advertisement.\n" + e.getMessage());
      return;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (Throwable throwable) {
          System.out.println(
              "Ignoring failure to close stream " + "on remote peer's advertisement");
          throwable.printStackTrace();
        }
      }
    }

    // now print out each discovered peer
    PeerAdvertisement newAdv = null;

    Enumeration responses = response.getResponses();

    while (responses.hasMoreElements()) {
      try {
        String responseString = (String) responses.nextElement();

        // create an advertisement object from each element
        newAdv =
            (PeerAdvertisement)
                AdvertisementFactory.newAdvertisement(
                    XML_MIME_TYPE, new ByteArrayInputStream(responseString.getBytes()));
        System.out.println(" Peer name = " + newAdv.getName());
      } catch (java.io.IOException e) {
        // got a bad response. continue to the next response
        System.out.println("Warning: cannot parse response element.\n" + e.getMessage());
        continue;
      }
    } // end while
  }
Пример #12
0
  ///////////////////////////////////////////////////////////////////
  ////                         public methods                    ////
  public void preinitialize() throws IllegalActionException {
    super.preinitialize();
    PropertyConfigurator.configure(System.getProperties());

    // if (configDir.hasToken()) {
    // String Dir = ((StringToken)configDir.getToken()).stringValue();
    // } else {
    String Dir = "c:/Cygwin/home/ellen_zh/ptII/ptolemy/actor/lib/jxta";

    // }
    // if (actorList.hasToken()) {
    // String _actorListFileName = ((StringToken)actorList.getToken()).stringValue();
    // } else {
    String _actorListFileName = "c:/Cygwin/home/ellen_zh/ptII/ptolemy/actor/lib/jxta/actors.xml";

    // }
    _properties = new Properties(System.getProperties());

    InputStream configProperties = null;

    try {
      configProperties = new FileInputStream(_CONFIG_FILE);
      _properties.load(configProperties);
    } catch (IOException e) {
      System.out.println(
          "Warning: Can't find configuration propertiees file. ' " + e.getMessage() + "'");
    } finally {
      if (configProperties != null) {
        try {
          configProperties.close();
        } catch (Throwable throwable) {
          System.out.println("Ignoring failure to close stream " + "on '" + _CONFIG_FILE + "'");
          throwable.printStackTrace();
        }
      }
    }

    PeerGroup netPeerGroup = null;

    try {
      netPeerGroup = PeerGroupFactory.newNetPeerGroup();
    } catch (PeerGroupException ex) {
      System.out.println("Error: cannot locate net peer group.\n" + ex.getMessage());
    }

    // load the peer group adv for actor exchange
    String groupAdvFileName = _properties.getProperty("GroupAdvFileName");

    if (groupAdvFileName == null) {
      System.out.println("Error: property undefined - GroupAdvFileName.\n");
    }

    PeerGroupAdvertisement groupAdv = null;

    try {
      groupAdv =
          (PeerGroupAdvertisement)
              AdvertisementFactory.newAdvertisement(
                  XML_MIME_TYPE, new FileInputStream(Dir + "/" + groupAdvFileName));
    } catch (FileNotFoundException ex) {
      System.out.println("Error: cannot find group adv file.\n" + ex.getMessage());
    } catch (IOException ex) {
      System.out.println("Error: reading group adv file.\n" + ex.getMessage());
    }

    System.out.println("peer groupAdv: " + groupAdvFileName);
    System.out.println("success before instantiate peer group");

    // instantiate the peer group for actor exchange
    try {
      _group = netPeerGroup.newGroup(groupAdv);
    } catch (PeerGroupException ex) {
      System.out.println("Error: cannot instantiate peer group.\n" + ex.getMessage());
    }

    // join the peer group for actor exchange
    // no authentication is done here
    // modeled after JoinDemo from JXTA Examples
    StructuredDocument identityInfo = null;

    try {
      AuthenticationCredential authCred = new AuthenticationCredential(_group, null, identityInfo);
      MembershipService membershipService = _group.getMembershipService();
      _authenticator = membershipService.apply(authCred);

      if (_authenticator.isReadyForJoin()) {
        _credential = membershipService.join(_authenticator);
        System.out.println("Info: join group successful.");
        _credential.getDocument(XML_MIME_TYPE).sendToStream(System.out);
      } else {
        System.out.println("Error: unable to join group.");
      }
    } catch (Exception ex) {
      System.out.println("Error: failure in authentication.\n" + ex.getMessage());
    }

    _discoveryService = _group.getDiscoveryService();
    _discoveryService.addDiscoveryListener(this);

    _resolverService = _group.getResolverService();

    // register this as a query handler
    _resolverService.registerHandler(_ACTOR_QUERY_HANDLER_NAME, this);

    // construct the actor query message
    StringBuffer queryTextBuffer = new StringBuffer("<?xml version=\"1.0\"?>\n\n");
    queryTextBuffer = queryTextBuffer.append("<ActorQuery>\n");
    queryTextBuffer = queryTextBuffer.append("What actors do you have?");
    queryTextBuffer = queryTextBuffer.append("\n</ActorQuery>\n");
    _actorQueryMessage =
        new ResolverQuery(_ACTOR_QUERY_HANDLER_NAME, null, null, queryTextBuffer.toString(), 0);
    _actorQueryMessage.setSrc(_group.getPeerID().toString());

    // construct the actor query response message
    if (_actorListFileName != null) {
      StringBuffer actorListText = new StringBuffer();

      BufferedReader fileReader = null;
      try {
        fileReader = new BufferedReader(new FileReader(_actorListFileName));
        String newline = System.getProperty("line.separator");

        while (true) {
          String line = fileReader.readLine();

          if (line == null) {
            break;
          }

          actorListText = actorListText.append(line);
          actorListText = actorListText.append(newline);
        }

        _actorQueryResponse =
            new ResolverResponse(_ACTOR_QUERY_HANDLER_NAME, null, 0, actorListText.toString());
      } catch (IOException ex) {
        System.out.println("Warning: error reading actor list file.\n" + ex.getMessage());
      } finally {
        if (fileReader != null) {
          try {
            fileReader.close();
          } catch (Exception ex) {
            System.out.println("Failed to close: " + ex.getMessage());
          }
        }
      }
    }
  }