Package org.openxri.xml

Examples of org.openxri.xml.XRDS


   * @return
   * @throws PartialResolutionException
   */
  protected XRDS fetchAuthXRDS(XRI qxri, XRD parent, List authResServices, XRISegment segment, ResolverFlags flags, ResolverState state, String parentXRI) throws PartialResolutionException
  {
    XRDS xrdsOut = null;
    XRD errXRD = null;
    String query = segment.getSubSegmentAt(0).toURINormalForm(true);
   
    ///// Try each URI in each selected service in turn
    Exception savedException = null;
    Iterator srvIterator = authResServices.iterator();
    while (srvIterator.hasNext()) {     
      Service srv = (Service) srvIterator.next();
      Iterator uriIterator = srv.getPrioritizedURIs().iterator();
     
      while (uriIterator.hasNext()) {
        SEPUri sepURI = (SEPUri) uriIterator.next();
        URI uri = sepURI.getURI();

        log.trace("fetchAuthXRDS - trying URI='" + uri + "'");

        // skip non-HTTPS URIs if HTTPS was requested
        if (flags.isHttps() && !uri.getScheme().equals(HTTPS)) {
          log.trace("fetchAuthXRDS - skipping non HTTPS URI");
          continue;
        }

        try {
          xrdsOut = fetchAuthXRDSHelper(qxri, uri, parent, srv, segment, flags, state, parentXRI);
          // if no error, return immediately
          return xrdsOut;
        }
        catch (PartialResolutionException e) {
          xrdsOut = e.getPartialXRDS();
        }
      }
    }

    if (xrdsOut == null) { // no appropriate URI found
      xrdsOut = new XRDS();
      String code = flags.isHttps()? Status.TRUSTED_RES_ERROR : Status.AUTH_RES_ERROR;
      xrdsOut.add(createErrorXRD(query, code, "No URI found for authority resolution"));
    }
   
    // we reach here if the subsegment did not resolve correctly, do negative caching
    if (cache != null) {
      String xriAuthority = XRI.fromURINormalForm(parentXRI + query).toURINormalForm();
      byte[] xrdsBuf = null;
      try {
        // copy first XRD from the error xrdsOut (in case it contains multiple XRD)
        XRDS xrdsCache = new XRDS();
        xrdsCache.add(xrdsOut.getDescriptorAt(0));
        xrdsBuf = xrdsCache.toString().getBytes("UTF-8");
      } catch (UnsupportedEncodingException e) {}
     
      log.debug("writing negative cache entry " + xriAuthority + ", cacheTTL = " + negativeCacheTTL);
      cache.put(xriAuthority, flags.isHttps(), flags.isSaml(), xrdsBuf, negativeCacheTTL);
    }
View Full Code Here


      throw ex2;
    }

    // the big goal is to make an XRDS, consisting of one or more XRDs

    XRDS xrds = new XRDS();
    boolean ret;

    // give subclasses a chance to init the XRDS before we begin

    ret = this.initXRDS(
        xrds,
        query,
        signed);

    // if a subclass returned true, it doesn't want us to do any more work

    if (ret == true) {

      log.debug("Subclass handled XRDS completely. Returning it without any more work.");
      return(xrds);
    }

    // generate XRDs for all subsegments in the request

    String utf8Query;

    try {

      utf8Query = IRIUtils.IRItoXRI(IRIUtils.URItoIRI(query));
    } catch (Exception ex) {

      ServerException ex2 = new ServerInternalException("Unsupported encoding in query: " + ex.getMessage(), ex);
      log.warn(ex2);
      throw ex2;
    }

    XRISegment segment = new XRISegment(utf8Query);

    for (int i=0; i<segment.getNumSubSegments(); i++) {

      String subSegmentName = segment.getSubSegmentAt(i).toString();

      try {

        // create a fresh XRD

        XRD xrd = new XRD();

        // using the parent authority and subsegment name, find the subsegment and the authority we are describing now
        // we must be prepared to have null values here, since not all pipeline configurations
        // may use objects from the store

        SubSegment subSegment = null;
        Authority authority = null;

        if (parentAuthority != null) subSegment = this.store.findSubSegment(parentAuthority, subSegmentName);
        if (subSegment != null) authority = this.store.getSubSegmentAuthority(subSegment);

        // give subclasses a chance to init the XRD

        ret = this.initXRD(
            xrd,
            parentAuthority,
            subSegmentName,
            signed);

        // if a subclass returned true, it doesn't want us to do any more work

        if (ret == true) {

          log.debug("Subclass handled XRD completely. Returning it without any more work.");
          xrds.add(xrd);
          continue;
        }

        // check if the parent authority overrides the LOOKUP pipeline. if not, use the default.

        ServerConfig serverConfig = ServerConfigFactory.getSingleton();
        PipelineRegistry pipelineRegistry = (serverConfig == null) ? null : serverConfig.getPipelineRegistry();
        Pipeline lookupPipeline = null;

        if (this.store instanceof StoreAttributable) {

          StoreAttributable storeAttributable = (StoreAttributable) this.store;

          String pipelineName = storeAttributable.getAuthorityAttributes(parentAuthority).get(Pipeline.ATTRIBUTE_OVERRIDE_LOOKUP_PIPELINE);
          if (pipelineRegistry != null && pipelineName != null) lookupPipeline = pipelineRegistry.getPipelineByName(pipelineName);
        }

        if (pipelineRegistry != null && lookupPipeline == null) lookupPipeline = pipelineRegistry.getDefaultLookupPipeline();

        // execute LOOKUP pipeline

        xrd = lookupPipeline.execute(
            this.store,
            xrd,
            segment,
            parentAuthority,
            subSegmentName,
            authority,
            false);

        // let our subclasses finish the XRD before we append it to the XRDS

        this.finishXRD(
            xrd,
            parentAuthority,
            subSegment,
            authority,
            signed);

        // authority becomes the parent authority for the next subsegment

        parentAuthority = authority;

        // if we were not able to get a XRD, that's ok if we found at least one before
        // (we are not necessarily authoritative for the whole query)

        if (xrd == null) {

          if (i > 0) {

            break;
          } else {

            xrds.add(makeNotFoundXrd(subSegmentName));
            break;
          }
        }

        // append XRD to the XRDS

        xrds.add(xrd);
      } catch (Exception ex) {

        log.error(ex);
        xrds.add(makeExceptionXrd(subSegmentName, ex));
        break;
      }
    }

    // let subclasses finish the XRDS before we send it out
View Full Code Here

  {
    log.debug("lookupByPath(" + path + ")");

    // the big goal is to make an XRDS, consisting of one or more XRDs

    XRDS xrds = new XRDS();
    boolean ret;

    // give subclasses a chance to init the XRDS before we begin

    ret = this.initXRDS(
        xrds,
        null,
        signed);

    // if a subclass returned true, it doesn't want us to do any more work

    if (ret == true) {

      log.debug("Subclass handled XRDS completely. Returning it without any more work.");
      return(xrds);
    }

    // find all mounted authorities for this path

    Authority[] authorities = new Authority[0];

    if (this.store instanceof StoreMountable) {

      try {

        StoreMountable storeMountable = (StoreMountable) this.store;

        authorities = storeMountable.listAuthoritiesByPath(path);
      } catch (StoreException ex) {

        ServerException ex2 = new ServerInternalException("Error while listing mounted authorities.", ex);
        log.warn(ex2);
        throw ex2;
      }
    }

    // add XRDs of all mounted authorities

    for (int i=0; i<authorities.length; i++) {

      String subSegmentName = path;

      try {

        // create a fresh XRD

        XRD xrd = new XRD();

        // get the current authority from the list

        Authority authority = authorities[i];

        // give subclasses a chance to init the XRD

        ret = this.initXRD(
            xrd,
            null,
            subSegmentName,
            signed);

        // if a subclass returned true, it doesn't want us to do any more work

        if (ret == true) {

          log.debug("Subclass handled XRD completely. Returning it without any more work.");
          xrds.add(xrd);
          continue;
        }

        // check if the authority overrides the LOOKUP pipeline. if not, use the default.

        ServerConfig serverConfig = ServerConfigFactory.getSingleton();
        PipelineRegistry pipelineRegistry = (serverConfig == null) ? null : serverConfig.getPipelineRegistry();
        Pipeline lookupPipeline = null;

        if (this.store instanceof StoreAttributable) {

          StoreAttributable storeAttributable = (StoreAttributable) this.store;

          String pipelineName = storeAttributable.getAuthorityAttributes(authority).get(Pipeline.ATTRIBUTE_OVERRIDE_LOOKUP_PIPELINE);
          if (pipelineRegistry != null && pipelineName != null) lookupPipeline = pipelineRegistry.getPipelineByName(pipelineName);
        }

        if (pipelineRegistry != null && lookupPipeline == null) lookupPipeline = pipelineRegistry.getDefaultLookupPipeline();

        // execute LOOKUP pipeline

        xrd = lookupPipeline.execute(
            this.store,
            xrd,
            null,
            null,
            subSegmentName,
            authority,
            false);

        // let our subclasses finish the XRD before we append it to the XRDS

        this.finishXRD(
            xrd,
            null,
            null,
            authority,
            signed);

        // if we were not able to get a XRD, return an error

        if (xrd == null) {

          xrds.add(makeNotFoundXrd(subSegmentName));
          break;
        }

        // append XRD to the XRDS

        xrds.add(xrd);
      } catch (Exception ex) {

        log.error(ex);
        xrds.add(makeExceptionXrd(subSegmentName, ex));
        break;
      }
    }

    // let subclasses finish the XRDS before we send it out
View Full Code Here

      ResolverFlags flags, ResolverState state)
      throws PartialResolutionException
  {
    log.trace("resolveAuthSegment - segment='" + segment + "'");

    XRDS xrdsOut = new XRDS();
    XRDS tmpXRDS = null;
    CanonicalID parentCID = null;
    boolean authResComplete = false;
    ResolverFlags currentFlags = null; // this is only for overriding by HttpsBypassAuthority settings

    String parentXRI = ((XRIAuthority)qxri.getAuthorityPath()).getRootAuthority();
    XRISegment remainingSegment = segment;

    // if caching in use, we know that the root is always considered "cached"
    boolean parentIsCached = cache != null;
   
    while (remainingSegment != null && remainingSegment.getNumSubSegments() > 0) {
      // clone flags
      currentFlags = new ResolverFlags(flags);
     
      // more subsegments to resolve
      String query = remainingSegment.getSubSegmentAt(0).toURINormalForm(true);

      log.debug("resolveAuthSegment - resolving subsegment '" + query + "'");
     
      checkMaxRequests(xrdsOut, query, state);

      // if HTTPS is requested and what we are resolving is allowed to bypass HTTPS, we turn off the HTTPS flag
      // for auth-res service selection
      if (currentFlags.isHttps() && isHttpsBypassAuthority(parentXRI)) {
        log.debug("Bypassing HTTPS for " + parentXRI);
        currentFlags.setHttps(false);
      }
     
      //// perform service selection
      String authResMediaType = Tags.CONTENT_TYPE_XRDS + ";" + currentFlags.getTrustParameters();
      List authResServices = selectServices(parent.getServices(), Tags.SERVICE_AUTH_RES, null, authResMediaType, currentFlags);
      if (authResServices.size() < 1) {
        log.debug("resolveAuthSegment - no authority resolution service found!");
        throw makeResolutionException(
          xrdsOut,
          query,
          Status.AUTH_RES_NOT_FOUND,
          "Authority Resolution Service Not Found"
        );
      }

      if (parentIsCached) {
        // try retrieving from cache
        String xriAuthority = XRI.fromURINormalForm(parentXRI + query).toURINormalForm();
        log.debug("resolveAuthSegment - looking up in cache '" + xriAuthority + "'");
        byte[] res = cache.get(xriAuthority, currentFlags.isHttps(), currentFlags.isSaml());
        log.debug("resolveAuthSegment - cache " + ((res == null)? "MISS" : "HIT"));
       
        if (res != null) {
          // cache hit!
          XRDS xrdsCached = null;
          try {
            xrdsCached = readXRDS(new ByteArrayInputStream(res));
          }
          catch (XRIResolutionException e) {
            throw makeResolutionException(
                xrdsOut,
                query,
                Status.INVALID_XRDS,
                "Cached XRDS is invalid"
              );
          }
          // we need to pass a Service object representing the authority resolution service
          // that was selected but this only matters for SAML resolution, in which case, only
          // one is allowed, so we just pass the first Service to it.
          Service authRes = (Service) authResServices.get(0);
          parseFetchedXRD(xrdsCached, xrdsCached.getDescriptorAt(0), parent, remainingSegment.getSubSegmentAt(0), authRes, flags);      
          tmpXRDS = xrdsCached;
        }
      }

      // fetch from network if it is not cached
View Full Code Here

      return;
    }

    // let the server do the lookup and create a complete XRD/XRDS descriptor

    XRDS descriptor = null;

    try {

      if (namespace != null) {

        if (soLog.isDebugEnabled()) soLog.debug("Looking up authority by namespace.");

        descriptor = moServer.lookupByNamespace(namespace, segment, bSigned);
      } else if (authorityId != null) {

        if (soLog.isDebugEnabled()) soLog.debug("Looking up authority by ID.");

        descriptor = moServer.lookupById(authorityId, segment, bSigned);
      }
     
      if (descriptor == null) throw new ServerNotFoundException("Null descriptor returned.");
    } catch(ServerNotFoundException ex) {

      soLog.warn("Got no descriptor from server.", ex);
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    } catch(ServerException ex) {

      soLog.warn("Internal server problem during resolution.", ex);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }

    // hopefully we got a result

    if (descriptor != null) {

      if (soLog.isDebugEnabled()) soLog.debug("Resolution successful. Sending descriptor.");
      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentType(Tags.CONTENT_TYPE_XRDS);
      response.getWriter().write(descriptor.toString());
      return;
    } else {

      if (soLog.isDebugEnabled()) soLog.debug("Resolution unsuccessful. Sending 404.");
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
View Full Code Here

 
 
  protected XRDS processRefs(XRD parent, ResolverFlags flags, ResolverState state)
    throws PartialResolutionException
  {
    XRDS xrdsOut = new XRDS();
    //// get all the Refs in the parent XRD
    List refs = parent.getPrioritizedRefs();
    Iterator it = refs.iterator();
   
    //// try each one in turn
    while (it.hasNext()) {
      Ref ref = (Ref)it.next();

      checkMaxRefs(xrdsOut, ref.getValue(), state);

      XRI refXRI;
      try {
        refXRI = parseAbsoluteQXRIOrError(ref.getValue());
      }
      catch (PartialResolutionException e) {
        xrdsOut.add(e.getPartialXRDS());
        continue;
      }
     
      // record that we are following a ref
      state.pushFollowingRef(refXRI);
     
      try {
        XRDS tmpXRDS = resolveAuthority(refXRI, flags, state);
        xrdsOut.add(tmpXRDS);
        break;
      }
      catch (PartialResolutionException e) {
        xrdsOut.add(e.getPartialXRDS());
View Full Code Here

          // construct URI
          String constructedURI = constructURI(uri, r.getAppend(), qxri);
          uri = new URI(constructedURI);
        }
      } catch (URISyntaxException e) {
        XRDS tmpXRDS = new XRDS();
        XRD err = createErrorXRD(r.getValue(), Status.INVALID_REDIRECT, "Invalid Redirect URI");
        tmpXRDS.add(err);
        xrdsOut.add(tmpXRDS);
        continue;
      }
     
      try {
        XRDS tmpXRDS = fetchRedirectXRDS(uri, parent, qxri, flags, state);
        xrdsOut.add(tmpXRDS);
       
        XRD finalXRD = tmpXRDS.getFinalXRD();
        tmpXRDS = new XRDS();
        List services = selectServiceFromXRD(tmpXRDS, finalXRD, qxri, sepType, sepMediaType, flags, state);
        xrdsOut.addAll(tmpXRDS);
        return services; // we're done!
      } catch (XRIResolutionException e) {
        XRDS tmpXRDS = new XRDS();
        XRD err = createErrorXRD(uri.toString(), Status.REDIRECT_ERROR, "Error fetching XRDS: " + e.getMessage());
        tmpXRDS.add(err);
        xrdsOut.add(tmpXRDS);
       
        // fall through to continue to the next
      }
    }
View Full Code Here

     
      // record that we are following a ref
      state.pushFollowingRef(refXRI);
     
      try {
        XRDS tmpXRDS = resolveSEPToXRDS(refXRI, sepType, sepMediaType, flags, state);
        xrdsOut.add(tmpXRDS);
        return tmpXRDS.getFinalXRD().getSelectedServices().getList();
      }
      catch (PartialResolutionException e) {
        xrdsOut.add(e.getPartialXRDS());
        // fall through to continue to the next
      }
View Full Code Here

 
 
  protected XRDS fetchRedirectXRDS(URI uri, XRD parent, XRI qxri, ResolverFlags flags, ResolverState state)
    throws PartialResolutionException
  {
      XRDS xrdsOut = new XRDS();
      String query = qxri.toURINormalForm();
      xrdsOut.setRedirect(uri.toString());
     
      XRDS tmpXRDS = null;
      try {
        log.info("fetchRedirectXRDS - fetching from URI(" + uri + ")");
        InputStream in = getDataFromURI(uri, query, flags, state).getInputStream();
       
        log.info("fetchRedirectXRDS - reading content from URI(" + uri + ")");
        tmpXRDS = readXRDS(in);

        log.debug("fetchRedirectXRDS - got XRDS = " + tmpXRDS.toString());
      } catch (IOException e) {
        log.error("fetchRedirectXRDS - got IOException from URI " + uri);
        throw makeResolutionException(xrdsOut, query, Status.NETWORK_ERROR, "Networking error encountered");
      } catch (Exception e) {
        log.error("fetchRedirectXRDS - unexpected error: " + e);
        e.printStackTrace();
        throw makeResolutionException(xrdsOut, query, Status.AUTH_RES_ERROR, e.getMessage());
      }

      //// sanity checks
     
      // there should be exactly one child element
      if (tmpXRDS.getNumChildren() != 1 || !tmpXRDS.isXRDAt(0)) {
        throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Invalid XRDS document: single XRD element expected");
      }
     
      if (!tmpXRDS.isXRDAt(0))
        throw makeResolutionException(xrdsOut, query, Status.INVALID_XRDS, "Authority XRDS document should not contain XRDS element");

      XRD xrd = tmpXRDS.getDescriptorAt(0);
      xrdsOut.add(xrd);


      ServerStatus sstat = xrd.getServerStatus();
      Status stat;
View Full Code Here

      return xrdsOut;
  }
 

  protected XRDS readXRDS(InputStream in) throws XRIResolutionException {
    XRDS xrds = null;

    if (in == null) {
      return xrds;
    }

    // Read response into DOM structure
    try {
      log.debug("readXRDS - parsing input stream");
      DOMParser domParser = DOMUtils.getDOMParser();
      domParser.parse(new InputSource(in));
      Document doc = domParser.getDocument();
      Element element = doc.getDocumentElement();
      log.debug("readXRDS - successfully read XML document into DOM");
      xrds = new XRDS(element, true);
      log.debug("readXRDS - successfully parsed XRDS document");
    } catch (IOException e) {
      throw new XRIResolutionException("I/O error while reading XRDS document: " + e, e);
    } catch (SAXException e) {
      throw new XRIResolutionException("Invalid XRDS document: " + e, e);
View Full Code Here

TOP

Related Classes of org.openxri.xml.XRDS

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.