Package org.w3c.jigsaw.http

Examples of org.w3c.jigsaw.http.Reply


  Request request = (Request) req;
  PipedInputStream pis = null;

  if (wrapper == null) {
      Reply reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent("Servlet Wrapper Frame not configured properly: "+
           "must be attached to a ServletWrapper.");
      throw new HTTPException(reply);
  }

  try {
      wrapper.checkServlet();
  } catch (ClassNotFoundException ex) {
      Reply reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent("The server was unable to find the "+
           "servlet class : "+ex.getMessage());
      if ( wrapper.debug )
    ex.printStackTrace();
      throw new HTTPException(reply);
  } catch (ServletException ex) {
      Reply reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent("The server was unable to initialize the "+
           "servlet : "+ex.getMessage());
      if ( wrapper.debug )
    ex.printStackTrace();
      throw new HTTPException(reply);
  }

  // Check that the servlet has been initialized properly:
  if ( ! wrapper.isInited() ) {
      Reply reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent("Servlet not configured properly");
      throw new HTTPException(reply);
  }
  // Dispatch the request:
  Reply reply = createDefaultReply(request, HTTP.OK);
  reply.setContentType(MimeType.TEXT_HTML);
  try {
      if (request.hasState(JigsawHttpServletResponse.INCLUDED)) {
    wrapper.service(request, reply);
      } else {
    pis = new PipedInputStream();
    request.setState(JigsawHttpServletResponse.STREAM, pis);
    PipedOutputStream pos = new PipedOutputStream(pis);
    reply.setState(JigsawHttpServletResponse.STREAM, pos);
    reply.setStream(pis);
    Object o = new Object();
    reply.setState(JigsawHttpServletResponse.MONITOR, o);
    // wait until the reply is constructed by the processing thread
    ServerInterface server = getServer();
    if (server instanceof httpd) {
        synchronized (o) {
      wrapper.service(request, reply);
      o.wait((long)((httpd)server).getRequestTimeOut());
        }
        Object strm;
        strm = reply.getState(JigsawHttpServletResponse.STREAM);
        if (strm != null) {
      // it is a timeout
      try {
          pis.close();
          pos.close();
      } catch (IOException ex) {};
      if (strm instanceof PipedOutputStream) {
          ServletWrapper.ServletRunner r;
          r = (ServletWrapper.ServletRunner)
                 reply.getState(ServletWrapper.RUNNER);
          if (r != null) {
        r.signalTimeout();
          }
          throw new ServletException("Timed out");
      }
        }
    } else {
        synchronized (o) {
      wrapper.service(request, reply);
      o.wait();
        }
    }
      }
  } catch (UnavailableException uex) {
       reply = request.makeReply(HTTP.SERVICE_UNAVAILABLE);
       if (uex.isPermanent()) {
     reply.setContent("<h2>The servlet is permanently "+
          "unavailable :</h2>"+
          "Details: <b>"+uex.getMessage()+"</b>");
       } else {
     int delay = uex.getUnavailableSeconds();
     if (delay > 0) {
         reply.setRetryAfter(delay);
         reply.setContent("<h2>The servlet is temporarily "+
              "unavailable :</h2>"+
              "Delay : "+delay+
              " seconds<br><br>Details: <b>"+
              uex.getMessage()+"</b>");
     } else {
         reply.setContent("<h2>The servlet is temporarily "+
              "unavailable :</h2>"+
              "Details: <b>"+uex.getMessage()+"</b>");
     }
       }
       if (pis != null) {
     try {
         pis.close();
     } catch (IOException ioex) {}
       }
  } catch (Exception ex) {
      if ( wrapper.debug )
    ex.printStackTrace();
      reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent("Servlet has thrown exception:" + ex.toString());
      if (pis != null) {
    try {
        pis.close();
    } catch (IOException ioex) {}
      }
  }
  if (reply != null) {
      reply.setDynamic(true);
  }
  return reply;
    }
View Full Code Here


  }
 
  //do nothing more with this reply
  jres.getReply().setStatus(HTTP.DONE);

  Reply reply = null;
  try {
      reply = (Reply) server.perform(req);
  } catch (ResourceException ex) {
      reply = req.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent(ex.getMessage());
  } catch (ProtocolException pex) {
      if (pex.hasReply())
    reply = (Reply) pex.getReply();
      else {
    reply = req.makeReply(HTTP.INTERNAL_SERVER_ERROR);
    reply.setContent(pex.getMessage());
      }
  }
  //copy reply into response...
  if (reply.hasStream()) {
      jres.getReply().setStatus(reply.getStatus());
      InputStream is = reply.openStream();
      try {
    ServletOutputStream out = jres.getOutputStream();
    byte buffer[] = new byte[512];
    int len = -1;
    while((len = is.read(buffer, 0, 512)) != -1)
View Full Code Here

      //should not occurs
  }

  jres.flushStream(false);

  Reply reply = null;
  try {
      //req.setState(CONTEXT_PATH_P, jreq.getContextPath());
      req.setState(REQUEST_URI_P, jreq.getRequestURI());
      req.setState(SERVLET_PATH_P, jreq.getServletPath());
      req.setState(PATH_INFO_P, jreq.getPathInfo());
      req.setState(QUERY_STRING_P, jreq.getQueryString());
      req.setState(JigsawHttpServletResponse.INCLUDED, Boolean.TRUE);
      reply = (Reply) server.perform(req);
  } catch (ResourceException ex) {
      reply = req.makeReply(HTTP.INTERNAL_SERVER_ERROR);
      reply.setContent(ex.getMessage());
  } catch (ProtocolException pex) {
      if (pex.hasReply())
    reply = (Reply) pex.getReply();
      else {
    reply = req.makeReply(HTTP.INTERNAL_SERVER_ERROR);
    reply.setContent(pex.getMessage());
      }
  }

  if (reply.hasStream()) {
      InputStream is = reply.openStream();
      try {
    ServletOutputStream out = jres.getOutputStream();
    byte buffer[] = new byte[512];
    int len = -1;
    while((len = is.read(buffer, 0, 512)) != -1)
View Full Code Here

  if ((name.equals("file-stamp")) || (name.equals("file-stamp")))
      comment = null;
    }

    public Reply createCommentReply(Request request, int status) {
  Reply reply = request.makeReply(status);
  updateCachedHeaders();
  reply.setContent(comment);
  reply.setContentType(getCommentType());
  reply.setVary(vary);
  if ( lastmodified != null )
      reply.setHeaderValue(Reply.H_LAST_MODIFIED, lastmodified);
  if ( contentencoding != null )
      reply.setHeaderValue(Reply.H_CONTENT_ENCODING,contentencoding);
  if ( contentlanguage != null )
      reply.setHeaderValue(Reply.H_CONTENT_LANGUAGE,contentlanguage);
  long maxage = getMaxAge();
  if ( maxage >= 0 ) {
      if (reply.getMajorVersion() >= 1 ) {
    if (reply.getMinorVersion() >= 1) {
        reply.setMaxAge((int) (maxage / 1000));
    }
    // If max-age is zero, say what you mean:
    long expires = (System.currentTimeMillis()
        + ((maxage == 0) ? -1000 : maxage));
    reply.setExpires(expires);
      }
  }
  // Set the date of the reply (round it to secs):
  reply.setDate((System.currentTimeMillis() / 1000L) * 1000L);
  reply.setETag(getComETag());
  String commenttype = getCommentType().toString();
  reply.setContentLocation(getURL(request).toExternalForm()
         + ";" + URLEncoder.encode(commenttype));
  return reply;
    }
View Full Code Here

    rr_cvsframe.unlock();
      }
  }

  public Reply createDefaultReply(Request request, int status) {
      Reply reply = super.createDefaultReply(request, status);
      HttpInteger contentlength =
    HttpFactory.makeInteger(getInt(ATTR_CONTENT_LENGTH, -1));
      reply.setHeaderValue(Reply.H_CONTENT_LENGTH, contentlength);
      return reply;
  }
View Full Code Here

  {
      try {
    try {
        checkRevisionNumber(revision);
    } catch (RevisionNumberException ex) {
        Reply error =
      request.makeReply(HTTP.BAD_REQUEST);
        error.setContent("Bad revision number : <b>"+
             ex.getMessage()+"</b>");
        return error;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        getCvsManager().revert(name, out, revision, null);
        byte content[] = out.toByteArray();
        ByteArrayInputStream in =
      new ByteArrayInputStream(content);
        this.setValue(ATTR_CONTENT_LENGTH,
          new Integer(content.length));
        Reply reply = createDefaultReply(request, HTTP.OK);
        reply.setStream(in);
        // fancy thing, we should get the content location
        // of the "real" resource...
        String req_s = request.getURL().toString();
        int first_sl = req_s.lastIndexOf((int)'/');
        int second_sl = req_s.lastIndexOf((int)'/', first_sl-1 );
        int third_sl = req_s.lastIndexOf((int)'/', second_sl-1 );
        String sub_u = req_s.substring(0, third_sl);
        reply.setContentLocation(sub_u+'/'+name);
        return reply;
    } catch (InvalidResourceException ex) {
        Reply error =
      request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
        error.setContent("CvsFrame invalid");
        return error;
    } finally {
        rr_cvsframe.unlock();
    }
      } catch (CvsException ex) {
    Reply error =
        request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
    error.setContent("Cvs operation failed : <b>"+
         ex.getMessage()+"</b>");
    return error;
      }
  }
View Full Code Here

      try {
    getResource().delete();
      } catch (MultipleLockException ex) {
    //will be deleted later...
      } finally {
    Reply reply = request.makeReply(HTTP.NOT_FOUND);
    reply.setContent ("<h1>Document not found</h1>"+
          "<p>The document "+request.getURL()+
          " has no acceptable variants "+
          "(probably deleted).");
    throw new HTTPException (reply);
      }
  }
  if ( variants.length < 2 ) {
      if ( variants.length == 0 ) {
    try {
        getResource().delete();
    } catch (MultipleLockException ex) {
        //will be deleted later...
    } finally {
        Reply reply = request.makeReply(HTTP.NOT_FOUND);
        reply.setContent ("<h1>Document not found</h1>"+
              "<p>The document "+request.getURL()+
              " has no acceptable variants "+
              "(probably deleted).");
        throw new HTTPException (reply);
    }
      } else {
    return variants[0] ;
      }
  }
  // Build a vector of variant negociation states, one per variants:
  Vector states = new Vector (variants.length) ;
  for (int i = 0 ; i < variants.length ; i++) {
      double qs = 1.0 ;
      try {
    FramedResource resource =
        (FramedResource) variants[i].unsafeLock() ;
    HTTPFrame itsframe =
        (HTTPFrame) resource.unsafeGetFrame(httpFrameClass);
    if (itsframe != null) {
        if ( itsframe.unsafeDefinesAttribute (ATTR_QUALITY) )
      qs = itsframe.unsafeGetQuality() ;
        if ( qs > REQUIRED_QUALITY )
      states.addElement(new VariantState (variants[i], qs)) ;
    }
      } catch (InvalidResourceException ex) {
    //FIXME
      } finally {
    variants[i].unlock();
      }
  }
  // Content-encoding negociation:
  if ( debug ) {
      printNegotiationState ("init:", states) ;
  }
  if ( negotiateContentEncoding (states, request) ) {
      // Remains a single acceptable variant:
      return ((VariantState) states.elementAt(0)).getResource() ;
  }
  if ( debug ) {
      printNegotiationState ("encoding:", states) ;
  }
  // Charset quality negociation:
  if ( negotiateCharsetQuality (states, request) ) {
      // Remains a single acceptable variant:
      return ((VariantState) states.elementAt(0)).getResource() ;
  }
  if ( debug ) {
      printNegotiationState ("charset:", states) ;
  }
  // Language quality negociation:
  if ( negotiateLanguageQuality (states, request) ) {
      // Remains a single acceptable variant:
      return ((VariantState) states.elementAt(0)).getResource() ;
  }
  if ( debug ) {
      printNegotiationState ("language:", states) ;
  }
  // Content-type negociation:
  if ( negotiateContentType (states, request) ) {
      // Remains a single acceptable variant:
      return ((VariantState) states.elementAt(0)).getResource() ;
  }
  if ( debug ) {
      printNegotiationState ("type:", states) ;
  }
  // If we reached this point, this means that multiple variants are
  // acceptable at this point. Keep the ones that have the best quality.
  if ( debug ) {
      printNegotiationState ("before Q selection:", states) ;
  }
  double qmax = REQUIRED_QUALITY ;

  for (int i=0; i< states.size() ; ) {
      VariantState state = (VariantState) states.elementAt(i) ;
      if ( state.getQ() > qmax ) {
    for (int j = i ; j > 0 ; j--)
        states.removeElementAt(0) ;
    qmax = state.getQ() ;
    i = 1 ;
      } else {
    if ( state.getQ() < qmax)
        states.removeElementAt(i) ;
    else
        i++;
      }
  }
  if ( debug )
      printNegotiationState ("After Q selection:", states) ;
  if ( qmax == REQUIRED_QUALITY ) {

      Reply reply = request.makeReply(HTTP.NOT_ACCEPTABLE) ;
       HtmlGenerator g = new HtmlGenerator("No acceptable");
       g.append("<P>The resource cannot be served according to the "
          + "headers sent</P>");
       reply.setStream (g) ;
      throw new HTTPException (reply) ;
  } else if ( states.size() == 1 ) {
      return ((VariantState) states.elementAt(0)).getResource() ;
  } else {
      // Respond with multiple choice (for the time being, there should
      // be a parameter to decide what to do.
      Reply reply = request.makeReply(HTTP.MULTIPLE_CHOICE) ;
      HtmlGenerator g = new HtmlGenerator ("Multiple choice for "+
             resource.getIdentifier()) ;
      g.append ("<ul>") ;
      for (int i = 0 ; i < states.size() ; i++) {
    VariantState state = (VariantState) states.elementAt(i) ;
    String name = null;
    ResourceReference rr = state.getResource();
    try {
        name = rr.unsafeLock().getIdentifier();
        g.append ("<li>"
            + "<a href=\"" + name + "\">" + name + "</a>"
            + " Q= " + state.getQ()) ;
    } catch (InvalidResourceException ex) {
        //FIXME
    } finally {
        rr.unlock();
    }
      }
      reply.setStream (g) ;
      reply.setHeaderValue(reply.H_VARY, getVary());
      throw new HTTPException (reply) ;
  }
    }
View Full Code Here

      try {
    getResource().delete();
      } catch (MultipleLockException ex) {
    //will be deleted later...
      } finally {
    Reply reply = request.makeReply(HTTP.NOT_FOUND);
    reply.setContent ("<h1>Document not found</h1>"+
          "<p>The document "+request.getURL()+
          " has no acceptable variants "+
          "(probably deleted).");
    throw new HTTPException (reply);
      }
  }
  // negotiate etag
  HttpEntityTag etag = request.getETag();
  HttpEntityTag etags[] = request.getIfMatch();
  // gather the etags
  if (etags == null && etag != null) {
      etags = new HttpEntityTag[1];
      etags[0] = etag;
  } else if (etag != null) {
      HttpEntityTag t_etags[] = new HttpEntityTag[etags.length+1];
      System.arraycopy(etags, 0, t_etags, 0, etags.length);
      t_etags[etags.length] = etag;
      etags = t_etags;
  }

  if (etags != null) {
      // yeah go for it!
      FramedResource resource;
      HttpEntityTag frametag;
      for (int i = 0 ; i < variants.length ; i++) {
    try {
        resource = (FramedResource)variants[i].unsafeLock() ;
        itsframe = (HTTPFrame)resource.getFrame(httpFrameClass);
        if (itsframe != null) {
      frametag = itsframe.getETag();
      if (frametag == null) {
          continue;
      }
      // Do we have a winner?
      try {
          for (int j=0; j<etags.length; j++)
        if(frametag.getTag().equals(etags[j].getTag()))
            return variants[i];
      } catch (NullPointerException ex) {
          // if the list of etag contains a null
          // it should never happen and the try doesn't cost
      }
        }
    } catch (InvalidResourceException ex) {
        //FIXME
    } finally {
        variants[i].unlock();
    }
      }
      // no matching variants...
      Reply reply = request.makeReply(HTTP.NOT_FOUND);
      reply.setContent ("<h1>Document not found</h1>"+
            "<p>The document "+request.getURL()+
            " has no acceptable variants "+
            "according to the ETag sent");
      throw new HTTPException (reply);
  }
  // if we are strict, don't go any further, etags
  // is the mandatory thing, otherwise PUT on the direct version
  if (getPutPolicy()) {
      Reply reply = request.makeReply(HTTP.NOT_FOUND);
      reply.setContent ("<h1>Document not found</h1>"+
            "<p>The document "+request.getURL()+
            " has no acceptable variants "+
            " for a PUT, as no ETags were sent");
      throw new HTTPException (reply);
  }
  // now filter out variants
  nb_v = variants.length;
  MimeType type = request.getContentType();
  String encodings[] = request.getContentEncoding();
  String languages[] = request.getContentLanguage();
  ResourceReference rr;

  if (type != null || encodings != null || languages != null) {
      // the request is not too bad ;)
      for (int i = 0 ; i < variants.length ; i++) {
    if (variants[i] == null)
        continue;
    rr = variants[i];
    try {
        resource = (FramedResource)rr.unsafeLock() ;
        itsframe = (HTTPFrame)resource.getFrame(httpFrameClass);
        if (itsframe == null) {
      nb_v--;
      variants[i] = null;
      continue;
        }
        // remove the non matching mime types
        if (type != null) {
      MimeType fmt = itsframe.getContentType();
      if (fmt == null || (fmt.match(type) !=
              MimeType.MATCH_SPECIFIC_SUBTYPE)) {
          nb_v--;
          variants[i] = null;
          continue;
      }
        }
        // remove the non matching languages
        if (languages != null) {
      String language = itsframe.getContentLanguage();
      nb_v--;
      variants[i] = null;
      if (language == null) {
          continue;
      }
      for (int j=0; j<languages.length; j++) {
          if (language.equals(languages[j])) {
        nb_v++;
        variants[i] = rr;
        break;
          }
      }
        }
        // remove the non matching encodings       
        if (encodings != null) {
      String encoding = itsframe.getContentEncoding();
      nb_v--;
      variants[i] = null;
      if (encoding == null) {
          continue;
      }
      for (int j=0; j<encodings.length; j++) {
          if (encoding.equals(languages[j])) {
        nb_v++;
        variants[i] = rr;
        break;
          }
      }
        }
    } catch (InvalidResourceException ex) {
        //FIXME
    } finally {
        rr.unlock();
    }
      }
      // a winner!
      if (nb_v == 1) {
    for (int i=0; i< variants.length; i++) {
        if (variants[i] != null)
      return variants[i];
    }
      }
      // no document matching
      if (nb_v <= 0 ) {
    Reply reply = request.makeReply(HTTP.NOT_FOUND);
    reply.setContent ("<h1>Document not found</h1>"+
          "<p>The document "+request.getURL()+
          " has no acceptable variants "+
          " for a PUT");
    throw new HTTPException (reply);
      }
  }
  // now we have multiple choice :(
  String name;
  Reply reply = request.makeReply(HTTP.MULTIPLE_CHOICE) ;
  HtmlGenerator g = new HtmlGenerator ("Multiple choice for "+
               resource.getIdentifier()) ;
  g.append ("<ul>") ;
  for (int i = 0 ; i < variants.length ; i++) {
      if (variants[i] != null) {
    try {
        name = variants[i].unsafeLock().getIdentifier();
        g.append ("<li>"
            + "<a href=\"" + name + "\">" +name+ "</a>");
    } catch (InvalidResourceException ex) {
        //FIXME (this should NOT happen :) )
    } finally {
        variants[i].unlock();
    }
      }
  }
  reply.setStream (g) ;
  reply.setHeaderValue(reply.H_VARY, getVary());
  throw new HTTPException (reply) ;
    }
View Full Code Here

  }

  // This should never happen: either the negotiation succeed, or the
  // negotiate method should return an error.
  if ( selected == null ) {
      Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
      error.setContent("Error negotiating among resource's variants.");
      throw new HTTPException(error) ;
  }

  try {
      FramedResource resource = (FramedResource) selected.unsafeLock();
      Reply reply = (Reply)resource.perform(request) ;
      reply.setHeaderValue(reply.H_VARY, getVary());
      HTTPFrame itsframe =
    (HTTPFrame) resource.unsafeGetFrame(httpFrameClass);
      if (itsframe != null) {
    reply.setContentLocation(
          itsframe.getURL(request).toExternalForm()) ;
    return reply;
      }
      Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
      error.setContent("Error negotiating : "+
           "selected resource has no HTTPFrame");
      throw new HTTPException(error) ;
  } catch (InvalidResourceException ex) {
      Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
      error.setContent("Error negotiating : Invalid selected resource");
      throw new HTTPException(error) ;
  } finally {
      selected.unlock();
  }
    }
View Full Code Here

     */
    protected static Reply error(Request request,
         String msg,
         String details)
    {
  Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
  HtmlGenerator g = getHtmlGenerator(msg);
  g.append ("<center>");
  g.append ("[ <A HREF=\"./CVS\">Back</A> ]<hr noshade width=\"80%\">");
  g.append ("</center>");
  g.append ("<div class=\"error\"> <center><p class=\"error\">", msg,
      "</center><p>\n");
  g.append ("Details : <p><em>",details,"</em><p></div>\n");
  g.append ("<hr noshade width=\"80%\">");
  error.setStream(g);
  return error;
    }
View Full Code Here

TOP

Related Classes of org.w3c.jigsaw.http.Reply

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.