@Restricted(DoNotUse.class) // accessed via REST API
 public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json)
     throws Exception {
   // TODO JENKINS-31458 is there not an easier way to do this?
   JSONObject jsonO = JSONObject.fromObject(json);
   Jenkins j = Jenkins.getActiveInstance();
   Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
   StepDescriptor descriptor = (StepDescriptor) j.getDescriptor(c.asSubclass(Step.class));
   Object o;
   try {
     o = descriptor.newInstance(req, jsonO);
   } catch (RuntimeException x) { // e.g. IllegalArgumentException
     return HttpResponses.plainText(Functions.printThrowable(x));
   }
   try {
     String groovy = object2Groovy(o);
     if (descriptor.isAdvanced()) {
       String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
       groovy = "// " + warning + "\n" + groovy;
     }
     return HttpResponses.plainText(groovy);
   } catch (UnsupportedOperationException x) {
     Logger.getLogger(CpsFlowExecution.class.getName())
         .log(Level.WARNING, "failed to render " + json, x);
     return HttpResponses.plainText(x.getMessage());
   }
 }
Beispiel #2
0
  /** Accepts <tt>config.xml</tt> submission, as well as serve it. */
  @WebMethod(name = "config.xml")
  public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException {
    if (req.getMethod().equals("GET")) {
      // read
      checkPermission(READ);
      return new HttpResponse() {
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
            throws IOException, ServletException {
          rsp.setContentType("application/xml");
          // pity we don't have a handy way to clone Jenkins.XSTREAM to temp add the omit Field
          XStream2 xStream2 = new XStream2();
          xStream2.omitField(View.class, "owner");
          xStream2.toXMLUTF8(View.this, rsp.getOutputStream());
        }
      };
    }
    if (req.getMethod().equals("POST")) {
      // submission
      updateByXml((Source) new StreamSource(req.getReader()));
      return HttpResponses.ok();
    }

    // huh?
    return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod());
  }
  /** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
 /** Depending on whether the user said "examin" or "dismiss", send him to the right place. */
 public HttpResponse doAct(@QueryParameter String dismiss) throws IOException {
   if (dismiss != null) {
     disable(true);
     return HttpResponses.redirectViaContextPath("/manage");
   } else {
     return HttpResponses.redirectTo("rule/");
   }
 }
Beispiel #5
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);
    }
  }
Beispiel #6
0
 @RequirePOST
 public HttpResponse doDoUninstall() throws IOException {
   Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
   archive.delete();
   return HttpResponses.redirectViaContextPath(
       "/pluginManager/installed"); // send back to plugin manager
 }
 private boolean uriMatchesComparison(URI actual, ComparisonTerm comparison) {
   String actualString = actual.toString();
   Value value = comparison.operand();
   if (!(value instanceof UriRefValue)) {
     throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
   }
   UriRefValue uriRef = (UriRefValue) value;
   String uri = uriRef.value();
   switch (comparison.operator()) {
     case EQUALS:
       return actualString.equals(uri);
     case NOT_EQUALS:
       return !actualString.equals(uri);
     default:
       throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
   }
 }
  /*
   * Determine the Hudson parameter values from the OSLC parameter instances
   * in the AutomationRequest
   */
  private List<ParameterValue> getParameterValues(
      AbstractProject<?, ?> project, ParameterInstance[] parameters) {
    ParametersDefinitionProperty pp = project.getProperty(ParametersDefinitionProperty.class);
    if (pp == null) {
      LOG.log(Level.FINE, "Job does not take parameters: " + project.getName());
      throw HttpResponses.status(
          HttpServletResponse.SC_BAD_REQUEST); // This build is not parameterized.
    }

    HashMap<String, String> inputMap = new HashMap<String, String>();
    for (ParameterInstance param : parameters) {
      inputMap.put(param.getName(), param.getValue());
    }

    List<ParameterValue> values = new ArrayList<ParameterValue>();
    for (ParameterDefinition def : pp.getParameterDefinitions()) {
      String inputValue = inputMap.get(def.getName());
      if (inputValue == null) {
        ParameterValue defaultValue = def.getDefaultParameterValue();
        if (defaultValue == null) {
          LOG.log(
              Level.FINE, "Missing parameter " + def.getName() + " for job " + project.getName());
          throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
        }

        values.add(defaultValue);
      } else {
        if (def instanceof SimpleParameterDefinition) {
          SimpleParameterDefinition simple = (SimpleParameterDefinition) def;
          values.add(simple.createValue(inputValue));
        } else {
          LOG.log(
              Level.WARNING,
              "Unsupported parameter type with name "
                  + def.getName()
                  + " for project "
                  + project.getName());
          throw HttpResponses.status(HttpServletResponse.SC_NOT_IMPLEMENTED);
        }
      }
    }

    return values;
  }
  /*
   * Parse the where clause from the oslc.where and oslc.prefix parameters.
   */
  private WhereClause parseWhere(String where, String prefixes) {
    final Map<String, String> prefixMap;
    if (prefixes == null) {
      prefixMap = PREFIX_MAP;
    } else {
      try {
        prefixMap = QueryUtils.parsePrefixes(prefixes);
      } catch (ParseException e) {
        LOG.log(Level.FINE, "Bad oslc.prefix", e);
        throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
      }
    }

    try {
      return QueryUtils.parseWhere(where, prefixMap);
    } catch (ParseException e) {
      LOG.log(Level.FINE, "Bad oslc.where", e);
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }
  }
 private boolean uriMatches(URI actual, SimpleTerm term) {
   switch (term.type()) {
     case COMPARISON:
       return uriMatchesComparison(actual, (ComparisonTerm) term);
     case IN_TERM:
       return uriMatchesInTerm(actual, (InTerm) term);
     case NESTED:
       throw HttpResponses.status(HttpServletResponse.SC_NOT_IMPLEMENTED);
     default:
       return true;
   }
 }
Beispiel #11
0
  /** Bare-minimum configuration mechanism to change the update center. */
  public HttpResponse doSiteConfigure(@QueryParameter String site) throws IOException {
    Jenkins hudson = Jenkins.getInstance();
    hudson.checkPermission(CONFIGURE_UPDATECENTER);
    UpdateCenter uc = hudson.getUpdateCenter();
    PersistedList<UpdateSite> sites = uc.getSites();
    for (UpdateSite s : sites) {
      if (s.getId().equals(UpdateCenter.ID_DEFAULT)) sites.remove(s);
    }
    sites.add(new UpdateSite(UpdateCenter.ID_DEFAULT, site));

    return HttpResponses.redirectToContextRoot();
  }
Beispiel #12
0
 public HttpResponse doChangeOfflineCause(@QueryParameter String offlineMessage)
     throws IOException, ServletException {
   checkPermission(DISCONNECT);
   offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
   setTemporarilyOffline(
       true,
       OfflineCause.create(
           hudson.slaves.Messages._SlaveComputer_DisconnectedBy(
               Jenkins.getAuthentication().getName(),
               offlineMessage != null ? " : " + offlineMessage : "")));
   return HttpResponses.redirectToDot();
 }
Beispiel #13
0
  /** Accepts <tt>config.xml</tt> submission, as well as serve it. */
  @WebMethod(name = "config.xml")
  public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException {
    if (req.getMethod().equals("GET")) {
      // read
      checkPermission(READ);
      return new HttpResponse() {
        public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
            throws IOException, ServletException {
          rsp.setContentType("application/xml");
          View.this.writeXml(rsp.getOutputStream());
        }
      };
    }
    if (req.getMethod().equals("POST")) {
      // submission
      updateByXml(new StreamSource(req.getReader()));
      return HttpResponses.ok();
    }

    // huh?
    return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod());
  }
    private User _doCreateAccount(StaplerRequest req, StaplerResponse rsp, String formView) throws ServletException, IOException {
        if(!allowsSignup())
            throw HttpResponses.error(SC_UNAUTHORIZED,new Exception("User sign up is prohibited"));

        boolean firstUser = !hasSomeUser();
        User u = createAccount(req, rsp, enableCaptcha, formView);
        if(u!=null) {
            if(firstUser)
                tryToMakeAdmin(u);  // the first user should be admin, or else there's a risk of lock out
            loginAndTakeBack(req, rsp, u);
        }
        return u;
    }
 public HttpResponse doRestart() throws IOException, ServletException {
   validateAdmin();
   try {
     channel.call(new StopHubCallable());
   } catch (Exception e) {
     throw new IOException(e);
   }
   channel.close();
   try {
     startHub();
     waitForHubLaunch();
   } catch (Exception e) {
     throw new IOException(e);
   }
   return HttpResponses.forwardToPreviousPage();
 }
 @Override
 public HttpResponse handle(
     Item item,
     ItemGroup<?> destination,
     AtomicReference<Item> newItem,
     List<? extends RelocationHandler> chain)
     throws IOException, InterruptedException {
   if (!(destination instanceof DirectlyModifiableTopLevelItemGroup)) {
     return chain.isEmpty()
         ? null
         : chain.get(0).handle(item, destination, newItem, chain.subList(1, chain.size()));
   }
   Item result = doMove(item, (DirectlyModifiableTopLevelItemGroup) destination);
   newItem.set(result);
   // AbstractItem.getUrl does weird magic here which winds up making it redirect to the old
   // location, so inline the correct part of this method.
   return HttpResponses.redirectViaContextPath(result.getParent().getUrl() + result.getShortUrl());
 }
  private boolean uriMatchesInTerm(URI actual, InTerm in) {
    String actualString = actual.toString();

    for (Object element : in.values()) {
      Value value = (Value) element;
      if (!(value instanceof UriRefValue)) {
        throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
      }

      UriRefValue uriRef = (UriRefValue) value;
      String uri = uriRef.value();
      if (uri.equals(actualString)) {
        return true;
      }
    }

    return false;
  }
  /*
   * 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);
  }
  /** Serves resources in the class loader. */
  public void doDynamic(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    String path = req.getRestOfPath();
    if (!allowedResources.containsKey(path)) {
      if (!allowResourceToBeServed(path)) {
        rsp.sendError(SC_FORBIDDEN);
        return;
      }
      // remember URLs that we can serve. but don't remember error ones, as it might be unbounded
      allowedResources.put(path, path);
    }

    if (path.charAt(0) == '/') path = path.substring(1);
    URL res = classLoader.getResource(path);
    if (res == null) {
      throw HttpResponses.error(
          SC_NOT_FOUND, new IllegalArgumentException("No such adjunct found: " + path));
    } else {
      long expires = MetaClass.NO_CACHE ? 0 : 24L * 60 * 60 * 1000; /*1 day*/
      rsp.serveFile(req, res, expires);
    }
  }
Beispiel #20
0
 @RequirePOST
 public HttpResponse doUnpin() throws IOException {
   Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
   pinFile.delete();
   return HttpResponses.ok();
 }
 public HttpResponse doWriteLog() throws IOException {
   System.out.println("JenkowWorkflowRun.doWriteLog");
   TaskListener l = createListener();
   l.getLogger().println("Current time is " + new Date());
   return HttpResponses.redirectTo("console");
 }
  // TODO: Break up this method and clean up URL handling.
  public void doJob(StaplerRequest request, StaplerResponse response)
      throws IOException, URISyntaxException, ServletException {
    requireGET();

    MediaType type = AcceptUtil.matchMediaType(request, ACCEPTABLE);
    if (type == null) {
      throw HttpResponses.status(HttpServletResponse.SC_NOT_ACCEPTABLE);
    }

    String restOfPath = request.getRestOfPath();
    if (restOfPath == null) {
      throw HttpResponses.notFound();
    }

    // Remove leading '/'
    restOfPath = restOfPath.substring(1);
    String segments[] = restOfPath.split("/");

    // URI patterns:
    //   <job-name>
    //   <job-name>/preview
    //   <job-name>/run/<run-number>
    //   <job-name>/run/<run-number>/preview
    //   <job-name>/run/<run-number>/request

    // Find the job.
    String jobName = segments[0];
    Job<?, ?> job = getJob(jobName);
    if (job == null) {
      throw HttpResponses.notFound();
    }

    // Is it a run?
    //   <job-name>/run/<run-number>
    if (segments.length >= 3 && PATH_RUN.equals(segments[1])) {
      String runNumber = segments[2];
      int i;
      try {
        i = Integer.valueOf(Integer.parseInt(runNumber));
      } catch (NumberFormatException e) {
        throw HttpResponses.notFound();
      }

      Run<?, ?> run = job.getBuildByNumber(i);
      if (run == null) {
        throw HttpResponses.notFound();
      }

      if (segments.length == 4) {
        // Is it a run preview?
        //   <job-name>/run/<run-number>/preview
        if (PATH_PREVIEW.equals(segments[3])) {
          /*
           * See /hudson-oslc-auto/src/main/resources/hudson/model/Run/preview.jelly
           */
          response.forward(run, "preview", request);
          return;
        }

        // Is it an AutomationRequest?
        //   <job-name>/run/<run-number>/request
        if (PATH_REQUEST.equals(segments[3])) {
          AutomationRequest autoRequest = toAutomationRequest(request, job, run);
          marshal(autoRequest);
        }

        if ("buildStatus".equals(segments[3])) {
          throw HttpResponses.redirectViaContextPath(run.getUrl() + "/buildStatus");
        }
      } else if (segments.length == 3) { // <job-name>/run/<run-number>
        if (MediaType.TEXT_HTML_TYPE.isCompatible(type)) {
          throw HttpResponses.redirectViaContextPath(run.getUrl());
        }

        if (MarshallerConstants.MT_OSLC_COMPACT.isCompatible(type)) {
          handleCompact(job, run);
        } else {
          AutomationResult result = toAutomationResult(request, job, run);
          marshal(result);
        }
      } else {
        throw HttpResponses.notFound();
      }
    } else {
      // Is it a job preview?
      //   <job-name>/preview
      if (segments.length == 2 && PATH_PREVIEW.equals(segments[1])) {
        /*
         * See /hudson-oslc-auto/src/main/resources/hudson/model/Job/preview.jelly
         */
        response.forward(job, "preview", request);
        return;
      }

      if (segments.length != 1) {
        throw HttpResponses.notFound();
      }

      // Is it just a job name with no other segments?
      //   <job-name>
      if (MediaType.TEXT_HTML_TYPE.isCompatible(type)) {
        throw HttpResponses.redirectViaContextPath(job.getUrl());
      }

      if (MarshallerConstants.MT_OSLC_COMPACT.isCompatible(type)) {
        handleCompact(job);
      } else {
        AutomationPlan plan = toAutomationPlan(job);
        marshal(plan);
      }
    }
  }
Beispiel #23
0
 /**
  * Runs {@link #prevalidateConfig} on posted XML and redirects to the {@link UpdateCenter}.
  *
  * @since 1.483
  */
 @RequirePOST
 public HttpResponse doInstallNecessaryPlugins(StaplerRequest req) throws IOException {
   prevalidateConfig(req.getInputStream());
   return HttpResponses.redirectViaContextPath("updateCenter");
 }
  /*
   * Path: /auto/scheduleBuild
   *
   * POST to create automation requests to schedule builds.
   */
  public void doScheduleBuild(StaplerRequest request, StaplerResponse response) throws Exception {
    requirePOST();

    OSLC4JUnmarshaller unmarshaller = OSLC4JContext.newInstance().createUnmarshaller();

    String contentType = request.getContentType();
    if (contentType == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }
    unmarshaller.setMediaType(MediaType.valueOf(contentType));

    final AutomationRequest autoRequest =
        unmarshaller.unmarshal(request.getInputStream(), AutomationRequest.class);
    if (autoRequest == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    Link planLink = autoRequest.getExecutesAutomationPlan();
    if (planLink == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    URI planURI = planLink.getValue();
    String jobName = getJobNameFromURI(planURI);
    if (jobName == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    Job<?, ?> job = getJob(jobName);
    if (job == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (!job.isBuildable()) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (!(job instanceof AbstractProject)) {
      LOG.log(
          Level.WARNING,
          "Cannot schedule builds for jobs that don't extend AbstractProject: " + jobName);
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    AbstractProject<?, ?> project = (AbstractProject<?, ?>) job;
    int nextBuildNumber = project.getNextBuildNumber();
    Cause cause =
        new Cause() {
          @Override
          public String getShortDescription() {
            String description = autoRequest.getDescription();
            return description != null ? description : "OSLC Automation Request";
          }
        };

    ParameterInstance[] parameters = autoRequest.getInputParameters();
    boolean suceeded;
    if (parameters.length == 0) {
      suceeded = project.scheduleBuild(cause);
    } else {
      List<ParameterValue> values = getParameterValues(project, parameters);
      suceeded =
          project.scheduleBuild2(project.getQuietPeriod(), cause, new ParametersAction(values))
              != null;
    }

    if (!suceeded) {
      // Build already queued.
      LOG.log(
          Level.WARNING,
          "Automation request rejected (409 conflict) since build is already queued: " + jobName);
      throw HttpResponses.status(HttpServletResponse.SC_CONFLICT);
    }

    URI requestURI = getAutoRequestURI(job, nextBuildNumber);
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader("Location", requestURI.toString());
  }
 public HttpResponse doIndex() {
   return HttpResponses.redirectTo("rule/");
 }
 public HttpResponse doComplete() throws IOException {
   System.out.println("JenkowWorkflowRun.doComplete");
   markCompleted(Result.SUCCESS);
   return HttpResponses.redirectToDot();
 }
Beispiel #27
0
 @RequirePOST
 public HttpResponse doPin() throws IOException {
   Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
   new FileOutputStream(pinFile).close();
   return HttpResponses.ok();
 }
 private void requireMethod(String method) {
   if (!method.equals(Stapler.getCurrentRequest().getMethod())) {
     throw HttpResponses.status(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
   }
 }
Beispiel #29
0
 @RequirePOST
 public HttpResponse doMakeDisabled() throws IOException {
   Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
   disable();
   return HttpResponses.ok();
 }