@Override
  public void rmview(String viewName) throws IOException, InterruptedException {
    // cleartool rmview -force <view name>
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("rmview");
    cmd.add("-force");
    cmd.add(viewName);

    // run the cleartool command
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    launcher.run(cmd.toCommandArray(), null, baos, null);
    String cleartoolOutput = ClearCaseUcmBaselineUtils.processCleartoolOuput(baos);
    baos.close();

    // ensure no error has occured
    if (cleartoolOutput.contains("cleartool: Error")) {
      launcher.getListener().error("Failed to remove view " + viewName + ".");
      throw new IOException("Failed to remove view " + viewName + ": " + cleartoolOutput);
    }

    // manually delete the view folder if cleartool rmview didn't actually remove it
    FilePath viewFilePath = launcher.getWorkspace().child(viewName);
    if (viewFilePath.exists()) {
      launcher
          .getListener()
          .getLogger()
          .println(
              "View folder was not actually removed by \"cleartool rmview\"; Removing it now...");
      viewFilePath.deleteRecursive();
    }
  }
 private boolean exist(FilePath filePath) throws DockerException {
   try {
     return filePath.exists();
   } catch (Exception e) {
     throw new DockerException(e);
   }
 }
  @Override
  public boolean checkout(
      AbstractBuild<?, ?> build,
      Launcher launcher,
      FilePath workspace,
      BuildListener listener,
      File changeLogFile)
      throws IOException, InterruptedException {
    if (workspace.exists()) {
      listener.getLogger().println("Deleting existing workspace " + workspace.getRemote());
      workspace.deleteRecursive();
    }
    listener.getLogger().println("Staging first zip: " + firstZip);
    workspace.unzipFrom(firstZip.openStream());
    listener.getLogger().println("Staging second zip: " + secondZip);
    workspace.unzipFrom(secondZip.openStream());

    // Get list of files changed in secondZip.
    ZipInputStream zip = new ZipInputStream(secondZip.openStream());
    ZipEntry e;
    ExtractChangeLogParser.ExtractChangeLogEntry changeLog =
        new ExtractChangeLogParser.ExtractChangeLogEntry(secondZip.toString());

    try {
      while ((e = zip.getNextEntry()) != null) {
        if (!e.isDirectory()) changeLog.addFile(new ExtractChangeLogParser.FileInZip(e.getName()));
      }
    } finally {
      zip.close();
    }
    saveToChangeLog(changeLogFile, changeLog);

    return true;
  }
 protected static FilePath[] getEmmaReports(File file) throws IOException, InterruptedException {
   FilePath path = new FilePath(file);
   if (path.isDirectory()) {
     return path.list("*xml");
   } else {
     // Read old builds (before 1.11)
     FilePath report = new FilePath(new File(path.getName() + ".xml"));
     return report.exists() ? new FilePath[] {report} : new FilePath[0];
   }
 }
 public String pwv(String viewPath) throws IOException, InterruptedException {
   ArgumentListBuilder cmd = new ArgumentListBuilder();
   cmd.add("pwv");
   cmd.add("-root");
   FilePath vp = getRootViewPath(launcher).child(viewPath);
   if (vp.exists()) {
     return runAndProcessOutput(cmd, null, vp, false, null);
   } else {
     return null;
   }
 }
 private FilePath locateValidFileInWorkspace(String relLocation) throws IOException {
   FilePath filePath = build.getWorkspace().child(relLocation);
   try {
     if (!filePath.exists()) {
       throw new IllegalStateException("File does not exists");
     }
   } catch (InterruptedException ie) {
     throw new RuntimeException(ie);
   }
   return filePath;
 }
 private FilePath locateValidFileInWorkspace(FilePath workspace, String relLocation)
     throws IOException {
   FilePath filePath = workspace.child(relLocation);
   try {
     if (!filePath.exists()) {
       throw new IllegalStateException(format("File %s does not exist in workspace", relLocation));
     }
   } catch (InterruptedException ie) {
     throw new IOException(ie);
   }
   return filePath;
 }
Exemple #8
0
 /**
  * Checks if the file path or file is valid.
  *
  * @param fp file path.
  * @param fext file extension.
  * @return true if file path is valid.
  */
 private boolean isValid(FilePath fp, String fext) {
   boolean valid = true;
   try {
     valid = fp.getRemote().endsWith(fext) && fp.exists();
   } catch (IOException ex) {
     lg.severe(ex);
     valid = false;
   } catch (InterruptedException ex) {
     lg.severe(ex);
     valid = false;
   }
   return valid;
 }
  public void addExecFiles(Iterable<FilePath> execFiles) throws IOException, InterruptedException {
    FilePath root = new FilePath(getExecFilesDir());
    int i = 0;
    for (FilePath file : execFiles) {
      FilePath separateExecDir;
      do {
        separateExecDir = new FilePath(root, "exec" + (i++));
      } while (separateExecDir.exists());

      FilePath fullExecName = separateExecDir.child("jacoco.exec");
      file.copyTo(fullExecName);
    }
  }
Exemple #10
0
  public boolean hasGitModules() throws GitException {
    try {

      FilePath dotGit = workspace.child(".gitmodules");

      return dotGit.exists();

    } catch (SecurityException ex) {
      throw new GitException(
          "Security error when trying to check for .gitmodules. Are you sure you have correct permissions?",
          ex);
    } catch (Exception e) {
      throw new GitException("Couldn't check for .gitmodules", e);
    }
  }
  @Override
  protected List<SeriesValue> loadSeries(AbstractBuild build) throws IOException {
    List<SeriesValue> values = new ArrayList<SeriesValue>();

    FilePath seriesFile = new FilePath(build.getWorkspace(), getFile());

    try {
      if (!seriesFile.exists()) {
        return values;
      }

      XPathExpression expression = XPathFactory.newInstance().newXPath().compile(xpath);

      InputSource source = null;

      try {
        source = new InputSource(seriesFile.read());

        Object xml = expression.evaluate(source, getNodeQName());

        if (NODESET.equals(getNodeQName())) {
          NodeList list = (NodeList) xml;

          for (int nodeIndex = 0; nodeIndex < list.getLength(); nodeIndex++) {
            Node node = list.item(nodeIndex);

            String localLabel = node.getLocalName(), value = node.getTextContent();

            if (localLabel != null && value != null) {
              values.add(createPlotPoint(value.trim(), localLabel, build));
            }
          }
        } else {
          values.add(createPlotPoint(nodeToString(xml), label, build));
        }
      } finally {
        if (source != null) {
          source.getByteStream().close();
        }
      }

      return values;
    } catch (XPathExpressionException e) {
      throw new RuntimeException(e);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
  private static String loadLastBuildNr(XTriggerLog xTriggerLog, FilePath lastBuildNrFile) {
    String lastBuildNr = null;

    try {
      if (lastBuildNrFile.exists()) {
        lastBuildNr = lastBuildNrFile.readToString();

        xTriggerLog.info(String.format("Loaded buildNr: %s", lastBuildNr));
      }
    } catch (IOException e) {
      logException(xTriggerLog, e);
    } catch (InterruptedException e) {
      logException(xTriggerLog, e);
    }

    return lastBuildNr;
  }
    protected void check() throws IOException, ServletException {
      String value = fixEmpty(request.getParameter("value"));
      AbstractProject<?, ?> p = (AbstractProject<?, ?>) subject;

      if (value == null || p == null) {
        ok(); // none entered yet, or something is seriously wrong
        return;
      }

      if (value.contains("*")) {
        // a common mistake is to use wildcard
        error("Wildcard is not allowed here");
        return;
      }

      try {
        FilePath ws = getBaseDirectory(p);

        if (ws == null) { // can't check
          ok();
          return;
        }

        if (!ws.exists()) { // no workspace. can't check
          ok();
          return;
        }

        if (ws.child(value).exists()) {
          if (expectingFile) {
            if (!ws.child(value).isDirectory()) ok();
            else error(value + " is not a file");
          } else {
            if (ws.child(value).isDirectory()) ok();
            else error(value + " is not a directory");
          }
        } else {
          String msg = "No such " + (expectingFile ? "file" : "directory") + ": " + value;
          if (errorIfNotExist) error(msg);
          else warning(msg);
        }
      } catch (InterruptedException e) {
        ok(); // coundn't check
      }
    }
  /** for dynamic views : viewPath == viewTag */
  public void mkview(
      String viewPath, String viewTag, String streamSelector, String defaultStorageDir)
      throws IOException, InterruptedException {
    ArgumentListBuilder cmd = new ArgumentListBuilder();

    cmd.add("mkview");
    if (streamSelector != null) {
      cmd.add("-stream");
      cmd.add(streamSelector);
    }
    cmd.add("-tag");
    cmd.add(viewTag);

    boolean isOptionalParamContainsHost = false;
    if (StringUtils.isNotEmpty(optionalMkviewParameters)) {
      String variabledResolvedParams =
          Util.replaceMacro(optionalMkviewParameters, this.variableResolver);
      cmd.addTokenized(variabledResolvedParams);
      isOptionalParamContainsHost = optionalMkviewParameters.contains("-host");
    }

    // add the default storage directory only if gpath/hpath are not set (only for windows)
    if (!isOptionalParamContainsHost && StringUtils.isNotEmpty(defaultStorageDir)) {
      String separator = PathUtil.fileSepForOS(getLauncher().getLauncher().isUnix());
      String viewStorageDir = defaultStorageDir + separator + viewTag;
      String base = viewStorageDir;
      FilePath fp = new FilePath(getLauncher().getLauncher().getChannel(), viewStorageDir);
      int i = 1;
      while (fp.exists()) {
        viewStorageDir = base + "." + i++;
        fp = new FilePath(getLauncher().getLauncher().getChannel(), viewStorageDir);
        if (i == Integer.MAX_VALUE) {
          throw new IOException("Cannot determine a view storage dir.");
        }
      }
      cmd.add(viewStorageDir);
    }

    launcher.run(cmd.toCommandArray(), null, null, null);
  }
  public void rmview(String viewPath) throws IOException, InterruptedException {
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("rmview");
    cmd.add("-force");
    cmd.add(viewPath);

    FilePath workspace = launcher.getWorkspace();
    String output = runAndProcessOutput(cmd, null, workspace, false, null);

    if (output.contains("cleartool: Error")) {
      throw new IOException("Failed to remove view: " + output);
    }

    FilePath viewFilePath = workspace.child(viewPath);
    if (viewFilePath.exists()) {
      launcher
          .getListener()
          .getLogger()
          .println("Removing view folder as it was not removed when the view was removed.");
      viewFilePath.deleteRecursive();
    }
  }
    protected void check() throws IOException, ServletException {
      String value = fixEmpty(request.getParameter("value"));
      AbstractProject<?, ?> p = (AbstractProject<?, ?>) subject;

      if (value == null || p == null) {
        ok(); // none entered yet, or something is seriously wrong
        return;
      }

      try {
        FilePath ws = getBaseDirectory(p);

        if (ws == null || !ws.exists()) { // no workspace. can't check
          ok();
          return;
        }

        String msg = ws.validateAntFileMask(value);
        if (errorIfNotExist) error(msg);
        else warning(msg);
      } catch (InterruptedException e) {
        ok(); // coundn't check
      }
    }
  /**
   * copy from MavenUtil but here we have to ignore localRepo path and setting as thoses paths comes
   * from the remote node and can not exist in master see
   * http://issues.jenkins-ci.org/browse/JENKINS-8711
   */
  private MavenEmbedder createEmbedder(TaskListener listener, AbstractBuild<?, ?> build)
      throws MavenEmbedderException, IOException, InterruptedException {
    MavenInstallation m = null;
    File settingsLoc = null, remoteGlobalSettingsFromConfig = null;
    String profiles = null;
    Properties systemProperties = null;
    String privateRepository = null;
    FilePath remoteSettingsFromConfig = null;

    File tmpSettings = File.createTempFile("jenkins", "temp-settings.xml");
    try {
      AbstractProject project = build.getProject();

      if (project instanceof MavenModuleSet) {
        MavenModuleSet mavenModuleSet = ((MavenModuleSet) project);
        profiles = mavenModuleSet.getProfiles();
        systemProperties = mavenModuleSet.getMavenProperties();

        // olamy see
        // we have to take about the settings use for the project
        // order tru configuration
        // TODO maybe in goals with -s,--settings last wins but not done in during pom parsing
        // or -Dmaven.repo.local
        // if not we must get ~/.m2/settings.xml then $M2_HOME/conf/settings.xml

        // TODO check if the remoteSettings has a localRepository configured and disabled it

        String settingsConfigId = mavenModuleSet.getSettingConfigId();
        String altSettingsPath = null;

        if (!StringUtils.isBlank(settingsConfigId)) {
          Config config =
              SettingsProviderUtils.findConfig(settingsConfigId, MavenSettingsProvider.class);
          if (config == null) {
            listener
                .getLogger()
                .println(
                    " your Apache Maven build is setup to use a config with id "
                        + settingsConfigId
                        + " but cannot find the config");
          } else {
            listener
                .getLogger()
                .println("redeploy publisher using settings config with name " + config.name);
            String settingsContent = config.content;
            if (config.content != null) {
              remoteSettingsFromConfig =
                  SettingsProviderUtils.copyConfigContentToFilePath(config, build.getWorkspace());
              altSettingsPath = remoteSettingsFromConfig.getRemote();
            }
          }
        }

        if (mavenModuleSet.getAlternateSettings() != null) {
          altSettingsPath = mavenModuleSet.getAlternateSettings();
        }

        String globalSettingsConfigId = mavenModuleSet.getGlobalSettingConfigId();
        if (!StringUtils.isBlank(globalSettingsConfigId)) {
          Config config =
              SettingsProviderUtils.findConfig(
                  globalSettingsConfigId, GlobalMavenSettingsProvider.class);
          if (config == null) {
            listener
                .getLogger()
                .println(
                    " your Apache Maven build is setup to use a global settings config with id "
                        + globalSettingsConfigId
                        + " but cannot find the config");
          } else {
            listener
                .getLogger()
                .println(
                    "redeploy publisher using global settings config with name " + config.name);
            if (config.content != null) {
              remoteGlobalSettingsFromConfig =
                  SettingsProviderUtils.copyConfigContentToFile(config);
            }
          }
        }
        Node buildNode = build.getBuiltOn();

        if (buildNode == null) {
          // assume that build was made on master
          buildNode = Jenkins.getInstance();
        }

        if (StringUtils.isBlank(altSettingsPath)) {
          // get userHome from the node where job has been executed
          String remoteUserHome = build.getWorkspace().act(new GetUserHome());
          altSettingsPath = remoteUserHome + "/.m2/settings.xml";
        }

        // we copy this file in the master in a  temporary file
        FilePath filePath = new FilePath(tmpSettings);
        FilePath remoteSettings = build.getWorkspace().child(altSettingsPath);
        if (!remoteSettings.exists()) {
          // JENKINS-9084 we finally use $M2_HOME/conf/settings.xml as maven do

          String mavenHome =
              ((MavenModuleSet) project).getMaven().forNode(buildNode, listener).getHome();
          String settingsPath = mavenHome + "/conf/settings.xml";
          remoteSettings = build.getWorkspace().child(settingsPath);
        }
        listener
            .getLogger()
            .println(
                "Maven RedeployPublished use remote "
                    + (buildNode != null ? buildNode.getNodeName() : "local")
                    + " maven settings from : "
                    + remoteSettings.getRemote());
        remoteSettings.copyTo(filePath);
        settingsLoc = tmpSettings;
      }

      MavenEmbedderRequest mavenEmbedderRequest =
          new MavenEmbedderRequest(
              listener,
              m != null ? m.getHomeDir() : null,
              profiles,
              systemProperties,
              privateRepository,
              settingsLoc);

      if (remoteGlobalSettingsFromConfig != null) {
        mavenEmbedderRequest.setGlobalSettings(remoteGlobalSettingsFromConfig);
      }

      mavenEmbedderRequest.setTransferListener(
          new ConsoleMavenTransferListener(listener.getLogger()));

      return MavenUtil.createEmbedder(mavenEmbedderRequest);
    } finally {
      if (tmpSettings != null) {
        tmpSettings.delete();
      }
      if (remoteSettingsFromConfig != null) {
        remoteSettingsFromConfig.delete();
      }
      FileUtils.deleteQuietly(remoteGlobalSettingsFromConfig);
    }
  }
  /**
   * Serves a file from the file system (Maps the URL to a directory in a file system.)
   *
   * @param icon The icon file name, like "folder-open.gif"
   * @param serveDirIndex True to generate the directory index. False to serve "index.html"
   * @deprecated as of 1.297 Instead of calling this method explicitly, just return the {@link
   *     DirectoryBrowserSupport} object from the {@code doXYZ} method and let Stapler generate a
   *     response for you.
   */
  public void serveFile(
      StaplerRequest req, StaplerResponse rsp, FilePath root, String icon, boolean serveDirIndex)
      throws IOException, ServletException, InterruptedException {
    // handle form submission
    String pattern = req.getParameter("pattern");
    if (pattern == null) pattern = req.getParameter("path"); // compatibility with Hudson<1.129
    if (pattern != null) {
      rsp.sendRedirect2(pattern);
      return;
    }

    String path = getPath(req);
    if (path.replace('\\', '/').indexOf("/../") != -1) {
      // don't serve anything other than files in the artifacts dir
      rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // split the path to the base directory portion "abc/def/ghi" which doesn't include any
    // wildcard,
    // and the GLOB portion "**/*.xml" (the rest)
    StringBuilder _base = new StringBuilder();
    StringBuilder _rest = new StringBuilder();
    int restSize = -1; // number of ".." needed to go back to the 'base' level.
    boolean zip = false; // if we are asked to serve a zip file bundle
    boolean plain = false; // if asked to serve a plain text directory listing
    {
      boolean inBase = true;
      StringTokenizer pathTokens = new StringTokenizer(path, "/");
      while (pathTokens.hasMoreTokens()) {
        String pathElement = pathTokens.nextToken();
        // Treat * and ? as wildcard unless they match a literal filename
        if ((pathElement.contains("?") || pathElement.contains("*"))
            && inBase
            && !(new FilePath(root, (_base.length() > 0 ? _base + "/" : "") + pathElement)
                .exists())) inBase = false;
        if (pathElement.equals("*zip*")) {
          // the expected syntax is foo/bar/*zip*/bar.zip
          // the last 'bar.zip' portion is to causes browses to set a good default file name.
          // so the 'rest' portion ends here.
          zip = true;
          break;
        }
        if (pathElement.equals("*plain*")) {
          plain = true;
          break;
        }

        StringBuilder sb = inBase ? _base : _rest;
        if (sb.length() > 0) sb.append('/');
        sb.append(pathElement);
        if (!inBase) restSize++;
      }
    }
    restSize = Math.max(restSize, 0);
    String base = _base.toString();
    String rest = _rest.toString();

    // this is the base file/directory
    FilePath baseFile = new FilePath(root, base);

    if (baseFile.isDirectory()) {
      if (zip) {
        rsp.setContentType("application/zip");
        baseFile.zip(rsp.getOutputStream(), rest);
        return;
      }
      if (plain) {
        rsp.setContentType("text/plain;charset=UTF-8");
        OutputStream os = rsp.getOutputStream();
        try {
          for (String kid : baseFile.act(new SimpleChildList())) {
            os.write(kid.getBytes("UTF-8"));
            os.write('\n');
          }
          os.flush();
        } finally {
          os.close();
        }
        return;
      }

      if (rest.length() == 0) {
        // if the target page to be displayed is a directory and the path doesn't end with '/',
        // redirect
        StringBuffer reqUrl = req.getRequestURL();
        if (reqUrl.charAt(reqUrl.length() - 1) != '/') {
          rsp.sendRedirect2(reqUrl.append('/').toString());
          return;
        }
      }

      FileCallable<List<List<Path>>> glob = null;

      if (rest.length() > 0) {
        // the rest is Ant glob pattern
        glob = new PatternScanner(rest, createBackRef(restSize));
      } else if (serveDirIndex) {
        // serve directory index
        glob = new ChildPathBuilder();
      }

      if (glob != null) {
        // serve glob
        req.setAttribute("it", this);
        List<Path> parentPaths = buildParentPath(base, restSize);
        req.setAttribute("parentPath", parentPaths);
        req.setAttribute("backPath", createBackRef(restSize));
        req.setAttribute("topPath", createBackRef(parentPaths.size() + restSize));
        req.setAttribute("files", baseFile.act(glob));
        req.setAttribute("icon", icon);
        req.setAttribute("path", path);
        req.setAttribute("pattern", rest);
        req.setAttribute("dir", baseFile);
        req.getView(this, "dir.jelly").forward(req, rsp);
        return;
      }

      // convert a directory service request to a single file service request by serving
      // 'index.html'
      baseFile = baseFile.child(indexFileName);
    }

    // serve a single file
    if (!baseFile.exists()) {
      rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    boolean view = rest.equals("*view*");

    if (rest.equals("*fingerprint*")) {
      rsp.forward(Hudson.getInstance().getFingerprint(baseFile.digest()), "/", req);
      return;
    }

    ContentInfo ci = baseFile.act(new ContentInfo());

    if (LOGGER.isLoggable(Level.FINE))
      LOGGER.fine(
          "Serving "
              + baseFile
              + " with lastModified="
              + ci.lastModified
              + ", contentLength="
              + ci.contentLength);

    InputStream in = baseFile.read();
    if (view) {
      // for binary files, provide the file name for download
      rsp.setHeader("Content-Disposition", "inline; filename=" + baseFile.getName());

      // pseudo file name to let the Stapler set text/plain
      rsp.serveFile(req, in, ci.lastModified, -1, ci.contentLength, "plain.txt");
    } else {
      rsp.serveFile(req, in, ci.lastModified, -1, ci.contentLength, baseFile.getName());
    }
  }
  private ArgumentListBuilder buildMavenCmdLine(
      AbstractBuild<?, ?> build, BuildListener listener, EnvVars env)
      throws IOException, InterruptedException {

    FilePath mavenHome = getMavenHomeDir(build, listener, env);

    if (!mavenHome.exists()) {
      listener.error("Couldn't find Maven home: " + mavenHome.getRemote());
      throw new Run.RunnerAbortedException();
    }

    ArgumentListBuilder args = new ArgumentListBuilder();

    FilePath mavenBootDir = new FilePath(mavenHome, "boot");
    FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar");
    if (classworldsCandidates == null || classworldsCandidates.length == 0) {
      listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote());
      throw new Run.RunnerAbortedException();
    }

    FilePath classWorldsJar = classworldsCandidates[0];

    // classpath
    args.add("-classpath");
    // String cpSeparator = launcher.isUnix() ? ":" : ";";

    args.add(classWorldsJar.getRemote());

    // maven home
    args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false);

    String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE);
    boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile);
    listener
        .getLogger()
        .println("Artifactory integration is " + (artifactoryIntegration ? "enabled" : "disabled"));
    String classworldsConfPath;
    if (artifactoryIntegration) {

      args.addKeyValuePair(
          "-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false);

      // use the classworlds conf packaged with this plugin and resolve the extractor libs
      File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class);
      FilePath actualDependencyDirectory =
          PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar);

      if (getMavenOpts() == null || !getMavenOpts().contains("-Dm3plugin.lib")) {
        args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false);
      }

      URL classworldsResource =
          getClass()
              .getClassLoader()
              .getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf");

      File classworldsConfFile =
          new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8"));
      if (!classworldsConfFile.exists()) {
        listener.error(
            "Unable to locate classworlds configuration file under "
                + classworldsConfFile.getAbsolutePath());
        throw new Run.RunnerAbortedException();
      }

      // If we are on a remote slave, make a temp copy of the customized classworlds conf
      if (Computer.currentComputer() instanceof SlaveComputer) {

        FilePath remoteClassworlds =
            build.getWorkspace().createTextTempFile("classworlds", "conf", "", false);
        remoteClassworlds.copyFrom(classworldsResource);
        classworldsConfPath = remoteClassworlds.getRemote();
      } else {
        classworldsConfPath = classworldsConfFile.getCanonicalPath();
      }
    } else {
      classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote();
    }

    args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false);

    // maven opts
    if (StringUtils.isNotBlank(getMavenOpts())) {
      String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver());
      args.add(mavenOpts);
    }

    // classworlds launcher main class
    args.add(CLASSWORLDS_LAUNCHER);

    // pom file to build
    String rootPom = getRootPom();
    if (StringUtils.isNotBlank(rootPom)) {
      args.add("-f", rootPom);
    }

    // maven goals
    args.addTokenized(getGoals());

    return args;
  }
Exemple #20
0
    protected Result doRun(BuildListener listener) throws Exception {
      // pick up a list of reporters to run
      reporters = getProject().createReporters();
      MavenModuleSet mms = getProject().getParent();
      if (debug) listener.getLogger().println("Reporters=" + reporters);

      for (BuildWrapper w : mms.getBuildWrappersList()) {
        Environment e = w.setUp(MavenBuild.this, launcher, listener);
        if (e == null) {
          return Result.FAILURE;
        }
        buildEnvironments.add(e);
      }

      EnvVars envVars = getEnvironment(listener); // buildEnvironments should be set up first

      MavenInstallation mvn = getProject().getParent().getMaven();

      mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener);

      MavenInformation mavenInformation =
          getModuleRoot().act(new MavenVersionCallable(mvn.getHome()));

      String mavenVersion = mavenInformation.getVersion();

      LOGGER.fine(
          getFullDisplayName()
              + " is building with mavenVersion "
              + mavenVersion
              + " from file "
              + mavenInformation.getVersionResourcePath());

      boolean maven3orLater = MavenUtil.maven3orLater(mavenVersion);

      ProcessCache.MavenProcess process =
          MavenBuild.mavenProcessCache.get(
              launcher.getChannel(),
              listener,
              maven3orLater
                  ? new Maven3ProcessFactory(
                      getParent().getParent(),
                      launcher,
                      envVars,
                      getMavenOpts(listener, envVars),
                      null)
                  : new MavenProcessFactory(
                      getParent().getParent(),
                      launcher,
                      envVars,
                      getMavenOpts(listener, envVars),
                      null));

      ArgumentListBuilder margs = new ArgumentListBuilder("-N", "-B");
      FilePath localRepo = mms.getLocalRepository().locate(MavenBuild.this);
      if (localRepo != null)
        // the workspace must be on this node, so getRemote() is safe.
        margs.add("-Dmaven.repo.local=" + localRepo.getRemote());

      if (mms.getAlternateSettings() != null) {
        if (IOUtils.isAbsolute(mms.getAlternateSettings())) {
          margs.add("-s").add(mms.getAlternateSettings());
        } else {
          FilePath mrSettings = getModuleRoot().child(mms.getAlternateSettings());
          FilePath wsSettings = getWorkspace().child(mms.getAlternateSettings());
          if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings;

          margs.add("-s").add(wsSettings.getRemote());
        }
      }

      margs.add("-f", getModuleRoot().child("pom.xml").getRemote());
      margs.addTokenized(getProject().getGoals());

      Map<String, String> systemProps = new HashMap<String, String>(envVars);
      // backward compatibility
      systemProps.put("hudson.build.number", String.valueOf(getNumber()));

      if (maven3orLater) {
        // FIXME here for maven 3 builds
        listener
            .getLogger()
            .println("Building single Maven modules is not implemented for Maven 3, yet!");
        return Result.ABORTED;
      } else {
        boolean normalExit = false;
        try {
          Result r =
              process.call(
                  new Builder(
                      listener, new ProxyImpl(), getProject(), margs.toList(), systemProps));
          normalExit = true;
          return r;
        } finally {
          if (normalExit) process.recycle();
          else process.discard();

          // tear down in reverse order
          boolean failed = false;
          for (int i = buildEnvironments.size() - 1; i >= 0; i--) {
            if (!buildEnvironments.get(i).tearDown(MavenBuild.this, listener)) {
              failed = true;
            }
          }
          // WARNING The return in the finally clause will trump any return before
          if (failed) return Result.FAILURE;
        }
      }
    }
  public Map<String, String> generateContents(AbstractProject<?, ?> project, GitSCM git)
      throws IOException, InterruptedException {

    Map<String, String> paramList = new LinkedHashMap<String, String>();
    // for (AbstractProject<?,?> project :
    // Hudson.getInstance().getItems(AbstractProject.class)) {
    if (project.getSomeWorkspace() == null) {
      this.errorMessage = "noWorkspace";
    }

    EnvVars environment = null;

    try {
      environment = project.getSomeBuildWithWorkspace().getEnvironment(TaskListener.NULL);
    } catch (Exception e) {
    }

    for (RemoteConfig repository : git.getRepositories()) {
      LOGGER.log(
          Level.INFO,
          "generateContents contenttype " + type + " RemoteConfig " + repository.getURIs());
      for (URIish remoteURL : repository.getURIs()) {
        GitClient newgit =
            git.createClient(
                TaskListener.NULL, environment, new Run(project) {}, project.getSomeWorkspace());
        FilePath wsDir = null;
        if (project.getSomeBuildWithWorkspace() != null) {
          wsDir = project.getSomeBuildWithWorkspace().getWorkspace();
          if (wsDir == null || !wsDir.exists()) {
            LOGGER.log(
                Level.WARNING, "generateContents create wsDir " + wsDir + " for " + remoteURL);
            wsDir.mkdirs();
            if (!wsDir.exists()) {
              LOGGER.log(Level.SEVERE, "generateContents wsDir.mkdirs() failed.");
              String errMsg = "!Failed To Create Workspace";
              return Collections.singletonMap(errMsg, errMsg);
            }
            newgit.init();
            newgit.clone(remoteURL.toASCIIString(), "origin", false, null);
            LOGGER.log(Level.INFO, "generateContents clone done");
          }
        } else {
          // probably our first build. We cannot yet fill in any
          // values.
          LOGGER.log(Level.INFO, "getSomeBuildWithWorkspace is null");
          String errMsg = "!No workspace. Please build the project at least once";
          return Collections.singletonMap(errMsg, errMsg);
        }

        long time = -System.currentTimeMillis();
        FetchCommand fetch = newgit.fetch_().from(remoteURL, repository.getFetchRefSpecs());
        fetch.execute();
        LOGGER.finest("Took " + (time + System.currentTimeMillis()) + "ms to fetch");
        if (type.equalsIgnoreCase(PARAMETER_TYPE_REVISION)) {
          List<ObjectId> oid;

          if (this.branch != null && !this.branch.isEmpty()) {
            oid = newgit.revList(this.branch);
          } else {
            oid = newgit.revListAll();
          }

          for (ObjectId noid : oid) {
            Revision r = new Revision(noid);
            paramList.put(r.getSha1String(), prettyRevisionInfo(newgit, r));
          }
        }
        if (type.equalsIgnoreCase(PARAMETER_TYPE_TAG)
            || type.equalsIgnoreCase(PARAMETER_TYPE_TAG_BRANCH)) {

          Set<String> tagSet = newgit.getTagNames(tagFilter);
          ArrayList<String> orderedTagNames;

          if (this.getSortMode().getIsSorting()) {
            orderedTagNames = sortByName(tagSet);
            if (this.getSortMode().getIsDescending()) Collections.reverse(orderedTagNames);
          } else {
            orderedTagNames = new ArrayList<String>(tagSet);
          }

          for (String tagName : orderedTagNames) {
            paramList.put(tagName, tagName);
          }
        }
        if (type.equalsIgnoreCase(PARAMETER_TYPE_BRANCH)
            || type.equalsIgnoreCase(PARAMETER_TYPE_TAG_BRANCH)) {
          time = -System.currentTimeMillis();
          Set<String> branchSet = new HashSet<String>();
          final boolean wildcard = "*".equals(branchfilter);
          for (Branch branch : newgit.getRemoteBranches()) {
            // It'd be nice if we could filter on remote branches via the GitClient,
            // but that's not an option.
            final String branchName = branch.getName();
            if (wildcard || branchName.matches(branchfilter)) {
              branchSet.add(branchName);
            }
          }
          LOGGER.finest("Took " + (time + System.currentTimeMillis()) + "ms to fetch branches");

          time = -System.currentTimeMillis();
          List<String> orderedBranchNames;
          if (this.getSortMode().getIsSorting()) {
            orderedBranchNames = sortByName(branchSet);
            if (this.getSortMode().getIsDescending()) Collections.reverse(orderedBranchNames);
          } else {
            orderedBranchNames = new ArrayList<String>(branchSet);
          }

          for (String branchName : orderedBranchNames) {
            paramList.put(branchName, branchName);
          }
          LOGGER.finest(
              "Took " + (time + System.currentTimeMillis()) + "ms to sort and add to param list.");
        }
      }
      break;
    }
    return paramList;
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException {
    listener.getLogger().println("[htmlpublisher] Archiving HTML reports...");

    // Grab the contents of the header and footer as arrays
    ArrayList<String> headerLines;
    ArrayList<String> footerLines;
    try {
      headerLines = this.readFile("/htmlpublisher/HtmlPublisher/header.html");
      footerLines = this.readFile("/htmlpublisher/HtmlPublisher/footer.html");
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
      return false;
    } catch (IOException e1) {
      e1.printStackTrace();
      return false;
    }

    for (int i = 0; i < this.reportTargets.size(); i++) {
      // Create an array of lines we will eventually write out, initially the header.
      ArrayList<String> reportLines = new ArrayList<String>(headerLines);
      HtmlPublisherTarget reportTarget = this.reportTargets.get(i);
      boolean keepAll = reportTarget.getKeepAll();

      FilePath archiveDir =
          build
              .getWorkspace()
              .child(resolveParametersInString(build, listener, reportTarget.getReportDir()));
      FilePath targetDir = reportTarget.getArchiveTarget(build);

      String levelString = keepAll ? "BUILD" : "PROJECT";
      listener
          .getLogger()
          .println(
              "[htmlpublisher] Archiving at "
                  + levelString
                  + " level "
                  + archiveDir
                  + " to "
                  + targetDir);

      // The index name might be a comma separated list of names, so let's figure out all the pages
      // we should index.
      String[] csvReports =
          resolveParametersInString(build, listener, reportTarget.getReportFiles()).split(",");
      ArrayList<String> reports = new ArrayList<String>();
      for (int j = 0; j < csvReports.length; j++) {
        String report = csvReports[j];
        report = report.trim();

        // Ignore blank report names caused by trailing or double commas.
        if (report.equals("")) {
          continue;
        }

        reports.add(report);
        String tabNo = "tab" + (j + 1);
        // Make the report name the filename without the extension.
        int end = report.lastIndexOf(".");
        String reportName;
        if (end > 0) {
          reportName = report.substring(0, end);
        } else {
          reportName = report;
        }
        String tabItem =
            "<li id=\""
                + tabNo
                + "\" class=\"unselected\" onclick=\"updateBody('"
                + tabNo
                + "');\" value=\""
                + report
                + "\">"
                + reportName
                + "</li>";
        reportLines.add(tabItem);
      }
      // Add the JS to change the link as appropriate.
      String hudsonUrl = Hudson.getInstance().getRootUrl();
      AbstractProject job = build.getProject();
      reportLines.add(
          "<script type=\"text/javascript\">document.getElementById(\"hudson_link\").innerHTML=\"Back to "
              + job.getName()
              + "\";</script>");
      // If the URL isn't configured in Hudson, the best we can do is attempt to go Back.
      if (hudsonUrl == null) {
        reportLines.add(
            "<script type=\"text/javascript\">document.getElementById(\"hudson_link\").onclick = function() { history.go(-1); return false; };</script>");
      } else {
        String jobUrl = hudsonUrl + job.getUrl();
        reportLines.add(
            "<script type=\"text/javascript\">document.getElementById(\"hudson_link\").href=\""
                + jobUrl
                + "\";</script>");
      }

      reportLines.add(
          "<script type=\"text/javascript\">document.getElementById(\"zip_link\").href=\"*zip*/"
              + reportTarget.getSanitizedName()
              + ".zip\";</script>");

      try {
        if (!archiveDir.exists()) {
          listener.error("Specified HTML directory '" + archiveDir + "' does not exist.");
          build.setResult(Result.FAILURE);
          return true;
        } else if (!keepAll) {
          // We are only keeping one copy at the project level, so remove the old one.
          targetDir.deleteRecursive();
        }

        if (archiveDir.copyRecursiveTo("**/*", targetDir) == 0) {
          listener.error(
              "Directory '" + archiveDir + "' exists but failed copying to '" + targetDir + "'.");
          if (build.getResult().isBetterOrEqualTo(Result.UNSTABLE)) {
            // If the build failed, don't complain that there was no coverage.
            // The build probably didn't even get to the point where it produces coverage.
            listener.error("This is especially strange since your build otherwise succeeded.");
          }
          build.setResult(Result.FAILURE);
          return true;
        }
      } catch (IOException e) {
        Util.displayIOException(e, listener);
        e.printStackTrace(listener.fatalError("HTML Publisher failure"));
        build.setResult(Result.FAILURE);
        return true;
      }

      reportTarget.handleAction(build);

      // Now add the footer.
      reportLines.addAll(footerLines);
      // And write this as the index
      try {
        writeFile(reportLines, new File(targetDir.getRemote(), reportTarget.getWrapperName()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return true;
  }