software.amazon.awssdk.utils.StringUtils Java Examples

The following examples show how to use software.amazon.awssdk.utils.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: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private Region getRegion(final ProviderConfigurationContext configurationContext) {
    final String regionValue = configurationContext.getProperties().get(REGION_PROP);
    if (StringUtils.isBlank(regionValue)) {
        throw new ProviderCreationException("The property '" + REGION_PROP + "' must be provided");
    }

    Region region = null;
    for (Region r : Region.regions()) {
        if (r.id().equals(regionValue)) {
            region = r;
            break;
        }
    }

    if (region == null) {
        LOGGER.warn("The provided region was not found in the list of known regions. This may indicate an invalid region, " +
                "or may indicate a region that is newer than the known list of regions");
        region = Region.of(regionValue);
    }

    LOGGER.debug("Using region {}", new Object[] {region.id()});
    return region;
}
 
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: BaseClientBuilderClass.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private MethodSpec mergeServiceDefaultsMethod() {
    boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData();

    MethodSpec.Builder builder = MethodSpec.methodBuilder("mergeServiceDefaults")
                                           .addAnnotation(Override.class)
                                           .addModifiers(PROTECTED, FINAL)
                                           .returns(SdkClientConfiguration.class)
                                           .addParameter(SdkClientConfiguration.class, "config")
                                           .addCode("return config.merge(c -> c.option($T.SIGNER, defaultSigner())\n",
                                                    SdkAdvancedClientOption.class)
                                           .addCode("                          .option($T"
                                                    + ".CRC32_FROM_COMPRESSED_DATA_ENABLED, $L)",
                                                    SdkClientOption.class, crc32FromCompressedDataEnabled);

    String clientConfigClassName = model.getCustomizationConfig().getServiceSpecificClientConfigClass();
    if (StringUtils.isNotBlank(clientConfigClassName)) {
        builder.addCode(".option($T.SERVICE_CONFIGURATION, $T.builder().build())",
                        SdkClientOption.class, ClassName.bestGuess(clientConfigClassName));
    }

    builder.addCode(");");
    return builder.build();
}
 
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 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 #6
Source File: RequestAdapter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the headers in the specified Netty HTTP request.
 */
private void addHeadersToRequest(DefaultHttpRequest httpRequest, SdkHttpRequest request) {
    httpRequest.headers().add(HOST, getHostHeaderValue(request));

    String scheme = request.getUri().getScheme();
    if (Protocol.HTTP2 == protocol && !StringUtils.isBlank(scheme)) {
        httpRequest.headers().add(ExtensionHeaderNames.SCHEME.text(), scheme);
    }

    // Copy over any other headers already in our request
    request.headers().entrySet().stream()
            /*
             * Skip the Host header to avoid sending it twice, which will
             * interfere with some signing schemes.
             */
            .filter(e -> !IGNORE_HEADERS.contains(e.getKey()))
            .forEach(e -> e.getValue().forEach(h -> httpRequest.headers().add(e.getKey(), h)));
}
 
Example #7
Source File: NonCollectionSetters.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public List<MethodSpec> beanStyle() {
    List<MethodSpec> methods = new ArrayList<>();
    methods.add(beanStyleSetterBuilder()
                    .addCode(beanCopySetterBody())
                    .build());

    if (StringUtils.isNotBlank(memberModel().getDeprecatedBeanStyleSetterMethodName())) {
        methods.add(deprecatedBeanStyleSetterBuilder()
                        .addCode(beanCopySetterBody())
                        .addAnnotation(Deprecated.class)
                        .addJavadoc("@deprecated Use {@link #" + memberModel().getBeanStyleSetterMethodName() + "} instead")
                        .build());
    }

    return methods;
}
 
Example #8
Source File: Mimetype.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Reads and stores the mime type setting corresponding to a file extension, by reading
 * text from an InputStream. If a mime type setting already exists when this method is run,
 * the mime type value is replaced with the newer one.
 */
private void loadAndReplaceMimetypes(InputStream is) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

    br.lines().filter(line -> !line.startsWith("#")).forEach(line -> {
        line = line.trim();

        StringTokenizer st = new StringTokenizer(line, " \t");
        if (st.countTokens() > 1) {
            String mimetype = st.nextToken();
            while (st.hasMoreTokens()) {
                String extension = st.nextToken();
                extensionToMimetype.put(StringUtils.lowerCase(extension), mimetype);
            }
        }
    });
}
 
Example #9
Source File: StreamingRequestMarshaller.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public SdkHttpFullRequest marshall(T in) {
    SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder();
    marshalled.contentStreamProvider(requestBody.contentStreamProvider());
    String contentType = marshalled.firstMatchingHeader(CONTENT_TYPE)
                                   .orElse(null);
    if (StringUtils.isEmpty(contentType)) {
        marshalled.putHeader(CONTENT_TYPE, requestBody.contentType());
    }

    // Currently, SDK always require content length in RequestBody. So we always
    // send Content-Length header for sync APIs
    // This change will be useful if SDK relaxes the content-length requirement in RequestBody
    addHeaders(marshalled, Optional.of(requestBody.contentLength()), requiresLength, transferEncoding, useHttp2);

    return marshalled.build();
}
 
Example #10
Source File: AddShapes.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private String deriveMarshallerLocationName(Shape memberShape, String memberName, Member member, String protocol) {
    String queryName = member.getQueryName();

    if (StringUtils.isNotBlank(queryName)) {
        return queryName;
    }

    String locationName;

    if (Protocol.EC2.getValue().equalsIgnoreCase(protocol)) {
        locationName = deriveLocationNameForEc2(member);
    } else if (memberShape.getListMember() != null && memberShape.isFlattened()) {
        locationName =  deriveLocationNameForListMember(memberShape, member);
    } else {
        locationName = member.getLocationName();
    }

    if (StringUtils.isNotBlank(locationName)) {
        return locationName;
    }

    return memberName;
}
 
Example #11
Source File: DefaultNamingStrategy.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public String getEnumValueName(String enumValue) {
    String result = enumValue;

    // Special cases
    result = result.replaceAll("textORcsv", "TEXT_OR_CSV");

    // Split into words
    result = String.join("_", splitOnWordBoundaries(result));

    // Enums should be upper-case
    result = StringUtils.upperCase(result);

    if (!result.matches("^[A-Z][A-Z0-9_]*$")) {
        String attempt = result;
        log.warn(() -> "Invalid enum member generated for input '" + enumValue + "'. Best attempt: '" + attempt + "' If this "
                       + "enum is not customized out, the build will fail.");
    }

    return result;
}
 
Example #12
Source File: SdkHttpUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Encode a string for use in the path of a URL; uses URLEncoder.encode,
 * (which encodes a string for use in the query portion of a URL), then
 * applies some postfilters to fix things up per the RFC. Can optionally
 * handle strings which are meant to encode a path (ie include '/'es
 * which should NOT be escaped).
 *
 * @param value the value to encode
 * @param ignoreSlashes  true if the value is intended to represent a path
 * @return the encoded value
 */
private static String urlEncode(String value, boolean ignoreSlashes) {
    if (value == null) {
        return null;
    }

    String encoded = invokeSafely(() -> URLEncoder.encode(value, DEFAULT_ENCODING));

    if (!ignoreSlashes) {
        return StringUtils.replaceEach(encoded,
                                       ENCODED_CHARACTERS_WITHOUT_SLASHES,
                                       ENCODED_CHARACTERS_WITHOUT_SLASHES_REPLACEMENTS);
    }

    return StringUtils.replaceEach(encoded, ENCODED_CHARACTERS_WITH_SLASHES, ENCODED_CHARACTERS_WITH_SLASHES_REPLACEMENTS);
}
 
Example #13
Source File: DefaultSdkHttpFullRequest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private String standardizePath(String path) {
    if (StringUtils.isEmpty(path)) {
        return "";
    }

    StringBuilder standardizedPath = new StringBuilder();

    // Path must always start with '/'
    if (!path.startsWith("/")) {
        standardizedPath.append('/');
    }

    standardizedPath.append(path);

    return standardizedPath.toString();
}
 
Example #14
Source File: ShapeModel.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to find the member model associated with the given c2j member name from this shape
 * model. Returns the member model if present else returns null.
 */
private MemberModel tryFindMemberModelByC2jName(String memberC2jName, boolean ignoreCase) {

    List<MemberModel> memberModels = getMembers();
    String expectedName = ignoreCase ? StringUtils.lowerCase(memberC2jName)
                                           : memberC2jName;

    if (memberModels != null) {
        for (MemberModel member : memberModels) {
            String actualName = ignoreCase ? StringUtils.lowerCase(member.getC2jName())
                                           : member.getC2jName();

            if (expectedName.equals(actualName)) {
                return member;
            }
        }
    }
    return null;
}
 
Example #15
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 #16
Source File: StreamsRecord.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public StreamsRecord(com.amazonaws.services.kinesis.model.Record record) {
    if (record instanceof RecordAdapter) {
        com.amazonaws.services.dynamodbv2.model.Record dynamoRecord = ((RecordAdapter) record).getInternalObject();
        this.key = Optional.of(dynamoRecord.getEventID());
        setProperty(EVENT_NAME, dynamoRecord.getEventName());
        setProperty(SEQUENCE_NUMBER, dynamoRecord.getDynamodb().getSequenceNumber());
    } else {
        this.key = Optional.of(record.getPartitionKey());
        setProperty(ARRIVAL_TIMESTAMP, record.getApproximateArrivalTimestamp().toString());
        setProperty(ENCRYPTION_TYPE, record.getEncryptionType());
        setProperty(PARTITION_KEY, record.getPartitionKey());
        setProperty(SEQUENCE_NUMBER, record.getSequenceNumber());
    }

    if (StringUtils.isBlank(record.getEncryptionType())) {
        String s = null;
        try {
            s = decoder.decode(record.getData()).toString();
        } catch (CharacterCodingException e) {
           // Ignore
        }
        this.value = (s != null) ? s.getBytes() : null;
    } else {
        // Who knows?
        this.value = null;
    }
}
 
Example #17
Source File: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void onConfigured(final ProviderConfigurationContext configurationContext) throws ProviderCreationException {
    s3BucketName = configurationContext.getProperties().get(BUCKET_NAME_PROP);
    if (StringUtils.isBlank(s3BucketName)) {
        throw new ProviderCreationException("The property '" + BUCKET_NAME_PROP + "' must be provided");
    }

    final String keyPrefixValue = configurationContext.getProperties().get(KEY_PREFIX_PROP);
    s3KeyPrefix = StringUtils.isBlank(keyPrefixValue) ? null : keyPrefixValue;

    s3Client = createS3Client(configurationContext);
}
 
Example #18
Source File: AbstractAwsConnector.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public AwsCredentialProviderPlugin createCredentialProvider(String awsCredentialPluginName,
                                                               String awsCredentialPluginParam) {
    if (StringUtils.isNotBlank(awsCredentialPluginName)) {
        return createCredentialProviderWithPlugin(awsCredentialPluginName, awsCredentialPluginParam);
    } else {
        return defaultCredentialProvider(awsCredentialPluginParam);
    }
}
 
Example #19
Source File: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private AwsCredentialsProvider getCredentialsProvider(final ProviderConfigurationContext configurationContext) {
    final String credentialsProviderValue = configurationContext.getProperties().get(CREDENTIALS_PROVIDER_PROP);
    if (StringUtils.isBlank(credentialsProviderValue)) {
        throw new ProviderCreationException("The property '" + CREDENTIALS_PROVIDER_PROP + "' must be provided");
    }

    CredentialProvider credentialProvider;
    try {
        credentialProvider = CredentialProvider.valueOf(credentialsProviderValue);
    } catch (Exception e) {
        throw new ProviderCreationException("The property '" + CREDENTIALS_PROVIDER_PROP + "' must be one of ["
                + CredentialProvider.STATIC + ", " + CredentialProvider.DEFAULT_CHAIN + " ]");
    }

    if (CredentialProvider.STATIC == credentialProvider) {
        final String accesKeyValue = configurationContext.getProperties().get(ACCESS_KEY_PROP);
        final String secretAccessKey = configurationContext.getProperties().get(SECRET_ACCESS_KEY_PROP);

        if (StringUtils.isBlank(accesKeyValue) || StringUtils.isBlank(secretAccessKey)) {
            throw new ProviderCreationException("The properties '" + ACCESS_KEY_PROP + "' and '" + SECRET_ACCESS_KEY_PROP
                    + "' must be provided when using " + CredentialProvider.STATIC + " credentials provider");
        }

        LOGGER.debug("Creating StaticCredentialsProvider");
        final AwsCredentials awsCredentials = AwsBasicCredentials.create(accesKeyValue, secretAccessKey);
        return StaticCredentialsProvider.create(awsCredentials);

    } else {
        LOGGER.debug("Creating DefaultCredentialsProvider");
        return DefaultCredentialsProvider.create();
    }
}
 
Example #20
Source File: S3BundlePersistenceProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private URI getS3EndpointOverride(final ProviderConfigurationContext configurationContext) {
    final URI s3EndpointOverride;
    final String endpointUrlValue = configurationContext.getProperties().get(ENDPOINT_URL_PROP);
    try {
        s3EndpointOverride = StringUtils.isBlank(endpointUrlValue) ? null : URI.create(endpointUrlValue);
    } catch (IllegalArgumentException e) {
        final String errMessage = "The optional property '" + ENDPOINT_URL_PROP + "' must be a valid URL if set. " +
                "URI Syntax Exception is: " + e.getLocalizedMessage();
        LOGGER.error(errMessage);
        LOGGER.debug("", e);
        throw new ProviderCreationException(errMessage, e);
    }
    return s3EndpointOverride;
}
 
Example #21
Source File: MemberModel.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public String getDefaultConsumerFluentSetterDocumentation() {
    return (StringUtils.isNotBlank(documentation) ? documentation : defaultSetter().replace("%s", name) + "\n")
           + LF
           + "This is a convenience that creates an instance of the {@link "
           + variable.getSimpleType()
           + ".Builder} avoiding the need to create one manually via {@link "
           + variable.getSimpleType()
           + "#builder()}.\n"
           + LF
           + "When the {@link Consumer} completes, {@link "
           + variable.getSimpleType()
           + ".Builder#build()} is called immediately and its result is passed to {@link #"
           + getFluentGetterMethodName()
           + "("
           + variable.getSimpleType()
           + ")}."
           + LF
           + "@param "
           + variable.getVariableName()
           + " a consumer that will call methods on {@link "
           + variable.getSimpleType() + ".Builder}"
           + LF
           + "@return " + stripHtmlTags(defaultFluentReturn())
           + LF
           + "@see #"
           + getFluentSetterMethodName()
           + "("
           + variable.getSimpleType()
           + ")";
}
 
Example #22
Source File: ProfileFileLocation.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Load the home directory that should be used for the profile file. This will check the same environment variables as the CLI
 * to identify the location of home, before falling back to java-specific resolution.
 */
@SdkInternalApi
static String userHomeDirectory() {
    boolean isWindows = JavaSystemSetting.OS_NAME.getStringValue()
                                                 .map(s -> StringUtils.lowerCase(s).startsWith("windows"))
                                                 .orElse(false);

    // To match the logic of the CLI we have to consult environment variables directly.
    // CHECKSTYLE:OFF
    String home = System.getenv("HOME");

    if (home != null) {
        return home;
    }

    if (isWindows) {
        String userProfile = System.getenv("USERPROFILE");

        if (userProfile != null) {
            return userProfile;
        }

        String homeDrive = System.getenv("HOMEDRIVE");
        String homePath = System.getenv("HOMEPATH");

        if (homeDrive != null && homePath != null) {
            return homeDrive + homePath;
        }
    }

    return JavaSystemSetting.USER_HOME.getStringValueOrThrow();
    // CHECKSTYLE:ON
}
 
Example #23
Source File: Utils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create the ShapeMarshaller to the input shape from the specified Operation.
 * The input shape in the operation could be empty.
 */
public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) {

    if (operation == null) {
        throw new IllegalArgumentException(
                "The operation parameter must be specified!");
    }

    ShapeMarshaller marshaller = new ShapeMarshaller()
            .withAction(operation.getName())
            .withVerb(operation.getHttp().getMethod())
            .withRequestUri(operation.getHttp().getRequestUri());
    Input input = operation.getInput();
    if (input != null) {
        marshaller.setLocationName(input.getLocationName());
        // Pass the xmlNamespace trait from the input reference
        XmlNamespace xmlNamespace = input.getXmlNamespace();
        if (xmlNamespace != null) {
            marshaller.setXmlNameSpaceUri(xmlNamespace.getUri());
        }
    }
    if (Metadata.isNotRestProtocol(service.getProtocol())) {
        marshaller.setTarget(StringUtils.isEmpty(service.getTargetPrefix()) ?
                             operation.getName() :
                             service.getTargetPrefix() + "." + operation.getName());
    }
    return marshaller;

}
 
Example #24
Source File: Utils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static String capitalize(String name) {
    if (name == null || name.trim().isEmpty()) {
        throw new IllegalArgumentException("Name cannot be null or empty");
    }
    return name.length() < 2 ? StringUtils.upperCase(name) : StringUtils.upperCase(name.substring(0, 1))
            + name.substring(1);
}
 
Example #25
Source File: AddShapes.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private String deriveLocationNameForListMember(Shape memberShape, Member member) {
    String locationName = memberShape.getListMember().getLocationName();

    if (StringUtils.isNotBlank(locationName)) {
        return locationName;
    }

    return member.getLocationName();
}
 
Example #26
Source File: AddShapes.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private String deriveLocationNameForEc2(Member member) {
    String locationName = member.getLocationName();

    if (StringUtils.isNotBlank(locationName)) {
        return StringUtils.upperCase(locationName.substring(0, 1)) +
               locationName.substring(1);
    }

    return null;
}
 
Example #27
Source File: AddShapes.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private String deriveUnmarshallerLocationName(Shape memberShape, String memberName, Member member) {
    String locationName;
    if (memberShape.getListMember() != null && memberShape.isFlattened()) {
        locationName = deriveLocationNameForListMember(memberShape, member);
    } else {
        locationName = member.getLocationName();
    }

    if (StringUtils.isNotBlank(locationName)) {
        return locationName;
    }

    return memberName;
}
 
Example #28
Source File: HostPrefixProcessor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Replace all the labels in host with %s symbols and collect the input shape member names into a list
 */
private void replaceHostLabelsWithStringSpecifier(String hostExpression) {
    if (StringUtils.isEmpty(hostExpression)) {
        throw new IllegalArgumentException("Given host prefix is either null or empty");
    }

    Matcher matcher = PATTERN.matcher(hostExpression);

    while (matcher.find()) {
        String matched = matcher.group(1);
        c2jNames.add(matched);
        hostWithStringSpecifier = hostWithStringSpecifier.replaceFirst("\\{" + matched + "}", "%s");
    }
}
 
Example #29
Source File: MemberModel.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private String getParamDoc() {
    return LF
           + "@param "
           + variable.getVariableName()
           + " "
           + stripHtmlTags(StringUtils.isNotBlank(documentation) ? documentation : defaultSetterParam().replace("%s", name));
}
 
Example #30
Source File: AmazonClientTransportRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void validateProxyEndpoint(String extension, URI endpoint, String clientType) {
    if (StringUtils.isBlank(endpoint.getScheme())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - scheme must be specified",
                        extension, clientType, endpoint.toString()));
    }
    if (StringUtils.isBlank(endpoint.getHost())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - host must be specified",
                        extension, clientType, endpoint.toString()));
    }
    if (StringUtils.isNotBlank(endpoint.getUserInfo())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - user info is not supported.",
                        extension, clientType, endpoint.toString()));
    }
    if (StringUtils.isNotBlank(endpoint.getPath())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - path is not supported.",
                        extension, clientType, endpoint.toString()));
    }
    if (StringUtils.isNotBlank(endpoint.getQuery())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - query is not supported.",
                        extension, clientType, endpoint.toString()));
    }
    if (StringUtils.isNotBlank(endpoint.getFragment())) {
        throw new RuntimeConfigurationError(
                String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - fragment is not supported.",
                        extension, clientType, endpoint.toString()));
    }
}