/**
  * Check method to validate the authentication details
  *
  * @param request the {@link StaplerRequest}
  * @return the {@link FormValidation} result
  * @throws IOException in case of IO exceptions
  */
 public FormValidation doLoginCheck(StaplerRequest request) throws IOException {
   String url = Util.fixEmpty(request.getParameter("url"));
   if (url == null) {
     return FormValidation.ok();
   }
   JIRASite site =
       new JIRASite(
           "Login Check",
           new URL(url),
           request.getParameter("user"),
           request.getParameter("pass"),
           false,
           null,
           false);
   try {
     site.createClient();
     return FormValidation.ok();
   } catch (RemoteAuthenticationException e) {
     return FormValidation.error(e.getMessage());
   } catch (AxisFault e) {
     return FormValidation.error(e.getFaultString());
   } catch (ServiceException e) {
     return FormValidation.error(e.getMessage());
   }
 }
  private void createCommitStatus(
      AbstractBuild<?, ?> build,
      TaskListener listener,
      String message,
      GHRepository repo,
      GHCommitState state)
      throws GhprcCommitStatusException {
    GhprcCause cause = Ghprc.getCause(build);

    String sha1 = cause.getCommit();
    String url = Jenkins.getInstance().getRootUrl() + build.getUrl();
    if (!StringUtils.isEmpty(statusUrl)) {
      url = Ghprc.replaceMacros(build, listener, statusUrl);
    }
    String context = Util.fixEmpty(commitStatusContext);
    context = Ghprc.replaceMacros(build, listener, context);

    listener
        .getLogger()
        .println(
            String.format(
                "Setting status of %s to %s with url %s and message: '%s'",
                sha1, state, url, message));
    if (context != null) {
      listener.getLogger().println(String.format("Using context: " + context));
    }
    try {
      repo.createCommitStatus(sha1, state, url, message, context);
    } catch (IOException e) {
      throw new GhprcCommitStatusException(e, state, message, cause.getPullID());
    }
  }
        @Restricted(DoNotUse.class)
        public ListBoxModel doFillNetworkIdItems(@QueryParameter String networkId,
                                                 @RelativePath("..") @QueryParameter String endPointUrl,
                                                 @RelativePath("..") @QueryParameter String identity,
                                                 @RelativePath("..") @QueryParameter String credential,
                                                 @RelativePath("..") @QueryParameter String zone
        ) {

            ListBoxModel m = new ListBoxModel();
            m.add("None specified", "");

            try {
                Openstack openstack = JCloudsCloud.getOpenstack(endPointUrl, identity, credential, zone);
                for (org.openstack4j.model.network.Network network: openstack.getSortedNetworks()) {
                    m.add(String.format("%s (%s)", network.getName(), network.getId()), network.getId());
                }
                return m;
            } catch (AuthenticationException _) {
                // Incorrect credentials - noop
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
            }

            if (Util.fixEmpty(networkId) != null) {
                m.add(networkId);
            }

            return m;
        }
Esempio n. 4
0
  /**
   * Handles the configuration submission.
   *
   * <p>Load view-specific properties here.
   */
  @Override
  protected void submit(StaplerRequest req) throws ServletException, FormException, IOException {
    jobNames.clear();
    for (TopLevelItem item : Hudson.getInstance().getItems()) {
      if (req.getParameter(item.getName()) != null) jobNames.add(item.getName());
    }

    if (req.getParameter("useincluderegex") != null) {
      includeRegex = Util.nullify(req.getParameter("includeRegex"));
      if (includeRegex == null) includePattern = null;
      else includePattern = Pattern.compile(includeRegex);
    } else {
      includeRegex = null;
      includePattern = null;
    }

    if (columns == null) {
      columns = new DescribableList<ListViewColumn, Descriptor<ListViewColumn>>(Saveable.NOOP);
    }
    columns.rebuildHetero(req, req.getSubmittedForm(), ListViewColumn.all(), "columns");

    if (jobFilters == null) {
      jobFilters = new DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>>(Saveable.NOOP);
    }
    jobFilters.rebuildHetero(req, req.getSubmittedForm(), ViewJobFilter.all(), "jobFilters");

    String filter = Util.fixEmpty(req.getParameter("statusFilter"));
    statusFilter = filter != null ? "1".equals(filter) : null;
  }
            @Override
            public Details newInstance(StaplerRequest req, JSONObject formData) throws FormException {
                String pwd = Util.fixEmpty(req.getParameter("user.password"));
                String pwd2= Util.fixEmpty(req.getParameter("user.password2"));

                if(!Util.fixNull(pwd).equals(Util.fixNull(pwd2)))
                    throw new FormException("Please confirm the password by typing it twice","user.password2");

                String data = Protector.unprotect(pwd);
                if(data!=null) {
                    String prefix = Stapler.getCurrentRequest().getSession().getId() + ':';
                    if(data.startsWith(prefix))
                        return Details.fromHashedPassword(data.substring(prefix.length()));
                }
                return Details.fromPlainPassword(Util.fixNull(pwd));
            }
  public void onBuildTriggered(GhprcTrigger trigger, GhprcPullRequest pr, GHRepository ghRepository)
      throws GhprcCommitStatusException {
    StringBuilder sb = new StringBuilder();
    GHCommitState state = GHCommitState.PENDING;

    AbstractProject<?, ?> project = trigger.getActualProject();

    String context = Util.fixEmpty(commitStatusContext);
    context = Ghprc.replaceMacros(project, context);

    if (!StringUtils.isEmpty(triggeredStatus)) {
      sb.append(Ghprc.replaceMacros(project, triggeredStatus));
    } else {
      sb.append("Build triggered.");
      if (pr.isMergeable()) {
        sb.append(" sha1 is merged.");
      } else {
        sb.append(" sha1 is original commit.");
      }
    }

    String url = Ghprc.replaceMacros(project, statusUrl);

    String message = sb.toString();
    try {
      ghRepository.createCommitStatus(pr.getHead(), state, url, message, context);
    } catch (IOException e) {
      throw new GhprcCommitStatusException(e, state, message, pr.getId());
    }
  }
  public List<Workspace> call() throws Exception {
    final Server server = createServer();
    final MockableVersionControlClient vcc = server.getVersionControlClient();
    final TaskListener listener = server.getListener();
    final PrintStream logger = listener.getLogger();

    final String listWorkspacesMessage = String.format(ListingWorkspacesTemplate, server.getUrl());
    logger.println(listWorkspacesMessage);

    final com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace[] sdkWorkspaces =
        vcc.queryWorkspaces(
            null, null, Util.fixEmpty(computer), WorkspacePermissions.NONE_OR_NOT_SUPPORTED);

    final List<Workspace> result = new ArrayList<Workspace>(sdkWorkspaces.length);
    for (final com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace sdkWorkspace :
        sdkWorkspaces) {
      final String name = sdkWorkspace.getName();
      final String computer = sdkWorkspace.getComputer();
      final String ownerName = sdkWorkspace.getOwnerName();
      final String comment = Util.fixNull(sdkWorkspace.getComment());

      final Workspace workspace = new Workspace(name, computer, ownerName, comment);
      result.add(workspace);
    }

    log(result, logger);

    return result;
  }
 @DataBoundConstructor
 public ScriptTrigger(
     String cronTabSpec,
     LabelRestrictionClass labelRestriction,
     boolean enableConcurrentBuild,
     String script,
     String scriptFilePath,
     String exitCode)
     throws ANTLRException {
   super(
       cronTabSpec,
       (labelRestriction == null) ? false : true,
       (labelRestriction == null) ? null : labelRestriction.getTriggerLabel(),
       enableConcurrentBuild);
   this.script = Util.fixEmpty(script);
   this.scriptFilePath = Util.fixEmpty(scriptFilePath);
   this.exitCode = Util.fixEmpty(exitCode);
 }
Esempio n. 9
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;
  }
Esempio n. 10
0
 /** Checks if the include regular expression is valid. */
 public FormValidation doCheckIncludeRegex(@QueryParameter String value)
     throws IOException, ServletException, InterruptedException {
   String v = Util.fixEmpty(value);
   if (v != null) {
     try {
       Pattern.compile(v);
     } catch (PatternSyntaxException pse) {
       return FormValidation.error(pse.getMessage());
     }
   }
   return FormValidation.ok();
 }
Esempio n. 11
0
    public FormValidation doCheck(@QueryParameter final String value)
        throws IOException, ServletException {

      String url = Util.fixEmpty(value);
      if (url == null) {
        return FormValidation.ok();
      }
      if (!url.startsWith("http://") && !url.startsWith("https://")) {
        return FormValidation.errorWithMarkup(
            "The URL should contain <tt>http://</tt> or <tt>https://</tt>");
      }
      return FormValidation.ok();
    }
Esempio n. 12
0
  private static View copy(StaplerRequest req, ViewGroup owner, String name) throws IOException {
    View v;
    String from = req.getParameter("from");
    View src = src = owner.getView(from);

    if (src == null) {
      if (Util.fixEmpty(from) == null) throw new Failure("Specify which view to copy");
      else throw new Failure("No such view: " + from);
    }
    String xml = Jenkins.XSTREAM.toXML(src);
    v = createViewFromXML(name, new StringInputStream(xml));
    return v;
  }
Esempio n. 13
0
  protected void submit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    super.submit(req, rsp);
    JSONObject json = req.getSubmittedForm();

    rootPOM = Util.fixEmpty(req.getParameter("rootPOM").trim());
    if (rootPOM != null && rootPOM.equals("pom.xml")) rootPOM = null; // normalization

    goals = Util.fixEmpty(req.getParameter("goals").trim());
    alternateSettings = Util.fixEmpty(req.getParameter("alternateSettings").trim());
    mavenOpts = Util.fixEmpty(req.getParameter("mavenOpts").trim());
    mavenName = req.getParameter("maven_version");
    aggregatorStyleBuild = !req.hasParameter("maven.perModuleBuild");
    usePrivateRepository = req.hasParameter("maven.usePrivateRepository");
    ignoreUpstremChanges = !json.has("triggerByDependency");
    incrementalBuild = req.hasParameter("maven.incrementalBuild");
    archivingDisabled = req.hasParameter("maven.archivingDisabled");

    reporters.rebuild(req, json, MavenReporters.getConfigurableList());
    publishers.rebuild(req, json, BuildStepDescriptor.filter(Publisher.all(), this.getClass()));
    buildWrappers.rebuild(req, json, BuildWrappers.getFor(this));
  }
Esempio n. 14
0
  @DataBoundConstructor
  public ScmOptionBlock(
      String scmSystem,
      String customTestTool,
      String scmToolArguments,
      String scmCommandArgs,
      String logFileLoc,
      String p4Port,
      String accRevRepo) {

    this.scmSystem = scmSystem;
    this.customTestTool = Util.fixEmpty(customTestTool);
    this.scmToolArguments = Util.fixEmpty(scmToolArguments);
    this.scmCommandArgs = Util.fixEmpty(scmCommandArgs);
    this.logFileLoc = Util.fixEmpty(logFileLoc);
    this.p4Port = Util.fixEmpty(p4Port); // Required if perforce is selected
    this.accRevRepo = Util.fixEmpty(accRevRepo); // Required if accurev is selected
  }
Esempio n. 15
0
 @DataBoundSetter
 public void setCredentialsId(String credentialsId) {
   this.credentialsId = Util.fixEmpty(credentialsId);
 }
Esempio n. 16
0
 private SlackService getSlack(AbstractBuild r) {
   AbstractProject<?, ?> project = r.getProject();
   String projectRoom =
       Util.fixEmpty(project.getProperty(SlackNotifier.SlackJobProperty.class).getRoom());
   return notifier.newSlackService(projectRoom);
 }
Esempio n. 17
0
 public void setDisplayName(String displayName) throws IOException {
     this.displayName = Util.fixEmpty(displayName);
     save();
 }
 @DataBoundConstructor
 public EnvInjectNodeProperty(boolean unsetSystemVariables, String propertiesFilePath) {
   this.unsetSystemVariables = unsetSystemVariables;
   this.propertiesFilePath = Util.fixEmpty(propertiesFilePath);
 }
 protected void addLoginArgument(MaskedArgumentListBuilder arguments) {
   if ((Util.fixEmpty(config.getUserName()) != null) && (config.getUserPassword() != null)) {
     arguments.addMasked(
         String.format("-login:%s,%s", config.getUserName(), config.getUserPassword()));
   }
 }