本文整理匯總了Java中hudson.util.Secret類的典型用法代碼示例。如果您正苦於以下問題:Java Secret類的具體用法?Java Secret怎麽用?Java Secret使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Secret類屬於hudson.util包,在下文中一共展示了Secret類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: addGlobalConfigDataForSonarInstance
import hudson.util.Secret; //導入依賴的package包/類
protected void addGlobalConfigDataForSonarInstance(JSONObject globalConfigData) {
String name = globalConfigData.optString("name");
int timeToWait = globalConfigData.optInt("timeToWait");
String url = globalConfigData.optString("url");
if (!"".equals(name)) {
GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance;
String token = globalConfigData.optString("token");
if (StringUtils.isNotEmpty(token)) {
globalConfigDataForSonarInstance = new GlobalConfigDataForSonarInstance(name, url, globalConfigData.optString("token"), timeToWait);
} else {
globalConfigDataForSonarInstance = new GlobalConfigDataForSonarInstance(name, url, globalConfigData.optString("account"), Secret.fromString(Util.fixEmptyAndTrim(globalConfigData.optString("password"))), timeToWait);
}
if (!containsGlobalConfigWithName(name)) {
listOfGlobalConfigInstances.add(globalConfigDataForSonarInstance);
}
}
}
示例2: doCheckToken
import hudson.util.Secret; //導入依賴的package包/類
/**
* Sanity check for a Gitea access token.
*
* @param value the token.
* @return the resulst of the sanity check.
*/
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused") // stapler
public FormValidation doCheckToken(@QueryParameter String value) {
Secret secret = Secret.fromString(value);
if (secret == null) {
return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenRequired());
}
if (StringUtils.equals(value, secret.getPlainText())) {
if (value.length() != 40) {
return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
}
} else if (secret.getPlainText().length() != 40) {
return FormValidation.warning(Messages.PersonalAccessTokenImpl_tokenWrongLength());
}
return FormValidation.ok();
}
示例3: getKeyVaultCredential
import hudson.util.Secret; //導入依賴的package包/類
public AzureKeyVaultCredential getKeyVaultCredential(Run<?, ?> build, Secret _applicationSecret, String _credentialID)
throws CredentialNotFoundException, CredentialException
{
// Try Credential
if (!AzureKeyVaultUtil.isNullOrEmpty(_credentialID))
{
LOGGER.log(Level.INFO, String.format("Fetching credentials by ID"));
AzureKeyVaultCredential credential = getCredentialById(_credentialID, build);
if (!credential.isApplicationIDValid())
{
LOGGER.log(Level.INFO, String.format("Credential is password-only. Setting the username"));
// Credential only contains the app secret - add the app id
credential.setApplicationID(getApplicationID());
}
return credential;
}
// Try AppID/Secret
if (!AzureKeyVaultUtil.isNullOrEmpty(_applicationSecret))
{
LOGGER.log(Level.WARNING, String.format("Using explicit application secret. This will be deprecated in 1.0. Use Credential ID instead."));
return new AzureKeyVaultCredential(getApplicationID(), _applicationSecret);
}
return new AzureKeyVaultCredential();
}
示例4: extractFromCertificate
import hudson.util.Secret; //導入依賴的package包/類
/**
* Extract the private key a client certificate from a X509 certificate and write them to disk.
*
* @param certificatCredential Jenkins certificateCredential
* @param clientCrtFile path where to write of the certificate
* @param clientKeyFile path where to write of the private key
* @throws IOException lol
* @throws InterruptedException on file operation
*/
public static void extractFromCertificate(StandardCertificateCredentials certificatCredential,
FilePath clientCrtFile,
FilePath clientKeyFile) throws IOException, InterruptedException {
try {
KeyStore keyStore = certificatCredential.getKeyStore();
String alias = keyStore.aliases().nextElement();
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
// Get private key using passphrase
Key key = keyStore.getKey(alias, Secret.toString(certificatCredential.getPassword()).toCharArray());
// Write certificate
String encodedClientCrt = wrapCertificate(Base64.encodeBase64String(certificate.getEncoded()));
clientCrtFile.write(encodedClientCrt, null);
// Write private key
String encodedClientKey = wrapPrivateKey(Base64.encodeBase64String(key.getEncoded()));
clientKeyFile.write(encodedClientKey, null);
} catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateEncodingException e) {
throw new AbortException(e.getMessage());
}
}
示例5: doFillProjectItems
import hudson.util.Secret; //導入依賴的package包/類
public ListBoxModel doFillProjectItems(@QueryParameter String serverUrl, @QueryParameter String username,
@QueryParameter Secret password) throws URISyntaxException {
ListBoxModel items = new ListBoxModel();
if (validInputs(serverUrl, username, password)) {
try {
TfsClient client = getTfsClientFactory().getValidatedClient(serverUrl, username, password);
List<TeamProjectReference> references = client.getProjectClient().getProjects();
for (TeamProjectReference ref : references) {
items.add(ref.getName(), String.valueOf(ref.getId()));
}
} catch (VssServiceException vse) {
return items;
}
}
return items;
}
示例6: doFillBuildDefinitionItems
import hudson.util.Secret; //導入依賴的package包/類
public ListBoxModel doFillBuildDefinitionItems(@QueryParameter String serverUrl, @QueryParameter String username,
@QueryParameter Secret password, @QueryParameter String project) throws URISyntaxException {
ListBoxModel items = new ListBoxModel();
if (validInputs(serverUrl, username, password, project)) {
try {
TfsClient client = getTfsClientFactory().getValidatedClient(serverUrl, username, password);
List<DefinitionReference> definitions = client.getBuildClient().getDefinitions(UUID.fromString(project));
for (DefinitionReference definition : definitions) {
items.add(definition.getName(), String.valueOf(definition.getId()));
}
} catch (VssServiceException vse) {
return items;
}
}
return items;
}
示例7: validInputs
import hudson.util.Secret; //導入依賴的package包/類
private boolean validInputs(Object... inputs) {
for (Object input : inputs) {
if (input == null) {
return false;
}
if (input instanceof String && Util.fixEmptyAndTrim((String) input) == null) {
return false;
}
if (input instanceof Secret && Util.fixEmptyAndTrim(Secret.toString((Secret)input)) == null) {
return false;
}
}
return true;
}
示例8: getValidatedClient
import hudson.util.Secret; //導入依賴的package包/類
public TfsClient getValidatedClient(String url, String username, Secret password) throws URISyntaxException, VssServiceException {
URI uri = new URI(url);
ServiceProvider provider = guessIsHostedInstallation(uri) ? ServiceProvider.VSO : ServiceProvider.TFS;
TfsClient client;
try {
client = new TfsClient(uri, provider, username, password);
// if this returns without throwing VssServiceException, client is working
client.getProjectClient().getProjects();
} catch (VssServiceException vse){
provider = (provider == ServiceProvider.TFS) ? ServiceProvider.VSO : ServiceProvider.TFS;
client = new TfsClient(uri, provider, username, password);
client.getProjectClient().getProjects();
}
return client;
}
示例9: setUp
import hudson.util.Secret; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
underTest = new TfsBuildWrapper();
facadeFactoryMock = Mockito.mock(TfsBuildFacadeFactory.class);
buildFacadeMock = Mockito.mock(TfsBuildFacade.class);
clientFactoryMock = Mockito.mock(TfsClientFactory.class);
tfsClientMock = Mockito.mock(TfsClient.class);
underTest.setTfsBuildFacadeFactory(facadeFactoryMock);
underTest.setTfsClientFactory(clientFactoryMock);
when(facadeFactoryMock.createBuildOnTfs(anyString(), anyInt(), any(AbstractBuild.class), any(TfsClient.class)))
.thenReturn(buildFacadeMock);
when(clientFactoryMock.getValidatedClient(anyString(), anyString(), any(Secret.class)))
.thenReturn(tfsClientMock);
when(buildFacadeMock.getTfsBuildId()).thenReturn(1);
}
示例10: loggerShouldBeDecorated
import hudson.util.Secret; //導入依賴的package包/類
@Test
public void loggerShouldBeDecorated() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
project.getPublishersList().add(new TfsBuildNotifier("http://testurl.com", "tester", Secret.fromString("testpass"), "testProj", "1"));
jenkinsBuild = project.scheduleBuild2(0).get();
OutputStream os = new ByteArrayOutputStream(2048);
OutputStream appender = underTest.decorateLogger(jenkinsBuild, os);
verify(buildFacadeMock, times(1)).startBuild();
verify(buildFacadeMock, times(1)).startAllTaskRecords();
assertNotNull("Did not create a log appender for TFS", appender);
// verify we properly set environments, this tests makeBuildVariables
Map<String,String> env = new HashMap<String, String>();
underTest.makeBuildVariables(jenkinsBuild, env);
assertTrue("Env is empty", env.size() > 0);
assertEquals("build is should be 1", 1, Integer.parseInt(env.get("TfsBuildId" + jenkinsBuild.getId())));
}
示例11: newTokenCredentials
import hudson.util.Secret; //導入依賴的package包/類
/**
* Helper method to update a credential stored within the Jenkins Credential Store. This creates a new credential
* to replace tokenCredentials.
*
* @param tokenCredentials The current, existing credential to update.
* @param token New token value for credential
* @return New Credentials constructed from tokenCredentials
*/
StringCredentials newTokenCredentials(final StringCredentials tokenCredentials, final String token) {
// retrieved a new token, now to update the existing credential in `tokenCredentials`
JSONObject json;
try {
json = JSONObject.fromObject(tokenCredentials.getSecret().getPlainText());
} catch (JSONException jse) {
json = new JSONObject();
}
json.put("jenkins_token", token);
return new StringCredentialsImpl(
tokenCredentials.getScope(),
tokenCredentials.getId(),
tokenCredentials.getDescription(),
Secret.fromString(json.toString()));
}
示例12: testRecorderInvalidToken
import hudson.util.Secret; //導入依賴的package包/類
/**
* 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());
}
示例13: testHSSecretKey
import hudson.util.Secret; //導入依賴的package包/類
/**
* Test that all other algorithms besides RS256 are rejected.
*
* @throws Exception
*/
@Test
public void testHSSecretKey() throws Exception {
final Secret secret = PowerMockito.mock(Secret.class);
final String[] algs = new String[]{"HS512", "HS256", "RS512"};
for (final String alg : algs) {
final String secretText = String.format(DCOS_AUTH_JSON, testUser, "a secret key", alg);
Whitebox.setInternalState(secret, "value", secretText);
when(credentials.getSecret()).thenReturn(secret);
when(secret.getPlainText()).thenReturn(secretText);
final DcosAuthImpl dcosAuth = new DcosAuthImpl(credentials,
options,
ContentType.APPLICATION_JSON,
builder,
context);
try {
dcosAuth.createDcosLoginPayload();
assertFalse("Invalid algorithm was accepted", true);
} catch (AuthenticationException e) {
assertTrue("Does not list valid algorithm in message", e.getMessage().contains("RS256"));
}
}
}
示例14: toString
import hudson.util.Secret; //導入依賴的package包/類
@Nonnull
protected static Collection<String> toString(@Nonnull Iterable<Credentials> credentials) {
List<String> result = new ArrayList<>();
for (Credentials creds : credentials) {
if (creds instanceof PasswordCredentials) {
PasswordCredentials passwordCredentials = (PasswordCredentials) creds;
result.add(passwordCredentials.getPassword().getPlainText());
} else if (creds instanceof SSHUserPrivateKey) {
SSHUserPrivateKey sshUserPrivateKey = (SSHUserPrivateKey) creds;
Secret passphrase = sshUserPrivateKey.getPassphrase();
if (passphrase != null) {
result.add(passphrase.getPlainText());
}
// omit the private key, there
} else {
LOGGER.log(Level.FINE, "Skip masking of unsupported credentials type {0}: {1}", new Object[]{creds.getClass(), creds.getDescriptor().getDisplayName()});
}
}
return result;
}
示例15: doTestConnection
import hudson.util.Secret; //導入依賴的package包/類
public FormValidation doTestConnection(
@QueryParameter("nexusUrl") final String nexusUrl,
@QueryParameter("nexusUser") final String nexusUser,
@QueryParameter("nexusPassword") final String nexusPassword) throws IOException, ServletException {
try {
NexusClient nexusClient = new NexusClient(null, null, null);
if( nexusClient.testConnection(nexusUrl, nexusUser, Secret.fromString( nexusPassword )) ) {
return FormValidation.ok("Success. Connection with Nexus Repository verified.");
}
return FormValidation.error("Failed. Please check the configuration. HTTP Status: isn't 200" );
} catch (Exception e) {
System.out.println("Exception " + e.getMessage() );
return FormValidation.error("Client error : " + e.getMessage());
}
}