com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials. 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: BitbucketBuildStatusNotifier.java    From bitbucket-build-status-notifier-plugin with MIT License 6 votes vote down vote up
private FormValidation checkCredentials(UsernamePasswordCredentials credentials) {
    try {
        OAuthConfig config = new OAuthConfig(credentials.getUsername(), credentials.getPassword().getPlainText());
        BitbucketApiService apiService = (BitbucketApiService) new BitbucketApi().createService(config);
        Verifier verifier = null;
        Token token = apiService.getAccessToken(OAuthConstants.EMPTY_TOKEN, verifier);

        if (token.isEmpty()) {
            return FormValidation.error("Invalid Bitbucket OAuth credentials");
        }
    } catch (Exception e) {
        return FormValidation.error(e.getClass() + e.getMessage());
    }

    return FormValidation.ok();
}
 
Example #2
Source File: BuildStatusConfig.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Validates the credentials id.
 *
 * @param item context for validation
 * @param value to validate
 * @return FormValidation
 */
public FormValidation doCheckCredentialsId(@AncestorInPath Item item, @QueryParameter String value) {
    if (item == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return FormValidation.ok();
        }
    }
    if (StringUtils.isEmpty(value)) {
        return FormValidation.ok();
    }
    if (null == getCredentials(UsernamePasswordCredentials.class, value)) {
        return FormValidation.error("Cannot find currently selected credentials");
    }
    return FormValidation.ok();
}
 
Example #3
Source File: BitbucketBuildStatusNotifier.java    From bitbucket-build-status-notifier-plugin with MIT License 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@QueryParameter final String credentialsId,
                                           @AncestorInPath final Job<?,?> owner) {
    String globalCredentialsId = this.getGlobalCredentialsId();

    if (credentialsId == null || credentialsId.isEmpty()) {
        if (globalCredentialsId == null || globalCredentialsId.isEmpty()) {
            return FormValidation.error("Please enter Bitbucket OAuth credentials");
        } else {
            return this.doCheckGlobalCredentialsId(this.getGlobalCredentialsId());
        }
    }

    UsernamePasswordCredentials credentials = BitbucketBuildStatusHelper.getCredentials(credentialsId, owner);

    return this.checkCredentials(credentials);
}
 
Example #4
Source File: AbstractAnsibleInvocation.java    From ansible-plugin with Apache License 2.0 6 votes vote down vote up
protected ArgumentListBuilder appendCredentials(ArgumentListBuilder args)
        throws IOException, InterruptedException
{
    if (credentials instanceof SSHUserPrivateKey) {
        SSHUserPrivateKey privateKeyCredentials = (SSHUserPrivateKey)credentials;
        key = Utils.createSshKeyFile(key, ws, privateKeyCredentials, copyCredentialsInWorkspace);
        args.add("--private-key").add(key);
        args.add("-u").add(privateKeyCredentials.getUsername());
        if (privateKeyCredentials.getPassphrase() != null) {
            script = Utils.createSshAskPassFile(script, ws, privateKeyCredentials, copyCredentialsInWorkspace);
            environment.put("SSH_ASKPASS", script.getRemote());
            // inspired from https://github.com/jenkinsci/git-client-plugin/pull/168
            // but does not work with MacOSX
            if (! environment.containsKey("DISPLAY")) {
                environment.put("DISPLAY", ":123.456");
            }
        }
    } else if (credentials instanceof UsernamePasswordCredentials) {
        args.add("-u").add(credentials.getUsername());
        args.add("-k");
    }
    return args;
}
 
Example #5
Source File: InfluxDbNotifierTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
@Test
public void testBasicAuth() {
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
                    influxDbCredentialsId,
                    "Description",
                    influxDbUser,
                    influxDbPassword);
    when(config.getCredentials())
            .thenReturn(credentials);

    InfluxDbNotifier instance = new InfluxDbNotifier(config);
    assertEquals("http://fake/write?db=mockdb",
            instance.influxDbUrlString);
    assertEquals(new String(Base64.getDecoder().decode(instance.authorization)),
            "mock-user:mock-password");
}
 
Example #6
Source File: MarathonBuilderImpl.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a Marathon client based on the provided credentialsId and execute an update for the configuration's
 * Marathon application.
 *
 * @param credentialsId A string ID for a credential within Jenkin's Credential store
 * @throws MarathonException thrown if the Marathon service has an error
 */
private void doUpdate(final String credentialsId) throws MarathonException {
    final Credentials credentials = MarathonBuilderUtils.getJenkinsCredentials(credentialsId, Credentials.class);

    Marathon client;

    if (credentials instanceof UsernamePasswordCredentials) {
        client = getMarathonClient((UsernamePasswordCredentials) credentials);
    } else if (credentials instanceof StringCredentials) {
        client = getMarathonClient((StringCredentials) credentials);
    } else {
        client = getMarathonClient();
    }

    if (client != null) {
        client.updateApp(getApp().getId(), getApp(), config.getForceUpdate());
    }
}
 
Example #7
Source File: AbstractAnsibleBuilderDescriptor.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Project project) {
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(anyOf(
                        instanceOf(SSHUserPrivateKey.class),
                        instanceOf(UsernamePasswordCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, project));
}
 
Example #8
Source File: GlobalPipelineMavenConfig.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillJdbcCredentialsIdItems() {
    // use deprecated "withMatching" because, even after 20 mins of research,
    // I didn't understand how to use the new "recommended" API
    return new StandardListBoxModel()
            .includeEmptyValue()
            .withMatching(
                    CredentialsMatchers.always(),
                    CredentialsProvider.lookupCredentials(UsernamePasswordCredentials.class,
                            Jenkins.getInstance(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST));
}
 
Example #9
Source File: BitbucketBuildStatusHelper.java    From bitbucket-build-status-notifier-plugin with MIT License 5 votes vote down vote up
public static void sendBuildStatusNotification(final UsernamePasswordCredentials credentials,
                                               final Run<?, ?> build,
                                               final BitbucketBuildStatusResource buildStatusResource,
                                               final BitbucketBuildStatus buildStatus,
                                               final TaskListener listener) throws Exception {
    if (credentials == null) {
        throw new Exception("Credentials could not be found!");
    }

    OAuthConfig config = new OAuthConfig(credentials.getUsername(), credentials.getPassword().getPlainText());
    BitbucketApiService apiService = (BitbucketApiService) new BitbucketApi().createService(config);

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(BitbucketBuildStatus.class, new BitbucketBuildStatusSerializer());
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();

    OAuthRequest request = new OAuthRequest(Verb.POST, buildStatusResource.generateUrl(Verb.POST));
    request.addHeader("Content-type", "application/json");
    request.addPayload(gson.toJson(buildStatus));

    Token token = apiService.getAccessToken(OAuthConstants.EMPTY_TOKEN, null);
    apiService.signRequest(token, request);

    Response response = request.send();

    logger.info("This request was sent: " + request.getBodyContents());
    logger.info("This response was received: " + response.getBody());
    listener.getLogger().println("Sending build status " + buildStatus.getState() +
            " for commit " + buildStatusResource.getCommitId() + " to BitBucket is done!");
}
 
Example #10
Source File: BitbucketBuildStatusHelper.java    From bitbucket-build-status-notifier-plugin with MIT License 5 votes vote down vote up
public static void notifyBuildStatus(UsernamePasswordCredentials credentials, boolean overrideLatestBuild,
                                     final Run<?, ?> build, final TaskListener listener,
                                     BitbucketBuildStatus buildStatus, String repoSlug, String commitId) throws Exception {

    List<BitbucketBuildStatusResource> buildStatusResources = createBuildStatusResources(build);

    Run<?, ?> prevBuild = build.getPreviousBuild();
    List<BitbucketBuildStatusResource> prevBuildStatusResources = new ArrayList<BitbucketBuildStatusResource>();
    if (prevBuild != null && prevBuild.getResult() != null && prevBuild.getResult() == Result.ABORTED) {
        prevBuildStatusResources = createBuildStatusResources(prevBuild);
    }

    for (BitbucketBuildStatusResource buildStatusResource : buildStatusResources) {

        // if previous build was manually aborted by the user and revision is the same than the current one
        // then update the bitbucket build status resource with current status and current build number
        for (BitbucketBuildStatusResource prevBuildStatusResource : prevBuildStatusResources) {
            if (prevBuildStatusResource.getCommitId().equals(buildStatusResource.getCommitId())) {
                BitbucketBuildStatus prevBuildStatus = createBitbucketBuildStatusFromBuild(prevBuild, overrideLatestBuild);
                buildStatus.setKey(prevBuildStatus.getKey());

                break;
            }
        }

        if (repoSlug != null && commitId != null) {
            buildStatusResource = new BitbucketBuildStatusResource(buildStatusResource.getOwner(), repoSlug, commitId);
        }

        sendBuildStatusNotification(credentials, build, buildStatusResource, buildStatus, listener);
    }
}
 
Example #11
Source File: AbstractAnsibleInvocation.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
protected ArgumentListBuilder prependPasswordCredentials(ArgumentListBuilder args) {
    if (credentials instanceof UsernamePasswordCredentials) {
        UsernamePasswordCredentials passwordCredentials = (UsernamePasswordCredentials)credentials;
        args.add("sshpass").addMasked("-p" + Secret.toString(passwordCredentials.getPassword()));
    }
    return args;
}
 
Example #12
Source File: BitbucketBuildStatusNotifier.java    From bitbucket-build-status-notifier-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckGlobalCredentialsId(@QueryParameter final String globalCredentialsId) {
    if (globalCredentialsId.isEmpty()) {
        return FormValidation.ok();
    }

    Job owner = null;
    UsernamePasswordCredentials credentials = BitbucketBuildStatusHelper.getCredentials(globalCredentialsId, owner);

    return this.checkCredentials(credentials);
}
 
Example #13
Source File: AnsiblePlaybookStep.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Project project) {
    return new StandardListBoxModel()
        .withEmptySelection()
        .withMatching(anyOf(
            instanceOf(SSHUserPrivateKey.class),
            instanceOf(UsernamePasswordCredentials.class)),
            CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, project));
}
 
Example #14
Source File: MarathonRecorder.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item) {
    return new StandardListBoxModel().withEmptySelection().withMatching(
            CredentialsMatchers.anyOf(
                    CredentialsMatchers.instanceOf(StringCredentials.class),
                    CredentialsMatchers.instanceOf(UsernamePasswordCredentials.class)
            ),
            CredentialsProvider.lookupCredentials(StandardCredentials.class, item, null, Collections.<DomainRequirement>emptyList())
    );
}
 
Example #15
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project) {
    AbstractIdCredentialsListBoxModel result = new StandardListBoxModel();
    if (!project.hasPermission(Item.CONFIGURE)) {
        return result;
    }
    List<UsernamePasswordCredentials> credentialsList = CredentialsProvider.lookupCredentials(UsernamePasswordCredentials.class, project, ACL.SYSTEM);
    for (UsernamePasswordCredentials credential : credentialsList) {
        result = result.with((IdCredentials) credential);
    }
    return result;
}
 
Example #16
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private static GitHub getGitHubIfValid(String credentialsId, String gitApiUrl, Item context) throws IOException {
    if (credentialsId == null || credentialsId.isEmpty()) {
        throw new IllegalArgumentException(NULL_CREDENTIALS_ID);
    }
    UsernamePasswordCredentials credentials = getCredentials(UsernamePasswordCredentials.class, credentialsId, context);
    if (credentials == null) {
        throw new IllegalArgumentException(CREDENTIALS_ID_NOT_EXISTS);
    }
    GitHubBuilder githubBuilder = new GitHubBuilder();

    githubBuilder.withOAuthToken(credentials.getPassword().getPlainText(), credentials.getUsername());

    if (gitApiUrl == null || gitApiUrl.isEmpty()) {
        githubBuilder = githubBuilder.withProxy(getProxy("https://api.github.com"));
    } else {
        githubBuilder = githubBuilder.withEndpoint(gitApiUrl);
        githubBuilder = githubBuilder.withProxy(getProxy(gitApiUrl));
    }

    GitHub github = githubBuilder.build();

    if (github.isCredentialValid()) {
        return github;
    } else {
        throw new IllegalArgumentException(CREDENTIALS_LOGIN_INVALID);
    }
}
 
Example #17
Source File: HttpNotifierConfigTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetCredentialsNotEmpty() {
  HttpNotifierConfig instance = HttpNotifierConfig.fromGlobalConfig("", "", "");
  StandardUsernamePasswordCredentials credentials =
          new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, httpCredentialsId,
                  "description", httpUsername, httpPassword);
  when(BuildStatusConfig.getCredentials(UsernamePasswordCredentials.class, httpCredentialsId)).thenReturn(credentials);
  assertEquals(instance.getCredentials(), credentials);
  assertEquals(httpCredentialsId, credentials.getId());
  assertEquals(httpUsername, credentials.getUsername());
  assertEquals(httpPassword, credentials.getPassword().getPlainText());
}
 
Example #18
Source File: HttpNotifierConfig.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Returns credentials for accessing the HTTP endpoint if they are configured.
 *
 * @return credentials; null if not provided
 */
@CheckForNull
public UsernamePasswordCredentials getCredentials() {
    return !Strings.isNullOrEmpty(httpCredentialsId) ?
            BuildStatusConfig.getCredentials(UsernamePasswordCredentials.class,
                    httpCredentialsId) :
            null;
}
 
Example #19
Source File: InfluxDbNotifierConfig.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Returns the credentials for calling InfluxDB if they are configured.
 *
 * @return the credentials; null if not provided.
 */
@CheckForNull
public UsernamePasswordCredentials getCredentials() {
    return !StringUtils.isEmpty(influxDbCredentialsId) ?
            BuildStatusConfig.getCredentials(UsernamePasswordCredentials.class,
                    influxDbCredentialsId) :
            null;
}
 
Example #20
Source File: HttpNotifier.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
public HttpNotifier(HttpNotifierConfig config) {
    if (null == config || Strings.isNullOrEmpty(config.getHttpEndpoint())) {
        return;
    }
    this.repoOwner = config.getRepoOwner();
    this.repoName = config.getRepoName();
    this.branchName = config.getBranchName();
    this.config = config;
    this.stageMap = new HashMap<>();
    UsernamePasswordCredentials credentials = config.getCredentials();
    if (credentials != null) {
        String username = credentials.getUsername();
        String password = credentials.getPassword().getPlainText();

        authorization = Base64.getEncoder().encodeToString(
                String.format("%s:%s", username, password).getBytes(StandardCharsets.UTF_8));
    }
    gson = new GsonBuilder()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getAnnotation(SkipSerialisation.class) != null;
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();
}
 
Example #21
Source File: InfluxDbNotifier.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Constructor
 *
 * @param config InfluxDB configuration info
 */
public InfluxDbNotifier(InfluxDbNotifierConfig config) {
    if (StringUtils.isEmpty(config.getInfluxDbUrlString()) || StringUtils.isEmpty(config.getInfluxDbDatabase())) {
        return;
    }
    String urlString = String.format("%s/write?db=%s", config.getInfluxDbUrlString(), config.getInfluxDbDatabase());
    try {
        UsernamePasswordCredentials credentials = config.getCredentials();
        if (credentials != null) {
            String influxDbUser = credentials.getUsername();
            String influxDbPassword = credentials.getPassword().getPlainText();

            authorization = Base64.getEncoder().encodeToString(
                    String.format("%s:%s", influxDbUser, influxDbPassword).getBytes(StandardCharsets.UTF_8));
        }
        if (!StringUtils.isEmpty(config.getInfluxDbRetentionPolicy())) {
            urlString = urlString.concat(
                    String.format("&rp=%s", URLEncoder.encode(config.getInfluxDbRetentionPolicy(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(InfluxDbNotifier.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (config.influxDbIsReachable()) {
        this.repoOwner = config.getRepoOwner();
        this.repoName = config.getRepoName();
        this.branchName = config.getBranchName();
        if (StringUtils.isEmpty(this.repoOwner)) {
            this.repoOwner = BuildNotifierConstants.DEFAULT_STRING;
        }
        if (StringUtils.isEmpty(this.repoName)) {
            this.repoName = BuildNotifierConstants.DEFAULT_STRING;
        }
        if (StringUtils.isEmpty(this.branchName)) {
            this.branchName = BuildNotifierConstants.DEFAULT_STRING;
        }
        this.influxDbUrlString = urlString;
        this.config = config;
    }
}
 
Example #22
Source File: UsernamePasswordDockerRegistryTokenSource.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public DockerRegistryToken convert(UsernamePasswordCredentials c) throws AuthenticationTokenException {
    return new DockerRegistryToken(c.getUsername(),
            Base64.encodeBase64String((c.getUsername() + ":" + c.getPassword().getPlainText())
                    .getBytes(Charsets.UTF_8)));
}
 
Example #23
Source File: PropertiesSecretSourceTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("PropertiesSecretSourceTest.yaml")
public void test_reading_secrets_from_properties() throws Exception {
    List<UsernamePasswordCredentials> credentialList = CredentialsProvider
        .lookupCredentials(UsernamePasswordCredentials.class,
            Jenkins.getInstanceOrNull(), null, Collections.emptyList());
    assertEquals(1, credentialList.size());

    UsernamePasswordCredentials credentials = credentialList.get(0);

    // https://leahneukirchen.org/blog/archive/2019/10/ken-thompson-s-unix-password.html
    assertEquals("ken", credentials.getUsername());
    assertEquals("p/q2-q4!", credentials.getPassword().getPlainText());
}
 
Example #24
Source File: GiteaAuthSourceTest.java    From gitea-plugin with MIT License 5 votes vote down vote up
@Test
public void given__userPassCredential__when__convert__then__tokenAuth() throws Exception {
    // we use a mock to ensure that java.lang.reflect.Proxy implementations of the credential interface work
    UsernamePasswordCredentials credential = Mockito.mock(UsernamePasswordCredentials.class);
    Mockito.when(credential.getUsername()).thenReturn("bob");
    Mockito.when(credential.getPassword()).thenReturn(Secret.fromString("secret"));
    GiteaAuth auth = AuthenticationTokens.convert(GiteaAuth.class, credential);
    assertThat(auth, instanceOf(GiteaAuthUser.class));
    assertThat(((GiteaAuthUser)auth).getUsername(), is("bob"));
    assertThat(((GiteaAuthUser)auth).getPassword(), is("secret"));
}
 
Example #25
Source File: DockerCloudTest.java    From docker-plugin with MIT License 5 votes vote down vote up
@Test
public void globalConfigRoundtrip() throws Exception {

    // Create fake credentials, so they are selectable on configuration for during configuration roundtrip
    final CredentialsStore store = CredentialsProvider.lookupStores(jenkins.getInstance()).iterator().next();
    DockerServerCredentials dc = new DockerServerCredentials(SYSTEM, "credentialsId", "test", null, null, null);
    store.addCredentials(Domain.global(), dc);
    UsernamePasswordCredentials rc = new UsernamePasswordCredentialsImpl(SYSTEM, "pullCredentialsId", null, null, null);
    store.addCredentials(Domain.global(), rc);

    final DockerTemplateBase templateBase = new DockerTemplateBase("image", "pullCredentialsId", "dnsString", "network",
            "dockerCommand", "volumesString", "volumesFromString", "environmentString",
            "hostname", "user1", "", 128, 256, 42, 102, "bindPorts", true, true, true, "macAddress", "extraHostsString");
    templateBase.setCapabilitiesToAddString("SYS_ADMIN");
    templateBase.setCapabilitiesToDropString("CHOWN");
    templateBase.setSecurityOptsString("seccomp=unconfined");
    final DockerTemplate template = new DockerTemplate(
            templateBase,
            new DockerComputerAttachConnector("jenkins"),
            "labelString", "remoteFs", "10");
    template.setPullStrategy(DockerImagePullStrategy.PULL_NEVER);
    template.setMode(Node.Mode.NORMAL);
    template.setRemoveVolumes(true);
    template.setStopTimeout(42);
    template.setRetentionStrategy(new DockerOnceRetentionStrategy(33));

    DockerCloud cloud = new DockerCloud("docker", new DockerAPI(new DockerServerEndpoint("uri", "credentialsId")),
            Collections.singletonList(template));

    jenkins.getInstance().clouds.replaceBy(Collections.singleton(cloud));

    jenkins.configRoundtrip();

    Assert.assertEquals(cloud, jenkins.getInstance().clouds.get(0));
}
 
Example #26
Source File: GiteaAuthUserSource.java    From gitea-plugin with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public GiteaAuthUser convert(@NonNull UsernamePasswordCredentials credential) throws AuthenticationTokenException {
    return new GiteaAuthUser(credential.getUsername(), credential.getPassword().getPlainText());
}
 
Example #27
Source File: UsernamePasswordDockerRegistryTokenSource.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
public UsernamePasswordDockerRegistryTokenSource() {
    super(DockerRegistryToken.class, UsernamePasswordCredentials.class);
}
 
Example #28
Source File: BitbucketBuildStatusHelper.java    From bitbucket-build-status-notifier-plugin with MIT License 4 votes vote down vote up
public static void notifyBuildStatus(UsernamePasswordCredentials credentials, boolean overrideLatestBuild,
                                     final Run<?, ?> build, final TaskListener listener) throws Exception {
    notifyBuildStatus(credentials, overrideLatestBuild, build, listener, createBitbucketBuildStatusFromBuild(build, overrideLatestBuild), null, null);
}
 
Example #29
Source File: HttpNotifierConfigTest.java    From github-autostatus-plugin with MIT License 4 votes vote down vote up
@Test
public void testGetCredentialsEmpty() {
  HttpNotifierConfig instance = HttpNotifierConfig.fromGlobalConfig("", "", "");
  when(BuildStatusConfig.getCredentials(UsernamePasswordCredentials.class, "not-exist-credential")).thenReturn(null);
  assertNull(instance.getCredentials());
}
 
Example #30
Source File: HttpNotifierTest.java    From github-autostatus-plugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  mockConfig = mock(HttpNotifierConfig.class);

  when(mockConfig.getHttpEndpoint()).thenReturn("https://mock.com/jenkins");
  when(mockConfig.getRepoName()).thenReturn(repoName);
  when(mockConfig.getRepoOwner()).thenReturn(repoOwner);
  when(mockConfig.getBranchName()).thenReturn("");
  when(mockConfig.getHttpCredentialsId()).thenReturn(credentialId);
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, credentialId, "description", username, password);
  when(mockConfig.getCredentials()).thenReturn(credentials);
  when(mockConfig.getHttpVerifySSL()).thenReturn(true);

  mockHttpClient = mock(CloseableHttpClient.class);
  when(mockConfig.getHttpClient(false)).thenReturn(mockHttpClient);

  CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
  mockStatusLine = mock(StatusLine.class);
  when(mockStatusLine.getStatusCode()).thenReturn(200);
  when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);

  when(mockHttpClient.execute(any())).thenAnswer((InvocationOnMock invocation) -> {
    HttpPost httpPost = (HttpPost) invocation.getArguments()[0];
    Header[] headers = httpPost.getAllHeaders();
    for (Header header : headers) {
      requestHeaders.put(header.getName(), header.getValue());
    }
    HttpEntity entity = httpPost.getEntity();
    bodyData = EntityUtils.toString(entity);
    return mockResponse;
  });

  Cause mockCause = mock(Cause.UserIdCause.UserIdCause.class);
  when(mockCause.getShortDescription()).thenReturn(trigger);

  mockRun = mock(AbstractBuild.class);
  when(mockRun.getCause(Cause.class)).thenReturn(mockCause);
  when(mockRun.getNumber()).thenReturn(buildNumber);
  when(mockRun.getUrl()).thenReturn(buildUrl);

  mockStageMap = mock(HashMap.class);
  notifier = new HttpNotifier(mockConfig);
  notifier.stageMap = mockStageMap;

  Jenkins jenkins = mock(Jenkins.class);
  when(jenkins.getRootUrl()).thenReturn(jenkinsUrl);
  PowerMockito.mockStatic(Jenkins.class);
  when(Jenkins.get()).thenReturn(jenkins);
}