Java Code Examples for software.amazon.awssdk.utils.StringUtils#trim()

The following examples show how to use software.amazon.awssdk.utils.StringUtils#trim() . 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: EnvironmentAwsCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AwsCredentials resolveCredentials() {
    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.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
        throw SdkClientException.create(
                "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
            ? AwsBasicCredentials.create(accessKey, secretKey)
            : AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
 
Example 2
Source File: ProfileFileReader.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Read a profile line and update the parser state with the results. This marks future properties as being in this profile.
 *
 * Configuration Files: [ Whitespace? profile Whitespace Identifier Whitespace? ] Whitespace? CommentLine?
 * Credentials Files: [ Whitespace? Identifier Whitespace? ] Whitespace? CommentLine?
 */
private static void readProfileDefinitionLine(ParserState state, String line) {
    // Profile definitions do not require a space between the closing bracket and the comment delimiter
    String lineWithoutComments = removeTrailingComments(line, "#", ";");
    String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);

    Validate.isTrue(lineWithoutWhitespace.endsWith("]"),
                    "Profile definition must end with ']' on line " + state.currentLineNumber);

    Optional<String> profileName = parseProfileDefinition(state, lineWithoutWhitespace);

    // If we couldn't get the profile name, ignore this entire profile.
    if (!profileName.isPresent()) {
        state.ignoringCurrentProfile = true;
        return;
    }

    state.currentProfileBeingRead = profileName.get();
    state.currentPropertyBeingRead = null;
    state.ignoringCurrentProfile = false;
    state.ignoringCurrentProperty = false;

    // If we've seen this profile before, don't override the existing properties. We'll be merging them.
    state.profiles.computeIfAbsent(profileName.get(), i -> new LinkedHashMap<>());
}
 
Example 3
Source File: ProfileFileReader.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Read a property continuation line and update the parser state with the results. This adds the value in the continuation
 * to the current property, prefixed with a newline.
 *
 * Non-Blank Parent Property: Whitespace Value Whitespace?
 * Blank Parent Property (Sub-Property): Whitespace Identifier Whitespace? = Whitespace? Value Whitespace?
 */
private static void readPropertyContinuationLine(ParserState state, String line) {
    // If we're in an invalid profile or property, ignore its continuations
    if (state.ignoringCurrentProfile || state.ignoringCurrentProperty) {
        return;
    }

    Validate.isTrue(state.currentProfileBeingRead != null && state.currentPropertyBeingRead != null,
                    "Expected a profile or property definition on line " + state.currentLineNumber);

    // Comments are not removed on property continuation lines. They're considered part of the value.
    line = StringUtils.trim(line);

    Map<String, String> profileProperties = state.profiles.get(state.currentProfileBeingRead);

    String currentPropertyValue = profileProperties.get(state.currentPropertyBeingRead);
    String newPropertyValue = currentPropertyValue + "\n" + line;

    // If this is a sub-property, make sure it can be parsed correctly by the CLI.
    if (state.validatingContinuationsAsSubProperties) {
        parsePropertyDefinition(state, line);
    }

    profileProperties.put(state.currentPropertyBeingRead, newPropertyValue);
}
 
Example 4
Source File: ProfileFileReader.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Given a property line, load the property key and value. If the property line is invalid and should be ignored, this will
 * return empty.
 */
private static Optional<Pair<String, String>> parsePropertyDefinition(ParserState state, String line) {
    int firstEqualsLocation = line.indexOf('=');
    Validate.isTrue(firstEqualsLocation != -1, "Expected an '=' sign defining a property on line " + state.currentLineNumber);

    String propertyKey = StringUtils.trim(line.substring(0, firstEqualsLocation));
    String propertyValue = StringUtils.trim(line.substring(firstEqualsLocation + 1));

    Validate.isTrue(!propertyKey.isEmpty(), "Property did not have a name on line " + state.currentLineNumber);

    // If the profile name includes invalid characters, it should be ignored.
    if (!isValidIdentifier(propertyKey)) {
        log.warn(() -> "Ignoring property '" + propertyKey + "' on line " + state.currentLineNumber + " because " +
                       "its name was not alphanumeric with only these special characters: - / . % @ _ :");
        return Optional.empty();
    }

    return Optional.of(Pair.of(propertyKey, propertyValue));
}
 
Example 5
Source File: ProfileFileReader.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Read a property definition line and update the parser state with the results. This adds the property to the current profile
 * and marks future property continuations as being part of this property.
 *
 * Identifier Whitespace? = Whitespace? Value? Whitespace? (Whitespace CommentLine)?
 */
private static void readPropertyDefinitionLine(ParserState state, String line) {
    // If we're in an invalid profile, ignore its properties
    if (state.ignoringCurrentProfile) {
        return;
    }

    Validate.isTrue(state.currentProfileBeingRead != null,
                    "Expected a profile definition on line " + state.currentLineNumber);

    // Property definition comments must have whitespace before them, or they will be considered part of the value
    String lineWithoutComments = removeTrailingComments(line, " #", " ;", "\t#", "\t;");
    String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);

    Optional<Pair<String, String>> propertyDefinition = parsePropertyDefinition(state, lineWithoutWhitespace);

    // If we couldn't get the property key and value, ignore this entire property.
    if (!propertyDefinition.isPresent()) {
        state.ignoringCurrentProperty = true;
        return;
    }

    Pair<String, String> property = propertyDefinition.get();

    if (state.profiles.get(state.currentProfileBeingRead).containsKey(property.left())) {
        log.warn(() -> "Warning: Duplicate property '" + property.left() + "' detected on line " + state.currentLineNumber +
                       ". The later one in the file will be used.");
    }

    state.currentPropertyBeingRead = property.left();
    state.ignoringCurrentProperty = false;
    state.validatingContinuationsAsSubProperties = property.right().equals("");

    state.profiles.get(state.currentProfileBeingRead).put(property.left(), property.right());
}
 
Example 6
Source File: AbstractAwsSigner.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the individual access key ID and secret key from the specified credentials, trimming any extra whitespace from the
 * credentials.
 *
 * <p>Returns either a {@link AwsSessionCredentials} or a {@link AwsBasicCredentials} object, depending on the input type.
 *
 * @return A new credentials object with the sanitized credentials.
 */
protected AwsCredentials sanitizeCredentials(AwsCredentials credentials) {
    String accessKeyId = StringUtils.trim(credentials.accessKeyId());
    String secretKey = StringUtils.trim(credentials.secretAccessKey());

    if (credentials instanceof AwsSessionCredentials) {
        AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials;
        return AwsSessionCredentials.create(accessKeyId,
                                            secretKey,
                                            StringUtils.trim(sessionCredentials.sessionToken()));
    }

    return AwsBasicCredentials.create(accessKeyId, secretKey);
}
 
Example 7
Source File: ProfileFileReader.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Given a profile line, load the profile name based on the file type. If the profile name is invalid for the file type,
 * this will return empty.
 */
private static Optional<String> parseProfileDefinition(ParserState state, String lineWithoutWhitespace) {
    String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1);
    String rawProfileName = StringUtils.trim(lineWithoutBrackets);
    boolean hasProfilePrefix = rawProfileName.startsWith("profile ") || rawProfileName.startsWith("profile\t");

    String standardizedProfileName;
    if (state.fileType == ProfileFile.Type.CONFIGURATION) {
        if (hasProfilePrefix) {
            standardizedProfileName = StringUtils.trim(rawProfileName.substring("profile".length()));
        } else if (rawProfileName.equals("default")) {
            standardizedProfileName = "default";
        } else {
            log.warn(() -> "Ignoring profile '" + rawProfileName + "' on line " + state.currentLineNumber + " because it " +
                           "did not start with 'profile ' and it was not 'default'.");
            return Optional.empty();
        }
    } else if (state.fileType == ProfileFile.Type.CREDENTIALS) {
        standardizedProfileName = rawProfileName;
    } else {
        throw new IllegalStateException("Unknown profile file type: " + state.fileType);
    }

    String profileName = StringUtils.trim(standardizedProfileName);

    // If the profile name includes invalid characters, it should be ignored.
    if (!isValidIdentifier(profileName)) {
        log.warn(() -> "Ignoring profile '" + standardizedProfileName + "' on line " + state.currentLineNumber + " because " +
                       "it was not alphanumeric with only these special characters: - / . % @ _ :");
        return Optional.empty();
    }

    // [profile default] must take priority over [default] in configuration files.
    boolean isDefaultProfile = profileName.equals("default");
    boolean seenProfileBefore = state.profiles.containsKey(profileName);

    if (state.fileType == ProfileFile.Type.CONFIGURATION && isDefaultProfile && seenProfileBefore) {
        if (!hasProfilePrefix && state.seenDefaultProfileWithProfilePrefix) {
            log.warn(() -> "Ignoring profile '[default]' on line " + state.currentLineNumber + ", because " +
                           "'[profile default]' was already seen in the same file.");
            return Optional.empty();
        } else if (hasProfilePrefix && !state.seenDefaultProfileWithProfilePrefix) {
            log.warn(() -> "Ignoring earlier-seen '[default]', because '[profile default]' was found on line " +
                           state.currentLineNumber);
            state.profiles.remove("default");
        }
    }

    if (isDefaultProfile && hasProfilePrefix) {
        state.seenDefaultProfileWithProfilePrefix = true;
    }

    return Optional.of(profileName);
}