/** 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("../../../..");
  }
  /** Gets the {@link ParameterDefinition} of the given name, if any. */
  public ParameterDefinition getParameterDefinition(String name) {
    if (parameterDefinitions == null) {
      return null;
    }

    for (ParameterDefinition pd : parameterDefinitions) if (pd.getName().equals(name)) return pd;

    return null;
  }
 private ArrayList<ParameterValue> getDefaultBuildParameters() {
   ArrayList<ParameterValue> values = new ArrayList<ParameterValue>();
   ParametersDefinitionProperty property = project.getProperty(ParametersDefinitionProperty.class);
   if (property != null) {
     for (ParameterDefinition pd : property.getParameterDefinitions()) {
       values.add(pd.getDefaultParameterValue());
     }
   }
   return values;
 }
  public List<ParameterValue> createDefaultValues() {
    List<ParameterValue> paramValues = new ArrayList<ParameterValue>();

    if (parameterDefinitions != null && !parameterDefinitions.isEmpty()) {
      for (ParameterDefinition d : parameterDefinitions) {
        paramValues.add(d.getDefaultParameterValue());
      }
    }
    return paramValues;
  }
Ejemplo n.º 5
0
  /**
   * Actually build a project, passing in parameters where appropriate
   *
   * @param project
   * @return
   */
  protected final boolean performBuildProject(AbstractProject<?, ?> project) {
    if (!project.hasPermission(AbstractProject.BUILD)) {
      LOGGER.log(Level.WARNING, "Insufficient permission to build job '" + project.getName() + "'");
      return false;
    }

    if (action.equals(BuildAction.POLL_SCM)) {
      project.schedulePolling();
      return true;
    }

    // no user parameters provided, just build it
    if (param == null) {
      project.scheduleBuild(new Cause.UserIdCause());
      return true;
    }

    ParametersDefinitionProperty pp =
        (ParametersDefinitionProperty) project.getProperty(ParametersDefinitionProperty.class);

    // project does not except any parameters, just build it
    if (pp == null) {
      project.scheduleBuild(new Cause.UserIdCause());
      return true;
    }

    List<ParameterDefinition> parameterDefinitions = pp.getParameterDefinitions();
    List<ParameterValue> values = new ArrayList<ParameterValue>();

    for (ParameterDefinition paramDef : parameterDefinitions) {

      if (!(paramDef instanceof StringParameterDefinition)) {
        // TODO add support for other parameter types
        values.add(paramDef.getDefaultParameterValue());
        continue;
      }

      StringParameterDefinition stringParamDef = (StringParameterDefinition) paramDef;
      ParameterValue value;

      // Did user supply this parameter?
      if (param.containsKey(paramDef.getName())) {
        value = stringParamDef.createValue(param.get(stringParamDef.getName()));
      } else {
        // No, then use the default value
        value = stringParamDef.createValue(stringParamDef.getDefaultValue());
      }

      values.add(value);
    }

    Jenkins.getInstance().getQueue().schedule(pp.getOwner(), 1, new ParametersAction(values));
    return true;
  }
  private static ParametersAction getDefaultParameters(AbstractProject<?, ?> project) {
    ParametersDefinitionProperty property = project.getProperty(ParametersDefinitionProperty.class);
    if (property == null) {
      return null;
    }

    List<ParameterValue> parameters = new ArrayList<ParameterValue>();
    for (ParameterDefinition pd : property.getParameterDefinitions()) {
      ParameterValue param = pd.getDefaultParameterValue();
      if (param != null) parameters.add(param);
    }

    return new ParametersAction(parameters);
  }
  public static InheritanceParametersDefinitionProperty createMerged(
      ParametersDefinitionProperty prior, ParametersDefinitionProperty latter) {
    // Determining which owner to use for the new merge.
    // It needs to be an InheritanceProject!
    InheritanceProject newOwner = null;
    ParametersDefinitionProperty[] pdps = {latter, prior};

    for (ParametersDefinitionProperty pdp : pdps) {
      if (pdp.getOwner() != null && pdp.getOwner() instanceof InheritanceProject) {
        newOwner = (InheritanceProject) pdp.getOwner();
        break;
      }
    }

    // Then, we merge their ParameterDefinitions based on their name
    HashMap<String, ParameterDefinition> unifyMap = new HashMap<String, ParameterDefinition>();
    for (int i = pdps.length - 1; i >= 0; i--) {
      ParametersDefinitionProperty pdp = pdps[i];
      for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
        unifyMap.put(pd.getName(), pd);
      }
    }
    List<ParameterDefinition> unifyList = new LinkedList<ParameterDefinition>(unifyMap.values());

    // With that, we create a new IPDP
    InheritanceParametersDefinitionProperty out =
        new InheritanceParametersDefinitionProperty(newOwner, unifyList);

    // At the end, we merge the scoping informations
    for (int i = pdps.length - 1; i >= 0; i--) {
      ParametersDefinitionProperty pdp = pdps[i];

      if (pdp instanceof InheritanceParametersDefinitionProperty) {
        // We deal with an already inherited parameter; so we need to
        // copy the scope exactly.
        InheritanceParametersDefinitionProperty ipdp =
            (InheritanceParametersDefinitionProperty) pdp;
        for (ScopeEntry scope : ipdp.getAllScopedParameterDefinitions()) {
          out.addScopedParameterDefinitions(scope);
        }
      } else {
        // No inheritance means the scope is fully local
        String ownerName = (pdp.getOwner() != null) ? pdp.getOwner().getName() : "";
        out.addScopedParameterDefinitions(ownerName, pdp.getParameterDefinitions());
      }
    }

    return out;
  }
 /** Do our best to get the value out. There might be a better way to do this. */
 protected String getStringValue(ParameterDefinition definition) {
   if (definition instanceof ChoiceParameterDefinition) {
     return ((ChoiceParameterDefinition) definition).getChoicesText();
   } else {
     ParameterValue value = definition.getDefaultParameterValue();
     return getStringValue(value);
   }
 }
 @SuppressWarnings("unchecked")
 protected boolean matchesDefaultValue(Job job) {
   ParametersDefinitionProperty property =
       (ParametersDefinitionProperty) job.getProperty(ParametersDefinitionProperty.class);
   if (property != null) {
     List<ParameterDefinition> defs = property.getParameterDefinitions();
     for (ParameterDefinition def : defs) {
       boolean multiline = isValueMultiline(def);
       String svalue = getStringValue(def);
       boolean matches = matchesParameter(def.getName(), svalue, multiline, def.getDescription());
       if (matches) {
         return true;
       }
     }
   }
   return false;
 }
 public void addScopedParameterDefinitions(String owner, Collection<ParameterDefinition> pds) {
   for (ParameterDefinition pd : pds) {
     String pdName = pd.getName();
     this.scopeLock.writeLock().lock();
     try {
       List<ScopeEntry> lst = fullScope.get(pdName);
       if (lst == null) {
         lst = new LinkedList<ScopeEntry>();
         lst.add(new ScopeEntry(owner, pd));
         fullScope.put(pdName, lst);
       } else {
         lst.add(new ScopeEntry(owner, pd));
       }
     } finally {
       this.scopeLock.writeLock().unlock();
     }
   }
 }
 public String toString() {
   StringBuilder b = new StringBuilder();
   b.append('[');
   b.append(owner);
   b.append(", ");
   b.append(param.toString());
   b.append(']');
   return b.toString();
 }
Ejemplo n.º 12
0
  /*
   * 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;
  }
  /** {@inheritDoc} */
  public void _doBuild(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    if (!req.getMethod().equals("POST")) {
      // show the parameter entry form.
      req.getView(this, "index.jelly").forward(req, rsp);
      return;
    }

    List<ParameterValue> values = new ArrayList<ParameterValue>();

    JSONObject formData = req.getSubmittedForm();
    JSONArray a = JSONArray.fromObject(formData.get("parameter"));

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

        ParameterDefinition d = getParameterDefinition(name);
        if (d == null) throw new IllegalArgumentException("No such parameter definition: " + name);
        ParameterValue parameterValue = d.createValue(req, jo);
        values.add(parameterValue);
      }
    }

    TimeDuration delay =
        (req.hasParameter("delay"))
            ? TimeDuration.fromString(req.getParameter("delay"))
            : new TimeDuration(0);

    Jenkins.getInstance()
        .getQueue()
        .schedule(
            owner,
            (int) delay.as(TimeUnit.SECONDS),
            new ParametersAction(values),
            new CauseAction(new Cause.UserIdCause()),
            new VersioningAction(this.getVersioningMap()));

    // Send the user back to the job page, except if "rebuildNoRedirect" is set
    if (req.getAttribute("rebuildNoRedirect") == null) {
      rsp.sendRedirect(".");
    }
  }
 @Override
 public ManualCondition newInstance(StaplerRequest req, JSONObject formData)
     throws FormException {
   ManualCondition instance = new ManualCondition();
   instance.users = formData.getString("users");
   instance.parameterDefinitions =
       Descriptor.newInstancesFromHeteroList(
           req, formData, "parameters", ParameterDefinition.all());
   return instance;
 }
  public void buildWithParameters(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    List<ParameterValue> values = new ArrayList<ParameterValue>();
    for (ParameterDefinition d : this.getParameterDefinitions()) {
      ParameterValue value = d.createValue(req);
      if (value != null) {
        values.add(value);
      }
    }

    CauseAction buildCause = null;
    if (owner instanceof InheritanceProject) {
      buildCause = ((InheritanceProject) owner).getBuildCauseOverride(req);
    } else {
      buildCause = new CauseAction(new Cause.UserIdCause());
    }

    TimeDuration delay =
        (req.hasParameter("delay"))
            ? TimeDuration.fromString(req.getParameter("delay"))
            : new TimeDuration(0);

    Jenkins.getInstance()
        .getQueue()
        .schedule(
            owner,
            (int) delay.as(TimeUnit.SECONDS),
            new ParametersAction(values),
            buildCause,
            new VersioningAction(this.getVersioningMap()));

    if (requestWantsJson(req)) {
      rsp.setContentType("application/json");
      rsp.serveExposedBean(req, owner, Flavor.JSON);
    } else {
      // send the user back to the job top page.
      rsp.sendRedirect(".");
    }
  }
Ejemplo n.º 16
0
 /**
  * Method for getting the ParameterValue instance from ParameterDefinition or ParamterAction.
  *
  * @param paramDefProp ParametersDefinitionProperty
  * @param parameterName Name of the Parameter.
  * @param paramAction ParametersAction
  * @param req StaplerRequest
  * @param jo JSONObject
  * @return ParameterValue instance of subclass of ParameterValue
  */
 public ParameterValue getParameterValue(
     ParametersDefinitionProperty paramDefProp,
     String parameterName,
     ParametersAction paramAction,
     StaplerRequest req,
     JSONObject jo) {
   ParameterDefinition paramDef;
   // this is normal case when user try to rebuild a parameterized job.
   if (paramDefProp != null) {
     paramDef = paramDefProp.getParameterDefinition(parameterName);
     if (paramDef != null) {
       // The copy artifact plugin throws an exception when using createValue(req, jo)
       // If the parameter comes from the copy artifact plugin, then use the single argument
       // createValue
       if (jo.toString().contains("BuildSelector")
           || jo.toString().contains("WorkspaceSelector")) {
         SimpleParameterDefinition parameterDefinition =
             (SimpleParameterDefinition) paramDefProp.getParameterDefinition(parameterName);
         return parameterDefinition.createValue(jo.getString("value"));
       }
       return paramDef.createValue(req, jo);
     }
   }
   /*
    * when user try to rebuild a build that was invoked by
    * parameterized trigger plugin in that case ParameterDefinition
    * is null for that parametername that is paased by parameterize
    * trigger plugin,so for handling that scenario, we need to
    * create an instance of that specific ParameterValue with
    * passed parameter value by form.
    *
    * In contrast to all other parameterActions, ListSubversionTagsParameterValue uses "tag" instead of "value"
    */
   if (jo.containsKey("value")) {
     return cloneParameter(paramAction.getParameter(parameterName), jo.getString("value"));
   } else {
     return cloneParameter(paramAction.getParameter(parameterName), jo.getString("tag"));
   }
 }
Ejemplo n.º 17
0
  /*
   * Convert an individual Hudson parameter definition to an OSLC Property.
   */
  private Property toProperty(StaplerRequest request, ParameterDefinition def)
      throws URISyntaxException {
    Property prop = new Property();
    prop.setName(def.getName());
    prop.setDescription(def.getDescription());

    if (def instanceof BooleanParameterDefinition) {
      prop.setValueType(new URI(XSDDatatype.XSDboolean.getURI()));
    } else if (def instanceof StringParameterDefinition
        || def instanceof PasswordParameterDefinition) {
      prop.setValueType(new URI(XSDDatatype.XSDstring.getURI()));
    } else if (def instanceof ChoiceParameterDefinition) {
      prop.setValueType(new URI(XSDDatatype.XSDstring.getURI()));
      ChoiceParameterDefinition choices = (ChoiceParameterDefinition) def;
      prop.setAllowedValuesCollection(choices.getChoices());
    }
    // TODO: Other types?

    ParameterValue defaultValue = def.getDefaultParameterValue();
    if (defaultValue == null) {
      prop.setOccurs(Occurs.ExactlyOne);
    } else {
      prop.setOccurs(Occurs.ZeroOrOne);
      if (!defaultValue.isSensitive()) {
        if (defaultValue instanceof BooleanParameterValue) {
          BooleanParameterValue bool = (BooleanParameterValue) defaultValue;
          prop.setDefaultValue(bool.value);
        } else if (defaultValue instanceof StringParameterValue) {
          StringParameterValue str = (StringParameterValue) defaultValue;
          prop.setDefaultValue(str.value);
        }
        // TODO: Other types?
      }
    }

    return prop;
  }
Ejemplo n.º 18
0
 public static List<ParameterDescriptor> getParameterDescriptors() {
   return ParameterDefinition.all();
 }