Java Code Examples for hudson.model.TaskListener#getLogger()

The following examples show how to use hudson.model.TaskListener#getLogger() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitHubBranchHashChangedEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubBranchCause check(@Nonnull GitHubBranchDecisionContext context) throws IOException {
    GHBranch remoteBranch = context.getRemoteBranch();
    GitHubBranch localBranch = context.getLocalBranch();
    TaskListener listener = context.getListener();

    GitHubBranchCause cause = null;
    if (nonNull(localBranch) && nonNull(remoteBranch)) { // didn't exist before
        final String localBranchSHA1 = localBranch.getCommitSha();
        final String remoteBranchSHA1 = remoteBranch.getSHA1();

        if (!localBranchSHA1.equals(remoteBranchSHA1)) {
            final PrintStream logger = listener.getLogger();
            logger.printf("%s: hash has changed '%s' -> '%s'%n", DISPLAY_NAME, localBranchSHA1, remoteBranchSHA1);
            LOG.debug("{}: hash has changed '{}' -> '{}'", DISPLAY_NAME, localBranchSHA1, remoteBranchSHA1);
            cause = context.newCause(DISPLAY_NAME, false);
        }
    }

    return cause;
}
 
Example 2
Source File: GitHubBranchDeletedEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubBranchCause check(@Nonnull GitHubBranchDecisionContext context) throws IOException {
    TaskListener listener = context.getListener();
    GitHubBranch localBranch = context.getLocalBranch();
    GHBranch remoteBranch = context.getRemoteBranch();

    GitHubBranchCause cause = null;
    if (nonNull(localBranch) && isNull(remoteBranch)) { // didn't exist before
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (branch was deleted)");
        LOG.debug("{}: state has changed (branch was deleted)", DISPLAY_NAME);
        localBranch.setCommitSha(null);
        cause = context.newCause(DISPLAY_NAME, false);
    }

    return cause;
}
 
Example 3
Source File: GitHubPRNonMergeableEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();

    Boolean mergeable;
    try {
        mergeable = remotePR.getMergeable();
    } catch (IOException e) {
        listener.error(DISPLAY_NAME + ": can't get mergeable status {}", e);
        LOGGER.warn("Can't get mergeable status: {}", e);
        mergeable = false;
    }
    mergeable = mergeable != null ? mergeable : false;

    if (!mergeable) {
        return prDecisionContext.newCause(DISPLAY_NAME, isSkip());
    }

    return null;
}
 
Example 4
Source File: GitHubPRCloseEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();

    if (isNull(localPR)) {
        return null;
    }

    GitHubPRCause cause = null;

    // must be closed once
    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        logger.println(DISPLAY_NAME + ": state has changed (PR was closed)");
        cause = prDecisionContext.newCause("PR was closed", false);
    }

    return cause;
}
 
Example 5
Source File: AWSDeviceFarmTestResultAction.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Blocking function which periodically polls the given AWS Device Farm run until its completed. During this waiting period,
 * we will grab the latest results reported by Device Farm and updated our internal result "snapshot" which will be used
 * to populate/inform the UI of test results/progress.
 *
 * @param runResult
 */
public void waitForRunCompletion(AWSDeviceFarm adf, ScheduleRunResult runResult, TaskListener listener) throws InterruptedException {
    PrintStream log = listener.getLogger();
    while (true) {
        GetRunResult latestRunResult = adf.describeRun(runResult.getRun().getArn());
        Run run = latestRunResult.getRun();
        result = new AWSDeviceFarmTestResult(owner, run);
        writeToLog(log, String.format("Run %s status %s", run.getName(), run.getStatus()));
        if (result.isCompleted()) {
            break;
        }
        try {
            Thread.sleep(DefaultUpdateInterval);
        } catch (InterruptedException ex) {
            writeToLog(log, String.format("Thread interrupted while waiting for the Run to complete"));
            throw ex;
        }
    }
}
 
Example 6
Source File: GitHubPROpenEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState() == CLOSED) {
        return null; // already closed, nothing to check
    }

    GitHubPRCause cause = null;
    String causeMessage = "PR opened";
    if (isNull(localPR)) { // new
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (PR was opened)");
        cause = prDecisionContext.newCause(causeMessage, false);
    }

    return cause;
}
 
Example 7
Source File: DockerBuildImageStep.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
                    @Nonnull TaskListener listener) throws InterruptedException, IOException {
    PrintStream llog = listener.getLogger();
    try {
        llog.println("Executing remote build image...");
        List<String> buildImages = workspace.act(newDockerBuildImageStepCallable()
                .withBuildImage(buildImage)
                .withConnector(connector)
                .withTaskListener(listener)
        );
        llog.println(buildImages);
    } catch (Throwable ex) {
        LOG.error("Can't build image", ex);
        throw ex;
    }
}
 
Example 8
Source File: DockerBuilderControlOptionProvisionAndStart.java    From docker-plugin with MIT License 6 votes vote down vote up
@Override
public void execute(Run<?, ?> build, Launcher launcher, TaskListener listener)
        throws DockerException {
    final PrintStream llog = listener.getLogger();

    final DockerCloud cloud = getCloud(build, launcher);
    final DockerTemplate template = cloud.getTemplate(templateId);
    if (template == null) {
        throw new IllegalStateException(
                "Template with ID " + templateId + " no longer exists in cloud " + cloud.name);
    }
    final DockerAPI dockerApi = cloud.getDockerApi();
    try(final DockerClient client = dockerApi.getClient()) {
        executeOnDocker(build, llog, cloud, template, client);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 9
Source File: PhabricatorNotifier.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
private void copyCoverageToJenkinsMaster(Run<?, ?> build, FilePath workspace, TaskListener listener) {
    Logger logger = new Logger(listener.getLogger());
    final File buildDir = build.getRootDir();
    FilePath buildTarget = new FilePath(buildDir);

    String finalCoverageReportPattern = coverageReportPattern != null ? coverageReportPattern :
            DEFAULT_XML_COVERAGE_REPORT_PATTERN;

    if (workspace != null) {
        try {
            int i = 0;
            for (FilePath report : workspace.list(finalCoverageReportPattern)) {
                final FilePath targetPath = new FilePath(buildTarget, PHABRICATOR_COVERAGE + (i == 0 ? "" : i) + ".xml");
                report.copyTo(targetPath);
                i++;
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            logger.warn(COVERAGE_TAG, "Unable to copy coverage to " + buildTarget);
        }
    }
}
 
Example 10
Source File: DockerBuilderControlOptionRun.java    From docker-plugin with MIT License 6 votes vote down vote up
@Override
public void execute(Run<?, ?> build, Launcher launcher, TaskListener listener)
        throws DockerException, IOException {
    final PrintStream llog = listener.getLogger();

    final DockerCloud cloud = getCloud(build,launcher);
    final DockerAPI dockerApi = cloud.getDockerApi();

    String xImage = expand(build, image);
    String xCommand = expand(build, dockerCommand);
    String xHostname = expand(build, hostname);
    String xUser = expand(build, user);

    LOG.info("Pulling image {}", xImage);
    llog.println("Pulling image " + xImage);

    // need a client that will tolerate lengthy pauses for a docker pull
    try(final DockerClient clientWithoutReadTimeout = dockerApi.getClient(0)) {
        executePullOnDocker(build, llog, xImage, clientWithoutReadTimeout);
    }
    // but the remainder can use a normal client with the default timeout
    try(final DockerClient client = dockerApi.getClient()) {
        executeOnDocker(build, llog, xImage, xCommand, xHostname, xUser, client);
    }
}
 
Example 11
Source File: GitHubPRLabelNotExistsEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> remoteLabels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<>();

    for (GHLabel ghLabel : remoteLabels) {
        existingLabels.add(ghLabel.getName());
    }

    existingLabels.retainAll(label.getLabelsSet());

    if (existingLabels.isEmpty()) {
        final PrintStream logger = listener.getLogger();
        LOG.debug("{}:{} not found", DISPLAY_NAME, label.getLabelsSet());
        logger.println(DISPLAY_NAME + ": " + label.getLabelsSet() + " not found");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels not exist", isSkip());
    }

    return cause;
}
 
Example 12
Source File: Logger.java    From dingtalk-plugin with MIT License 5 votes vote down vote up
/**
 * 分割线
 *
 * @param listener 任务监听器
 * @param lineType 线的类型
 */
public static void line(TaskListener listener, LineType lineType) {
  PrintStream logger = listener.getLogger();
  if (LineType.START.equals(lineType)) {
    logger.println();
    logger.println(LOG_ICON + LOG_HALF_LINE + LOG_TITLE + LOG_HALF_LINE + LOG_ICON);
  } else {
    logger.println(LOG_ICON + LOG_HALF_LINE + LOG_TITLE_PLACEHOLDER + LOG_HALF_LINE + LOG_ICON);
    logger.println();
  }
}
 
Example 13
Source File: InNamespaceStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start() throws Exception {
    TaskListener listener = getContext().get(TaskListener.class);
    NamespaceAction namespaceAction = new NamespaceAction(getContext().get(Run.class));

    sessionId = generateSessionId();
    namespace = generateNamespaceId(step.getName(), step.getPrefix(), sessionId);

    client = getKubernetesClient();
    isOpenshift = client.isAdaptable(OpenShiftClient.class);

    configuration = new DefaultConfigurationBuilder()
            .withNamespace(namespace)
            .withNamespaceLazyCreateEnabled(step.isNamespaceLazyCreateEnabled())
            .withNamespaceDestroyEnabled(step.isNamespaceDestroyEnabled())
            .withMasterUrl(client.getMasterUrl())
            .build();

    StreamLogger logger = new StreamLogger(listener.getLogger());
    LabelProvider labelProvider = new MapLabelProvider(step.getLabels());

    namespaceService = isOpenshift
            ? new OpenshiftNamespaceService.ImmutableOpenshiftNamespaceService(client, configuration, labelProvider, logger)
            : new DefaultNamespaceService.ImmutableNamespaceService(client, configuration, labelProvider, logger);


    if (!namespaceService.exists(namespace) && configuration.isNamespaceLazyCreateEnabled()) {
        namespaceService.create(namespace);
    }
    namespaceAction.push(namespace);

    getContext().newBodyInvoker().
            withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new NamespaceExpander(namespace))).
            withCallback(new NamespaceDestructionCallback(namespace, configuration, namespaceService, namespaceAction)).
            start();

    return false;
}
 
Example 14
Source File: GitHubPRLabelAddedEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    if (isNull(label)) {
        LOG.error("Label is null. Bad configured event: {}", getDescriptor().getDisplayName());
        throw new IllegalStateException("Label is null. Bad configured event: " + getDescriptor().getDisplayName());
    }

    //localPR exists before, checking for changes
    if (localPR != null && localPR.getLabels().containsAll(label.getLabelsSet())) {
        return null; // label existed before exiting
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> labels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<String>();

    for (GHLabel curLabel : labels) {
        existingLabels.add(curLabel.getName());
    }

    if (existingLabels.containsAll(label.getLabelsSet())) {
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (" + label.getLabelsSet() + " labels were added");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels were added", false);
    }

    return cause;
}
 
Example 15
Source File: PhabricatorNotifier.java    From phabricator-jenkins-plugin with MIT License 4 votes vote down vote up
/**
 * Get the coverage provider for the build
 *
 * @param build The current build
 * @param listener The build listener
 * @return The current coverage, if any
 */
private CoverageProvider getCoverageProvider(
        Run<?, ?> build, FilePath workspace,
        TaskListener listener,
        Set<String> includeFiles) {
    Result buildResult;
    if (build.getResult() == null) {
        buildResult = Result.SUCCESS;
    } else {
        buildResult = build.getResult();
    }
    if (!buildResult.isBetterOrEqualTo(Result.UNSTABLE)) {
        return null;
    }

    copyCoverageToJenkinsMaster(build, workspace, listener);

    CoverageProvider coverageProvider = null;
    Logger logger = new Logger(listener.getLogger());

    // First check if any coverage plugins are applied. These take precedence over other providers
    // Only one coverage plugin provider is supported per build
    if (Jenkins.getInstance().getPlugin("cobertura") != null) {
        CoberturaBuildAction coberturaBuildAction = build.getAction(CoberturaBuildAction.class);
        if (coberturaBuildAction != null) { // Choose only a single coverage provider
            logger.info(UBERALLS_TAG, "Using coverage metrics from Cobertura Jenkins Plugin");
            coverageProvider = new CoberturaPluginCoverageProvider(getCoverageReports(build), includeFiles, coberturaBuildAction);
        }
    }

    if (coverageProvider == null && Jenkins.getInstance().getPlugin("jacoco") != null) {
        JacocoBuildAction jacocoBuildAction = build.getAction(JacocoBuildAction.class);
        if (jacocoBuildAction != null) {
            logger.info(UBERALLS_TAG, "Using coverage metrics from Jacoco Jenkins Plugin");
            coverageProvider = new JacocoPluginCoverageProvider(getCoverageReports(build), includeFiles, jacocoBuildAction);
        }
    }

    if (coverageProvider == null) {
        logger.info(UBERALLS_TAG, "Trying to obtain coverage metrics by parsing coverage xml files");
        coverageProvider = new XmlCoverageProvider(getCoverageReports(build), includeFiles);
    }

    coverageProvider.computeCoverageIfNeeded();
    cleanupCoverageFilesOnJenkinsMaster(build);

    if (coverageProvider.hasCoverage()) {
        return coverageProvider;
    } else {
        logger.info(UBERALLS_TAG, "No coverage results found");
        return null;
    }
}
 
Example 16
Source File: AbstractSessionManagerStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 4 votes vote down vote up
protected void init() throws Exception {
    String sessionId = generateSessionId();
    String namespace = generateNamespaceId(sessionId);

    client = getKubernetesClient();
    isOpenShift = client.isAdaptable(OpenShiftClient.class);

    boolean isNamespaceCleanupEnabled = getStep().isNamespaceCleanupEnabled() != null
            ? getStep().isNamespaceCleanupEnabled()
            : false;

    boolean isNamespaceDestroyEnabled = getStep().isNamespaceDestroyEnabled() != null
            ? getStep().isNamespaceDestroyEnabled()
            : !isNamespaceProvided();

    configuration = new DefaultConfigurationBuilder()
            .withMasterUrl(client.getMasterUrl())
            .withNamespace(namespace)
            .withEnvironmentInitEnabled(true)
            .withNamespaceLazyCreateEnabled(getStep().isNamespaceLazyCreateEnabled())
            .withNamespaceCleanupEnabled(isNamespaceCleanupEnabled)
            .withNamespaceDestroyEnabled(isNamespaceDestroyEnabled)
            .withEnvironmentDependencies(toURL(getStep().getEnvironmentDependencies()))
            .withEnvironmentConfigUrl(toURL(getStep().getEnvironmentConfigUrl()))
            .withScriptEnvironmentVariables(getStep().getScriptEnvironmentVariables())
            .withEnvironmentSetupScriptUrl(toURL(getStep().getEnvironmentSetupScriptUrl()))
            .withEnvironmentTeardownScriptUrl(toURL(getStep().getEnvironmentTeardownScriptUrl()))
            .withWaitForServiceList(getStep().getWaitForServiceList())
            .withWaitTimeout(getStep().getWaitTimeout())
            .build();

    TaskListener listener = getContext().get(TaskListener.class);
    StreamLogger logger = new StreamLogger(listener.getLogger());
    session = new DefaultSession(sessionId, namespace, logger);

    LabelProvider labelProvider = new MapLabelProvider(getStep().getLabels());
    AnnotationProvider annotationProvider = new MapAnnotationProvider(getStep().getAnnotations());

    NamespaceService namespaceService = isOpenShift
            ? new OpenshiftNamespaceService.ImmutableOpenshiftNamespaceService(client, configuration, labelProvider, logger)
            : new DefaultNamespaceService.ImmutableNamespaceService(client, configuration, labelProvider, logger);

    KubernetesResourceLocator resourceLocator = isOpenShift
            ? new OpenshiftKubernetesResourceLocator()
            : new DefaultKubernetesResourceLocator();


    ResourceInstaller resourceInstaller = isOpenShift
            ? new OpenshiftResourceInstaller.ImmutableResourceInstaller(client, configuration, logger, Collections.emptyList())
            : new DefaultResourceInstaller.ImmutableResourceInstaller(client, configuration, logger, Collections.emptyList());

    FeedbackProvider feedbackProvider = new DefaultFeedbackProvider.ImmutableFeedbackProvider(client, logger);
    DependencyResolver dependencyResolver = new EmptyDependencyResolver();

    sessionManager = new SessionManager(session, client, configuration,
            annotationProvider, namespaceService, resourceLocator,
            dependencyResolver, resourceInstaller, feedbackProvider);
}
 
Example 17
Source File: DockerComputerIOLauncher.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Override
public void launch(SlaveComputer computer, TaskListener listener)
        throws IOException, InterruptedException {
    final PrintStream llog = listener.getLogger();
    DockerComputer dockerComputer;
    if (computer instanceof DockerComputer) {
        dockerComputer = (DockerComputer) computer;
    } else {
        listener.error("Docker JNLP Launcher accepts only DockerComputer.class");
        throw new IllegalArgumentException("Docker JNLP Launcher accepts only DockerComputer.class");
    }
    Objects.requireNonNull(dockerComputer);

    final String containerId = dockerComputer.getContainerId();
    final DockerCloud dockerCloud = dockerComputer.getCloud();
    if (isNull(dockerCloud)) {
        listener.error("Cloud not found for computer " + computer.getName());
        throw new NullPointerException("Cloud not found for computer " + computer.getName());
    }
    final DockerClient client = dockerCloud.getClient();
    final DockerSlave node = dockerComputer.getNode();
    if (isNull(node)) {
        throw new NullPointerException("Node can't be null");
    }
    InspectContainerResponse inspect = client.inspectContainerCmd(containerId).exec();
    if (nonNull(inspect) && nonNull(inspect.getState().getRunning()) &&
            !inspect.getState().getRunning()) {
        throw new IllegalStateException("Container is not running!");
    }

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream inputStream = new PipedInputStream(out, 4096);

    IOCallback callback = new IOCallback(listener, out);

    PipedInputStream pipedInputStream = new PipedInputStream(4096);
    PipedOutputStream outputStream = new PipedOutputStream(pipedInputStream);
    llog.println("Attaching to container...");

    String java = getJavaPath();

    if (StringUtils.isEmpty(java)) {
        java = "java";
    }

    OsType osType = node.getDockerSlaveTemplate().getOsType();

    ExecCreateCmdResponse cmdResponse = client.execCreateCmd(containerId)
            .withAttachStderr(true)
            .withAttachStdin(true)
            .withAttachStdout(true)
            .withTty(false)
            .withCmd(
                    osType == OsType.WINDOWS ? "cmd" : "/bin/sh",
                    osType == OsType.WINDOWS ? "/c" : "-c",
                    java + " " + getJvmOpts() + " -jar " + SLAVE_JAR)
            .exec();

    client.execStartCmd(cmdResponse.getId())
            .withStdIn(pipedInputStream)
            .exec(callback);

    computer.setChannel(inputStream, outputStream, listener.getLogger(), new Channel.Listener() {
        @Override
        public void onClosed(Channel channel, IOException cause) {
            try {
                callback.close();
            } catch (IOException e) {
                Throwables.propagate(e);
            }
        }
    });
}
 
Example 18
Source File: JvctgPerformer.java    From violation-comments-to-github-plugin with MIT License 4 votes vote down vote up
public static void jvctsPerform(
    final ViolationsToGitHubConfig configUnexpanded,
    final FilePath fp,
    final Run<?, ?> build,
    final TaskListener listener) {
  final PrintStream logger = listener.getLogger();
  try {
    final EnvVars env = build.getEnvironment(listener);
    final ViolationsToGitHubConfig configExpanded = expand(configUnexpanded, env);
    logger.println("---");
    logger.println("--- Jenkins Violation Comments to GitHub ---");
    logger.println("---");
    logConfiguration(configExpanded, build, listener);

    final Optional<StandardCredentials> credentials =
        findCredentials(
            build.getParent(), configExpanded.getCredentialsId(), configExpanded.getGitHubUrl());

    if (!isNullOrEmpty(configExpanded.getoAuth2Token())) {
      logger.println("Using OAuth2Token");
    } else if (credentials.isPresent()) {
      final StandardCredentials standardCredentials = credentials.get();
      if (standardCredentials instanceof StandardUsernamePasswordCredentials) {
        logger.println("Using username / password");
      } else if (standardCredentials instanceof StringCredentials) {
        logger.println("Using OAuth2Token credential style");
      }
    } else {
      throw new IllegalStateException("No credentials found!");
    }

    logger.println("Running Jenkins Violation Comments To GitHub");
    logger.println("PR " + configExpanded.getPullRequestId());

    fp.act(
        new FileCallable<Void>() {

          private static final long serialVersionUID = 6166111757469534436L;

          @Override
          public void checkRoles(final RoleChecker checker) throws SecurityException {}

          @Override
          public Void invoke(final File workspace, final VirtualChannel channel)
              throws IOException, InterruptedException {
            setupFindBugsMessages();
            listener.getLogger().println("Workspace: " + workspace.getAbsolutePath());
            doPerform(configExpanded, workspace, credentials.orNull(), listener);
            return null;
          }
        });
  } catch (final Exception e) {
    Logger.getLogger(JvctgPerformer.class.getName()).log(SEVERE, "", e);
    final StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    logger.println(sw.toString());
    return;
  }
}
 
Example 19
Source File: GitHubPRBuildStatusPublisher.java    From github-integration-plugin with MIT License 4 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
                    @Nonnull TaskListener listener) throws InterruptedException, IOException {
    PrintStream listenerLogger = listener.getLogger();
    String publishedURL = getTriggerDescriptor().getJenkinsURL();

    if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
        return;
    }

    if (isEmpty(publishedURL)) {
        return;
    }

    GHCommitState state = getCommitState(run, unstableAs);

    GitHubPRCause c = ghPRCauseFromRun(run);

    String statusMsgValue = getStatusMsg().expandAll(run, listener);
    String buildUrl = publishedURL + run.getUrl();

    LOGGER.info("Setting status of {} to {} with url {} and message: {}",
            c.getHeadSha(), state, buildUrl, statusMsgValue);

    // TODO check permissions to write human friendly message
    final GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
    if (isNull(trigger)) {
        listener.error("Can't get trigger for this run! Silently skipping. " +
                "TODO implement error handler, like in publishers");
        return;
    }

    try {
        trigger.getRemoteRepository().createCommitStatus(c.getHeadSha(), state, buildUrl, statusMsgValue,
                run.getParent().getFullName());
    } catch (IOException ex) {
        if (nonNull(buildMessage)) {
            String comment = null;
            LOGGER.error("Could not update commit status of the Pull Request on GitHub. ", ex);
            if (state == GHCommitState.SUCCESS) {
                comment = buildMessage.getSuccessMsg().expandAll(run, listener);
            } else if (state == GHCommitState.FAILURE) {
                comment = buildMessage.getFailureMsg().expandAll(run, listener);
            }
            listenerLogger.println("Adding comment...");
            LOGGER.info("Adding comment, because: ", ex);
            addComment(c.getNumber(), comment, run, listener);
        } else {
            listenerLogger.println("Could not update commit status of the Pull Request on GitHub." + ex.getMessage());
            LOGGER.error("Could not update commit status of the Pull Request on GitHub.", ex);
        }
        handlePublisherError(run);
    }
}
 
Example 20
Source File: Logger.java    From dingtalk-plugin with MIT License 2 votes vote down vote up
/**
 * 统一输出调试日志
 *
 * @param listener 任务监听器
 * @param msg      消息
 */
public static void debug(TaskListener listener, String msg, Object... args) {
  PrintStream logger = listener.getLogger();
  logger.println();
  logger.println(String.format(msg, args));
}