/**
   * Determines if the given configuration is currently running. If any of the configurations are
   * currently stuck in the queue, it is logged.
   *
   * @param execution Contains information about the general build, including the listener used to
   *     log queue blockage.
   * @param configuration The configuration being checked to see if it's running.
   * @param mutableWhyMap Mutable map used to track the reasons a configuration is stuck in the
   *     queue. This prevents duplicate reasons from flooding the logs.
   * @return True if the build represented by the given configuration is currently running or stuck
   *     in the queue. False if the build has finished running.
   */
  private boolean isBuilding(
      MatrixBuild.MatrixBuildExecution execution,
      MatrixConfiguration configuration,
      Map<String, String> mutableWhyMap) {
    MatrixRun build = configuration.getBuildByNumber(execution.getBuild().getNumber());
    if (build != null) {
      return build.isBuilding();
    }

    Queue.Item queueItem = configuration.getQueueItem();
    if (queueItem != null) {
      String why = queueItem.getWhy();
      String key = queueItem.task.getFullDisplayName() + " " + queueItem.id;
      String oldWhy = mutableWhyMap.get(key);
      if (why == null) {
        mutableWhyMap.remove(key);
      }
      if (why != null && !why.equals(oldWhy)) {
        mutableWhyMap.put(key, why);
        BuildListener listener = execution.getListener();
        PrintStream logger = listener.getLogger();
        logger.print(
            "Configuration "
                + ModelHyperlinkNote.encodeTo(configuration)
                + " is still in the queue: ");
        queueItem.getCauseOfBlockage().print(listener); // this is still shown on the same line
      }
    }

    return true;
  }
  @Override
  public Data getTestData(AbstractBuild<?, ?> ab, Launcher lnchr, BuildListener bl, TestResult tr)
      throws IOException, InterruptedException {
    bl.getLogger().println("Scanning for test data...");
    boolean foundSession = false;
    List<String> sessionIDs = null;

    for (SuiteResult sr : tr.getSuites()) {
      for (CaseResult cr : sr.getCases()) {
        sessionIDs = TestingBotReportFactory.findSessionIDs(cr);
        if (!sessionIDs.isEmpty()) {
          String errorDetails = cr.getErrorDetails();
          if (errorDetails == null) {
            errorDetails = "";
          }
          TestingBotAPI api = new TestingBotAPI();
          Map<String, String> data = new HashMap<String, String>();
          data.put("success", cr.isPassed() ? "1" : "0");
          data.put("status_message", errorDetails);
          data.put("name", cr.getFullName());
          api.updateTest(sessionIDs.get(0), data);

          foundSession = true;
        }
      }
    }

    if (!foundSession) {
      bl.getLogger().println("No TestingBot sessionIDs found in test output.");
      return null;
    } else {
      return TestingBotReportFactory.INSTANCE;
    }
  }
  @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;
  }
  private void addTestflightLinks(
      AbstractBuild<?, ?> build, BuildListener listener, Map parsedMap) {
    TestflightBuildAction installAction = new TestflightBuildAction();
    String installUrl = (String) parsedMap.get("install_url");
    installAction.displayName = Messages.TestflightRecorder_InstallLinkText();
    installAction.iconFileName = "package.gif";
    installAction.urlName = installUrl;
    build.addAction(installAction);
    listener.getLogger().println(Messages.TestflightRecorder_InfoInstallLink(installUrl));

    TestflightBuildAction configureAction = new TestflightBuildAction();
    String configUrl = (String) parsedMap.get("config_url");
    configureAction.displayName = Messages.TestflightRecorder_ConfigurationLinkText();
    configureAction.iconFileName = "gear2.gif";
    configureAction.urlName = configUrl;
    build.addAction(configureAction);
    listener.getLogger().println(Messages.TestflightRecorder_InfoConfigurationLink(configUrl));

    build.addAction(new EnvAction());

    // Add info about the selected build into the environment
    EnvAction envData = build.getAction(EnvAction.class);
    if (envData != null) {
      envData.add("TESTFLIGHT_INSTALL_URL", installUrl);
      envData.add("TESTFLIGHT_CONFIG_URL", configUrl);
    }
  }
  private void triggerAllBuildsConcurrent(AbstractBuild build, BuildListener listener) {

    final List<String> newBuildNodes = new ArrayList<String>();

    final ParametersAction origParamsAction = build.getAction(ParametersAction.class);
    final List<ParameterValue> origParams = origParamsAction.getParameters();
    final List<ParameterValue> newPrams = new ArrayList<ParameterValue>();
    for (ParameterValue parameterValue : origParams) {
      if (parameterValue instanceof LabelParameterValue) {
        if (parameterValue instanceof NodeParameterValue) {
          NodeParameterValue origNodePram = (NodeParameterValue) parameterValue;
          List<String> nextNodes = origNodePram.getNextLabels();
          if (nextNodes != null) {
            listener.getLogger().print("next nodes: " + nextNodes);
            newBuildNodes.addAll(nextNodes);
          }
        }
      } else {
        newPrams.add(parameterValue);
      }
    }
    for (String nodeName : newBuildNodes) {
      final List<String> singleNodeList = new ArrayList<String>();
      singleNodeList.add(nodeName);
      final NodeParameterValue nodeParameterValue =
          new NodeParameterValue(nodeName, singleNodeList);
      List<ParameterValue> copies = new ArrayList<ParameterValue>(newPrams);
      copies.add(nodeParameterValue); // where to do the next build
      listener.getLogger().print("schedule build on node " + nodeName);
      build
          .getProject()
          .scheduleBuild(0, new NextLabelCause(nodeName), new ParametersAction(copies));
    }
  }
  public boolean perform(Build build, Launcher launcher, BuildListener listener) {
    // this is where you 'build' the project
    // since this is a dummy, we just say 'hello world' and call that a build

    // this also shows how you can consult the global configuration of the builder
    if (DESCRIPTOR.useFrench()) listener.getLogger().println("Bonjour, " + name + "!");
    else listener.getLogger().println("Hello, " + name + "!");

    listener.getLogger().println("START");

    Project project = new HelloAntProject();
    project.init();

    BuildLogger logger = new DefaultLogger();
    logger.setMessageOutputLevel(Project.MSG_INFO);
    logger.setOutputPrintStream(new java.io.PrintStream(System.out));
    logger.setErrorPrintStream(new java.io.PrintStream(System.err));
    logger.setEmacsMode(false);
    //		project.addBuildListener((org.apache.tools.ant.BuildListener) listener);
    project.addBuildListener(logger);

    java.util.Vector list = new java.util.Vector();

    /*
     * ターゲットを指定 list.add("compile"); のようにすれば任意のターゲットを指定できます。
     */
    list.add(project.getDefaultTarget());
    // project.executeTargets(new java.util.Vector(list));

    listener.getLogger().println("DONE");
    return true;
  }
示例#7
0
  @Override
  public boolean checkout(
      @SuppressWarnings("rawtypes") final AbstractBuild build,
      final Launcher launcher,
      final FilePath workspace,
      final BuildListener listener,
      final File changelogFile)
      throws IOException, InterruptedException {

    FilePath repoDir;
    if (destinationDir != null) {
      repoDir = workspace.child(destinationDir);
      if (!repoDir.isDirectory()) {
        repoDir.mkdirs();
      }
    } else {
      repoDir = workspace;
    }

    if (!checkoutCode(launcher, repoDir, listener.getLogger())) {
      return false;
    }
    final String manifest = getStaticManifest(launcher, repoDir, listener.getLogger());
    final RevisionState currentState =
        new RevisionState(manifest, manifestBranch, listener.getLogger());
    build.addAction(currentState);
    final RevisionState previousState = getLastState(build.getPreviousBuild());

    ChangeLog.saveChangeLog(currentState, previousState, changelogFile, launcher, repoDir);
    build.addAction(new TagAction(build));
    return true;
  }
 @Override
 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
     throws InterruptedException, IOException {
   PrintMessages.printDeletingProjects(listener.getLogger(), nodes.size());
   NodeUtils.deleteLockingProjects(nodes, build, listener.getLogger());
   return true;
 }
 private static void addAddressesFromRecipientList(
     Set<InternetAddress> addresses,
     Set<InternetAddress> ccAddresses,
     String recipientList,
     EnvVars envVars,
     BuildListener listener) {
   try {
     Set<InternetAddress> internetAddresses =
         new EmailRecipientUtils()
             .convertRecipientString(recipientList, envVars, EmailRecipientUtils.TO);
     addresses.addAll(internetAddresses);
     if (ccAddresses != null) {
       Set<InternetAddress> ccInternetAddresses =
           new EmailRecipientUtils()
               .convertRecipientString(recipientList, envVars, EmailRecipientUtils.CC);
       ccAddresses.addAll(ccInternetAddresses);
     }
   } catch (AddressException ae) {
     LOGGER.log(Level.WARNING, "Could not create email address.", ae);
     listener.getLogger().println("Failed to create e-mail address for " + ae.getRef());
   } catch (UnsupportedEncodingException e) {
     LOGGER.log(Level.WARNING, "Could not create email address.", e);
     listener.getLogger().println("Failed to create e-mail address because of invalid encoding");
   }
 }
  @Override
  public Environment setUp(final AbstractBuild build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    final String artifactoryServerName = getArtifactoryName();
    if (StringUtils.isBlank(artifactoryServerName)) {
      return super.setUp(build, launcher, listener);
    }
    final ArtifactoryServer artifactoryServer = getArtifactoryServer();
    if (artifactoryServer == null) {
      listener
          .getLogger()
          .format(
              "[JFROG] No Artifactory server configured for %s. "
                  + "Please check your configuration.",
              artifactoryServerName)
          .println();
      build.setResult(Result.FAILURE);
      throw new IllegalArgumentException(
          "No Artifactory server configured for " + artifactoryServerName);
    }

    Credentials preferredDeployer;
    ArtifactoryServer server = getArtifactoryServer();
    if (isOverridingDefaultDeployer()) {
      preferredDeployer = getOverridingDeployerCredentials();
    } else {
      preferredDeployer = server.getResolvingCredentials();
    }

    hudson.ProxyConfiguration proxy = Hudson.getInstance().proxy;
    ProxyConfiguration proxyConfiguration = null;
    if (proxy != null && proxy.getName() != null) {
      proxyConfiguration = new ProxyConfiguration();
      proxyConfiguration.host = proxy.name;
      proxyConfiguration.port = proxy.port;
      proxyConfiguration.username = proxy.getUserName();
      proxyConfiguration.password = proxy.getPassword();
    }
    ArtifactoryDependenciesClient dependenciesClient =
        server.createArtifactoryDependenciesClient(
            preferredDeployer.getUsername(),
            preferredDeployer.getPassword(),
            proxyConfiguration,
            listener);
    try {
      GenericArtifactsResolver artifactsResolver =
          new GenericArtifactsResolver(build, listener, dependenciesClient, getResolvePattern());
      publishedDependencies = artifactsResolver.retrievePublishedDependencies();
      buildDependencies = artifactsResolver.retrieveBuildDependencies();

      return createEnvironmentOnSuccessfulSetup();
    } catch (Exception e) {
      e.printStackTrace(listener.error(e.getMessage()));
    } finally {
      dependenciesClient.shutdown();
    }

    return null;
  }
示例#11
0
 private static void logItems(BuildListener listener, String message, Collection<?> collection) {
   if (!collection.isEmpty()) {
     listener.getLogger().println(message + ":");
     for (Object item : collection) {
       listener.getLogger().println("    " + item.toString());
     }
   }
 }
  private MimeBodyPart getContent(
      final EmailType type,
      final AbstractBuild<?, ?> build,
      BuildListener listener,
      String charset,
      EmailTrigger trigger)
      throws MessagingException {
    final String text = new ContentBuilder().transformText(type.getBody(), this, build, listener);

    String messageContentType = contentType;
    // contentType is null if the project was not reconfigured after upgrading.
    if (messageContentType == null || "default".equals(messageContentType)) {
      messageContentType = DESCRIPTOR.getDefaultContentType();
      // The defaultContentType is null if the main Jenkins configuration
      // was not reconfigured after upgrading.
      if (messageContentType == null) {
        messageContentType = "text/plain";
      }
    }
    messageContentType += "; charset=" + charset;

    try {
      if (saveOutput) {
        Random random = new Random();
        String extension = ".html";
        if (messageContentType.startsWith("text/plain")) {
          extension = ".txt";
        }

        FilePath savedOutput =
            new FilePath(
                build.getWorkspace(),
                String.format(
                    "%s-%s%d%s",
                    trigger.getDescriptor().getDisplayName(),
                    build.getId(),
                    random.nextInt(),
                    extension));
        savedOutput.write(text, charset);
      }
    } catch (IOException e) {
      listener.getLogger().println("Error trying to save email output to file. " + e.getMessage());
    } catch (InterruptedException e) {
      listener.getLogger().println("Error trying to save email output to file. " + e.getMessage());
    }

    // set the email message text
    // (plain text or HTML depending on the content type)
    MimeBodyPart msgPart = new MimeBodyPart();
    debug(listener.getLogger(), "messageContentType = %s", messageContentType);
    if (messageContentType.startsWith("text/html")) {
      String inlinedCssHtml = new CssInliner().process(text);
      msgPart.setContent(inlinedCssHtml, messageContentType);
    } else {
      msgPart.setContent(text, messageContentType);
    }
    return msgPart;
  }
 @Override
 public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) {
   debug(listener.getLogger(), "Checking for pre-build");
   if (!(build instanceof MatrixRun) || isExecuteOnMatrixNodes()) {
     debug(listener.getLogger(), "Executing pre-build step");
     return _perform(build, listener, true);
   }
   return true;
 }
  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
    // This is where you 'build' the project.
    // Since this is a dummy, we just say 'hello world' and call that a build.

    // This also shows how you can consult the global configuration of the builder
    if (getDescriptor().getUseFrench()) listener.getLogger().println("Bonjour, " + name + "!");
    else listener.getLogger().println("Hello, " + name + "!");
    return true;
  }
 @Override
 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
     throws InterruptedException, IOException {
   debug(listener.getLogger(), "Checking for post-build");
   if (!(build instanceof MatrixRun) || isExecuteOnMatrixNodes()) {
     debug(listener.getLogger(), "Performing post-build step");
     return _perform(build, listener, false);
   }
   return true;
 }
示例#16
0
 /** Called by Jenkins when a build is finishing. */
 @Override
 public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
     throws IOException, InterruptedException {
   listener.getLogger().println("Recording plot data");
   // add the build to each plot
   for (Plot plot : getPlots()) {
     plot.addBuild(build, listener.getLogger());
   }
   // misconfigured plots will not fail a build so always return true
   return true;
 }
示例#17
0
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    ArgumentListBuilder args = new ArgumentListBuilder();

    VariableResolver<String> vr = build.getBuildVariableResolver();

    String execName = NantInstallation.getExecutableName();

    // Get the path to the nant installation
    NantInstallation ni = getNant();
    if (ni == null) {
      args.add(
          launcher.isUnix()
              ? NantConstants.NANT_EXECUTABLE_UNIX
              : NantConstants.NANT_EXECUTABLE_WINDOWS);
    } else {
      args.add(ni.getExecutable(launcher));
    }

    // If a nant build file is specified, then add it as an argument, otherwise
    // nant will search for any file that ends in .build
    if (nantBuildFile != null && nantBuildFile.trim().length() > 0) {
      args.add("-buildfile:" + nantBuildFile);
    }

    // add the property declarations to the command line
    args.addKeyValuePairsFromPropertyString("-D:", properties, vr);

    // Remove all tabs, carriage returns, and newlines and replace them with
    // spaces, so that we can add them as parameters to the executable
    String normalizedTarget = targets.replaceAll("[\t\r\n]+", " ");
    if (normalizedTarget.trim().length() > 0) args.addTokenized(normalizedTarget);

    // According to the Ant builder source code, in order to launch a program
    // from the command line in windows, we must wrap it into cmd.exe.  This
    // way the return code can be used to determine whether or not the build failed.
    if (!launcher.isUnix()) {
      args = args.toWindowsCommand();
    }

    // Try to execute the command
    listener.getLogger().println("Executing command: " + args.toString());
    Map<String, String> env = build.getEnvironment(listener);
    try {
      int r =
          launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
      return r == 0;
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed"));
      return false;
    }
  }
示例#18
0
  public BufferedReader loadFileFromWorkSpace(
      String buildID,
      int buildNumber,
      String workPlacePath,
      String inputFile,
      BuildListener listener,
      boolean deleteInputFile,
      String fileTypeEndingName)
      throws Exception {

    BufferedReader reader = null;
    String fileName = null;
    boolean notInTestMode = true;
    if (listener == null) {
      notInTestMode = false;
    }

    try {

      if ("".equals(inputFile) || inputFile == null) {
        fileName =
            workPlacePath + File.separator + buildNumber + "." + buildID + "." + fileTypeEndingName;
        if (notInTestMode) {
          listener.getLogger().print("Loading input file '" + fileName + "\n");
        }
        reader = new BufferedReader(new FileReader(fileName));
      } else {
        // fileName = workPlacePath + File.separator + inputFile;
        fileName = inputFile;
        if (notInTestMode) {
          listener.getLogger().print("Loading input file '" + fileName + "\n");
        }
        reader = new BufferedReader(new FileReader(fileName));
      }
    } catch (Exception e) {

      if (notInTestMode) {
        listener
            .getLogger()
            .print("Failed to open input file.  Failed to load file '" + fileName + "'\n");

      } else {

        System.out.println(
            "Failed to open the input file .  Failed to load file '" + fileName + "'");
      }

      throw e;
    }
    return reader;
  }
 private String getJobDefinedMavenInstallation(BuildListener listener, VirtualChannel channel) {
   Maven.MavenInstallation mvn = getMavenInstallation();
   if (mvn == null) {
     listener.error(
         "Maven version is not configured for this project. Can't determine which Maven to run");
     throw new Run.RunnerAbortedException();
   }
   String mvnHome = mvn.getHome();
   if (mvnHome == null) {
     listener.error("Maven '%s' doesn't have its home set", mvn.getName());
     throw new Run.RunnerAbortedException();
   }
   return mvnHome;
 }
    /**
     * Runs Docker command using Docker CLI.
     *
     * @param cmd Command to be executed
     * @param logStdOut If true, propagate STDOUT to the build log
     * @param logStdErr If true, propagate STDERR to the build log
     * @return Execution result
     * @throws IOException Execution error
     * @throws InterruptedException The build has been interrupted
     */
    private @Nonnull Result executeCmd(@Nonnull String cmd, boolean logStdOut, boolean logStdErr)
        throws IOException, InterruptedException {
      ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream();
      ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream();
      OutputStream stdout =
          logStdOut ? new TeeOutputStream(listener.getLogger(), baosStdOut) : baosStdOut;
      OutputStream stderr =
          logStdErr ? new TeeOutputStream(listener.getLogger(), baosStdErr) : baosStdErr;

      // get Docker registry credentials
      KeyMaterial registryKey = getRegistry().newKeyMaterialFactory(build).materialize();
      // Docker server credentials. If server is null (right after upgrading) do not use credentials
      KeyMaterial serverKey =
          server == null ? null : server.newKeyMaterialFactory(build).materialize();

      logger.log(Level.FINER, "Executing: {0}", cmd);

      try {
        EnvVars env = new EnvVars();
        env.putAll(build.getEnvironment(listener));
        env.putAll(registryKey.env());
        if (serverKey != null) {
          env.putAll(serverKey.env());
        }

        boolean result =
            launcher
                    .launch()
                    .envs(env)
                    .pwd(build.getWorkspace())
                    .stdout(stdout)
                    .stderr(stderr)
                    .cmdAsSingleString(cmd)
                    .start()
                    .join()
                == 0;

        // capture the stdout so it can be parsed later on
        final String stdOutStr = DockerCLIHelper.getConsoleOutput(baosStdOut, logger);
        final String stdErrStr = DockerCLIHelper.getConsoleOutput(baosStdErr, logger);
        return new Result(result, stdOutStr, stdErrStr);

      } finally {
        registryKey.close();
        if (serverKey != null) {
          serverKey.close();
        }
      }
    }
  /**
   * Invoked by the notifier, responsible for commiting or rolling back the workspace
   *
   * @throws IllegalArgumentException
   * @throws IOException
   */
  public boolean finalise(Launcher launcher, BuildListener listener)
      throws IllegalArgumentException, IOException {
    listener.getLogger().println("Finalising");
    scmInterface.handlePostBuild(build, launcher, listener);

    scmInterface.getDescriptor().save();

    // Trigger a new build if there are more commits
    Commit<?> next = scmInterface.nextCommit(build, launcher, listener, getCommit());
    if (next != null) {
      listener.getLogger().println("Triggering new build");
      build.getProject().scheduleBuild2(0);
    }
    return true;
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {

    Result result = build.getResult();
    if (result == null) {
      result = Result.SUCCESS;
    }

    String packIdString = getPackageId(build, listener);
    PackId packId = PackId.parsePid(packIdString);
    if (packId == null) {
      listener.fatalError("Failed to parse Package ID: %s%n", packIdString);
      return false;
    }

    String wspFilterString = getWspFilter(build, listener);
    WspFilter filter = WspFilter.parseSimpleSpec(wspFilterString);

    GraniteClientConfig clientConfig =
        new GraniteClientConfig(
            getBaseUrl(build, listener), credentialsId, requestTimeout, serviceTimeout, waitDelay);

    BuildPackageCallable callable =
        new BuildPackageCallable(clientConfig, listener, packId, filter, download);

    final String fLocalDirectory = getLocalDirectory(build, listener);
    result = result.combine(build.getWorkspace().child(fLocalDirectory).act(callable));

    return result.isBetterOrEqualTo(Result.UNSTABLE);
  }
  private void addUserTriggeringTheBuild(
      AbstractBuild<?, ?> build,
      Set<InternetAddress> recipientAddresses,
      Set<InternetAddress> ccAddresses,
      EnvVars env,
      BuildListener listener) {
    User user = getByUserIdCause(build);
    if (user == null) {
      user = getByLegacyUserCause(build);
    }

    if (user != null) {
      String adrs = user.getProperty(Mailer.UserProperty.class).getAddress();
      if (adrs != null) {
        addAddressesFromRecipientList(recipientAddresses, ccAddresses, adrs, env, listener);
      } else {
        listener
            .getLogger()
            .println(
                "Failed to send e-mail to "
                    + user.getFullName()
                    + " because no e-mail address is known, and no default e-mail domain is configured");
      }
    }
  }
  @Override
  public boolean perform(DynamicBuild dynamicBuild, Launcher launcher, BuildListener listener) {

    /*
     * public CheckStylePublisher(final String healthy, final String
     * unHealthy, final String thresholdLimit, final String defaultEncoding,
     * final boolean useDeltaValues, final String unstableTotalAll, final
     * String unstableTotalHigh, final String unstableTotalNormal, final
     * String unstableTotalLow, final String unstableNewAll, final String
     * unstableNewHigh, final String unstableNewNormal, final String
     * unstableNewLow, final String failedTotalAll, final String
     * failedTotalHigh, final String failedTotalNormal, final String
     * failedTotalLow, final String failedNewAll, final String
     * failedNewHigh, final String failedNewNormal, final String
     * failedNewLow, final boolean canRunOnFailed, final boolean
     * useStableBuildAsReference, final boolean shouldDetectModules, final
     * boolean canComputeNew, final String pattern)
     */
    CheckStylePublisher publisher = new CheckStylePublisher();
    boolean result = false;
    try {
      result = publisher.perform(((AbstractBuild) dynamicBuild), launcher, listener);
    } catch (Exception e) {
      e.printStackTrace(listener.getLogger());
    }

    return result;
  }
  private static AndroidSdk doInstall(
      Launcher launcher, BuildListener listener, String androidSdkHome)
      throws SdkInstallationException, IOException, InterruptedException {
    // We should install the SDK on the current build machine
    Node node = Computer.currentComputer().getNode();

    // Install the SDK if required
    String androidHome;
    try {
      androidHome = installBasicSdk(listener, node).getRemote();
    } catch (IOException e) {
      throw new SdkInstallationException(Messages.SDK_DOWNLOAD_FAILED(), e);
    } catch (SdkUnavailableException e) {
      throw new SdkInstallationException(Messages.SDK_DOWNLOAD_FAILED(), e);
    }

    // Check whether we need to install the SDK components
    if (!isSdkInstallComplete(node, androidHome)) {
      PrintStream logger = listener.getLogger();
      log(logger, Messages.INSTALLING_REQUIRED_COMPONENTS());
      AndroidSdk sdk = new AndroidSdk(androidHome, androidSdkHome);
      installComponent(logger, launcher, sdk, "platform-tool", "tool");

      // If we made it this far, confirm completion by writing our our metadata file
      getInstallationInfoFilename(node).write(String.valueOf(SDK_VERSION), "UTF-8");

      // As this SDK will not be used manually, opt out of the stats gathering;
      // this also prevents the opt-in dialog from popping up during execution
      optOutOfSdkStatistics(launcher, listener, androidSdkHome);
    }

    // Create an SDK object now that all the components exist
    return Utils.getAndroidSdk(launcher, androidHome, androidSdkHome);
  }
示例#26
0
  public Mercurial(
      MercurialSCM mercurialSCM,
      AbstractMavenProject<?, ?> project,
      AbstractBuild<?, ?> build,
      Launcher launcher,
      BuildListener listener)
      throws IOException, InterruptedException {

    // TODO check whether there is an issue between "Default" and "(Default)"
    MercurialInstallation mercurialInstallation = null;
    for (MercurialInstallation inst : MercurialInstallation.allInstallations()) {
      if (inst.getName().equals(mercurialSCM.getInstallation())) {
        mercurialInstallation = inst;
        break;
      }
    }
    assert mercurialInstallation != null;

    // get credentials (username-password, ssh key-passphrase
    StandardUsernameCredentials credentials = this.getCredentials(mercurialSCM, project);
    listener
        .getLogger()
        .println(EvoSuiteRecorder.LOG_PREFIX + "Credentials " + credentials.getDescription());

    // get a MercurialClient to handle hg commands
    this.hgClient =
        new HgExe(
            mercurialInstallation,
            credentials,
            launcher,
            Jenkins.getInstance(),
            listener,
            build.getEnvironment(listener));
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars envVars = build.getEnvironment(listener);
    envVars.overrideAll(build.getBuildVariables());
    boolean result = true;

    for (PostBuildStackBean stack : stacks) {
      final CloudFormation cloudFormation =
          newCloudFormation(stack, build, envVars, listener.getLogger());
      /*CloudFormation cloudFormation = new CloudFormation(
      		listener.getLogger(),
      		stack.getStackName(),
      		"",
      		new HashMap<String, String>(),
      		0,
      		stack.getParsedAwsAccessKey(envVars),
      		stack.getParsedAwsSecretKey(envVars),
      		stack.getAwsRegion(),
      		false,
      		envVars
      );*/
      if (cloudFormation.create()) {
        LOGGER.info("Success");
      } else {
        LOGGER.warning("Failed");
        result = false;
      }
    }
    return result;
  }
示例#28
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;
  }
示例#29
0
  public SlackService newSlackService(AbstractBuild r, BuildListener listener) {
    String teamDomain = this.teamDomain;
    if (StringUtils.isEmpty(teamDomain)) {
      teamDomain = getDescriptor().getTeamDomain();
    }
    String authToken = this.authToken;
    if (StringUtils.isEmpty(authToken)) {
      authToken = getDescriptor().getToken();
    }
    String room = this.room;
    if (StringUtils.isEmpty(room)) {
      room = getDescriptor().getRoom();
    }

    EnvVars env = null;
    try {
      env = r.getEnvironment(listener);
    } catch (Exception e) {
      listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
      env = new EnvVars();
    }
    teamDomain = env.expand(teamDomain);
    authToken = env.expand(authToken);
    room = env.expand(room);

    return new StandardSlackService(teamDomain, authToken, room);
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {

    boolean result = true;
    try {
      String testResultsFile = getExpandedResolvedPattern(this.testResultsFile, build, listener);
      listener.getLogger().println("Processing tests results in file(s) " + testResultsFile);
      MSTestTransformer transformer =
          new MSTestTransformer(testResultsFile, new MSTestReportConverter(), listener);
      result = build.getWorkspace().act(transformer);

      if (result) {
        // Run the JUnit test archiver
        result =
            recordTestResult(MSTestTransformer.JUNIT_REPORTS_PATH + "/TEST-*.xml", build, listener);
        build.getWorkspace().child(MSTestTransformer.JUNIT_REPORTS_PATH).deleteRecursive();
      }

    } catch (TransformerException te) {
      throw new AbortException(
          "Could not read the XSL XML file. Please report this issue to the plugin author");
    }

    return result;
  }