Esempio n. 1
0
  private List<Component> resolveComponents(Stream stream, ClearTool ct)
      throws IOException, InterruptedException, ClearToolError {
    List<Component> components = new ArrayList<Component>();
    if (Util.fixEmptyAndTrim(this.components) != null) {

      String[] compTab = Util.fixEmptyAndTrim(this.components).split("\\s");
      for (String compName : compTab) {
        if (Util.fixEmptyAndTrim(compName) != null) {
          Baseline bl = ct.getLatestBl(new Component(compName), stream);

          List<Baseline> dependingBls = ct.getDependingBaselines(bl);
          if (!dependingBls.isEmpty()) {
            CompositeComponent c_comp = new CompositeComponent(compName);
            for (Baseline depBl : dependingBls) {
              Component depComp = ct.getComponentFromBL(depBl);
              c_comp.getAttachedComponents().add(depComp);
            }
            components.add(c_comp);
          } else {
            Component comp = new Component(compName);
            components.add(comp);
          }
        }
      }
    }
    return components;
  }
Esempio n. 2
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;
  }
  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 GithubSecurityRealm(String githubUri, String clientID, String clientSecret) {
    super();

    this.githubUri = Util.fixEmptyAndTrim(githubUri);
    this.clientID = Util.fixEmptyAndTrim(clientID);
    this.clientSecret = Util.fixEmptyAndTrim(clientSecret);
  }
Esempio n. 5
0
  @Override
  protected Set<ResourceActivity> getResourceActivities() {
    final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();

    activities.addAll(super.getResourceActivities());
    activities.addAll(Util.filter(publishers, ResourceActivity.class));
    activities.addAll(Util.filter(buildWrappers, ResourceActivity.class));

    return activities;
  }
 @DataBoundConstructor
 public MySQLSecurityRealm(
     String myServer,
     String myUsername,
     String myPassword,
     String myPort,
     String myDatabase,
     String myDataTable,
     String myUserField,
     String myPassField,
     String myCondition,
     String encryption) {
   this.myServer = Util.fixEmptyAndTrim(myServer);
   this.myUsername = Util.fixEmptyAndTrim(myUsername);
   this.myPassword = Util.fixEmptyAndTrim(myPassword);
   this.myPort = Util.fixEmptyAndTrim(myPort);
   if ((myPort == null) || (myPort.equals(""))) myPort = "3306";
   this.myPort = myPort;
   this.myDatabase = Util.fixEmptyAndTrim(myDatabase);
   this.myCondition = Util.fixEmptyAndTrim(myCondition);
   this.myDataTable = Util.fixEmptyAndTrim(myDataTable);
   this.myUserField = Util.fixEmptyAndTrim(myUserField);
   this.myPassField = Util.fixEmptyAndTrim(myPassField);
   this.encryption = encryption;
 }
Esempio n. 7
0
 /** Determines the file name from md5sum. */
 private static File getFingerprintFile(byte[] md5sum) {
   assert md5sum.length == 16;
   return new File(
       Jenkins.getInstance().getRootDir(),
       "fingerprints/"
           + Util.toHexString(md5sum, 0, 1)
           + '/'
           + Util.toHexString(md5sum, 1, 1)
           + '/'
           + Util.toHexString(md5sum, 2, md5sum.length - 2)
           + ".xml");
 }
Esempio n. 8
0
  /** Performs tagging. */
  public void perform(String tagName, TaskListener listener) {
    File destdir = null;
    try {
      destdir = Util.createTempDir();

      // unzip the archive
      listener
          .getLogger()
          .println(hudson.scm.cvs.Messages.CVSSCM_ExpandingWorkspaceArchive(destdir));
      Expand e = new Expand();
      e.setProject(new org.apache.tools.ant.Project());
      e.setDest(destdir);
      e.setSrc(CVSSCM.getArchiveFile(build));
      e.setTaskType("unzip");
      e.execute();

      // run cvs tag command
      listener.getLogger().println(hudson.scm.cvs.Messages.CVSSCM_TaggingWorkspace());
      for (ModuleLocation moduleLocation : scmInstance.getModuleLocations()) {
        @SuppressWarnings("unchecked")
        ModuleLocation parametrizedLocation =
            new ParametrizedModuleLocationImpl(moduleLocation, build.getBuildVariables());
        for (String module : parametrizedLocation.getNormalizedModules()) {
          if (!createTag(
              tagName,
              listener,
              destdir,
              parametrizedLocation.getLocalDir(),
              module,
              scmInstance.isFlatten())) {
            return;
          }
        }
      }

      // completed successfully
      onTagCompleted(tagName);
      build.save();
    } catch (Throwable e) {
      e.printStackTrace(listener.fatalError(e.getMessage()));
    } finally {
      try {
        if (destdir != null) {
          listener.getLogger().println("cleaning up " + destdir);
          Util.deleteRecursive(destdir);
        }
      } catch (IOException e) {
        e.printStackTrace(listener.fatalError(e.getMessage()));
      }
    }
  }
Esempio n. 9
0
    @DataBoundConstructor
    public NoteToPush(
        String targetRepoName, String noteMsg, String noteNamespace, boolean noteReplace) {
      super(targetRepoName);
      this.noteMsg = Util.fixEmptyAndTrim(noteMsg);
      this.noteReplace = noteReplace;

      if (noteNamespace != null && !noteNamespace.trim().isEmpty())
        this.noteNamespace = Util.fixEmptyAndTrim(noteNamespace);
      else this.noteNamespace = "master";

      //    throw new GitException("Toimii2 " + this.noteMsg + "   namespace: "+this.noteNamespace
      // );
    }
Esempio n. 10
0
    /** Performs syntactical check on the remote FS for slaves. */
    public FormValidation doCheckRemoteFS(@QueryParameter String value)
        throws IOException, ServletException {
      if (Util.fixEmptyAndTrim(value) == null)
        return FormValidation.error(Messages.Slave_Remote_Director_Mandatory());

      if (value.startsWith("\\\\") || value.startsWith("/net/"))
        return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning());

      if (Util.isRelativePath(value)) {
        return FormValidation.warning(Messages.Slave_Remote_Relative_Path_Warning());
      }

      return FormValidation.ok();
    }
    /*
     * Save the descriptor configuration
     */
    @Override
    public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
      // Get the values and check them
      String deploy = req.getParameter("dimensionsbuildnotifier.deployState");
      String action = req.getParameter("dimensionsbuildnotifier.actionState");

      if (deploy != null)
        deploy = Util.fixNull(req.getParameter("dimensionsbuildnotifier.deployState").trim());

      if (action != null)
        action = Util.fixNull(req.getParameter("dimensionsbuildnotifier.actionState").trim());

      this.save();
      return super.configure(req, formData);
    }
 public String getNormalizedUnixDynStorageDir(VariableResolver<String> variableResolver) {
   if (variableResolver != null) {
     return Util.replaceMacro(getUnixDynStorageDir(), variableResolver);
   } else {
     return getUnixDynStorageDir();
   }
 }
    public FormValidation doCheckWorkflowName(
        @QueryParameter final String serverUrl,
        @QueryParameter final String userName,
        @QueryParameter final String password,
        @QueryParameter final String tenant,
        @QueryParameter final String workflowName)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException,
            URISyntaxException {

      String workflowNameValue = Util.fixEmptyAndTrim(workflowName);
      if (workflowNameValue == null) {
        return FormValidation.error("Please enter workflow name.");
      }

      if (workflowNameValue.indexOf('$') >= 0) {
        // set by variable, can't validate
        return FormValidation.ok();
      }
      // Call server and validate
      BuildParam buildParam = new BuildParam(serverUrl, userName, password, tenant, null);
      OrchestratorClient client = new OrchestratorClient(buildParam);
      List<Workflow> workflows = client.fetchWorkflows();

      boolean isWorkflowFound = false;
      for (Workflow workflow : workflows) {
        if (workflow.getName().equals(workflowName)) {
          isWorkflowFound = true;
        }
      }
      if (!isWorkflowFound) {
        return FormValidation.error("Workflow with the given name doesn't exist in the server.");
      }
      return FormValidation.ok();
    }
 /**
  * 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());
   }
 }
Esempio n. 15
0
    @Override
    public boolean configure(StaplerRequest req, JSONObject o) {
      globalMavenOpts = Util.fixEmptyAndTrim(o.getString("globalMavenOpts"));
      save();

      return true;
    }
    @Override
    public boolean configure(StaplerRequest req, JSONObject o) {
      dotExe = Util.fixEmptyAndTrim(o.getString("dotExe"));
      save();

      return true;
    }
Esempio n. 17
0
  @Override
  public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
    EnvVars env = super.getEnvironment(log);
    FilePath ws = getWorkspace();
    if (ws
        != null) // if this is done very early on in the build, workspace may not be decided yet.
                 // see HUDSON-3997
    env.put("WORKSPACE", ws.getRemote());
    // servlet container may have set CLASSPATH in its launch script,
    // so don't let that inherit to the new child process.
    // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html
    env.put("CLASSPATH", "");

    JDK jdk = project.getJDK();
    if (jdk != null) {
      Computer computer = Computer.currentComputer();
      if (computer != null) { // just in case were not in a build
        jdk = jdk.forNode(computer.getNode(), log);
      }
      jdk.buildEnvVars(env);
    }
    project.getScm().buildEnvVars(this, env);

    if (buildEnvironments != null) for (Environment e : buildEnvironments) e.buildEnvVars(env);

    for (EnvironmentContributingAction a :
        Util.filter(getActions(), EnvironmentContributingAction.class)) a.buildEnvVars(this, env);

    EnvVars.resolve(env);

    return env;
  }
  public static final EmulatorConfig create(
      String avdName,
      String osVersion,
      String screenDensity,
      String screenResolution,
      String deviceLocale,
      String sdCardSize,
      boolean wipeData,
      boolean showWindow,
      boolean useSnapshots,
      String commandLineOptions,
      String targetAbi,
      String androidSdkHome) {
    if (Util.fixEmptyAndTrim(avdName) == null) {
      return new EmulatorConfig(
          osVersion,
          screenDensity,
          screenResolution,
          deviceLocale,
          sdCardSize,
          wipeData,
          showWindow,
          useSnapshots,
          commandLineOptions,
          targetAbi,
          androidSdkHome);
    }

    return new EmulatorConfig(
        avdName, wipeData, showWindow, useSnapshots, commandLineOptions, androidSdkHome);
  }
  public void mkview(String viewPath, String viewTag, String streamSelector)
      throws IOException, InterruptedException {
    Validate.notEmpty(viewPath);
    boolean isOptionalParamContainsHost = false;
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("mkview");
    cmd.add("-snapshot");
    if (streamSelector != null) {
      cmd.add("-stream");
      cmd.add(streamSelector);
    }
    cmd.add("-tag");
    cmd.add(viewTag);

    if ((optionalMkviewParameters != null) && (optionalMkviewParameters.length() > 0)) {
      String variabledResolvedParams =
          Util.replaceMacro(optionalMkviewParameters, this.variableResolver);
      cmd.addTokenized(variabledResolvedParams);
      isOptionalParamContainsHost = optionalMkviewParameters.contains("-host");
    }

    if (!isOptionalParamContainsHost) {
      cmd.add(viewPath);
    }

    launcher.run(cmd.toCommandArray(), null, null, null);
  }
  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());
    }
  }
  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());
    }
  }
Esempio n. 22
0
  /**
   * Scans a directory for files matching the includes pattern.
   *
   * @param directory the directory to scan.
   * @param includes the includes pattern.
   * @param listener Hudson Build listener.
   * @return array of strings of paths for files that match the includes pattern in the directory.
   * @throws IOException
   */
  protected String[] scan(final File directory, final String includes, final BuildListener listener)
      throws IOException {
    String[] fileNames = new String[0];

    if (StringUtils.isNotBlank(includes)) {
      FileSet fs = null;

      try {
        fs = Util.createFileSet(directory, includes);

        DirectoryScanner ds = fs.getDirectoryScanner();
        fileNames = ds.getIncludedFiles();
      } catch (BuildException e) {
        e.printStackTrace(listener.getLogger());
        throw new IOException(e);
      }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      for (String fileName : fileNames) {
        LOGGER.log(Level.FINE, "Test result file found: " + fileName);
      }
    }

    return fileNames;
  }
Esempio n. 23
0
 /** @since 1.347 */
 @DataBoundConstructor
 public RedeployPublisher(String id, String url, boolean uniqueVersion, boolean evenIfUnstable) {
   this.id = id;
   this.url = Util.fixEmptyAndTrim(url);
   this.uniqueVersion = uniqueVersion;
   this.evenIfUnstable = evenIfUnstable;
 }
 /** @return configured dot executable or a default */
 public String getDotExeOrDefault() {
   if (Util.fixEmptyAndTrim(dotExe) == null) {
     return Functions.isWindows() ? "dot.exe" : "dot";
   } else {
     return dotExe;
   }
 }
        @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. 26
0
 @Override
 public boolean configure(final StaplerRequest req, final JSONObject json)
     throws hudson.model.Descriptor.FormException {
   repoExecutable = Util.fixEmptyAndTrim(json.getString("executable"));
   save();
   return super.configure(req, json);
 }
Esempio n. 27
0
  private void scan(String pattern) {
    LOGGER.fine("Scanning " + pattern + " for hs_err_pid files");

    pattern = pattern.replace("%p", "*").replace("%%", "%");
    File f = new File(pattern).getAbsoluteFile();
    if (!pattern.contains("*")) scanFile(f);
    else { // GLOB
      File commonParent = f;
      while (commonParent != null && commonParent.getPath().contains("*")) {
        commonParent = commonParent.getParentFile();
      }
      if (commonParent == null) {
        LOGGER.warning("Failed to process " + f);
        return; // huh?
      }

      FileSet fs =
          Util.createFileSet(
              commonParent, f.getPath().substring(commonParent.getPath().length() + 1), null);
      DirectoryScanner ds = fs.getDirectoryScanner(new Project());
      for (String child : ds.getIncludedFiles()) {
        scanFile(new File(commonParent, child));
      }
    }
  }
Esempio n. 28
0
  public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml)
      throws IOException {
    acl.checkPermission(Job.CREATE);

    Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
    // place it as config.xml
    File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
    configXml.getParentFile().mkdirs();
    try {
      IOUtils.copy(xml, configXml);

      // load it
      TopLevelItem result;
      Items.updatingByXml.set(true);
      try {
        result = (TopLevelItem) Items.load(parent, configXml.getParentFile());
      } finally {
        Items.updatingByXml.set(false);
      }
      add(result);

      ItemListener.fireOnCreated(result);
      Jenkins.getInstance().rebuildDependencyGraph();

      return result;
    } catch (IOException e) {
      // if anything fails, delete the config file to avoid further confusion
      Util.deleteRecursive(configXml.getParentFile());
      throw e;
    }
  }
Esempio n. 29
0
  /**
   * Return a list of projects which can be built
   *
   * @return
   */
  protected final List<AbstractProject<?, ?>> getProjects(String viewName) {

    List<AbstractProject<?, ?>> projects = new ArrayList<AbstractProject<?, ?>>();
    Collection<TopLevelItem> items = Jenkins.getInstance().getItems();
    View view = null;
    BulkBuilderAction bulkBuilderAction = new BulkBuilderAction();

    if (viewName != null) {
      for (View currentView : bulkBuilderAction.getViews()) {
        if (currentView.getViewName().equals(viewName)) {
          view = currentView;
        }
      }

      if (view != null) {
        items = view.getItems();
      }
    }

    for (AbstractProject<?, ?> project : Util.createSubList(items, AbstractProject.class)) {
      if (!project.isBuildable()) {
        continue;
      }
      projects.add(project);
    }

    return projects;
  }
    public FormValidation doCheckWorkflowActionName(@QueryParameter String value) {
      if (Util.fixNull(value).trim().length() == 0) {
        return FormValidation.warning(Messages.JiraIssueUpdateBuilder_NoWorkflowAction());
      }

      return FormValidation.ok();
    }