Ejemplo n.º 1
0
  /** Serves <tt>help.html</tt> from the resource of {@link #clazz}. */
  public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    String path = req.getRestOfPath();
    if (path.contains("..")) throw new ServletException("Illegal path: " + path);

    path = path.replace('/', '-');

    for (Class c = clazz; c != null; c = c.getSuperclass()) {
      RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help" + path);
      if (rd != null) { // Jelly-generated help page
        rd.forward(req, rsp);
        return;
      }

      InputStream in = getHelpStream(c, path);
      if (in != null) {
        // TODO: generalize macro expansion and perhaps even support JEXL
        rsp.setContentType("text/html;charset=UTF-8");
        String literal = IOUtils.toString(in, "UTF-8");
        rsp.getWriter()
            .println(
                Util.replaceMacro(
                    literal, Collections.singletonMap("rootURL", req.getContextPath())));
        in.close();
        return;
      }
    }
    rsp.sendError(SC_NOT_FOUND);
  }
Ejemplo n.º 2
0
 private void writeBody(StaplerResponse response, JSONObject body) throws IOException {
   response.setContentType("application/json");
   PrintWriter writer = response.getWriter();
   writer.write(body.toString());
   writer.flush();
   writer.close();
 }
Ejemplo n.º 3
0
 @Restricted(DoNotUse.class)
 public void doStatic(StaplerRequest req, StaplerResponse rsp) throws Exception {
   rsp.setContentType("text/html;charset=UTF-8");
   PrintWriter pw = rsp.getWriter();
   pw.println("<html><head><title>Jenkins Workflow Reference</title></head><body>");
   pw.println("<h1>Steps</h1>");
   for (StepDescriptor d : getStepDescriptors(false)) {
     generateStepHelp(d, pw);
   }
   pw.println("<h1>Advanced/Deprecated Steps</h1>");
   for (StepDescriptor d : getStepDescriptors(true)) {
     generateStepHelp(d, pw);
   }
   pw.println("<h1>Variables</h1>");
   for (GlobalVariable v : getGlobalVariables()) {
     pw.println("<h2><code>" + v.getName() + "</code></h2>");
     RequestDispatcher rd = req.getView(v, "help");
     if (rd != null) {
       pw.println("(help for variables not currently supported here)");
       /* TODO RequestDispatcher.include sends that content, but then closes the stream and prevents further output from appearing.
               Also ${rootURL} etc. are not set, but no idea what JellyContext to pass to Functions.initPageVariables
               Not clear how to fix these issues except by rewriting all of this to be driven from a static.jelly page.
               Also need to use new PrintWriter(new OutputStreamWriter(rsp.getOutputStream(), "UTF-8")) and pw.flush() at the end
               (cannot use getWriter since RequestDispatcher.include will call getOutputStream).
       rd.include(req, rsp);
       */
     } else {
       pw.println("(no help)");
     }
   }
   pw.println("</body></html>");
 }
Ejemplo n.º 4
0
  /**
   * @param rsp The stapler response to write the output to.
   * @throws IOException
   */
  private void writeJSON(StaplerResponse rsp, JSONObject jsonObject) throws IOException {
    rsp.setContentType("application/json");
    PrintWriter w = rsp.getWriter();

    if (jsonObject == null) {
      w.write("null");
    } else {
      w.write(jsonObject.toString());
    }

    w.flush();
    w.close();
  }
 /**
  * Check whether the "incorrect version" msg should be displayed, and returns what the currently
  * configured version is, in a json.
  */
 public void doVersionCheck(StaplerRequest req, StaplerResponse rsp, @QueryParameter String url)
     throws IOException {
   rsp.setContentType("text/plain;charset=UTF-8");
   JSONObject versionJSON = new JSONObject();
   String error_display_style = "none";
   if (!isGoodCNVersion(url)) {
     error_display_style = "inline";
   }
   versionJSON.element("error_display_style", error_display_style);
   VersionNumber version = getVersion(url);
   if (version != null) {
     versionJSON.element("version", version.toString());
   } else {
     versionJSON.element("version", "unknown");
   }
   rsp.getWriter().print(versionJSON.toString());
 }
Ejemplo n.º 6
0
 private void _errorWithMarkup(String message, String cssClass)
     throws IOException, ServletException {
   if (message == null) {
     ok();
   } else {
     response.setContentType("text/html;charset=UTF-8");
     // 1x16 spacer needed for IE since it doesn't support min-height
     response
         .getWriter()
         .print(
             "<div class="
                 + cssClass
                 + "><img src='"
                 + request.getContextPath()
                 + Hudson.RESOURCE_PATH
                 + "/images/none.gif' height=16 width=1>"
                 + message
                 + "</div>");
   }
 }
Ejemplo n.º 7
0
  /*
   * Set the correct media based on the request Accept header and marshal the
   * response. Set any common headers for all responses.
   */
  private void marshal(Object objects[]) throws IOException {
    OSLC4JMarshaller marshaller = OSLC4JContext.newInstance().createMarshaller();

    MediaType type = AcceptUtil.matchMediaType(Stapler.getCurrentRequest());
    if (type == null) {
      throw HttpResponses.status(HttpServletResponse.SC_NOT_ACCEPTABLE);
    }

    marshaller.setMediaType(type);

    StaplerResponse response = Stapler.getCurrentResponse();
    response.setCharacterEncoding("UTF-8");
    response.setHeader("OSLC-Core-Version", "2.0");
    response.setHeader("Content-Type", type.toString());
    response.setHeader("Vary", "Accept, Accept-Encoding");

    // Use WriterOutputStream since Stapler has already called response.getWriter().
    WriterOutputStream out = new WriterOutputStream(response.getWriter());
    marshaller.marshal(objects, out);
  }
Ejemplo n.º 8
0
  /** Accepts and serves the job description */
  public void doDescription(StaplerRequest req, StaplerResponse rsp) throws IOException {
    if (req.getMethod().equals("GET")) {
      // read
      rsp.setContentType("text/plain;charset=UTF-8");
      rsp.getWriter().write(Util.fixNull(this.getDescription()));
      return;
    }
    if (req.getMethod().equals("POST")) {
      checkPermission(CONFIGURE);

      // submission
      if (req.getParameter("description") != null) {
        this.setDescription(req.getParameter("description"));
        rsp.sendError(SC_NO_CONTENT);
        return;
      }
    }

    // huh?
    rsp.sendError(SC_BAD_REQUEST);
  }
  /**
   * Serve a page at this URL.
   *
   * @param request
   * @param response
   * @throws IOException
   */
  public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
    int precision = getPrecision(request);
    response.setContentType("text/plain;charset=UTF-8");
    PrintWriter writer = response.getWriter();

    TimestampsReader reader = new TimestampsReader(build);
    boolean timestampsFound = false;
    while (true) {
      List<Timestamp> timestamps = reader.read(1000);
      if (timestamps.isEmpty()) {
        break;
      }
      timestampsFound = true;
      for (Timestamp timestamp : timestamps) {
        writer.write(formatTimestamp(timestamp, precision));
      }
    }

    if (!timestampsFound) {
      writeConsoleNotes(writer, precision);
    }

    writer.flush();
  }
Ejemplo n.º 10
0
 public void doGetDot(StaplerRequest req, StaplerResponse rsp) throws IOException {
   new DOTExporter().export(rsp.getWriter(), builds);
 }
Ejemplo n.º 11
0
 /** Sends out an arbitrary HTML fragment. */
 public void respond(String html) throws IOException, ServletException {
   response.setContentType("text/html");
   response.getWriter().print(html);
 }
 protected Writer createWriter(StaplerRequest req, StaplerResponse rsp, long size)
     throws IOException {
   // when sending big text, try compression. don't bother if it's small
   if (size > 4096) return rsp.getCompressedWriter(req);
   else return rsp.getWriter();
 }
 @Override
 public void doHelp(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   rsp.getWriter().println(Messages.StillFailingTrigger_HelpText());
 }
Ejemplo n.º 14
0
  /** Exposes the bean as XML. */
  public void doXml(
      StaplerRequest req,
      StaplerResponse rsp,
      @QueryParameter String xpath,
      @QueryParameter String wrapper,
      @QueryParameter String tree,
      @QueryParameter int depth)
      throws IOException, ServletException {
    setHeaders(rsp);

    String[] excludes = req.getParameterValues("exclude");

    if (xpath == null && excludes == null) {
      // serve the whole thing
      rsp.serveExposedBean(req, bean, Flavor.XML);
      return;
    }

    StringWriter sw = new StringWriter();

    // first write to String
    Model p = MODEL_BUILDER.get(bean.getClass());
    TreePruner pruner = (tree != null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth);
    p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw));

    // apply XPath
    Object result;
    try {
      Document dom = new SAXReader().read(new StringReader(sw.toString()));

      // apply exclusions
      if (excludes != null) {
        for (String exclude : excludes) {
          List<org.dom4j.Node> list = (List<org.dom4j.Node>) dom.selectNodes(exclude);
          for (org.dom4j.Node n : list) {
            Element parent = n.getParent();
            if (parent != null) parent.remove(n);
          }
        }
      }

      if (xpath == null) {
        result = dom;
      } else {
        List list = dom.selectNodes(xpath);
        if (wrapper != null) {
          Element root = DocumentFactory.getInstance().createElement(wrapper);
          for (Object o : list) {
            if (o instanceof String) {
              root.addText(o.toString());
            } else {
              root.add(((org.dom4j.Node) o).detach());
            }
          }
          result = root;
        } else if (list.isEmpty()) {
          rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
          rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
          return;
        } else if (list.size() > 1) {
          rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
          rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size()));
          return;
        } else {
          result = list.get(0);
        }
      }

    } catch (DocumentException e) {
      LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e);
      throw new IOException2(
          "Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e);
    }

    OutputStream o = rsp.getCompressedOutputStream(req);
    try {
      if (result instanceof CharacterData
          || result instanceof String
          || result instanceof Number
          || result instanceof Boolean) {
        if (INSECURE) {
          rsp.setContentType("text/plain;charset=UTF-8");
          String text =
              result instanceof CharacterData
                  ? ((CharacterData) result).getText()
                  : result.toString();
          o.write(text.getBytes("UTF-8"));
        } else {
          rsp.sendError(
              HttpURLConnection.HTTP_FORBIDDEN,
              "primitive XPath result sets forbidden; can use -Dhudson.model.Api.INSECURE=true if you run without security");
        }
        return;
      }

      // otherwise XML
      rsp.setContentType("application/xml;charset=UTF-8");
      new XMLWriter(o).write(result);
    } finally {
      o.close();
    }
  }
Ejemplo n.º 15
0
 public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
     throws IOException, ServletException {
   rsp.setContentType("text/plain");
   rsp.getWriter().print(msg.keyValueFormEncoding());
 }
Ejemplo n.º 16
0
 XMLDataWriter(Object bean, StaplerResponse rsp) throws IOException {
   this(bean, rsp.getWriter());
 }