com.amazonaws.util.StringUtils Java Examples

The following examples show how to use com.amazonaws.util.StringUtils. 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: ConvertService.java    From alexa-meets-polly with Apache License 2.0 7 votes vote down vote up
public static AmazonS3 getS3Client(final String region, final String roleArn) {
    final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region);

    if (StringUtils.isNullOrEmpty(roleArn)) {
        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build();
    } else {
        final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter");

        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build();
        final Credentials credentials = sts.assumeRole(assumeRole).getCredentials();

        final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
                credentials.getAccessKeyId(),
                credentials.getSecretAccessKey(),
                credentials.getSessionToken());

        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
    }
}
 
Example #2
Source File: PatchStoreProviderZkS3.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
private static DetailsS3 accessS3(LocalServerConfig configuration) {
    // Access and checking.
    String bucketName = configuration.getProperty(pBucketName);
    if ( StringUtils.isNullOrEmpty(bucketName) )
        throw new IllegalArgumentException("Missing required property: "+pBucketName);

    String region = configuration.getProperty(pRegion);
    if ( StringUtils.isNullOrEmpty(region) )
        throw new IllegalArgumentException("Missing required property: "+pRegion);

    String prefixStr = configuration.getProperty(pPrefix);
    if ( StringUtils.isNullOrEmpty(prefixStr) )
        prefixStr = DEFAULT_PREFIX;
    String prefix = (prefixStr!=null) ? prefixStr : DEFAULT_PREFIX;
    AmazonS3 client = S3.buildS3(configuration);
    return new DetailsS3(bucketName, prefix, client);
    //return access.computeIfAbsent(bucketName, n->new DetailsS3(bucketName, prefix, client));
}
 
Example #3
Source File: EnvironmentAWSCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) {
        throw new SdkClientException(
            "Unable to load AWS credentials from environment " +
                "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and " +
                SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null ?
        new BasicAWSCredentials(accessKey, secretKey)
        :
        new BasicSessionCredentials(accessKey, secretKey, sessionToken);
}
 
Example #4
Source File: RepositoryS3.java    From github-bucket with ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example #5
Source File: DateTimeFormatterUtil.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms the raw string to LocalDate using the provided default format
 *
 * @param value raw value to be transformed to LocalDate
 * @param dateFormat customer specified or inferred dateformat
 * @param defaultTimeZone default timezone to be applied
 * @return LocalDate object parsed from value
 */
public static LocalDate stringToLocalDate(String value, String dateFormat,
                                          ZoneId defaultTimeZone)
{
    if (StringUtils.isNullOrEmpty(dateFormat)) {
        logger.info("Unable to parse {} as Date type due to invalid dateformat", value);
        return null;
    }
    Date dateTransformedValue = stringToDate(value, dateFormat);
    if (dateTransformedValue == null) {
        return null;
    }
    return dateTransformedValue.toInstant()
            .atZone(defaultTimeZone)
            .toLocalDate();
}
 
Example #6
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example #7
Source File: CloudInsightSqlServer.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static Connection getDBConnection() throws SQLException {
	String hostName = getClouldInsightSqlServer();
	String dbName = "cloudinsightbillingdb";
	String user = getClouldInsightUser();
	String password = getClouldInsightPassWord();

	if (StringUtils.isNullOrEmpty(hostName) || StringUtils.isNullOrEmpty(user)
			|| StringUtils.isNullOrEmpty(password)) {
		throw new RuntimeException(
				" Cloud insight server mandatory configuration CLOUD_INSIGHT_SQL_SERVER/CLOUD_INSIGHT_USER/CLOUD_INSIGHT_PASSWORD ");
	}
	String url = String.format(
			"jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;"
					+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;",
			hostName, dbName, user, password);
	Connection connection = null;

	connection = DriverManager.getConnection(url);
	return connection;
}
 
Example #8
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withRole(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRole())) {
		
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);

		AssumeRole assumeRole = IamRoleUtils.validRoleArn(this.step.getRole()) ? new AssumeRole(this.step.getRole()) :
				new AssumeRole(this.step.getRole(), this.createAccountId(sts), IamRoleUtils.selectPartitionName(this.step.getRegion()));
		assumeRole.withDurationSeconds(this.step.getDuration());
		assumeRole.withExternalId(this.step.getExternalId());
		assumeRole.withPolicy(this.step.getPolicy());
		assumeRole.withSamlAssertion(this.step.getSamlAssertion(), this.step.getPrincipalArn());
		assumeRole.withSessionName(this.createRoleSessionName());

		this.getContext().get(TaskListener.class).getLogger().format("Requesting assume role");
		AssumedRole assumedRole = assumeRole.assumedRole(sts);
		this.getContext().get(TaskListener.class).getLogger().format("Assumed role %s with id %s %n ", assumedRole.getAssumedRoleUser().getArn(), assumedRole.getAssumedRoleUser().getAssumedRoleId());

		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, assumedRole.getCredentials().getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, assumedRole.getCredentials().getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, assumedRole.getCredentials().getSessionToken());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #9
Source File: RepositoryS3.java    From github-bucket with ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example #10
Source File: HmacKeyDerivationFunctionTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultSalt() throws Exception {
    // Tests all the different ways to get the default salt

    testCase trial = testCases[0];
    HmacKeyDerivationFunction kdf1 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf1.init(trial.ikm, null);
    HmacKeyDerivationFunction kdf2 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf2.init(trial.ikm, new byte[0]);
    HmacKeyDerivationFunction kdf3 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf3.init(trial.ikm);
    HmacKeyDerivationFunction kdf4 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf4.init(trial.ikm, new byte[32]);

    byte[] testBytes = "Test".getBytes(StringUtils.UTF8);
    byte[] key1 = kdf1.deriveKey(testBytes, 16);
    byte[] key2 = kdf2.deriveKey(testBytes, 16);
    byte[] key3 = kdf3.deriveKey(testBytes, 16);
    byte[] key4 = kdf4.deriveKey(testBytes, 16);

    assertArrayEquals(key1, key2);
    assertArrayEquals(key1, key3);
    assertArrayEquals(key1, key4);
}
 
Example #11
Source File: DefaultFileHelper.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private String getUniqueDateWithIncrementalFileName(String keyPrefix) {
  fileCount++;
  StringBuilder fileName = new StringBuilder();
  fileName.append(keyPrefix).append(fileCount);

  if (!StringUtils.isNullOrEmpty(s3TargetConfigBean.fileNameSuffix)) {
    fileName.append(DOT);
    fileName.append(s3TargetConfigBean.fileNameSuffix);
  }

  if (s3TargetConfigBean.compress) {
    fileName.append(GZIP_EXTENSION);
  }
  return fileName.toString();
}
 
Example #12
Source File: AWSSecretsManagerMSSQLServerDriver.java    From aws-secretsmanager-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:sqlserver://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += ";databaseName=" + dbname + ";";
    }
    return url;
}
 
Example #13
Source File: KinesisServiceImpl.java    From Serverless-Programming-Cookbook with MIT License 5 votes vote down vote up
private void flushBatch(final String streamName, final LambdaLogger logger) {
    final PutRecordsResult result = this.kinesisClient.putRecords(new PutRecordsRequest()
            .withStreamName(streamName)
            .withRecords(this.kinesisBatch));

    result.getRecords().forEach(r -> {
        if (!(StringUtils.hasValue(r.getErrorCode()))) {
            String successMessage = "Successfully processed record with sequence number: " + r.getSequenceNumber()
                    + ", shard id: " + r.getShardId();
            logger.log(successMessage);
        } else {
            this.documentAddedCount--;

            String errorMessage = "Did not process record with sequence number: " + r.getSequenceNumber()
                    + ", error code: " + r.getErrorCode()
                    + ", error message: " + r.getErrorMessage();
            logger.log(errorMessage);
            this.isError = true;
        }
    });


    // You may also implement a retry logic only for failed records (e.g. Create a list for failed records,
    // add error records to that list and finally retry all failed records until a max retry count is reached.)
    /*
    if (result.getFailedRecordCount() != null && result.getFailedRecordCount() > 0) {
        result.getRecords().forEach(r -> {
            if ((r != null) && (StringUtils.hasValue(r.getErrorCode()))) {
                // add this record to the retry list.
            }
        });
    }
    */
}
 
Example #14
Source File: MailUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
* Formate common fix body.
*
* @param silentautoFixTrans the silentauto fix trans
* @param ruleParam the rule param
* @param resourceOwner the resource owner
* @return the string
*/
public static String formateCommonFixBody(List<AutoFixTransaction> silentautoFixTrans,Map<String, String> ruleParam,ResourceOwner resourceOwner) {
    TemplateEngine templateEngine = new TemplateEngine();
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("HTML");
    templateResolver.setSuffix(".html");
    templateEngine.setTemplateResolver(templateResolver);
    
    List<String> columnsList = Arrays.asList(CommonUtils.getPropValue(PacmanSdkConstants.PACMAN_MAIL_TEMPLATE_COLUMNS
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).split("\\s*,\\s*"));
   
    Context context = new Context(); 
  
    context.setVariable("columns", columnsList);
    context.setVariable("resources", silentautoFixTrans);
    String policyUrl = getPolicyKnowledgeBasePathURL(ruleParam);
    String name =CommonUtils.getPropValue(PacmanSdkConstants.SEND_EMAIL_SILENT_FIX_ADMIN
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    
    if(StringUtils.isNullOrEmpty(name)){
  	 name = resourceOwner.getName(); 
    }
    String postFixMessage = CommonUtils.getPropValue(PacmanSdkConstants.EMAIL_FIX_MESSAGE_PREFIX
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    context.setVariable("AUTOFIX_POST_FIX_MESSAGE", postFixMessage);
    context.setVariable("POLICY_URL", policyUrl);
    context.setVariable("NAME", "Hello "+name);
    context.setVariable("RESOURCE_TYPE", " Resource Type : "+ruleParam.get(PacmanSdkConstants.TARGET_TYPE));
    context.setVariable("AUTO_FIX_APPLIED", "Total AutoFixs Applied : "+silentautoFixTrans.size());
    StringWriter writer = new StringWriter();
    
  if(CommonUtils.getPropValue("pacman.auto.fix.common.email.notifications."
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).equals("commonTemplate")){
    	templateEngine.process("/template/autofix-user-notification-action-common.html", context, writer);
}else{
    	templateEngine.process("/template/autofix-silent-autodelete-usernotification-info.html", context, writer);
    }
    return writer.toString();
    
}
 
Example #15
Source File: CommonUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Date format.
 *
 * @param dateInString the date in string
 * @param formatFrom the format from
 * @param formatTo the format to
 * @return the date
 * @throws ParseException the parse exception
 */
public static Date dateFormat(final String dateInString, String formatFrom, String formatTo)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (StringUtils.isNullOrEmpty(formatFrom)) {
        formatFrom = dateDormatter;
    }
    if (StringUtils.isNullOrEmpty(formatTo)) {
        formatTo = dateDormatter;
    }
    DateFormat dateFromFormater = new SimpleDateFormat(formatFrom);
    DateFormat dateToFormater = new SimpleDateFormat(formatTo);
    return dateToFormater.parse(dateToFormater.format(dateFromFormater.parse(dateInString)));
}
 
Example #16
Source File: CommonUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the date from string.
 *
 * @param dateInString the date in string
 * @param format the format
 * @return the date from string
 * @throws ParseException the parse exception
 */
public static Date getDateFromString(final String dateInString, final String format)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (!StringUtils.isNullOrEmpty(format)) {
        dateDormatter = format;
    }
    SimpleDateFormat formatter = new SimpleDateFormat(dateDormatter);
    return formatter.parse(dateInString);
}
 
Example #17
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private String createAccountId(final AWSSecurityTokenService sts) {
	if (!StringUtils.isNullOrEmpty(this.step.getRoleAccount())) {
		return this.step.getRoleAccount();
	} else {
		return sts.getCallerIdentity(new GetCallerIdentityRequest()).getAccount();
	}
}
 
Example #18
Source File: AuthenticationHelper.java    From alexa-web-information-service-api-samples with MIT License 5 votes vote down vote up
private byte[] getPasswordAuthenticationKey(String userId,
                                            String userPassword,
                                            BigInteger B,
                                            BigInteger salt) {
    // Authenticate the password
    // u = H(A, B)
    MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
    messageDigest.reset();
    messageDigest.update(A.toByteArray());
    BigInteger u = new BigInteger(1, messageDigest.digest(B.toByteArray()));
    if (u.equals(BigInteger.ZERO)) {
        throw new SecurityException("Hash of A and B cannot be zero");
    }

    // x = H(salt | H(poolName | userId | ":" | password))
    messageDigest.reset();
    messageDigest.update(this.userPoolID.split("_", 2)[1].getBytes(StringUtils.UTF8));
    messageDigest.update(userId.getBytes(StringUtils.UTF8));
    messageDigest.update(":".getBytes(StringUtils.UTF8));
    byte[] userIdHash = messageDigest.digest(userPassword.getBytes(StringUtils.UTF8));

    messageDigest.reset();
    messageDigest.update(salt.toByteArray());
    BigInteger x = new BigInteger(1, messageDigest.digest(userIdHash));
    BigInteger S = (B.subtract(k.multiply(g.modPow(x, N))).modPow(a.add(u.multiply(x)), N)).mod(N);

    Hkdf hkdf;
    try {
        hkdf = Hkdf.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(e.getMessage(), e);
    }
    hkdf.init(S.toByteArray(), u.toByteArray());
    byte[] key = hkdf.deriveKey(DERIVED_KEY_INFO, DERIVED_KEY_SIZE);
    return key;
}
 
Example #19
Source File: DateTimeFormatterUtil.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the raw string to LocalDateTime using the provided default format
 *
 * @param value raw value to be transformed to LocalDateTime
 * @param dateFormat customer specified or inferred dateformat
 * @param defaultTimeZone default timezone to be applied
 * @return LocalDateTime or ZonedDateTime object parsed from value
 */
public static Object stringToDateTime(String value, String dateFormat, ZoneId defaultTimeZone)
{
    if (StringUtils.isNullOrEmpty(dateFormat)) {
        logger.warn("Unable to parse {} as DateTime type due to invalid date format", value);
        return null;
    }
    Date dateTransformedValue = stringToDate(value, dateFormat);
    if (dateTransformedValue == null) {
        return null;
    }
    return dateTransformedValue.toInstant()
            .atZone(defaultTimeZone)
            .toLocalDateTime();
}
 
Example #20
Source File: AWSSecretsManagerMariaDBDriver.java    From aws-secretsmanager-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:mariadb://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example #21
Source File: AWSSecretsManagerOracleDriver.java    From aws-secretsmanager-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:oracle:thin:@//" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example #22
Source File: AWSSecretsManagerMySQLDriver.java    From aws-secretsmanager-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:mysql://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example #23
Source File: AwsMetricsPublisher.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public AwsMetricsPublisher(MetricsConfig metricsConfig) {
  super(metricsConfig.getClusterId());
  snsTopicOperations = metricsConfig.getAwsMetricsConfig().getOperationsMetricsTopic();
  awsAccessKeyId = metricsConfig.getAwsMetricsConfig().getAwsAccessKeyId();
  awsSecretKey = metricsConfig.getAwsMetricsConfig().getAwsSecretKey();
  region = metricsConfig.getAwsMetricsConfig().getRegion();
  snsClientMaxConnections = metricsConfig.getAwsMetricsConfig().getSnsClientMaxConnections();
  if (!StringUtils.isNullOrEmpty(snsTopicOperations)
      && snsClientMaxConnections > 0
      && !StringUtils.isNullOrEmpty(awsAccessKeyId)
      && !StringUtils.isNullOrEmpty(awsSecretKey)
      && !StringUtils.isNullOrEmpty(region)) {
    snsClient = initSnsClient();
  }
}
 
Example #24
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private String createRoleSessionName() {
	if (StringUtils.isNullOrEmpty(this.step.roleSessionName)) {
		return RoleSessionNameBuilder
				.withJobName(this.envVars.get("JOB_NAME"))
				.withBuildNumber(this.envVars.get("BUILD_NUMBER"))
				.build();
	} else {
		return this.step.roleSessionName;
	}
}
 
Example #25
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withProfile(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getProfile())) {
		this.getContext().get(TaskListener.class).getLogger().format("Setting AWS profile %s %n ", this.step.getProfile());
		localEnv.override(AWSClientFactory.AWS_DEFAULT_PROFILE, this.step.getProfile());
		localEnv.override(AWSClientFactory.AWS_PROFILE, this.step.getProfile());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #26
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withEndpointUrl(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getEndpointUrl())) {
		this.getContext().get(TaskListener.class).getLogger().format("Setting AWS endpointUrl %s %n ", this.step.getEndpointUrl());
		localEnv.override(AWSClientFactory.AWS_ENDPOINT_URL, this.step.getEndpointUrl());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #27
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withRegion(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRegion())) {
		this.getContext().get(TaskListener.class).getLogger().format("Setting AWS region %s %n ", this.step.getRegion());
		localEnv.override(AWSClientFactory.AWS_DEFAULT_REGION, this.step.getRegion());
		localEnv.override(AWSClientFactory.AWS_REGION, this.step.getRegion());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #28
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) {
		StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				StandardUsernamePasswordCredentials.class, run, Collections.emptyList());

		AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				AmazonWebServicesCredentials.class, run, Collections.emptyList());
		if (usernamePasswordCredentials != null) {
			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText());
		} else if (amazonWebServicesCredentials != null) {
			AWSCredentials awsCredentials;

			if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) {
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials");
				awsCredentials = amazonWebServicesCredentials.getCredentials();
			} else {
				// Since the getCredentials does its own roleAssumption, this is all it takes to get credentials
				// with this token.
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token");
				awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken());
				BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials;
				localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken());
			}

			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey());
		} else {
			throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials());
		}
	} else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) {
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion");
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion");
	}
	this.envVars.overrideAll(localEnv);
}
 
Example #29
Source File: AbstractTranslator.java    From alexa-meets-polly with Apache License 2.0 5 votes vote down vote up
@Override
public final Optional<String> translate(final String term, final String language) {
    return getTargetLangCodeIfSupported(language)
            // return text as is or delegate translation to child in case source and target language differ
            .map(targetLanguageCode -> targetLanguageCode.equalsIgnoreCase(sourceLanguageCode) ? term : doTranslate(term, targetLanguageCode))
            // translation must be not null or empty
            .filter(translation -> !StringUtils.isNullOrEmpty(translation));
}
 
Example #30
Source File: AbstractTranslator.java    From alexa-meets-polly with Apache License 2.0 5 votes vote down vote up
@Override
public final Optional<String> getTargetLangCodeIfSupported(final String language) {
    return Optional.ofNullable(language)
            // map language to target-language-code
            .map(l -> this.yamlReader.getRandomUtterance(l.toLowerCase().replace(" ", "_")).orElse(""))
            // if source and target language are equal target language is not supported
            .filter(c -> !StringUtils.isNullOrEmpty(c) && !c.equalsIgnoreCase(sourceLanguageCode));
}