Java Code Examples for org.jenkinsci.plugins.plaincredentials.StringCredentials

The following examples show how to use org.jenkinsci.plugins.plaincredentials.StringCredentials. These examples are extracted from open source projects. 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
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter final String credentialsId) {
    Jenkins instance = Jenkins.get();
    if (!instance.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    instance,
                    StringCredentials.class,
                    URIRequirementBuilder.fromUri(ATLASSIAN_API_URL).build(),
                    CredentialsMatchers.always());
}
 
Example 2
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST
                    ));
}
 
Example 3
Source Project: remoting-kafka-plugin   Source File: KafkaKubernetesCloud.java    License: MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                                    : Collections.EMPTY_LIST
                    ));
}
 
Example 4
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: MIT License 6 votes vote down vote up
private String getgApiKey() {
    StandardCredentials credentials = null;
    try {
        credentials = CredentialsMatchers.firstOrNull(
                lookupCredentials(StandardCredentials.class, (Item) null, ACL.SYSTEM, new ArrayList<DomainRequirement>()),
                CredentialsMatchers.withId(gApiKeyID));
    }
    catch (NullPointerException e) {
        throw new ConnectionException(SR.getString("api.key.not.set"));
    }
    if (credentials != null) {
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("Could not find Acunetix API Key ID: " + gApiKeyID);
}
 
Example 5
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: MIT License 6 votes vote down vote up
public ListBoxModel doFillGApiKeyIDItems(
        @AncestorInPath Item item) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    }
    if (gApiKeyID != null) {
        result.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.withId(gApiKeyID)));
    }
    return result
            .includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                    Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.instanceOf(StringCredentials.class)));
}
 
Example 6
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example 7
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example 8
Source Project: marathon-plugin   Source File: MarathonBuilderImpl.java    License: 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 9
Source Project: marathon-plugin   Source File: MarathonBuilderImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a Marathon client with Authorization headers using the token within provided credentials. If the content of
 * credentials is JSON, this will use the "jenkins_token" field; if the content is just a string, that will be
 * used as the token value.
 *
 * @param credentials String credentials
 * @return Marathon client with token in auth header
 */
private Marathon getMarathonClient(StringCredentials credentials) {
    String token;

    try {
        final JSONObject json = JSONObject.fromObject(credentials.getSecret().getPlainText());
        if (json.has("jenkins_token")) {
            token = json.getString("jenkins_token");
        } else {
            token = "";
        }
    } catch (JSONException jse) {
        token = credentials.getSecret().getPlainText();
    }

    if (StringUtils.isNotEmpty(token)) {
        return MarathonClient
                .getInstanceWithTokenAuth(getURL(), token);
    }

    return getMarathonClient();
}
 
Example 10
Source Project: marathon-plugin   Source File: MarathonRecorderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that a JSON credential without a "jenkins_token" field and without a proper DC/OS service account value
 * results in a 401 and only 1 web request.
 *
 * @throws Exception
 */
@Test
public void testRecorderInvalidToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 credentialValue = "{\"field1\":\"some value\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "invalidtoken", "a token for JSON token test", secret);
    TestUtils.enqueueFailureResponse(httpServer, 401);

    systemStore.addCredentials(Domain.global(), credential);

    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "invalidtoken");

    final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon] Authentication to Marathon instance failed:", build);
    j.assertLogContains("[Marathon] Invalid DC/OS service account JSON", build);
    assertEquals("Only 1 request should have been made.", 1, httpServer.getRequestCount());
}
 
Example 11
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example 12
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example 13
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
    ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
    StandardCredentials credentials = CredentialsMatchers.firstOrNull(
        lookupCredentials(
                StandardCredentials.class,
                context, 
                ACL.SYSTEM,
                URIRequirementBuilder.fromUri(url).build()),
        CredentialsMatchers.withId(apiTokenId));
    if (credentials != null) {
        if (credentials instanceof GitLabApiToken) {
            return ((GitLabApiToken) credentials).getApiToken().getPlainText();
        }
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
 
Example 14
public Optional<String> getSecretFor(final String credentialsId) {

        final List<StringCredentials> credentials =
                CredentialsProvider.lookupCredentials(
                        StringCredentials.class,
                        Jenkins.get(),
                        ACL.SYSTEM,
                        Collections.emptyList());
        final CredentialsMatcher matcher = CredentialsMatchers.withId(credentialsId);

        return Optional.ofNullable(CredentialsMatchers.firstOrNull(credentials, matcher))
                .flatMap(creds -> Optional.ofNullable(creds.getSecret()))
                .flatMap(secret -> Optional.ofNullable(secret.getPlainText()));
    }
 
Example 15
Source Project: marathon-plugin   Source File: MarathonRecorder.java    License: 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 16
Source Project: marathon-plugin   Source File: DcosAuthImpl.java    License: Apache License 2.0 5 votes vote down vote up
public DcosAuthImpl(final StringCredentials credentials) {
    this(
            credentials,
            new JWTSigner.Options(),
            ContentType.APPLICATION_JSON,
            HttpClientBuilder.create(),
            new HttpClientContext()
    );
}
 
Example 17
Source Project: marathon-plugin   Source File: DcosAuthImpl.java    License: Apache License 2.0 5 votes vote down vote up
DcosAuthImpl(final StringCredentials credentials,
             final JWTSigner.Options options,
             final ContentType contentType,
             final HttpClientBuilder clientBuilder,
             final HttpClientContext clientContext) {
    this.options = options;

    this.contentType = contentType;
    this.client = clientBuilder;
    this.context = clientContext;
    this.credentials = credentials;
}
 
Example 18
Source Project: marathon-plugin   Source File: DcosAuthImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateTokenCredentials(final Credentials tokenCredentials) throws AuthenticationException {
    if (tokenCredentials instanceof StringCredentials) {
        final StringCredentials oldCredentials = (StringCredentials) tokenCredentials;

        if (credentials != null) {
            try {
                final String token = getToken();
                if (token == null) {
                    // TODO: better message somewhere in getToken flow of what happened?
                    final String errorMessage = "Failed to retrieve authentication token from DC/OS.";
                    LOGGER.warning(errorMessage);
                    throw new AuthenticationException(errorMessage);
                }
                final StringCredentials updatedCredentials = newTokenCredentials(oldCredentials, token);
                return doTokenUpdate(oldCredentials.getId(), updatedCredentials);
            } catch (IOException e) {
                LOGGER.warning(e.getMessage());
                throw new AuthenticationException(e.getMessage());
            }
        }
    } else {
        LOGGER.warning("Invalid credential type, expected String Credentials, received: " + tokenCredentials.getClass().getName());
    }

    return false;
}
 
Example 19
Source Project: marathon-plugin   Source File: TokenAuthProvider.java    License: Apache License 2.0 5 votes vote down vote up
public static TokenAuthProvider getTokenAuthProvider(final Providers provider, final Credentials credentials) {
    switch (provider) {
        case DCOS:
            return new DcosAuthImpl((StringCredentials) credentials);
        default:
            return null;
    }
}
 
Example 20
Source Project: marathon-plugin   Source File: TokenAuthProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to update tokenCredentials with contents of creds.
 * <p>
 * This searches all domains for the id associated with tokenCredentials and updates the first credential it finds.
 *
 * @param tokenId Existing credentials that should be updated.
 * @param creds   New credentials
 * @throws IOException If problems reading or writing to Jenkins Credential Store
 */
boolean doTokenUpdate(final String tokenId, final Credentials creds) throws IOException {
    final SystemCredentialsProvider.ProviderImpl systemProvider = ExtensionList.lookup(CredentialsProvider.class)
            .get(SystemCredentialsProvider.ProviderImpl.class);
    if (systemProvider == null) return false;

    final CredentialsStore credentialsStore = systemProvider.getStore(Jenkins.getInstance());
    if (credentialsStore == null) return false;

    /*
        Walk through all domains and credentials for each domain to find a credential with the matching id.
     */
    for (final Domain d : credentialsStore.getDomains()) {
        for (Credentials c : credentialsStore.getCredentials(d)) {
            if (!(c instanceof StringCredentials)) continue;

            final StringCredentials stringCredentials = (StringCredentials) c;
            if (stringCredentials.getId().equals(tokenId)) {
                final boolean wasUpdated = credentialsStore.updateCredentials(d, c, creds);
                if (!wasUpdated) {
                    LOGGER.warning("Updating Token credential failed during update call.");
                }
                return wasUpdated;
            }
        }
    }

    // if the credential was not found, then put a warning in the console log.
    LOGGER.warning("Token credential was not found in the Credentials Store.");
    return false;
}
 
Example 21
Source Project: marathon-plugin   Source File: MarathonBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Perform the actual update call to Marathon. If a 401 (Unauthenticated) response is received,
 * this will try to retrieve a new token from DC/OS using JWT credentials.
 *
 * @return this Marathon builder
 * @throws MarathonException       If Marathon does not return a 20x OK response
 * @throws AuthenticationException If an authentication provider was used and encountered a problem.
 */
@Override
public MarathonBuilder update() throws MarathonException, AuthenticationException {
    if (getApp() != null) {
        try {
            doUpdate(config.getCredentialsId());
        } catch (MarathonException marathonException) {
            LOGGER.warning("Marathon Exception: " + marathonException.getMessage());

            // 401 results may be possible to resolve, others not so much
            if (marathonException.getStatus() != 401) throw marathonException;
            LOGGER.fine("Received 401 when updating Marathon application.");

            final StringCredentials tokenCredentials = MarathonBuilderUtils.getTokenCredentials(config.getCredentialsId());
            if (tokenCredentials == null) {
                LOGGER.warning("Unauthorized (401) and service account credentials are not filled in.");
                throw marathonException;
            }

            // check if service account credentials were configured
            // try to determine correct provider and update token
            // (there is only one provider thus far, so this is simple)
            boolean                 updatedToken = false;
            final TokenAuthProvider provider     = TokenAuthProvider.getTokenAuthProvider(TokenAuthProvider.Providers.DCOS, tokenCredentials);
            if (provider != null) {
                updatedToken = provider.updateTokenCredentials(tokenCredentials);
            }

            // use the new token if it was updated
            if (updatedToken) {
                LOGGER.info("Token was successfully updated.");
                doUpdate(config.getCredentialsId());
            }
        }
    }

    return this;
}
 
Example 22
Source Project: marathon-plugin   Source File: MarathonRecorderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test a basic API token using StringCredentials.
 *
 * @throws Exception
 */
@Test
public void testRecorderBasicToken() throws Exception {
    final FreeStyleProject                       project     = j.createFreeStyleProject();
    final String                                 responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system      = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore = system.getStore(j.getInstance());
    final String                                 tokenValue  = "my secret token";
    final Secret                                 secret      = Secret.fromString(tokenValue);
    final StringCredentials                      credential  = new StringCredentialsImpl(CredentialsScope.GLOBAL, "basictoken", "a token for basic token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);
    // add post-builder
    addPostBuilders(project, "basictoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request = httpServer.takeRequest();

    final String authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
 
Example 23
Source Project: marathon-plugin   Source File: MarathonRecorderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test that a JSON credential with "jenkins_token" uses the token value as the authentication token.
 *
 * @throws Exception
 */
@Test
public void testRecorderJSONToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final String                                 responseStr     = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 tokenValue      = "my secret token";
    final String                                 credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "jsontoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request           = httpServer.takeRequest();
    final String    authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
 
Example 24
Source Project: git-changelog-plugin   Source File: CredentialsHelper.java    License: MIT License 5 votes vote down vote up
public static Optional<String> findSecretString(String credentialsId) {
  Optional<String> token = Optional.empty();
  if (!isNullOrEmpty(credentialsId)) {
    final Optional<StringCredentials> credentials =
        CredentialsHelper.findCredentials(credentialsId);
    if (credentials.isPresent()) {
      final StringCredentials stringCredential =
          checkNotNull(credentials.get(), "Credentials selected but not set!");
      token = Optional.of(stringCredential.getSecret().getPlainText());
    }
  }
  return token;
}
 
Example 25
Source Project: git-changelog-plugin   Source File: CredentialsHelper.java    License: MIT License 5 votes vote down vote up
public static Optional<StringCredentials> findCredentials(String apiTokenCredentialsId) {
  if (isNullOrEmpty(apiTokenCredentialsId)) {
    return Optional.empty();
  }

  return Optional.ofNullable(
      firstOrNull(
          getAllCredentials(StringCredentials.class), allOf(withId(apiTokenCredentialsId))));
}
 
Example 26
@Override
public boolean matches(@NonNull Credentials credentials) {
    try {
        return credentials instanceof GitLabApiToken || credentials instanceof StringCredentials;
    } catch (Throwable e) {
        return false;
    }
}
 
Example 27
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 28
Source Project: git-changelog-plugin   Source File: CredentialsHelper.java    License: MIT License 4 votes vote down vote up
public static ListBoxModel doFillApiTokenCredentialsIdItems() {
  List<StringCredentials> credentials = getAllCredentials(StringCredentials.class);
  return new StandardListBoxModel() //
      .includeEmptyValue() //
      .withAll(credentials);
}
 
Example 29
Source Project: credentials-binding-plugin   Source File: StringBinding.java    License: MIT License 4 votes vote down vote up
@Override protected Class<StringCredentials> type() {
    return StringCredentials.class;
}
 
Example 30
Source Project: credentials-binding-plugin   Source File: StringBinding.java    License: MIT License 4 votes vote down vote up
@Override protected Class<StringCredentials> type() {
    return StringCredentials.class;
}