Java 类hudson.model.BuildListener 实例源码

项目:sonar-quality-gates-plugin    文件:JobConfigurationService.java   
public JobConfigData checkProjectKeyIfVariable(JobConfigData jobConfigData, AbstractBuild build, BuildListener listener) throws QGException {

        String projectKey = jobConfigData.getProjectKey();

        if (projectKey.isEmpty()) {
            throw new QGException("Empty project key.");
        }

        final JobConfigData envVariableJobConfigData = new JobConfigData();
        envVariableJobConfigData.setSonarInstanceName(jobConfigData.getSonarInstanceName());

        try {
            envVariableJobConfigData.setProjectKey(getProjectKey(projectKey, build.getEnvironment(listener)));
        } catch (IOException | InterruptedException e) {
            throw new QGException(e);
        }

        envVariableJobConfigData.setSonarInstanceName(jobConfigData.getSonarInstanceName());

        return envVariableJobConfigData;
    }
项目:run-selector-plugin    文件:FileWriteBuilder.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
        BuildListener listener) throws InterruptedException, IOException {
    EnvVars envVars = build.getEnvironment(listener);
    String expandedFilename = envVars.expand(filename);
    String expandedContent = envVars.expand(content);

    FilePath file = build.getWorkspace().child(expandedFilename);
    file.write(expandedContent, encoding);
    return true;
}
项目:run-selector-plugin    文件:RemoveUpstreamBuilder.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    for (Cause.UpstreamCause c: Util.filter(build.getCauses(), Cause.UpstreamCause.class)) {
        Job<?,?> upstreamProject = Jenkins.getInstance().getItemByFullName(c.getUpstreamProject(), Job.class);
        if (upstreamProject == null) {
            listener.getLogger().println(String.format("Not Found: %s", c.getUpstreamProject()));
            continue;
        }

        Run<?,?> upstreamBuild = upstreamProject.getBuildByNumber(c.getUpstreamBuild());
        if (upstreamBuild == null) {
            listener.getLogger().println(String.format("Not Found: %s - %d", upstreamProject.getFullName(), c.getUpstreamBuild()));
            continue;
        }

        listener.getLogger().println(String.format("Removed: %s - %s", upstreamProject.getFullName(), upstreamBuild.getFullDisplayName()));
        upstreamBuild.delete();
    }
    return true;
}
项目:SlackUploader    文件:SlackUploader.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    //To change body of generated methods, choose Tools | Templates.
    LogOutput log = new LogOutput();
    Runtime runtime = Runtime.getRuntime();
    Process process = null;

    try {
        String script = generateScript();

        process = runScript(runtime, script);

        log.logOutput(listener, process);
    } catch (Throwable cause) {
        log.logOutput(listener, process);
    }
    return true;
}
项目:jagger-jaas-jenkins-plugin    文件:JaggerTestExecutionBuilder.java   
private void parseBuildParams(AbstractBuild<?, ?> build, BuildListener listener) throws IOException, InterruptedException {
    final EnvVars envVars = build.getEnvironment(listener);
    final VariableResolver<String> buildVariableResolver = build.getBuildVariableResolver();

    clearEvaluated();
    evaluatedJaasEndpoint = evaluate(jaasEndpoint, buildVariableResolver, envVars);
    evaluatedTestProjectUrl = evaluate(testProjectUrl, buildVariableResolver, envVars);
    evaluatedEnvId = evaluate(envId, buildVariableResolver, envVars);
    evaluatedLoadScenarioId = evaluate(loadScenarioId, buildVariableResolver, envVars);
    evaluatedTimeout = evaluate(executionStartTimeoutInSeconds, buildVariableResolver, envVars);
}
项目:jenkins-telegram-plugin    文件:TelegramNotifier.java   
public TelegramService newTelegramService(AbstractBuild r, BuildListener listener) {


        String authToken = this.authToken;
        if (StringUtils.isEmpty(authToken)) {
            authToken = getDescriptor().getToken();
        }
        String chatId = this.chatId;
        if (StringUtils.isEmpty(chatId)) {
            chatId = getDescriptor().getChatId();
        }

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

        return new StandardTelegramService(authToken, chatId);
    }
项目:jenkins-plugin-google-driver-uploader    文件:GoogleDriveUploader.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {

    try {
        GoogleRobotCredentials credentials = GoogleRobotCredentials.getById(getCredentialsId());
        GoogleDriveManager driveManager = new GoogleDriveManager(authorize(credentials));

        String pattern = Util.replaceMacro(getPattern(), build.getEnvironment(listener));
        String workspace = build.getWorkspace().getRemote();
        String[] filesToUpload = listFiles(workspace, pattern);
        for (String file : filesToUpload) {
            listener.getLogger().println("Uploading file: " + file);
            driveManager.store(file, getDriveLocation());
        }
    } catch (GeneralSecurityException e) {
        build.setResult(Result.FAILURE);
        return false;
    }
    return true;
}
项目:browserstack-integration-plugin    文件:BrowserStackBuildWrapper.java   
@Override
public Environment setUp(final AbstractBuild build, final Launcher launcher,
                         final BuildListener listener) throws IOException, InterruptedException {
    final PrintStream logger = listener.getLogger();

    final BrowserStackCredentials credentials = BrowserStackCredentials.getCredentials(build.getProject(), credentialsId);
    if (credentials != null) {
        this.username = credentials.getUsername();
        this.accesskey = credentials.getDecryptedAccesskey();
    }

    AutomateBuildEnvironment buildEnv = new AutomateBuildEnvironment(credentials, launcher, logger);
    if (accesskey != null && this.localConfig != null) {
        try {
            buildEnv.startBrowserStackLocal(build.getFullDisplayName());
        } catch (Exception e) {
            listener.fatalError(e.getMessage());
            throw new IOException(e.getCause());
        }
    }

    recordBuildStats();
    return buildEnv;
}
项目:browserstack-integration-plugin    文件:CopyResourceFileToWorkspaceTarget.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    FilePath workspace = build.getWorkspace();
    workspace.child(this.finalReportDir).mkdirs();
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        outputStream = workspace.child(this.finalReportDir + this.resourceFileToCopy).write();
        inputStream = this.getClass().getClassLoader().getResourceAsStream(this.resourceFileToCopy);
        IOUtils.copy(inputStream, outputStream);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
    return true;
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerBuildWrapper.java   
/**
 * {@inheritDoc}
 */
@Override
public EphemeralDeployment setUp(AbstractBuild build, Launcher launcher, BuildListener listener)
    throws IOException, InterruptedException {
  EnvVars environment = build.getEnvironment(listener);
  FilePath workspace = requireNonNull(build.getWorkspace());

  try {
    synchronized (deployment) {
      deployment.insert(workspace, environment, listener.getLogger());
    }
  } catch (CloudManagementException e) {
    e.printStackTrace(listener.error(e.getMessage()));
    return null; // Build must be aborted
  }

  return new EphemeralDeployment(environment);
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerDeployerTest.java   
@Test
public void getEnvironmentExceptionTest() throws Exception {
  GoogleCloudManagerDeployer deployer =
      new GoogleCloudManagerDeployer(getNewTestingTemplatedCloudDeployment(credentials.getId(),
          DEPLOYMENT_NAME, CONFIG_FILE, PathUtils.toRemotePaths(importPaths), null));

  BuildListener listener = mock(BuildListener.class);
  PrintStream printStream = new PrintStream(new ByteArrayOutputStream());
  when(listener.getLogger()).thenReturn(printStream);
  when(listener.error(any(String.class))).thenReturn(new PrintWriter(printStream));

  AbstractBuild build = mock(AbstractBuild.class);
  when(build.getResult()).thenReturn(Result.SUCCESS);
  when(build.getEnvironment(listener)).thenThrow(new IOException("test"));

  // Check that we failed the build step due to a failure to retrieve
  // the environment.
  assertFalse(deployer.perform(build, null, listener));
}
项目:batch-jenkins    文件:TestInParallelPostBuild.java   
private void initialize(AbstractBuild<?, ?> build, BuildListener listener) throws FileNotFoundException, IOException, InterruptedException {        
    this.sharedResourceEntityList = new ArrayList<>();

    Map<String, String> envVars = build.getEnvironment(listener);
    workspaceHelper = new WorkspaceHelper(envVars.get("WORKSPACE"));

    String tempFolderPath = workspaceHelper.getTempFolderPath();

    // if the directory does not exist, create it else detlete it
    if (Utils.dirExists(tempFolderPath)) {
        Logger.log(listener, workspaceHelper.getTempFolderPath() + " already exist.. deleting it");
        Utils.deleteDirectoryIncludeContent(tempFolderPath);
    }

    Logger.log(listener, "Creating directory: " + tempFolderPath);
    Files.createDirectory(Paths.get(tempFolderPath));

    if (Utils.dirExists(tempFolderPath)) {
        Logger.log(listener, workspaceHelper.getTempFolderPath() + " got created");
    }
    else
    {
        throw new FileNotFoundException(String.format("Directory %s doesn't exist", tempFolderPath));
    }
}
项目:batch-jenkins    文件:JobGenerator.java   
JobGenerator(BuildListener listener, WorkspaceHelper workspaceHelper,
        ProjectConfigHelper projectConfigHelper, JobSplitterHelper jobSplitterHelper, List<ResourceEntity> sharedResourceEntityList,
        BatchClient client, String jobId, String poolId,
        StorageAccountInfo storageAccountInfo, String containerSasKey) throws URISyntaxException, StorageException, InvalidKeyException, IOException {
    this.listener = listener;
    this.workspaceHelper = workspaceHelper;
    this.projectConfigHelper = projectConfigHelper;
    this.jobSplitterHelper = jobSplitterHelper;
    this.sharedResourceEntityList = sharedResourceEntityList;
    this.client = client;
    this.jobId = jobId;
    this.poolId = poolId;
    this.storageAccountInfo = storageAccountInfo;
    this.containerSasKey = containerSasKey;

    scriptTempFolder = workspaceHelper.getPathRelativeToTempFolder("scripts");
    if (!Utils.dirExists(scriptTempFolder)) {
        Files.createDirectory(Paths.get(scriptTempFolder));
    }
}
项目:batch-jenkins    文件:ProjectConfigFactory.java   
/**
 * Generate project config
 * @param listener BuildListener
 * @param fullFilePath full file path of project config file
 * @return ProjectConfig instance
 * @throws IOException
 */
public static ProjectConfig generateProjectConfig(BuildListener listener, String fullFilePath) throws IOException
{              
    Logger.log(listener, "Reading project configurations from %s...", fullFilePath);

    if (!Utils.fileExists(fullFilePath)) {
        throw new IOException(String.format("Project config file '%s' doesn't exist, please double check your configuration.", fullFilePath));
    }

    Gson gson = new Gson();
    ProjectConfig config = null;
    try (Reader reader = new InputStreamReader(new FileInputStream(new File(fullFilePath)), Charset.defaultCharset())) {
        config = gson.fromJson(reader, ProjectConfig.class);
    }

    // TODO: validate against schema
    // Do some basic check for project config, in case customer may provide wrong config file.
    basicCheckProjectConfig(config);

    Logger.log(listener, "Created project config from config %s", fullFilePath);
    return config;
}
项目:batch-jenkins    文件:JobSplitterFactory.java   
/**
 * Generate JobSplitter
 * @param listener BuildListener
 * @param fullFilePath full file path of config file
 * @return JobSplitter object
 * @throws IOException
 */
public static JobSplitter generateJobSplitter(BuildListener listener, String fullFilePath)
        throws IOException
{
    Logger.log(listener, "Reading job splitter configurations from %s...", fullFilePath);

    if (!Utils.fileExists(fullFilePath)) {
        throw new IOException(String.format("Job splitter config file '%s' doesn't exist, please double check your configuration.", fullFilePath));
    }

    Gson gson = new Gson();     
    JobSplitter splitter = null;
    try (Reader reader = new InputStreamReader(new FileInputStream(new File(fullFilePath)), Charset.defaultCharset())) {
        splitter = gson.fromJson(reader, JobSplitter.class);
    }

    // TODO: validate against schema
    // Do some basic check for splitter config, in case customer may provide wrong config file.
    basicCheckJobSplitterConfig(splitter);

    Logger.log(listener, "Created job splitter from config %s", fullFilePath);
    return splitter;
}
项目:batch-jenkins    文件:AzureStorageHelper.java   
/**
 * Get container SAS
 * @param listener BuildListener
 * @param container storage container
 * @param expirationInMins SAS expiration in minutes
 * @return container SAS
 * @throws StorageException
 * @throws InvalidKeyException
 */
public static String getContainerSas(BuildListener listener, CloudBlobContainer container, int expirationInMins) throws StorageException, InvalidKeyException {
    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.setTime(new Date());

    calendar.add(Calendar.MINUTE, expirationInMins);
    policy.setSharedAccessExpiryTime(calendar.getTime());
    // Set READ permission for downloading resource files to VM.
    // Set WRITE and LIST permissions for uploading test results to storage.
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ, 
            SharedAccessBlobPermissions.WRITE, SharedAccessBlobPermissions.LIST));

    BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    containerPermissions.getSharedAccessPolicies().put("jenkins" + System.currentTimeMillis(), policy);
    container.uploadPermissions(containerPermissions);

    // Create a shared access signature for the container.
    return container.generateSharedAccessSignature(policy, null);
}
项目:batch-jenkins    文件:AzureStorageHelper.java   
/**
 * Download blobs having given prefix
 * @param listener BuildListener
 * @param container storage container
 * @param blobPrefix blob prefix
 * @param targetFolderName target folder name
 * @throws StorageException
 * @throws IOException
 * @throws URISyntaxException
 */
public static void download(BuildListener listener, CloudBlobContainer container, String blobPrefix, String targetFolderName) throws StorageException, IOException, URISyntaxException {
    if (!Utils.dirExists(targetFolderName)) {
        Files.createDirectory(Paths.get(targetFolderName));
    }

    int count = 0;
    for (ListBlobItem blobItem : container.listBlobs(blobPrefix, true, EnumSet.of(BlobListingDetails.METADATA), null, null))
    {
        if (blobItem instanceof CloudBlockBlob) {
            CloudBlockBlob retrievedBlob = (CloudBlockBlob) blobItem;

            String fileName = retrievedBlob.getName();
            fileName = fileName.substring(fileName.lastIndexOf('/') + 1);

            retrievedBlob.downloadToFile(targetFolderName + File.separator + fileName);

            count++;
        }
    }
    if (count == 0) {
        Logger.log(listener, "No blobs are found in storage container %s.", container.getName());            
    } else {
        Logger.log(listener, "Downloaded %d blobs.", count);            
    }
}
项目:pipeline-maven-plugin    文件:WithMavenStepExecution.java   
@Override
protected void finished(StepContext context) throws Exception {
    mavenSpyLogProcessor.processMavenSpyLogs(context, tempBinDir, options);

    try {
        tempBinDir.deleteRecursive();
    } catch (IOException | InterruptedException e) {
        BuildListener listener = context.get(BuildListener.class);
        try {
            if (e instanceof IOException) {
                Util.displayIOException((IOException) e, listener); // Better IOException display on windows
            }
            e.printStackTrace(listener.fatalError("Error deleting temporary files"));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
项目:jira-ext-plugin    文件:AddLabel.java   
@Override
public void perform(List<JiraCommit> jiraCommitList,
                    AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit jiraCommit : JiraCommit.filterDuplicateIssues(jiraCommitList))
    {
        listener.getLogger().println("Add label to ticket: " + jiraCommit.getJiraTicket());
        listener.getLogger().println("Label: " + labelName);
        try
        {
            String expandedName = build.getEnvironment(listener).expand(labelName);
            getJiraClientSvc().addLabelToTicket(jiraCommit.getJiraTicket(), expandedName);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("ERROR Updating jira notifications");
            t.printStackTrace(listener.getLogger());
        }
    }
}
项目:jira-ext-plugin    文件:UpdateField.java   
@Override
public void perform(List<JiraCommit> commits, AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit commit : JiraCommit.filterDuplicateIssues(commits))
    {
        try
        {
            String expandedValue = build.getEnvironment(listener).expand(fieldValue);
            getJiraClientSvc().updateStringField(commit.getJiraTicket(), fieldName, expandedValue);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("Error updating ticket, continuing");
            t.printStackTrace(listener.getLogger());
        }
    }
}
项目:jira-ext-plugin    文件:SingleTicketStrategy.java   
@Override
public List<JiraCommit> getJiraCommits(AbstractBuild build,
                                       BuildListener listener)
{
    List<JiraCommit> jiraCommits = new ArrayList<>();
    String expandedIssueKey = issueKey;
    try
    {
        expandedIssueKey = build.getEnvironment(listener).expand(issueKey);
    }
    catch (IOException|InterruptedException e)
    {
        e.printStackTrace(listener.getLogger());
    }
    jiraCommits.add(new JiraCommit(expandedIssueKey, null));
    return jiraCommits;
}
项目:jira-ext-plugin    文件:AddFixVersion.java   
@Override
public void perform(List<JiraCommit> commits, AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit commit : JiraCommit.filterDuplicateIssues(commits))
    {
        try
        {
            String expandedFixVersion = build.getEnvironment(listener).expand(fixVersion);
            getJiraClientSvc().addFixVersion(commit.getJiraTicket(), expandedFixVersion);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("ERROR Updating fix versions, skipping");
            t.printStackTrace(listener.getLogger());
        }
    }
}
项目:jira-ext-plugin    文件:JiraPublisherStepTest.java   
@Test
public void testInvokeOperations()
        throws Exception
{
    IssueStrategyExtension mockStrategy = mock(IssueStrategyExtension.class);
    JiraOperationExtension mockOperation = mock(JiraOperationExtension.class);
    Descriptor mockDescriptor = mock(Descriptor.class);
    when(mockDescriptor.getDisplayName()).thenReturn("Mock descriptor");
    when(mockOperation.getDescriptor()).thenReturn(mockDescriptor);
    JiraExtPublisherStep publisher = new JiraExtPublisherStep(mockStrategy,
            Arrays.asList(mockOperation));
    List<JiraCommit> commits = Arrays.asList(new JiraCommit("JENKINS-101",
            MockChangeLogUtil.mockChangeLogSetEntry("example ticket")));

    when(mockStrategy.getJiraCommits(any(AbstractBuild.class), any(BuildListener.class)))
            .thenReturn(commits);

    assertTrue(publisher.perform(mock(AbstractBuild.class), mock(Launcher.class),
            new StreamBuildListener(System.out, Charset.defaultCharset())));
    verify(mockOperation).perform(eq(commits), any(AbstractBuild.class), any(Launcher.class), any(BuildListener.class));
}
项目:jira-ext-plugin    文件:JiraBuildStepPublisherTest.java   
@Test
public void testInvokeOperations()
{
    IssueStrategyExtension mockStrategy = mock(IssueStrategyExtension.class);
    JiraOperationExtension mockOperation = mock(JiraOperationExtension.class);
    Descriptor mockDescriptor = mock(Descriptor.class);
    when(mockDescriptor.getDisplayName()).thenReturn("Mock descriptor");
    when(mockOperation.getDescriptor()).thenReturn(mockDescriptor);
    JiraExtBuildStep builder = new JiraExtBuildStep(mockStrategy,
            Arrays.asList(mockOperation));
    List<JiraCommit> commits = Arrays.asList(new JiraCommit("JENKINS-101",
                    MockChangeLogUtil.mockChangeLogSetEntry("example ticket")));

    when(mockStrategy.getJiraCommits(any(AbstractBuild.class), any(BuildListener.class)))
                .thenReturn(commits);

    assertTrue(builder.perform(mock(AbstractBuild.class), mock(Launcher.class), new StreamBuildListener(System.out)));
    verify(mockOperation).perform(eq(commits), any(AbstractBuild.class), any(Launcher.class), any(BuildListener.class));
}
项目:starwars-plugin    文件:StarWarsRecorderTest.java   
public void testPerformWithFailureResultAddsStarWarsActionWithFailResultAndExpectedQuote() throws Exception {
    List<Action> actions = new ArrayList<Action>();
    Quote expectedQuote = generateQuote(StarWarsResult.FAIL);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getResult()).thenReturn(Result.FAILURE);
    when(mockBuild.getActions()).thenReturn(actions);

    mockQuotesGenerator.add(expectedQuote);
    when(mockQuotesGenerator.generate(StarWarsResult.FAIL)).thenReturn(expectedQuote);
    assertEquals(0, actions.size());

    Launcher mockLauncher = mock(Launcher.class); 
    BuildListener mockBuildListener = mock(BuildListener.class);
    recorder.perform(mockBuild, mockLauncher, mockBuildListener);

    assertEquals(1, actions.size());
    assertTrue(actions.get(0) instanceof StarWarsAction);

    StarWarsAction action = (StarWarsAction) actions.get(0);
    assertEquals(StarWarsResult.FAIL, action.getResult());
    assertEquals(expectedQuote, action.getQuote());
}
项目:ontrack-plugin    文件:OntrackPluginSupport.java   
public static String expand(String template, AbstractBuild<?, ?> theBuild, BuildListener listener) {
    if (StringUtils.isBlank(template)) {
        return template;
    } else {
        Pattern pattern = Pattern.compile(REGEX_ENV_VARIABLE);
        Matcher matcher = pattern.matcher(template);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String name = matcher.group(1);
            String value = getParameter(name, theBuild, listener);
            if (value == null) {
                throw new IllegalStateException("Cannot find any replacement value for environment variable " + name);
            }
            matcher = matcher.appendReplacement(result, value);
        }
        matcher.appendTail(result);
        return result.toString();
    }
}
项目:evosuite    文件:Mercurial.java   
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));
}
项目:ssh2easy-plugin    文件:GsshShellBuilder.java   
@SuppressWarnings("rawtypes")
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
        BuildListener listener) throws IOException, InterruptedException {
    PrintStream logger = listener.getLogger();
    GsshBuilderWrapper.printSplit(logger);
    if(isDisable()){
        logger.println("current step is disabled , skip to execute");
        return true;
    }
    // This is where you 'build' the project.
    SshClient sshHandler = GsshBuilderWrapper.DESCRIPTOR.getSshClient(
            getGroupName(), getIp());

    EnvVars env = build.getEnvironment(listener);
    String shell = Util.fixEmptyAndTrim(Util.replaceMacro(getShell(), env));
    int exitStatus = sshHandler.executeShell(logger, shell);
    GsshBuilderWrapper.printSplit(logger);
    return exitStatus == SshClient.STATUS_SUCCESS;
}
项目:ssh2easy-plugin    文件:GsshCommandBuilder.java   
@SuppressWarnings("rawtypes")
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
        BuildListener listener) throws IOException, InterruptedException {
    PrintStream logger = listener.getLogger();
    GsshBuilderWrapper.printSplit(logger);
    if(isDisable()){
        logger.println("current step is disabled , skip to execute");
        return true;
    }
    logger.println("execute on server -- "+getServerInfo());
    // This is where you 'build' the project.
    SshClient sshHandler = GsshBuilderWrapper.DESCRIPTOR.getSshClient(
            getGroupName(), getIp());

    EnvVars env = build.getEnvironment(listener);
    String shell = Util.fixEmptyAndTrim(Util.replaceMacro(getShell(), env));
    int exitStatus = sshHandler.executeCommand(logger, shell);
    GsshBuilderWrapper.printSplit(logger);
    return exitStatus == SshClient.STATUS_SUCCESS;
}
项目:CI-Jenkins-Plugin    文件:GithubCommitStatusUpdate.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
    throws InterruptedException, IOException {
  GithubInitializerAction initializerAction;
  CommitStatus commitStatusApi;
  PrintStream logger;
  logger = listener.getLogger();        
  initializerAction = build.getAction(GithubInitializerAction.class);
  if (initializerAction == null) {
    logger.println("Pull Requests could not be found. Failed to update commit status in Github");
    return true;
  } 
  commitStatusApi = new CommitStatus(initializerAction.getOrgName(), logger,
      initializerAction.isTestingMode(), initializerAction.getOauthAccessToken());    
  if (build.getResult() == Result.SUCCESS) {
    commitStatusApi.updateAll(initializerAction.getPullRequests(), 
        State.SUCCESS, build.getUrl());
  } else {
    commitStatusApi.updateAll(initializerAction.getPullRequests(), 
        State.FAILURE, build.getUrl(), initializerAction.getFailureReason());
  }

  return true;
}
项目:Tank    文件:ProxyPlugin.java   
/**
 * This function executes after pre-build steps and arbitrarily before the
 * build itself is run.
 */
@Override
public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) {
    PrintStream logger = listener.getLogger();
    try {
        LogPrinter.print("Sending remote command to start proxy on port "
                + proxyPort + ".", logger);
        Launcher launcher = build.getBuiltOn().createLauncher(listener);
        launcher.getChannel().call(
                new CreateProxyCallable(new ProxyRequest(listener,
                        proxyPort, build.getExternalizableId(), build.getWorkspace(), getDescriptor())));

        build.addAction(new AddEnvironmentVariableAction(PROXY_PORT_ENVIRONMENT_KEY, Integer.toString(proxyPort)));
    } catch (Exception e) {
        LogPrinter.print(e, logger);
        return false;
    }
    return true;
}
项目:Tank    文件:ProxyPlugin.java   
/**
 * Once we've finished building, this method gets called (regardless of
 * build result) to stop the proxy.
 */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
        BuildListener listener) {
    PrintStream logger = listener.getLogger();
    try {
        LogPrinter.print("Sending remote command to stop proxy on port "
                + proxyPort + ".", logger);
        launcher.getChannel().call(
                new StopProxyCallable(new ProxyRequest(listener, proxyPort, build.getExternalizableId(), 
                        build.getWorkspace(), getDescriptor())));
    } catch (Exception e) {
        LogPrinter.print(e, logger);
        return false;
    }
    return true;
}
项目:evosuite    文件:ModuleAction.java   
/**
 * 
 * @param project_info
 * @return
 */
public boolean build(VirtualChannel channel, ByteArrayInputStream stream, BuildListener listener) {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Project.class);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(ContinuousTestGeneration.class.getResourceAsStream("/xsd/ctg_project_report.xsd")));
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        this.project = (Project) jaxbUnmarshaller.unmarshal(stream);

        for (CUT cut : this.project.getCut()) {
            ClassAction c = new ClassAction(this.getBuild(), cut);
            c.highlightSource(channel, listener);
            this.classes.add(c);
        }
    }
    catch(Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}
项目:zaproxy-plugin    文件:ZAProxy.java   
/**
 * set up script based authentication method for the created context
 * @author Abdellah AZOUGARH
 * @param listener the listener to display log during the job execution in jenkins
 * @param zapClientAPI the ZAP API client  
 * @param scriptName the name of the authentication script used to authenticate the user
 * @param scriptLoggedInIndicator the indication that the user is logged in
 * @throws UnsupportedEncodingException
 * @throws ClientApiException
 */
private void setUpScriptBasedAuthenticationMethod( BuildListener listener, ClientApi zapClientAPI,String scriptName , String contextId, String scriptLoggedInIndicator) throws UnsupportedEncodingException, ClientApiException {

    // set script based authentication method       
    // Prepare the configuration in a format similar to how URL parameters are formed. This
    // means that any value we add for the configuration values has to be URL encoded.
    StringBuilder scriptBasedConfig = new StringBuilder();
    scriptBasedConfig.append("scriptName=").append(URLEncoder.encode(scriptName, "UTF-8"));
    listener.getLogger().println("Setting Script based authentication configuration as: " + scriptBasedConfig.toString());

    zapClientAPI.authentication.setAuthenticationMethod(API_KEY, contextId, "scriptBasedAuthentication",scriptBasedConfig.toString());

    listener.getLogger().println("Authentication config: " + zapClientAPI.authentication.getAuthenticationMethod(contextId).toString(0));

    //add logged in idicator
    if (!scriptLoggedInIndicator.equals("")) {
    listener.getLogger().println("---------------------------------------");
    zapClientAPI.authentication.setLoggedInIndicator(API_KEY,contextId, scriptLoggedInIndicator );
    }


}
项目:distributed-test-job    文件:DTDumbBuilder.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
        BuildListener listener) throws InterruptedException, IOException {
    try {
        boolean isPProjectBuilding = false;
        while (true) {
            isPProjectBuilding = false;
            List<DTJob> listOfProjects = getAllParentProjects();
            for (Project<?, ?> project : listOfProjects) {
                isPProjectBuilding = checkIfParentIsBuilding(project);
            }
            if (!isPProjectBuilding) {
                return true;
            }
            Thread.sleep(1000);
        }

    } catch (InterruptedException ex) {
        return false;
    }
}
项目:distributed-test-job    文件:DTBuilder.java   
/**
 * Used to execute/start a remote process that initializes the testing
 * process.
 * 
 * @param build
 *            the current build
 * @param listener
 *            the build's listener
 * @param entry
 *            containing the {@link Node} and its {@link EnvVars}
 * @return the started process
 * @throws InterruptedException
 * @throws IOException
 * @since 1.0
 */
private Proc executeTest(AbstractBuild<?, ?> build, BuildListener listener,
        Entry<Node, EnvVars> entry) throws InterruptedException,
        IOException {
    final EnvVars vars = NodeUtils.getEnvironment(entry.getKey(),
            entry.getValue());
    final Node node = entry.getKey();

    // Get testing environment on the specific node
    FilePath testEnv = FilePathUtils.getPathToTestEnvOnNode(node, build);

    // Create a remote launcher
    RemoteLauncher remoteLaucher = new RemoteLauncher(listener,
            node.getChannel(), true);

    // Create process starter
    ProcStarter starter = remoteLaucher.launch()
            .cmds(buildShellCmds(vars, node, build)).stdout(listener)
            .stderr(listener.getLogger()).pwd(testEnv.getParent());

    // Launch the process
    Proc proc = remoteLaucher.launch(starter);

    return proc;
}
项目:aws-codepipeline-plugin-for-jenkins    文件:CompressionTools.java   
public static void compressZipFile(
        final File temporaryZipFile,
        final Path pathToCompress,
        final BuildListener listener)
        throws IOException {
    try (final ZipArchiveOutputStream zipArchiveOutputStream =
                 new ZipArchiveOutputStream(
                 new BufferedOutputStream(
                 new FileOutputStream(temporaryZipFile)))) {

        compressArchive(
                pathToCompress,
                zipArchiveOutputStream,
                new ArchiveEntryFactory(CompressionType.Zip),
                CompressionType.Zip,
                listener);
    }
}
项目:aws-codepipeline-plugin-for-jenkins    文件:CompressionTools.java   
public static void compressTarFile(
        final File temporaryTarFile,
        final Path pathToCompress,
        final BuildListener listener)
        throws IOException {
    try (final TarArchiveOutputStream tarArchiveOutputStream =
                 new TarArchiveOutputStream(
                 new BufferedOutputStream(
                 new FileOutputStream(temporaryTarFile)))) {

        compressArchive(
                pathToCompress,
                tarArchiveOutputStream,
                new ArchiveEntryFactory(CompressionType.Tar),
                CompressionType.Tar,
                listener);
    }
}
项目:aws-codepipeline-plugin-for-jenkins    文件:CompressionTools.java   
public static void compressTarGzFile(
        final File temporaryTarGzFile,
        final Path pathToCompress,
        final BuildListener listener)
        throws IOException {
    try (final TarArchiveOutputStream tarGzArchiveOutputStream =
            new TarArchiveOutputStream(
            new BufferedOutputStream(
            new GzipCompressorOutputStream(
            new FileOutputStream(temporaryTarGzFile))))) {

        compressArchive(
                pathToCompress,
                tarGzArchiveOutputStream,
                new ArchiveEntryFactory(CompressionType.TarGz),
                CompressionType.TarGz,
                listener);
    }
}
项目:aws-codepipeline-plugin-for-jenkins    文件:CompressionTools.java   
private static void compressArchive(
        final Path pathToCompress,
        final ArchiveOutputStream archiveOutputStream,
        final ArchiveEntryFactory archiveEntryFactory,
        final CompressionType compressionType,
        final BuildListener listener)
        throws IOException {
    final List<File> files = addFilesToCompress(pathToCompress, listener);

    LoggingHelper.log(listener, "Compressing directory '%s' as a '%s' archive",
            pathToCompress.toString(),
            compressionType.name());

    for (final File file : files) {
        final String newTarFileName = pathToCompress.relativize(file.toPath()).toString();
        final ArchiveEntry archiveEntry = archiveEntryFactory.create(file, newTarFileName);
        archiveOutputStream.putArchiveEntry(archiveEntry);

        try (final FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream, archiveOutputStream);
        }

        archiveOutputStream.closeArchiveEntry();
    }
}