Exemple #1
0
 /** Sends out the raw polling log output. */
 public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
   rsp.setContentType("text/plain;charset=UTF-8");
   // Prevent jelly from flushing stream so Content-Length header can be added afterwards
   FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
   getPollingLogText().writeLogTo(0, out);
   out.close();
 }
  /**
   * Implements the progressive text handling. This method is used as a "web method" with
   * progressiveText.jelly.
   */
  public void doProgressText(StaplerRequest req, StaplerResponse rsp) throws IOException {
    setContentType(rsp);
    rsp.setStatus(HttpServletResponse.SC_OK);

    if (!source.exists()) {
      // file doesn't exist yet
      rsp.addHeader("X-Text-Size", "0");
      rsp.addHeader("X-More-Data", "true");
      return;
    }

    long start = 0;
    String s = req.getParameter("start");
    if (s != null) start = Long.parseLong(s);

    if (source.length() < start) start = 0; // text rolled over

    CharSpool spool = new CharSpool();
    long r = writeLogTo(start, spool);

    rsp.addHeader("X-Text-Size", String.valueOf(r));
    if (!completed) rsp.addHeader("X-More-Data", "true");

    Writer w = createWriter(req, rsp, r - start);
    spool.writeTo(new LineEndNormalizingWriter(w));
    w.close();
  }
Exemple #3
0
  /** Accepts submission from the configuration page. */
  @RequirePOST
  public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    checkPermission(CONFIGURE);

    description = req.getParameter("description");

    keepDependencies = req.getParameter("keepDependencies") != null;

    try {
      JSONObject json = req.getSubmittedForm();

      setDisplayName(json.optString("displayNameOrNull"));

      if (req.getParameter("logrotate") != null)
        logRotator = LogRotator.DESCRIPTOR.newInstance(req, json.getJSONObject("logrotate"));
      else logRotator = null;

      DescribableList<JobProperty<?>, JobPropertyDescriptor> t =
          new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP, getAllProperties());
      t.rebuild(
          req,
          json.optJSONObject("properties"),
          JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass()));
      properties.clear();
      for (JobProperty p : t) {
        p.setOwner(this);
        properties.add(p);
      }

      submit(req, rsp);

      save();
      ItemListener.fireOnUpdated(this);

      String newName = req.getParameter("name");
      final ProjectNamingStrategy namingStrategy = Jenkins.getInstance().getProjectNamingStrategy();
      if (newName != null && !newName.equals(name)) {
        // check this error early to avoid HTTP response splitting.
        Jenkins.checkGoodName(newName);
        namingStrategy.checkName(newName);
        rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
      } else {
        if (namingStrategy.isForceExistingJobs()) {
          namingStrategy.checkName(name);
        }
        FormApply.success(".").generateResponse(req, rsp, null);
      }
    } catch (JSONException e) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      pw.println("Failed to parse form data. Please report this problem as a bug");
      pw.println("JSON=" + req.getSubmittedForm());
      pw.println();
      e.printStackTrace(pw);

      rsp.setStatus(SC_BAD_REQUEST);
      sendError(sw.toString(), req, rsp, true);
    }
  }
Exemple #4
0
  public static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup owner)
      throws FormException, IOException, ServletException {
    String requestContentType = req.getContentType();
    if (requestContentType == null) throw new Failure("No Content-Type header set");

    boolean isXmlSubmission =
        requestContentType.startsWith("application/xml")
            || requestContentType.startsWith("text/xml");

    String name = req.getParameter("name");
    checkGoodName(name);
    if (owner.getView(name) != null)
      throw new FormException(Messages.Hudson_ViewAlreadyExists(name), "name");

    String mode = req.getParameter("mode");
    if (mode == null || mode.length() == 0) {
      if (isXmlSubmission) {
        View v;
        v = createViewFromXML(name, req.getInputStream());
        v.owner = owner;
        rsp.setStatus(HttpServletResponse.SC_OK);
        return v;
      } else throw new FormException(Messages.View_MissingMode(), "mode");
    }

    // create a view
    View v = all().findByName(mode).newInstance(req, req.getSubmittedForm());
    v.owner = owner;

    // redirect to the config screen
    rsp.sendRedirect2(req.getContextPath() + '/' + v.getUrl() + v.getPostConstructLandingPage());

    return v;
  }
Exemple #5
0
  public void doIndex(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    List<Ancestor> l = req.getAncestors();
    for (int i = l.size() - 1; i >= 0; i--) {
      Ancestor a = l.get(i);
      if (a.getObject() instanceof SearchableModelObject) {
        SearchableModelObject smo = (SearchableModelObject) a.getObject();

        SearchIndex index = smo.getSearchIndex();
        String query = req.getParameter("q");
        if (query != null) {
          SuggestedItem target = find(index, query);
          if (target != null) {
            // found
            rsp.sendRedirect2(a.getUrl() + target.getUrl());
            return;
          }
        }
      }
    }

    // no exact match. show the suggestions
    rsp.setStatus(SC_NOT_FOUND);
    req.getView(this, "search-failed.jelly").forward(req, rsp);
  }
 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();
 }
 @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>");
 }
Exemple #8
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);
  }
Exemple #9
0
 /** Generate schema. */
 public void doSchema(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   setHeaders(rsp);
   rsp.setContentType("application/xml");
   StreamResult r = new StreamResult(rsp.getOutputStream());
   new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
   r.getOutputStream().close();
 }
 /** Depending on whether the user said "yes" or "no", send him to the right place. */
 public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
   if (req.hasParameter("no")) {
     disable(true);
     rsp.sendRedirect(req.getContextPath() + "/manage");
   } else {
     rsp.sendRedirect(req.getContextPath() + "/configureSecurity");
   }
 }
Exemple #11
0
 /** Exposes the bean as JSON. */
 public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
   if (INSECURE || req.getParameter("jsonp") == null) {
     setHeaders(rsp);
     rsp.serveExposedBean(req, bean, Flavor.JSON);
   } else {
     rsp.sendError(
         HttpURLConnection.HTTP_FORBIDDEN,
         "jsonp forbidden; can use -Dhudson.model.Api.INSECURE=true if you run without security");
   }
 }
Exemple #12
0
  /**
   * Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList' or
   * throws an exception if it fails.
   */
  public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    acl.checkPermission(Job.CREATE);

    TopLevelItem result;

    String requestContentType = req.getContentType();
    if (requestContentType == null) throw new Failure("No Content-Type header set");

    boolean isXmlSubmission =
        requestContentType.startsWith("application/xml")
            || requestContentType.startsWith("text/xml");

    String name = req.getParameter("name");
    if (name == null) throw new Failure("Query parameter 'name' is required");

    { // check if the name looks good
      Jenkins.checkGoodName(name);
      name = name.trim();
      if (parent.getItem(name) != null) throw new Failure(Messages.Hudson_JobAlreadyExists(name));
    }

    String mode = req.getParameter("mode");
    if (mode != null && mode.equals("copy")) {
      String from = req.getParameter("from");

      // resolve a name to Item
      Item src = null;
      if (!from.startsWith("/")) src = parent.getItem(from);
      if (src == null) src = Jenkins.getInstance().getItemByFullName(from);

      if (src == null) {
        if (Util.fixEmpty(from) == null) throw new Failure("Specify which job to copy");
        else throw new Failure("No such job: " + from);
      }
      if (!(src instanceof TopLevelItem)) throw new Failure(from + " cannot be copied");

      result = copy((TopLevelItem) src, name);
    } else {
      if (isXmlSubmission) {
        result = createProjectFromXML(name, req.getInputStream());
        rsp.setStatus(HttpServletResponse.SC_OK);
        return result;
      } else {
        if (mode == null) throw new Failure("No mode given");

        // create empty job and redirect to the project config screen
        result = createProject(Items.all().findByName(mode), name, true);
      }
    }

    rsp.sendRedirect2(redirectAfterCreateItem(req, result));
    return result;
  }
Exemple #13
0
 public void doIndex(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   URLConnection con = connect();
   // since we end up redirecting users to jnlpJars/foo.jar/, set the content disposition
   // so that browsers can download them in the right file name.
   // see http://support.microsoft.com/kb/260519 and
   // http://www.boutell.com/newfaq/creating/forcedownload.html
   rsp.setHeader("Content-Disposition", "attachment; filename=" + fileName);
   InputStream in = con.getInputStream();
   rsp.serveFile(req, in, con.getLastModified(), con.getContentLength(), "*.jar");
   in.close();
 }
    @WebMethod(name = "heapdump.hprof")
    public void doHeapDump(StaplerRequest req, StaplerResponse rsp)
        throws IOException, InterruptedException {
      owner.checkPermission(Jenkins.RUN_SCRIPTS);
      rsp.setContentType("application/octet-stream");

      FilePath dump = obtain();
      try {
        dump.copyTo(rsp.getCompressedOutputStream(req));
      } finally {
        dump.delete();
      }
    }
 private void redirectToBuildPage(StaplerResponse res, Run build) {
   if (build != null) {
     try {
       res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getUrl());
     } catch (IOException e) {
       try {
         res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
       } catch (IOException e1) {
         e1.printStackTrace();
       }
     }
   }
 }
Exemple #16
0
  /** Deletes this user from Hudson. */
  public void doDoDelete(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    requirePOST();
    checkPermission(Hudson.ADMINISTER);
    if (id.equals(Hudson.getAuthentication().getName())) {
      rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot delete self");
      return;
    }

    delete();

    rsp.sendRedirect2("../..");
  }
  /**
   * @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();
  }
Exemple #18
0
  public static void adminCheck(
      StaplerRequest req, StaplerResponse rsp, Object required, Permission permission)
      throws IOException, ServletException {
    // this is legacy --- all views should be eventually converted to
    // the permission based model.
    if (required != null && !Hudson.adminCheck(req, rsp)) {
      // check failed. commit the FORBIDDEN response, then abort.
      rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
      rsp.getOutputStream().close();
      throw new ServletException("Unauthorized access");
    }

    // make sure the user owns the necessary permission to access this page.
    if (permission != null) checkPermission(permission);
  }
  // Called when we click on "release resource" button
  public void doFreeResource(
      StaplerRequest res, StaplerResponse rsp, @QueryParameter("resourceName") String resourceName)
      throws IOException, InterruptedException {

    // For each resource
    for (RessourcesMonitor rm : list) {
      // Check if the resource is the one chosen by the user
      if (rm.getRessource().equals(resourceName) && rm.getBuild()) {

        // Get the Id by resource name
        DefaultIdType p = new DefaultIdType(resourceName);
        // "null" for params not used
        // Only used to get the Id
        Id i = p.allocate(false, null, CriticalBlockStart.pam, null, null);

        // Cleanup only if the job is currently using the resource
        // So we get the name of the job that uses the resource and we look in the list
        AbstractBuild get = IdAllocationManager.ids.get(resourceName);
        if (get != null) {
          if (get.getProject().getName().equals(rm.getJobName())) {
            // Release resource
            i.cleanUp();
          }
        }
      }
    }
    // Redirectsto the administration panel
    rsp.sendRedirect(res.getContextPath() + getUrlName());
  }
Exemple #20
0
  /** Accepts submission from the configuration page. */
  public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    checkPermission(Hudson.ADMINISTER);

    fullName = req.getParameter("fullName");
    description = req.getParameter("description");

    JSONObject json = req.getSubmittedForm();

    List<UserProperty> props = new ArrayList<UserProperty>();
    int i = 0;
    for (UserPropertyDescriptor d : UserProperty.all()) {
      UserProperty p = getProperty(d.clazz);

      JSONObject o = json.optJSONObject("userProperty" + (i++));
      if (o != null) {
        if (p != null) {
          p = p.reconfigure(req, o);
        } else {
          p = d.newInstance(req, o);
        }
        p.setUser(this);
      }

      if (p != null) props.add(p);
    }
    this.properties = props;

    save();

    rsp.sendRedirect(".");
  }
  /**
   * Saves the form to the configuration and disk.
   *
   * @param req StaplerRequest
   * @param rsp StaplerResponse
   * @throws ServletException if something unfortunate happens.
   * @throws IOException if something unfortunate happens.
   * @throws InterruptedException if something unfortunate happens.
   */
  public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws ServletException, IOException, InterruptedException {
    getProject().checkPermission(AbstractProject.BUILD);
    if (isRebuildAvailable()) {
      if (!req.getMethod().equals("POST")) {
        // show the parameter entry form.
        req.getView(this, "index.jelly").forward(req, rsp);
        return;
      }
      build = req.findAncestorObject(AbstractBuild.class);
      ParametersDefinitionProperty paramDefProp =
          build.getProject().getProperty(ParametersDefinitionProperty.class);
      List<ParameterValue> values = new ArrayList<ParameterValue>();
      ParametersAction paramAction = build.getAction(ParametersAction.class);
      JSONObject formData = req.getSubmittedForm();
      if (!formData.isEmpty()) {
        JSONArray a = JSONArray.fromObject(formData.get("parameter"));
        for (Object o : a) {
          JSONObject jo = (JSONObject) o;
          String name = jo.getString("name");
          ParameterValue parameterValue =
              getParameterValue(paramDefProp, name, paramAction, req, jo);
          if (parameterValue != null) {
            values.add(parameterValue);
          }
        }
      }

      CauseAction cause = new CauseAction(new RebuildCause(build));
      Hudson.getInstance()
          .getQueue()
          .schedule(build.getProject(), 0, new ParametersAction(values), cause);
      rsp.sendRedirect("../../");
    }
  }
Exemple #22
0
 /**
  * Deletes this item.
  * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete}
  * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page
  * which should now be unused by core but is left in case plugins are still using it.
  */
 @CLIMethod(name="delete-job")
 @RequirePOST
 public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
     delete();
     if (rsp != null) // null for CLI
         rsp.sendRedirect2(req.getContextPath()+"/"+getParent().getUrl());
 }
Exemple #23
0
  /** Clears the error status. */
  public synchronized void doClearError(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    getACL().checkPermission(getPermission());

    if (workerThread != null && !workerThread.isRunning()) workerThread = null;
    rsp.sendRedirect(".");
  }
Exemple #24
0
  public void doReturn(StaplerRequest request, StaplerResponse rsp) throws IOException {
    try {
      // --- processing the authentication response

      // extract the parameters from the authentication response
      // (which comes in as a HTTP request from the OpenID provider)
      ParameterList responselist = new ParameterList(request.getParameterMap());

      // extract the receiving URL from the HTTP request
      StringBuffer receivingURL = request.getRequestURL();
      String queryString = request.getQueryString();
      if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(request.getQueryString());

      // verify the response
      VerificationResult verification =
          manager.verify(receivingURL.toString(), responselist, discovered);

      // examine the verification result and extract the verified identifier
      Identifier verified = verification.getVerifiedId();
      if (verified != null) {
        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

        openid = authSuccess.getIdentity();
        claimedOpenid = authSuccess.getClaimed();
        rsp.sendRedirect(".");
      } else {
        throw HttpResponses.error(500, "Failed to login");
      }
    } catch (OpenIDException e) {
      throw new Error(e);
    }
  }
 /** Schedules a new build. */
 public void doBuild(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   if (!getTarget().hasPermission(Promotion.PROMOTE)) return;
   getProcess().scheduleBuild(getTarget(), new UserCause());
   // TODO: we need better visual feed back so that the user knows that the build happened.
   rsp.forwardToPreviousPage(req);
 }
 /**
  * Redirects the index page to the last result.
  *
  * @param request Stapler request
  * @param response Stapler response
  * @throws IOException in case of an error
  */
 public void doIndex(final StaplerRequest request, final StaplerResponse response)
     throws IOException {
   AbstractBuild<?, ?> build = getLastFinishedBuild();
   if (build != null) {
     response.sendRedirect2(String.format("../%d/%s", build.getNumber(), resultUrl));
   }
 }
  /** Web method to handle the approval action submitted by the user. */
  public void doApprove(
      StaplerRequest req,
      StaplerResponse rsp,
      @AncestorInPath PromotionProcess promotionProcess,
      @AncestorInPath AbstractBuild<?, ?> build)
      throws IOException, ServletException {

    JSONObject formData = req.getSubmittedForm();

    if (canApprove(promotionProcess, build)) {
      List<ParameterValue> paramValues = new ArrayList<ParameterValue>();

      if (parameterDefinitions != null && !parameterDefinitions.isEmpty()) {
        JSONArray a = JSONArray.fromObject(formData.get("parameter"));

        for (Object o : a) {
          JSONObject jo = (JSONObject) o;
          String name = jo.getString("name");

          ParameterDefinition d = getParameterDefinition(name);
          if (d == null)
            throw new IllegalArgumentException("No such parameter definition: " + name);

          paramValues.add(d.createValue(req, jo));
        }
      }
      approve(build, promotionProcess, paramValues);
    }

    rsp.sendRedirect2("../../../..");
  }
Exemple #28
0
  /** Used by search box auto-completion. Returns JSON array. */
  public void doSuggest(StaplerRequest req, StaplerResponse rsp, @QueryParameter String query)
      throws IOException, ServletException {
    Result r = new Result();
    for (SuggestedItem item : getSuggestions(req, query))
      r.suggestions.add(new Item(item.getPath()));

    rsp.serveExposedBean(req, r, Flavor.JSON);
  }
Exemple #29
0
  @Override
  public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    checkPermission(Hudson.ADMINISTER);

    Hudson.getInstance().setSystemMessage(req.getParameter("description"));
    rsp.sendRedirect(".");
  }
  public void doGraph(StaplerRequest req, StaplerResponse rsp) throws IOException {
    if (ChartUtil.awtProblemCause != null) {
      rsp.sendRedirect2(req.getContextPath() + DEFAULT_IMAGE);
      return;
    }

    getGraph().doPng(req, rsp);
  }