@Override
  public void createOrUpdateView(String path, String config, boolean ignoreExisting) {
    validateUpdateArgs(path, config);
    String viewBaseName = FilenameUtils.getName(path);
    Jenkins.checkGoodName(viewBaseName);
    try {
      InputStream inputStream = new ByteArrayInputStream(config.getBytes("UTF-8"));

      ItemGroup parent = lookupStrategy.getParent(build.getProject(), path);
      if (parent instanceof ViewGroup) {
        View view = ((ViewGroup) parent).getView(viewBaseName);
        if (view == null) {
          if (parent instanceof Jenkins) {
            ((Jenkins) parent).addView(createViewFromXML(viewBaseName, inputStream));
          } else if (parent instanceof Folder) {
            ((Folder) parent).addView(createViewFromXML(viewBaseName, inputStream));
          } else {
            LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass()));
          }
        } else if (!ignoreExisting) {
          view.updateByXml(new StreamSource(inputStream));
        }
      } else if (parent == null) {
        throw new DslException(format(Messages.CreateView_UnknownParent(), path));
      } else {
        LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass()));
      }
    } catch (UnsupportedEncodingException e) {
      LOGGER.log(Level.WARNING, "Unsupported encoding used in config. Should be UTF-8.");
    } catch (IOException e) {
      e.printStackTrace();
      LOGGER.log(Level.WARNING, format("Error writing config for new view %s.", path), e);
    }
  }
示例#2
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;
  }
示例#3
0
文件: Job.java 项目: neo2buha/jenkins
  /** 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);
    }
  }
  /** Creates a new log recorder. */
  @RequirePOST
  public HttpResponse doNewLogRecorder(@QueryParameter String name) {
    Jenkins.checkGoodName(name);

    logRecorders.put(name, new LogRecorder(name));

    // redirect to the config screen
    return new HttpRedirect(name + "/configure");
  }
示例#5
0
文件: View.java 项目: zlosch/jenkins
 /** Renames this view. */
 public void rename(String newName) throws Failure, FormException {
   if (name.equals(newName)) return; // noop
   checkGoodName(newName);
   if (owner.getView(newName) != null)
     throw new FormException(Messages.Hudson_ViewAlreadyExists(newName), "name");
   String oldName = name;
   name = newName;
   owner.onViewRenamed(this, oldName, newName);
 }
示例#6
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;
  }
示例#7
0
 public static boolean needsEscape(String name) {
   try {
     Jenkins.checkGoodName(name);
     // additional restricted chars
     for (int i = 0; i < name.length(); i++) {
       char ch = name.charAt(i);
       if (" ()\t\n".indexOf(ch) != -1) return true;
     }
     return false;
   } catch (Failure failure) {
     return true;
   }
 }
示例#8
0
 /**
  * Instantiate View subtype from XML stream.
  *
  * @param name Alternative name to use or <tt>null</tt> to keep the one in xml.
  */
 public static View createViewFromXML(String name, InputStream xml) throws IOException {
   InputStream in = new BufferedInputStream(xml);
   try {
     View v = (View) Jenkins.XSTREAM.fromXML(in);
     if (name != null) v.name = name;
     checkGoodName(v.name);
     return v;
   } catch (StreamException e) {
     throw new IOException("Unable to read", e);
   } catch (ConversionException e) {
     throw new IOException("Unable to read", e);
   } catch (Error e) { // mostly reflection errors
     throw new IOException("Unable to read", e);
   } finally {
     in.close();
   }
 }
示例#9
0
  /** Accepts the update to the node configuration. */
  @RequirePOST
  public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    checkPermission(CONFIGURE);

    String name = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name"));
    Jenkins.checkGoodName(name);

    Node node = getNode();
    if (node == null) {
      throw new ServletException("No such node " + nodeName);
    }
    Node result = node.reconfigure(req, req.getSubmittedForm());
    replaceBy(result);

    // take the user back to the slave top page.
    rsp.sendRedirect2("../" + result.getNodeName() + '/');
  }
示例#10
0
文件: View.java 项目: zlosch/jenkins
  public static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup owner)
      throws FormException, IOException, ServletException {
    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)
      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;
  }
  /**
   * TODO cache the <jobName,config> and then let the calling method collect the tuples, so they can
   * be saved at once. Maybe even connect to their template
   */
  @Override
  public boolean createOrUpdateConfig(String jobName, String config, boolean ignoreExisting)
      throws JobNameNotProvidedException, JobConfigurationMissingException {

    LOGGER.log(Level.INFO, String.format("createOrUpdateConfig for %s", jobName));
    boolean created = false;

    validateUpdateArgs(jobName, config);

    AbstractProject<?, ?> project =
        (AbstractProject<?, ?>) Jenkins.getInstance().getItemByFullName(jobName);
    Jenkins.checkGoodName(jobName);

    if (project == null) {
      created = createNewJob(jobName, config);
    } else if (!ignoreExisting) {
      created = updateExistingJob(project, config);
    }
    return created;
  }
  @Override
  public boolean createOrUpdateConfig(String path, String config, boolean ignoreExisting)
      throws NameNotProvidedException, ConfigurationMissingException {

    LOGGER.log(Level.INFO, format("createOrUpdateConfig for %s", path));
    boolean created = false;

    validateUpdateArgs(path, config);

    AbstractItem item = lookupStrategy.getItem(build.getProject(), path, AbstractItem.class);
    String jobName = FilenameUtils.getName(path);
    Jenkins.checkGoodName(jobName);

    if (item == null) {
      created = createNewItem(path, config);
    } else if (!ignoreExisting) {
      created = updateExistingItem(item, config);
    }
    return created;
  }
示例#13
0
文件: Job.java 项目: neo2buha/jenkins
  /** Renames this job. */
  @RequirePOST
  public /* not synchronized. see renameTo() */ void doDoRename(
      StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    // rename is essentially delete followed by a create
    checkPermission(CREATE);
    checkPermission(DELETE);

    String newName = req.getParameter("newName");
    Jenkins.checkGoodName(newName);

    if (isBuilding()) {
      // redirect to page explaining that we can't rename now
      rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
      return;
    }

    renameTo(newName);
    // send to the new job page
    // note we can't use getUrl() because that would pick up old name in the
    // Ancestor.getUrl()
    rsp.sendRedirect2("../" + newName);
  }