Skip to content

Change generated Getters to have a 'get' prefix #655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@ public PreRequest parse(Document input) {

@Override
public IdentityResolver<?> identityResolver(PreRequest input) {
return new SdkCredentialsResolver(ProfileCredentialsProvider.create(input.awsProfileName()));
return new SdkCredentialsResolver(ProfileCredentialsProvider.create(input.getAwsProfileName()));
}

@Override
public EndpointResolver endpointResolver(PreRequest input) {
// TODO: error reporting
return ignore -> {
var endpoint = URI.create(Objects.requireNonNull(serviceMetadata.endpoints().get(input.awsRegion()),
"no endpoint for region " + input.awsRegion()));
var endpoint =
URI.create(Objects.requireNonNull(serviceMetadata.getEndpoints().get(input.getAwsProfileName()),
"no endpoint for region " + input.getAwsRegion()));
return CompletableFuture.completedFuture(Endpoint.builder()
.uri(endpoint)
.build());
Expand All @@ -59,13 +60,13 @@ public EndpointResolver endpointResolver(PreRequest input) {

@Override
public AuthScheme<?, ?> authScheme(PreRequest input) {
return new SigV4AuthScheme(serviceMetadata.sigv4SigningName());
return new SigV4AuthScheme(serviceMetadata.getSigv4SigningName());
}

@Override
public RequestOverrideConfig.Builder adaptConfig(PreRequest args) {
return ConfigProvider.super.adaptConfig(args)
.putConfig(RegionSetting.REGION, args.awsRegion());
.putConfig(RegionSetting.REGION, args.getAwsRegion());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ public class AwsServiceBundlerTest {
@Test
public void accessAnalyzer() {
var bundler = new AwsServiceBundler("accessanalyzer-2019-11-01.json", AwsServiceBundlerTest::getModel);
var bundle = bundler.bundle().config().asShape(AwsServiceMetadata.builder());
var bundle = bundler.bundle().getConfig().asShape(AwsServiceMetadata.builder());

assertEquals("access-analyzer", bundle.sigv4SigningName());
assertEquals("AccessAnalyzer", bundle.serviceName());
assertEquals("access-analyzer", bundle.getSigv4SigningName());
assertEquals("AccessAnalyzer", bundle.getServiceName());

assertNotEquals(0, bundle.endpoints().size());
assertNotEquals(0, bundle.getEndpoints().size());
}

private static String getModel(String path) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public void testToBuilderList() {
.build();
var copy = original.toBuilder().optionalList(List.of("1")).build();
assertThat(copy)
.returns(original.requiredList(), ListMembersInput::requiredList)
.returns(List.of("1"), ListMembersInput::optionalList);
.returns(original.getRequiredList(), ListMembersInput::getRequiredList)
.returns(List.of("1"), ListMembersInput::getOptionalList);
}

@Test
Expand All @@ -33,7 +33,7 @@ public void testToBuilderMap() {
.build();
var copy = original.toBuilder().optionalMap(Map.of("1", "2")).build();
assertThat(copy)
.returns(original.requiredMap(), MapMembersInput::requiredMap)
.returns(Map.of("1", "2"), MapMembersInput::optionalMap);
.returns(original.getRequiredMap(), MapMembersInput::getRequiredMap)
.returns(Map.of("1", "2"), MapMembersInput::getOptionalMap);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,32 @@
import software.amazon.smithy.java.codegen.test.model.NestedIntEnum;

public class ClientErrorCorrectionTest {

@Test
void correctsErrors() {
var corrected = ClientErrorCorrectionInput.builder()
.errorCorrection()
.build();

assertFalse(corrected.booleanMember());
assertEquals(corrected.bigDecimal(), BigDecimal.ZERO);
assertEquals(corrected.bigInteger(), BigInteger.ZERO);
assertEquals(corrected.byteMember(), (byte) 0);
assertEquals(corrected.doubleMember(), 0);
assertEquals(corrected.floatMember(), 0);
assertEquals(corrected.integer(), 0);
assertEquals(corrected.longMember(), 0);
assertEquals(corrected.shortMember(), (short) 0);
assertEquals(corrected.blob(), ByteBuffer.allocate(0));
assertEquals(corrected.streamingBlob().contentLength(), 0);
corrected.streamingBlob().asByteBuffer().thenAccept(bytes -> assertEquals(0, bytes.remaining()));
assertNull(corrected.document());
assertEquals(corrected.list(), List.of());
assertEquals(corrected.map(), Map.of());
assertEquals(corrected.timestamp(), Instant.EPOCH);
assertEquals(corrected.enumMember().type(), NestedEnum.Type.$UNKNOWN);
assertEquals(corrected.enumMember().value(), "");
assertEquals(corrected.intEnum().type(), NestedIntEnum.Type.$UNKNOWN);
assertEquals(corrected.intEnum().value(), 0);
assertFalse(corrected.isBoolean());
assertEquals(corrected.getBigDecimal(), BigDecimal.ZERO);
assertEquals(corrected.getBigInteger(), BigInteger.ZERO);
assertEquals(corrected.getByte(), (byte) 0);
assertEquals(corrected.getDouble(), 0);
assertEquals(corrected.getFloat(), 0);
assertEquals(corrected.getInteger(), 0);
assertEquals(corrected.getLong(), 0);
assertEquals(corrected.getShort(), (short) 0);
assertEquals(corrected.getBlob(), ByteBuffer.allocate(0));
assertEquals(corrected.getStreamingBlob().contentLength(), 0);
corrected.getStreamingBlob().asByteBuffer().thenAccept(bytes -> assertEquals(0, bytes.remaining()));
assertNull(corrected.getDocument());
assertEquals(corrected.getList(), List.of());
assertEquals(corrected.getMap(), Map.of());
assertEquals(corrected.getTimestamp(), Instant.EPOCH);
assertEquals(corrected.getEnum().getType(), NestedEnum.Type.$UNKNOWN);
assertEquals(corrected.getEnum().getValue(), "");
assertEquals(corrected.getIntEnum().getType(), NestedIntEnum.Type.$UNKNOWN);
assertEquals(corrected.getIntEnum().getValue(), 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,29 @@ public class DefaultsTest {
void setsCorrectDefault() {
var defaults = DefaultsInput.builder().build();

assertTrue(defaults.booleanMember());
assertEquals(defaults.bigDecimal(), BigDecimal.valueOf(1.0));
assertEquals(defaults.bigInteger(), BigInteger.valueOf(1));
assertEquals(defaults.byteMember(), (byte) 1);
assertEquals(defaults.doubleMember(), 1.0);
assertEquals(defaults.floatMember(), 1f);
assertEquals(defaults.integer(), 1);
assertEquals(defaults.longMember(), 1);
assertEquals(defaults.shortMember(), (short) 1);
assertEquals(defaults.blob(), ByteBuffer.wrap(Base64.getDecoder().decode("YmxvYg==")));
defaults.streamingBlob()
assertTrue(defaults.isBoolean());
assertEquals(defaults.getBigDecimal(), BigDecimal.valueOf(1.0));
assertEquals(defaults.getBigInteger(), BigInteger.valueOf(1));
assertEquals(defaults.getByte(), (byte) 1);
assertEquals(defaults.getDouble(), 1.0);
assertEquals(defaults.getFloat(), 1f);
assertEquals(defaults.getInteger(), 1);
assertEquals(defaults.getLong(), 1);
assertEquals(defaults.getShort(), (short) 1);
assertEquals(defaults.getBlob(), ByteBuffer.wrap(Base64.getDecoder().decode("YmxvYg==")));
defaults.getStreamingBlob()
.asByteBuffer()
.thenAccept(b -> assertEquals(b, ByteBuffer.wrap(Base64.getDecoder().decode("c3RyZWFtaW5n"))));
assertEquals(defaults.boolDoc(), Document.of(true));
assertEquals(defaults.stringDoc(), Document.of("string"));
assertEquals(defaults.numberDoc(), Document.of(1));
assertEquals(defaults.floatingPointnumberDoc(), Document.of(1.2));
assertEquals(defaults.listDoc(), Document.of(Collections.emptyList()));
assertEquals(defaults.mapDoc(), Document.of(Collections.emptyMap()));
assertEquals(defaults.list(), List.of());
assertEquals(defaults.map(), Map.of());
assertEquals(defaults.timestamp(), Instant.parse("1985-04-12T23:20:50.52Z"));
assertEquals(defaults.enumMember(), NestedEnum.A);
assertEquals(defaults.intEnum(), NestedIntEnum.A);
assertEquals(defaults.getBoolDoc(), Document.of(true));
assertEquals(defaults.getStringDoc(), Document.of("string"));
assertEquals(defaults.getNumberDoc(), Document.of(1));
assertEquals(defaults.getFloatingPointnumberDoc(), Document.of(1.2));
assertEquals(defaults.getListDoc(), Document.of(Collections.emptyList()));
assertEquals(defaults.getMapDoc(), Document.of(Collections.emptyMap()));
assertEquals(defaults.getList(), List.of());
assertEquals(defaults.getMap(), Map.of());
assertEquals(defaults.getTimestamp(), Instant.parse("1985-04-12T23:20:50.52Z"));
assertEquals(defaults.getEnum(), NestedEnum.A);
assertEquals(defaults.getIntEnum(), NestedIntEnum.A);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ void unknownTypeDeserializedIntoUnknownVariant() {
try (var codec = JsonCodec.builder().useJsonName(true).useTimestampFormat(true).build()) {
output = codec.deserializeShape("\"option-n\"", EnumType.builder());
}
assertEquals(output.type(), EnumType.Type.$UNKNOWN);
assertEquals(output.getType(), EnumType.Type.$UNKNOWN);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ void nullDistinctFromEmpty() {
assertTrue(emptyInput.hasListOfBoolean());
assertFalse(nullInput.hasListOfBoolean());
// Collections should return empty collections for access
assertEquals(emptyInput.listOfBoolean(), Collections.emptyList());
assertEquals(emptyInput.listOfBoolean(), nullInput.listOfBoolean());
assertEquals(emptyInput.getListOfBoolean(), Collections.emptyList());
assertEquals(emptyInput.getListOfBoolean(), nullInput.getListOfBoolean());
var emptyDocument = Document.of(emptyInput);
var nullDocument = Document.of(nullInput);
assertNotNull(emptyDocument.getMember("listOfBoolean"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ void nullDistinctFromEmpty() {
assertTrue(emptyInput.hasStringBooleanMap());
assertFalse(nullInput.hasStringBooleanMap());
// Collections should return empty collections for access
assertEquals(emptyInput.stringBooleanMap(), Collections.emptyMap());
assertEquals(emptyInput.stringBooleanMap(), nullInput.stringBooleanMap());
assertEquals(emptyInput.getStringBooleanMap(), Collections.emptyMap());
assertEquals(emptyInput.getStringBooleanMap(), nullInput.getStringBooleanMap());

var emptyDocument = Document.of(emptyInput);
var nullDocument = Document.of(nullInput);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ public final class CodegenUtils {
CodegenUtils.class.getResource("object-reserved-members.txt"));
private static final URL SMITHY_RESERVED_MEMBERS_FILE = Objects.requireNonNull(
CodegenUtils.class.getResource("smithy-reserved-members.txt"));
private static final URL SMITHY_RESERVED_METHODS_FILE = Objects.requireNonNull(
CodegenUtils.class.getResource("smithy-reserved-methods.txt"));

private static final List<String> DELIMITERS = List.of("_", "-", " ");

public static final ReservedWords SHAPE_ESCAPER = new ReservedWordsBuilder()
.loadCaseInsensitiveWords(RESERVED_WORDS_FILE, word -> word + "Shape")
Expand All @@ -55,6 +59,9 @@ public final class CodegenUtils {
.loadCaseInsensitiveWords(OBJECT_RESERVED_MEMBERS_FILE, word -> word + "Member")
.loadCaseInsensitiveWords(SMITHY_RESERVED_MEMBERS_FILE, word -> word + "Member")
.build();
public static final ReservedWords METHODS_ESCAPER = new ReservedWordsBuilder()
.loadCaseInsensitiveWords(SMITHY_RESERVED_METHODS_FILE, word -> word + "Member")
.build();

private static final String SCHEMA_STATIC_NAME = "$SCHEMA";

Expand Down Expand Up @@ -255,6 +262,33 @@ public static String toDefaultValueName(String memberName) {
return CaseUtils.toSnakeCase(memberName).toUpperCase(Locale.ENGLISH) + "_DEFAULT";
}

/**
*
* Gets the name to use when defining a member as instance variable in a class.
*
* @param memberShape MemberShape
* @param model Model
* @return Instance variable name of a member.
*/
public static String toMemberName(MemberShape memberShape, Model model) {
return getMemberName(memberShape, model, true);
}

/**
* Gets the name to use when defining the getter method of a member.
*
* @param memberShape memberShape.
* @return Getter method name of a member.
*/
public static String toGetterName(MemberShape memberShape, Model model) {
var target = model.expectShape(memberShape.getTarget());
var prefix = target.isBooleanShape() ? "is" : "get";
var memberName = getMemberName(memberShape, model, false);
var suffix =
Character.toUpperCase(memberName.charAt(0)) + (memberName.length() == 1 ? "" : memberName.substring(1));
return METHODS_ESCAPER.escape(prefix + suffix);
}

/**
* Gets the file name to use for the SharedSerde utility class
*
Expand Down Expand Up @@ -449,4 +483,46 @@ public static Symbol getServiceApiSymbol(String packageNamespace, String service
.declarationFile(filename)
.build();
}

private static String getMemberName(MemberShape shape, Model model, boolean escape) {
Shape containerShape = model.expectShape(shape.getContainer());
if (containerShape.isEnumShape() || containerShape.isIntEnumShape()) {
return CaseUtils.toSnakeCase(shape.getMemberName()).toUpperCase(Locale.ENGLISH);
}

// If a member name contains an underscore, space, or dash, convert to camel case using Smithy utility
var memberName = shape.getMemberName();
if (DELIMITERS.stream().anyMatch(memberName::contains)) {
memberName = CaseUtils.toCamelCase(memberName);
} else {
memberName = uncapitalizeAcronymAware(memberName);
}

if (escape) {
memberName = CodegenUtils.MEMBER_ESCAPER.escape(memberName);
}
return memberName;
}

private static String uncapitalizeAcronymAware(String str) {
if (Character.isLowerCase(str.charAt(0))) {
return str;
} else if (str.equals(str.toUpperCase())) {
return str.toLowerCase();
}
int strLen = str.length();
StringBuilder sb = new StringBuilder(strLen);
boolean nextIsUpperCase;
for (int idx = 0; idx < strLen; idx++) {
var currentChar = str.charAt(idx);
nextIsUpperCase = (idx + 1 < strLen) && Character.isUpperCase(str.charAt(idx + 1));
if (Character.isUpperCase(currentChar) && (nextIsUpperCase || idx == 0)) {
sb.append(Character.toLowerCase(currentChar));
} else {
sb.append(currentChar);
}
}
return sb.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Flow;
import software.amazon.smithy.codegen.core.CodegenException;
Expand Down Expand Up @@ -52,7 +51,6 @@
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.StreamingTrait;
import software.amazon.smithy.model.traits.UnitTypeTrait;
import software.amazon.smithy.utils.CaseUtils;

/**
* Maps Smithy types to Java Symbols
Expand All @@ -61,7 +59,6 @@ public class JavaSymbolProvider implements ShapeVisitor<Symbol>, SymbolProvider

private static final InternalLogger LOGGER = InternalLogger.getLogger(JavaSymbolProvider.class);
private static final Symbol UNIT_SYMBOL = CodegenUtils.fromClass(Unit.class);
private static final List<String> DELIMITERS = List.of("_", "-", " ");

private final Model model;
private final ServiceShape service;
Expand All @@ -82,39 +79,7 @@ public Symbol toSymbol(Shape shape) {

@Override
public String toMemberName(MemberShape shape) {
Shape containerShape = model.expectShape(shape.getContainer());
if (containerShape.isEnumShape() || containerShape.isIntEnumShape()) {
return CaseUtils.toSnakeCase(shape.getMemberName()).toUpperCase(Locale.ENGLISH);
}

// If a member name contains an underscore, space, or dash, convert to camel case using Smithy utility
var memberName = shape.getMemberName();
if (DELIMITERS.stream().anyMatch(memberName::contains)) {
return CodegenUtils.MEMBER_ESCAPER.escape(CaseUtils.toCamelCase(memberName));
}

return CodegenUtils.MEMBER_ESCAPER.escape(uncapitalizeAcronymAware(memberName));
}

private static String uncapitalizeAcronymAware(String str) {
if (Character.isLowerCase(str.charAt(0))) {
return str;
} else if (str.equals(str.toUpperCase())) {
return str.toLowerCase();
}
int strLen = str.length();
StringBuilder sb = new StringBuilder(strLen);
boolean nextIsUpperCase;
for (int idx = 0; idx < strLen; idx++) {
var currentChar = str.charAt(idx);
nextIsUpperCase = (idx + 1 < strLen) && Character.isUpperCase(str.charAt(idx + 1));
if (Character.isUpperCase(currentChar) && (nextIsUpperCase || idx == 0)) {
sb.append(Character.toLowerCase(currentChar));
} else {
sb.append(currentChar);
}
}
return sb.toString();
return CodegenUtils.toMemberName(shape, model);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,14 @@ public void run() {
/**
* Value contained by this Enum.
*/
public ${value:N} value() {
public ${value:N} getValue() {
return value;
}

/**
* Type of this Enum variant.
*/
public ${type:N} type() {
public ${type:N} getType() {
return type;
}

Expand Down
Loading