index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/block_without_braces.java
if (x == 3) System.out.println("hello");
700
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/statements_and_newlines.java
public Number doThing() { Number x = 1; // x seems to be equal to 1 return x + 1; } public boolean doThing2(Number x) { if (x == 1) { return true; } return false; } public Number doThing3() { Number x = 1; return x + 1; } public void doThing4() { Number x = 1; x = 85; }
701
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/vararg_any_call.java
public void test(Object... _args) { } test(Map.of("Key", "Value", "also", 1337)); test(Map.of("Key", "Value"), Map.of("also", 1337));
702
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/for_of_loop.java
for (Object x : xs) { System.out.println(x); }
703
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/whitespace_between_statements_in_a_block.java
if (condition) { statementOne(); statementTwo(); }
704
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/if_then_else.java
if (x == 3) { System.out.println("bye"); } else { System.out.println("toodels"); }
705
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/if.java
if (x == 3) { System.out.println("bye"); }
706
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/empty_control_block.java
if (x == 3) { }
707
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/statements/multiline_if_then_else.java
if (x == 3) { x += 1; System.out.println("bye"); } else { System.out.println("toodels"); }
708
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_top_level_statements_using_void_directive.java
foo(3);
709
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_block_level_statements_using_void_directive.java
if (true) { System.out.println("everything is well"); } onlyToEndOfBlock();
710
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_halfway_into_class_using_comments.java
prepare(); System.out.println(this + "it seems to work");
711
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_parameter_sequence.java
foo(3, 8);
712
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_expression_with_explicit_ellipsis.java
foo(3, ...);
713
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/hiding/hide_statements_with_explicit_ellipsis.java
before(); // ... after();
714
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/any_type_never_a_struct.java
functionThatTakesAnAny(Map.of( "argument", 5));
715
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/optional_known_struct.java
Vpc.Builder.create(this, "Something") .argument(5) .build();
716
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/var_new_class_unknown_struct.java
Object vpc = Vpc.Builder.create(this, "Something") .argument(5) .build();
717
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/struct_starting_with_i.java
Integration.Builder.create(this, "Something") .argument(5) .build();
718
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/infer_struct_from_union.java
takes(MyProps.builder() .struct(SomeStruct.builder() .enabled(false) .option("option") .build()) .build());
719
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/structs/var_new_class_known_struct.java
Vpc vpc = Vpc.Builder.create(this, "Something") .argument(5) .build();
720
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/map-literal.java
Map<String, Object> map = Map.of( "Access-Control-Allow-Origin", "\"*\"");
721
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/string_literal.java
String literal = "\nThis is a multiline string literal.\n\n\"It's cool!\".\n\nYEAH BABY!!\n\nLitteral \\n right here (not a newline!)\n";
722
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/ellipsis_at_a_random_place.java
callThisFunction(foo, ...);
723
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/backtick_string_w_o_substitutions.java
String x = "some string";
724
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/as_expression.java
System.out.println((Number)3);
725
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/enum_like_access.java
System.out.println(EnumType.ENUM_VALUE_A);
726
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/await.java
Number x = future();
727
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/enum_access.java
System.out.println(EnumType.ENUM_VALUE_A);
728
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/computed_key.java
String y = "WHY?"; Map<String, String> x = Map.of(String.format("key-%s", y), "value"); Map<String, Boolean> z = Map.of(y, true);
729
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/double_quoted_dict_keys.java
Map<String, String> x = Map.of("key", "value");
730
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/unary_and_binary_operators.java
System.out.println(-3); System.out.println(!false); System.out.println(a == b);
731
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/string_interpolation.java
String x = "world"; String y = "well"; System.out.println(String.format("Hello, %s, it works %s!", x, y)); // And now a multi-line expression System.out.println(String.format("%nHello, %s.%n%nIt works %s!%n", x, y));
732
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/struct_assignment.java
public class Test { private String key; public String getKey() { return this.key; } public Test key(String key) { this.key = key; return this; } } Test x = new Test().key("value");
733
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/array_index.java
String[] array; System.out.println(array[3]);
734
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/expressions/non_null_expression.java
Object x = someObject.getSomeAttribute();
735
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/interfaces/interface_with_method.java
public interface IThing { void doAThing(); }
736
0
Create_ds/jsii/packages/jsii-rosetta/test/translations
Create_ds/jsii/packages/jsii-rosetta/test/translations/interfaces/interface_with_props.java
public interface IThing { String getThingArn(); }
737
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon/jsii/JsiiObjectTest.java
package software.amazon.jsii; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import java.util.List; import java.util.Map; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.STRICT_STUBS) public final class JsiiObjectTest { private final JsonNodeFactory nodeFactory = JsonNodeFactory.instance; private int nextInstanceId = 50000; /** * "Legacy" tests allow ensuring that code generated before the fix for https://github.com/aws/jsii/issues/1196 was * rolled out continue to work with fixed runtimes (that leverage a newer API). The collection elements are expected * to "incorrectly" be instances of {@link JsiiObject} instead of the desired interface type. Those tests * essentially ensure the code does not crash where it used to work (even though incorrectly). */ @Test public void testJsiiCall_Legacy_ReturnsListOfInterfaces() { // GIVEN final JsiiEngine mockEngine = mock(JsiiEngine.class, "MockEngine"); final JsiiClient mockClient = mock(JsiiClient.class, "MockClient"); final JsiiObjectRef objectRef = JsiiObjectRef.fromObjId("Object@10000"); // WHEN when(mockEngine.getClient()).thenReturn(mockClient); when(mockEngine.nativeToObjRef(any())).thenReturn(objectRef); when(mockClient.callMethod(objectRef, "listOfInterfaces", nodeFactory.arrayNode())) .thenReturn(nodeFactory.arrayNode() .add(makeObjectReferenceNode()) .add(makeObjectReferenceNode())); // THEN final LegacySubject subject = new LegacySubject(mockEngine, objectRef); final List<TestInterface> result = subject.listOfInterfaces(); assertNotNull(result); for (final Object element : result) { assertTrue(element instanceof JsiiObject, String.format("Element %s (of type %s) is not a %s", element, element.getClass(), JsiiObject.class)); } final ArgumentCaptor<LegacySubject> capture = ArgumentCaptor.forClass(LegacySubject.class); verify(mockEngine).registerObject(eq(objectRef), capture.capture()); assertEquals(subject, capture.getValue()); } /** * "Legacy" tests allow ensuring that code generated before the fix for https://github.com/aws/jsii/issues/1196 was * rolled out continue to work with fixed runtimes (that leverage a newer API). The collection elements are expected * to "incorrectly" be instances of {@link JsiiObject} instead of the desired interface type. Those tests * essentially ensure the code does not crash where it used to work (even though incorrectly). */ @Test public void testJsiiGet_ReturnsListOfInterfaces() { // GIVEN final JsiiEngine mockEngine = mock(JsiiEngine.class, "MockEngine"); final JsiiClient mockClient = mock(JsiiClient.class, "MockClient"); final JsiiObjectRef objectRef = JsiiObjectRef.fromObjId("Object@10000"); // WHEN when(mockEngine.getClient()).thenReturn(mockClient); when(mockEngine.nativeToObjRef(any())).thenReturn(objectRef); when(mockClient.getPropertyValue(objectRef, "interfaces")) .thenReturn(nodeFactory.arrayNode() .add(makeObjectReferenceNode()) .add(makeObjectReferenceNode())); // THEN final LegacySubject subject = new LegacySubject(mockEngine, objectRef); final List<TestInterface> result = subject.getInterfaces(); assertNotNull(result); for (final Object element : result) { assertTrue(element instanceof JsiiObject, String.format("Element %s (of type %s) is not a %s", element, element.getClass(), JsiiObject.class)); } final ArgumentCaptor<LegacySubject> capture = ArgumentCaptor.forClass(LegacySubject.class); verify(mockEngine).registerObject(eq(objectRef), capture.capture()); assertEquals(subject, capture.getValue()); } /** * "Legacy" tests allow ensuring that code generated before the fix for https://github.com/aws/jsii/issues/1196 was * rolled out continue to work with fixed runtimes (that leverage a newer API). The collection elements are expected * to "incorrectly" be instances of {@link JsiiObject} instead of the desired interface type. Those tests * essentially ensure the code does not crash where it used to work (even though incorrectly). */ @Test public void testJsiiCall_ReturnsMapOfInterfaces() { // GIVEN final JsiiEngine mockEngine = mock(JsiiEngine.class, "MockEngine"); final JsiiClient mockClient = mock(JsiiClient.class, "MockClient"); final JsiiObjectRef objectRef = JsiiObjectRef.fromObjId("Object@10000"); // WHEN when(mockEngine.getClient()).thenReturn(mockClient); when(mockEngine.nativeToObjRef(any())).thenReturn(objectRef); when(mockClient.callMethod(objectRef, "mapOfInterfaces", nodeFactory.arrayNode())) .thenReturn(nodeFactory.objectNode().set("A", makeObjectReferenceNode())); // THEN final LegacySubject subject = new LegacySubject(mockEngine, objectRef); final Map<String, TestInterface> result = subject.mapOfInterfaces(); assertNotNull(result); for (final Object element : result.values()) { assertTrue(element instanceof JsiiObject, String.format("Element %s (of type %s) is not a %s", element, element.getClass(), JsiiObject.class)); } final ArgumentCaptor<LegacySubject> capture = ArgumentCaptor.forClass(LegacySubject.class); verify(mockEngine).registerObject(eq(objectRef), capture.capture()); assertEquals(subject, capture.getValue()); } /** * "Legacy" tests allow ensuring that code generated before the fix for https://github.com/aws/jsii/issues/1196 was * rolled out continue to work with fixed runtimes (that leverage a newer API). The collection elements are expected * to "incorrectly" be instances of {@link JsiiObject} instead of the desired interface type. Those tests * essentially ensure the code does not crash where it used to work (even though incorrectly). */ @Test public void testJsiiGet_ReturnsMapOfInterfaces() { // GIVEN final JsiiEngine mockEngine = mock(JsiiEngine.class, "MockEngine"); final JsiiClient mockClient = mock(JsiiClient.class, "MockClient"); final JsiiObjectRef objectRef = JsiiObjectRef.fromObjId("Object@10000"); // WHEN when(mockEngine.getClient()).thenReturn(mockClient); when(mockEngine.nativeToObjRef(any())).thenReturn(objectRef); when(mockClient.getPropertyValue(objectRef, "interfaceMap")) .thenReturn(nodeFactory.objectNode().set("A", makeObjectReferenceNode())); // THEN final LegacySubject subject = new LegacySubject(mockEngine, objectRef); final Map<String, TestInterface> result = subject.getInterfaceMap(); assertNotNull(result); for (final Object element : result.values()) { assertTrue(element instanceof JsiiObject, String.format("Element %s (of type %s) is not a %s", element, element.getClass(), JsiiObject.class)); } final ArgumentCaptor<LegacySubject> capture = ArgumentCaptor.forClass(LegacySubject.class); verify(mockEngine).registerObject(eq(objectRef), capture.capture()); assertEquals(subject, capture.getValue()); } private ObjectNode makeObjectReferenceNode() { final ObjectNode objectNode = nodeFactory.objectNode() .put(JsiiObjectRef.TOKEN_REF, String.format("Object@%d", nextInstanceId += 11)); objectNode.putArray(JsiiObjectRef.TOKEN_INTERFACES).add("@jsii/java-runtime.TestInterface"); return objectNode; } @SuppressWarnings({ "deprecation", "unchecked" }) private static final class LegacySubject extends JsiiObject { public LegacySubject(final JsiiEngine engine, final JsiiObjectRef objectRef) { super(engine, objectRef); } public final List<TestInterface> listOfInterfaces() { // Intentionally uses the "legacy" API that predates https://github.com/aws/jsii/issues/1196 return this.jsiiCall("listOfInterfaces", List.class); } public final List<TestInterface> getInterfaces() { // Intentionally uses the "legacy" API that predates https://github.com/aws/jsii/issues/1196 return this.jsiiGet("interfaces", List.class); } public final Map<String, TestInterface> mapOfInterfaces() { // Intentionally uses the "legacy" API that predates https://github.com/aws/jsii/issues/1196 return this.jsiiCall("mapOfInterfaces", Map.class); } public final Map<String, TestInterface> getInterfaceMap() { // Intentionally uses the "legacy" API that predates https://github.com/aws/jsii/issues/1196 return this.jsiiGet("interfaceMap", Map.class); } } private interface TestInterface { /* Intentionally left empty. */ } }
738
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon/jsii/JsiiRuntimeTest.java
package software.amazon.jsii; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; public final class JsiiRuntimeTest { @Test public void withNoCustomization() { final JsiiRuntime runtime = new JsiiRuntime(null, null); runtime.getClient().createObject("Object", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); runtime.terminate(); } @Test public void withCustomNode_Simple() { final String customNode = resolveNodeFromPath(); final JsiiRuntime runtime = new JsiiRuntime(null, customNode); runtime.getClient().createObject("Object", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); runtime.terminate(); } @Test public void withCustomNode_WithSpace() { final JsiiRuntime runtime = new JsiiRuntime(null, "node --max_old_space_size=1024"); runtime.getClient().createObject("Object", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); runtime.terminate(); } @Test public void withCustomRuntime_Simple() throws Exception { final Path launcher = Files.createTempFile("jsii-runtime", ".launcher.bat"); try (final Writer writer = new FileWriter(launcher.toFile())) { writer.write("node ./src/main/resources/software/amazon/jsii/bin/jsii-runtime.js\n"); } Assertions.assertTrue(launcher.toFile().setExecutable(true)); final JsiiRuntime runtime = new JsiiRuntime(launcher.toString(), null); runtime.getClient().createObject("Object", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); runtime.terminate(); } @Test public void withCustomRuntime_WithSpace() { final JsiiRuntime runtime = new JsiiRuntime("node ./src/main/resources/software/amazon/jsii/bin/jsii-runtime.js", null); runtime.getClient().createObject("Object", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); runtime.terminate(); } private static String resolveNodeFromPath() { try { final String[] command = System.getProperty("os.name").startsWith("Windows") ? new String[]{"cmd.exe", "/d", "/s", "/c", "where node"} : new String[]{"sh", "-c", "command -v node"}; final Process process = Runtime.getRuntime().exec(command); try { final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); return br.readLine(); } finally { process.waitFor(); } } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } }
739
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon/jsii/UnsafeCastTest.java
package software.amazon.jsii; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; public final class UnsafeCastTest { @Test public void canCastToAnyInterface() { final JsiiObject subject = new JsiiObject(new JsiiObjectRef("Object@1000", Collections.emptySet())); final IManagedInterface result = UnsafeCast.unsafeCast(subject, IManagedInterface.class); Assertions.assertInstanceOf(IManagedInterface.class, result); } @Jsii(fqn = "test.IManagedInterface", module = JsiiModule.class) @Jsii.Proxy(ManagedInterfaceProxy.class) private interface IManagedInterface extends JsiiSerializable { boolean getBooleanProperty(); } private final static class ManagedInterfaceProxy extends JsiiObject implements IManagedInterface { public ManagedInterfaceProxy(final JsiiObjectRef objRef) { super(objRef); } @Override public boolean getBooleanProperty() { throw new UnsupportedOperationException("Not Implemented"); } } }
740
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/test/java/software/amazon/jsii/JsiiObjectMapperTest.java
package software.amazon.jsii; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public final class JsiiObjectMapperTest { private JsiiEngine jsiiEngine; private ObjectMapper subject; @BeforeEach public void setUp() { this.jsiiEngine = mock(JsiiEngine.class); this.subject = new JsiiObjectMapper(jsiiEngine).getObjectMapper(); } @AfterEach public void cleanUp() { this.jsiiEngine = null; this.subject = null; } @Test public void testDeserialization() throws Exception { final Object mockObject1 = new Object(); when(jsiiEngine.nativeFromObjRef(JsiiObjectRef.fromObjId("module.Type@1"))).thenReturn(mockObject1); when((TestEnum) jsiiEngine.findEnumValue("module.Enum#value")).thenReturn(TestEnum.DUMMY); try (final InputStream stream = this.getClass().getResourceAsStream("complex-callback.json"); final InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); final BufferedReader buffered = new BufferedReader(reader)) { final String json = buffered.lines().collect(Collectors.joining("\n")); final TestCallback callback = subject.treeToValue(subject.readTree(json), TestCallback.class); assertEquals("CallbackID", callback.getCbid()); assertNotNull(callback.getInvoke()); if (callback.getCbid() != null) { assertEquals("methodName", callback.getInvoke().getMethod()); assertEquals(1337, callback.getInvoke().getArgs().get(0)); assertEquals(mockObject1, callback.getInvoke().getArgs().get(1)); assertEquals(Instant.ofEpochMilli(1553624863569L), callback.getInvoke().getArgs().get(2)); assertEquals(TestEnum.DUMMY, callback.getInvoke().getArgs().get(3)); } } } @Test public void testSerializationOfJsiiSerializables() throws Exception { final String dummyValue = "{\"foo\":\"Bar\"}"; final JsiiSerializable object = mock(JsiiSerializable.class); when(object.$jsii$toJson()).thenReturn(new ObjectMapper().readTree(dummyValue)); final String json = subject.writeValueAsString(object); assertEquals(dummyValue, json); } @Test public void testSerializationOfInstant() throws Exception { final Instant object = Instant.ofEpochMilli(1553691207095L); final String json = subject.writeValueAsString(object); assertEquals("{\"$jsii.date\":\"2019-03-27T12:53:27.095Z\"}", json); } private static enum TestEnum { DUMMY } /** * Kinda like the Callback object expcet it does not model stuff as JsonNodes, * so we can verify the deserialization behaviour. */ public static final class TestCallback { private String cbid; private TestInvokeRequest invoke; public String getCbid() { return cbid; } public void setCbid(String cbid) { this.cbid = cbid; } public TestInvokeRequest getInvoke() { return invoke; } public void setInvoke(TestInvokeRequest invoke) { this.invoke = invoke; } } /** * Kinda like the InvokeRequest, except it does not model anything as JsonNode, * so we can test the deserialization behavior properly. */ public static final class TestInvokeRequest { private String method; private List<Object> args; public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public List<Object> getArgs() { return args; } public void setArgs(List<Object> args) { this.args = args; } } }
741
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java
package software.amazon.jsii; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import software.amazon.jsii.api.Callback; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.nio.channels.Channels; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static software.amazon.jsii.JsiiVersion.JSII_RUNTIME_VERSION; /** * Manages the jsii-runtime child process. */ @Internal public final class JsiiRuntime { /** * Extract the "+<sha>" postfix from a full version number. */ private static final String VERSION_BUILD_PART_REGEX = "\\+[a-z0-9]+$"; /** * */ static final ThreadLocal<MessageInspector> messageInspector = new ThreadLocal<>(); /** * The HTTP client connected to this child process. */ private JsiiClient client; /** * The child procesds. */ private Process childProcess; /** * Child's standard output. */ private BufferedReader stdout; /** * Child's standard input. */ private Writer stdin; /** * The error stream sink for the child process. */ private ErrorStreamSink errorStreamSink; /** * Handler for synchronous callbacks. Must be set using setCallbackHandler. */ private JsiiCallbackHandler callbackHandler; /** * The JVM shutdown hook registered by this instance, if any. */ private Thread shutdownHook; /** The value of the JSII_RUNTIME environment variable */ @Nullable private final String customRuntime; /** The value of the JSII_NODE environment variable */ @Nullable private final String customNode; public JsiiRuntime() { this(System.getenv("JSII_RUNTIME"), System.getenv("JSII_NODE")); } @VisibleForTesting JsiiRuntime(@Nullable final String customRuntime, @Nullable final String customNode) { this.customRuntime = customRuntime; this.customNode = customNode; } /** * The main API of this class. Sends a JSON request to jsii-runtime and returns the JSON response. * * @param request The JSON request * @return The JSON response * @throws JsiiError If the runtime returns an error response originating from the @jsii/kernel. * @throws RuntimeException If the runtime returns an error response. */ JsonNode requestResponse(final JsonNode request) { try { JsiiRuntime.notifyInspector(request, MessageInspector.MessageType.Request); // write request String str = request.toString(); this.stdin.write(str + "\n"); this.stdin.flush(); // read response JsonNode resp = readNextResponse(); // throw if this is an error response if (resp.has("error")) { return processErrorResponse(resp); } // process synchronous callbacks (which 'interrupt' the response flow). if (resp.has("callback")) { return processCallbackResponse(resp); } // null "ok" means undefined result (or void). return resp.get("ok"); } catch (IOException e) { throw new JsiiError("Unable to send request to jsii-runtime: " + e.toString(), e); } } /** * Handles an "error" response by extracting the message and stack trace * and throwing a JsiiError or a RuntimeException. * * @param resp The response * @return Never */ private JsonNode processErrorResponse(final JsonNode resp) { String errorName = resp.get("name").asText(); String errorMessage = resp.get("error").asText(); if (resp.has("stack")) { errorMessage += "\n" + resp.get("stack").asText(); } if (errorName.equals(JsiiException.Type.RUNTIME_ERROR.toString())) { throw new RuntimeException(errorMessage); } throw new JsiiError(errorMessage); } /** * Processes a "callback" response, which is a request to invoke a synchronous callback * and send back the result. * * @param resp The response. * @return The next response in the req/res chain. */ private JsonNode processCallbackResponse(final JsonNode resp) { if (this.callbackHandler == null) { throw new JsiiError("Cannot process callback since callbackHandler was not set"); } Callback callback = JsiiObjectMapper.treeToValue(resp.get("callback"), NativeType.forClass(Callback.class)); JsonNode result = null; String error = null; String name = null; try { result = this.callbackHandler.handleCallback(callback); } catch (Exception e) { if (e.getCause() instanceof InvocationTargetException) { error = e.getCause().getCause().getMessage(); } else { error = e.getMessage(); } name = e instanceof JsiiError ? JsiiException.Type.JSII_FAULT.toString() : JsiiException.Type.RUNTIME_ERROR.toString(); } ObjectNode completeResponse = JsonNodeFactory.instance.objectNode(); completeResponse.put("cbid", callback.getCbid()); if (error != null) { completeResponse.put("err", error); completeResponse.put("name", name); } if (result != null) { completeResponse.set("result", result); } ObjectNode req = JsonNodeFactory.instance.objectNode(); req.set("complete", completeResponse); return requestResponse(req); } /** * Sets the handler for sync callbacks. * * @param callbackHandler The handler. */ public void setCallbackHandler(final JsiiCallbackHandler callbackHandler) { this.callbackHandler = callbackHandler; } @Override protected void finalize() throws Throwable { try { this.terminate(); } finally { super.finalize(); } } synchronized void terminate() { // The jsii Kernel process exists after having received the "exit" message if (stdin != null) { try { stdin.write("{\"exit\":0}\n"); stdin.close(); } catch (final IOException ioe) { // Ignore - the stream might have already been closed, if the child exited already. } finally { stdin = null; } } // Cleaning up stdout (ensuring buffers are flushed, etc...) if (stdout != null) { try { stdout.close(); } catch (final IOException ioe) { // Ignore - the stream might have already been closed. } finally { stdout = null; } } // Cleaning up error stream sink (ensuring all messages are flushed, etc...) if (this.errorStreamSink != null) { try { this.errorStreamSink.close(); } catch (final InterruptedException ie) { // Ignore - we can no longer do anything about this... } finally { this.errorStreamSink = null; } } if (childProcess != null) { // Wait for the child process to complete try { // Giving the process up to 5 seconds to clean up and exit if (!childProcess.waitFor(5, TimeUnit.SECONDS)) { // If it's still not done, forcibly terminate it at this point. childProcess.destroyForcibly(); } } catch (final InterruptedException ie) { throw new RuntimeException(ie); } finally { childProcess = null; } } // We shut down already, no need for the shutdown hook anymore if (this.shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (final IllegalStateException ise) { // VM Shutdown is in progress, removal is now impossible (and unnecessary) } finally { this.shutdownHook = null; } } } /** * Starts jsii-server as a child process if it is not already started. */ private synchronized void startRuntimeIfNeeded() { if (childProcess != null) { return; } // If JSII_DEBUG is set, enable traces. final String jsiiDebug = System.getenv("JSII_DEBUG"); final boolean traceEnabled = jsiiDebug != null && !jsiiDebug.isEmpty() && !jsiiDebug.equalsIgnoreCase("false") && !jsiiDebug.equalsIgnoreCase("0"); final List<String> jsiiRuntimeCommand = jsiiRuntimeCommand(); if (traceEnabled) { System.err.println("jsii-runtime: " + String.join(" ", jsiiRuntimeCommand)); } try { final ProcessBuilder pb = new ProcessBuilder() .command(jsiiRuntimeCommand) .redirectError(ProcessBuilder.Redirect.PIPE) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectInput(ProcessBuilder.Redirect.PIPE); pb.environment().put("JSII_AGENT", String.format("Java/%s", System.getProperty("java.version"))); if (jsiiDebug != null) { pb.environment().put("JSII_DEBUG", jsiiDebug); } this.childProcess = pb.start(); this.stdin = new OutputStreamWriter(this.childProcess.getOutputStream(), StandardCharsets.UTF_8); this.stdout = new BufferedReader(new InputStreamReader(this.childProcess.getInputStream(), StandardCharsets.UTF_8)); this.errorStreamSink = new ErrorStreamSink(this.childProcess.getErrorStream()); this.errorStreamSink.start(); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } this.shutdownHook = new Thread(this::terminate, "Terminate jsii client"); Runtime.getRuntime().addShutdownHook(this.shutdownHook); handshake(); this.client = new JsiiClient(this); } /** * Determines the correct command to execute in order to start the jsii runtime program. If custom runtimes are * configured (either via `JSII_RUNTIME` or `JSII_NODE`), defer to `sh -c` in order to ensure platform-appropriate * command parsing is performed, since {@link ProcessBuilder#command(String...)} won't do any of this by itself. * * @return The command to execute to start the jsii runtime program. */ private List<String> jsiiRuntimeCommand() { if (this.customRuntime != null) { if (this.customRuntime.matches(".*\\s.*")) { // Shell out only if the custom runtime includes white space. return shellOut(this.customRuntime); } return Collections.singletonList(this.customRuntime); } // We don't use a custom runtime, so extract the bundled one... final String bundledRuntime = BundledRuntime.extract(JsiiRuntime.class); if (this.customNode != null && this.customNode.matches(".*\\s.*")) { // Shell out only if the custom node includes white space. return shellOut(this.customNode, bundledRuntime); } return Arrays.asList(this.customNode != null ? this.customNode : "node", bundledRuntime); } /** * Creates a command to sub-shell to the specified end-user command, that uses `/bin/sh` on *NIXes, and %COMSPEC%, or * cmd.exe on Windows. * * <p> * This is heavily inspired from <a href="https://github.com/nodejs/node/blob/434bdde97464cc04f79ed3c8398f2a50c71c39d1/lib/child_process.js#L617-L642">how Node.js does the same thing</a>. * </p> * * @param command the end-user command to be run. * * @return a full sub-shell command that is platform-appropriate. */ private static List<String> shellOut(final String... command) { final boolean isWindows = System.getProperty("os.name").startsWith("Windows"); if (isWindows) { String cmd = System.getenv("COMSPEC"); if (cmd == null) { cmd = "cmd.exe"; } return Arrays.asList(cmd, "/d", "/s", "/c", String.join(" ", command)); } return Arrays.asList("/bin/sh", "-c", String.join(" ", command)); } /** * Verifies the "hello" message and runtime version compatibility. * In the meantime, we require full version compatibility, but we should use semver eventually. */ private void handshake() { JsonNode helloResponse = this.readNextResponse(); if (!helloResponse.has("hello")) { throw new JsiiError("Expecting 'hello' message from jsii-runtime"); } String runtimeVersion = helloResponse.get("hello").asText(); assertVersionCompatible(JSII_RUNTIME_VERSION, runtimeVersion); } /** * Reads the next response from STDOUT of the child process. * * @return The parsed JSON response. * @throws JsiiError if we couldn't parse the response. */ JsonNode readNextResponse() { try { String responseLine = this.stdout.readLine(); if (responseLine == null) { throw new JsiiError("Child process exited unexpectedly!"); } final JsonNode response = JsiiObjectMapper.INSTANCE.readTree(responseLine); JsiiRuntime.notifyInspector(response, MessageInspector.MessageType.Response); return response; } catch (IOException e) { throw new JsiiError("Unable to read reply from jsii-runtime: " + e.toString(), e); } } /** * This will return the server process in case it is not already started. * * @return A {@link JsiiClient} connected to the server process. */ public JsiiClient getClient() { this.startRuntimeIfNeeded(); if (this.client == null) { throw new JsiiError("Client not created"); } return this.client; } /** * Asserts that a peer runtimeVersion is compatible with this Java runtime version, which means * they share the same version components, with the possible exception of the build number. * * @param expectedVersion The version this client expects from the runtime * @param actualVersion The actual version the runtime reports * @throws JsiiError if versions mismatch */ static void assertVersionCompatible(final String expectedVersion, final String actualVersion) { final String shortActualVersion = actualVersion.replaceAll(VERSION_BUILD_PART_REGEX, ""); final String shortExpectedVersion = expectedVersion.replaceAll(VERSION_BUILD_PART_REGEX, ""); if (shortExpectedVersion.compareTo(shortActualVersion) != 0) { throw new JsiiError("Incompatible jsii-runtime version. Expecting " + shortExpectedVersion + ", actual was " + shortActualVersion); } } private static void notifyInspector(final JsonNode message, final MessageInspector.MessageType type) { final MessageInspector inspector = JsiiRuntime.messageInspector.get(); if (inspector == null) { return; } inspector.inspect(message, type); } /** * This {@link Thread} takes the standard error output from a child process and handles it correctly as per the jsii * runtime protocol. It is implemented in such a way that it is interruptible, drawing inspiration from how it's * done at zt-exec (so credits to ZeroTurnaround & contributors). * * @see <a href="https://github.com/zeroturnaround/zt-exec/blob/master/src/main/java/org/zeroturnaround/exec/stream/InputStreamPumper.java">zt-exec</a> */ private static final class ErrorStreamSink extends Thread { private final ObjectMapper objectMapper = new ObjectMapper(); private final InputStream inputStream; private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private boolean eof = false; private boolean stop = false; public ErrorStreamSink(final InputStream inputStream) { this.inputStream = inputStream; this.setDaemon(true); this.setName(this.getClass().getCanonicalName()); this.setUncaughtExceptionHandler((thread, throwable) -> { System.err.printf("Unexpected error in background thread \"%s\": %s%n", thread.getName(), throwable); }); } public void run() { try { while (!this.stop) { this.acceptData(false); if (!this.stop) { // Short interruptible sleep, so we can be stopped by a signal... This is a bit ugly (busy-waiting) // but is in fact the only way to be reliably interruptible with the InputStream API. Thread.sleep(100); } } // Finish flushing the stream until no data is left, so no log entries are dropped on the floor. this.acceptData(true); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } catch (final InterruptedException ie) { // Ignore - simply exit right away. } } public void close() throws InterruptedException { this.stop = true; this.join(); } /** * Accepts data from {@link #inputStream} as long as data is available, or until EOF is reached if the * {@code uninterruptible} parameter is set to {@code true}. * * @param uninterruptible whether data should be read in a blocking manner until EOF is reached or not. * * @throws IOException */ private void acceptData(final boolean uninterruptible) throws IOException { while (!this.eof && (uninterruptible || this.inputStream.available() > 0)) { final int read = this.inputStream.read(); if (read == -1) { this.eof = true; } else { this.buffer.write(read); } if (read == '\n' || this.eof) { processLine(new String(buffer.toByteArray(), StandardCharsets.UTF_8)); buffer.reset(); } } } private void processLine(final String line) { try { final JsonNode tree = objectMapper.readTree(line); final ConsoleOutput consoleOutput = objectMapper.treeToValue(tree, ConsoleOutput.class); if (consoleOutput.stderr != null) { System.err.write(consoleOutput.stderr, 0, consoleOutput.stderr.length); } if (consoleOutput.stdout != null) { System.out.write(consoleOutput.stdout, 0, consoleOutput.stdout.length); } } catch (final JsonProcessingException exception) { // If not JSON, then this goes straight to stderr without touches... System.err.println(line); } } } private static final class ConsoleOutput { @Nullable public final byte[] stderr; @Nullable public final byte[] stdout; @JsonCreator public ConsoleOutput( @JsonProperty("stderr") @Nullable final byte[] stderr, @JsonProperty("stdout") @Nullable final byte[] stdout ) { this.stderr = stderr; this.stdout = stdout; } } }
742
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Jsii.java
package software.amazon.jsii; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a class is a jsii class, which means that it's logic is implemented in * a JavaScript module. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface Jsii { /** * The jsii module class that hosts this type. * @return The class which represents this jsii module. */ Class<? extends JsiiModule> module(); /** * The jsii FQN (fully qualified name) for this type. * @return The jsii FQN of the type. */ String fqn(); /** * Indicates that a proxy implementation exists for this type, and what it is. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited @interface Proxy { Class<? extends JsiiObject> value(); } }
743
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiCallbackHandler.java
package software.amazon.jsii; import software.amazon.jsii.api.Callback; import com.fasterxml.jackson.databind.JsonNode; /** * Invoked to handle native synchronous callbacks. */ public interface JsiiCallbackHandler { /** * Invoked to handle a request from jsii to process a native (java) callback. * @param callback The callback info. * @return The return value of the callback. */ JsonNode handleCallback(Callback callback); }
744
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/UnsafeCast.java
package software.amazon.jsii; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public final class UnsafeCast { /** * Unsafely obtains a view on a given value as an instance of an interface annotated with the {@link Jsii.Proxy} * annotation. * * @param value the value to be converted. * @param target the target type to obtain. This must be an interface with the {@link Jsii.Proxy} annotation. * * @return the converted value. Will only return {@code null} if {@code value} is {@code null}. * * @param <T> the return type of the cast. * * @throws IllegalArgumentException if the provided {@code target} is not a {@link Jsii.Proxy} annotated interface. */ @SuppressWarnings("unchecked") public static <T extends JsiiSerializable> T unsafeCast(final JsiiObject value, final Class<T> target) { if (value == null) { return null; } if (target.isAssignableFrom(value.getClass())) { return (T)value; } if (!target.isAnnotationPresent(Jsii.class)) { throw new IllegalArgumentException(String.format("Class %s does not have the @Jsii annotation!", target.getCanonicalName())); } if (!target.isAnnotationPresent(Jsii.Proxy.class)) { throw new IllegalArgumentException(String.format("Class %s does not have the @Jsii.Proxy annotation!", target.getCanonicalName())); } final String fqn = target.getAnnotation(Jsii.class).fqn(); final Jsii.Proxy annotation = target.getAnnotation(Jsii.Proxy.class); try { final Constructor<? extends JsiiObject> constructor = annotation.value().getDeclaredConstructor(JsiiObjectRef.class); @SuppressWarnings("deprecated") final boolean oldAccessible = constructor.isAccessible(); try { constructor.setAccessible(true); final JsiiObject proxyInstance = constructor.newInstance(value.jsii$objRef.withInterface(fqn)); return (T) proxyInstance; } finally { constructor.setAccessible(oldAccessible); } } catch (final NoSuchMethodException nsme) { throw new JsiiError(String.format("Unable to find interface proxy constructor on %s", annotation.value().getCanonicalName()), nsme); } catch (final InvocationTargetException | InstantiationException e) { throw new JsiiError(String.format("Unable to initialize interface proxy %s", annotation.value().getCanonicalName()), e); } catch (final IllegalAccessException iae) { throw new JsiiError(String.format("Unable to invoke constructor of %s", annotation.value().getCanonicalName()), iae); } } private UnsafeCast(){ throw new UnsupportedOperationException(); } }
745
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiException.java
package software.amazon.jsii; /* * An error raised by the jsii runtime. */ public abstract class JsiiException extends RuntimeException { public static final long serialVersionUID = 1L; static enum Type { JSII_FAULT("@jsii/kernel.Fault"), RUNTIME_ERROR("@jsii/kernel.RuntimeError"); private final String errorType; Type(String str) { this.errorType = str; } public String toString() { return this.errorType; } } /** * Creates an exception. * @param message The error message */ JsiiException(final String message) { super(message); } /** * Creates an exception. * @param e The error that caused this exception */ JsiiException(final Throwable e) { super(e); } /** * Creates an exception. * @param message The error message * @param e The error that caused this exception */ JsiiException(final String message, final Throwable e) { super(message, e); } }
746
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Util.java
package software.amazon.jsii; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import static java.util.stream.Collectors.toList; /** * Utilities. */ final class Util { /** * Size of java property method prefixes ("set" or "get"). */ static final int PROPERTY_METHOD_PREFIX_LEN = 3; /** * Utility class. */ private Util() { } /** * Reads a string from an input stream. * @param is The input stream., * @return A string. */ static String readString(final InputStream is) { try (final Scanner s = new Scanner(is, "UTF-8")) { s.useDelimiter("\\A"); if (s.hasNext()) { return s.next(); } else { return ""; } } } /** * Checks if the method name looks like a java property getter (getXxx). * @param method The reflected method that may be a get/setter * @return true if the method is a get/setter. */ static boolean isJavaPropertyMethod(final Method method) { final String methodName = method.getName(); if (methodName.length() <= PROPERTY_METHOD_PREFIX_LEN) { // Needs to have at least one character after the "get" or "set" prefix return false; } if (methodName.startsWith("get") && method.getParameterCount() == 0) { // Require something else than a lowercase letter after the "get" prefix return !Character.isLowerCase(methodName.charAt(3)); } if (methodName.startsWith("set") && method.getParameterCount() == 1) { // Require something else than a lowercase letter after the "get" prefix return !Character.isLowerCase(methodName.charAt(3)) // Require a matching getter && isMatchingGetterPresent(method.getName().replaceFirst("set", "get"), method.getParameterTypes()[0], method.getDeclaringClass()); } return false; } private static boolean isMatchingGetterPresent(final String getterName, final Class<?> returnType, final Class<?> declaring) { try { final Method getter = declaring.getDeclaredMethod(getterName); return getter.getReturnType().equals(returnType); } catch (final NoSuchMethodException nsme) { return !declaring.equals(Object.class) && isMatchingGetterPresent(getterName, returnType, declaring.getSuperclass()); } } /** * Convert a java property method name (getXxx/setXxx) to a javascript property name (xxx). * @param method The reflected method (assumed to be a get/setter according to #isJavaPropertyMethod) * @return The javascript property name */ static String javaPropertyToJSProperty(final Method method) { final String getterSetterMethod = method.getName(); if (!isJavaPropertyMethod(method)) { throw new JsiiError("Invalid getter/setter method. Must start with get/set"); } String camelCase = getterSetterMethod.substring( PROPERTY_METHOD_PREFIX_LEN, PROPERTY_METHOD_PREFIX_LEN + 1).toLowerCase(); if (getterSetterMethod.length() > PROPERTY_METHOD_PREFIX_LEN + 1) { camelCase += getterSetterMethod.substring(PROPERTY_METHOD_PREFIX_LEN + 1); } return camelCase; } /** * Converts a javascript property name (xxx) to a Java property method (setXxx/getXxx). * @param prefix The prefix (get/set) * @param jsPropertyName The javascript property name * @return The java method name */ static String javaScriptPropertyToJavaPropertyName(final String prefix, final String jsPropertyName) { if (jsPropertyName.isEmpty()) { throw new JsiiError("jsPropertyName must not be empty"); } StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(jsPropertyName.substring(0, 1).toUpperCase()); if (jsPropertyName.length() > 1) { sb.append(jsPropertyName.substring(1)); } return sb.toString(); } /** * Extracts a resource file from the .jar and saves it into an output directory. * @param klass The referent class for the resource (used to determine the correct ClassLoader, etc...) * @param resourceName The name of the resource to be loaded. * @param outputDirectory The output directory (optional) * @return The full path of the saved resource * @throws IOException If there was an I/O error */ static Path extractResource(final Class<?> klass, final String resourceName, final Path outputDirectory) throws IOException { Path directory = outputDirectory; if (directory == null) { directory = Files.createTempDirectory("jsii-java-runtime-resource"); } Path target = directory.resolve(resourceName); // make sure directory tree is created, for the case of "@scoped/deps" Files.createDirectories(target.getParent()); try (InputStream inputStream = klass.getResourceAsStream(resourceName)) { Files.copy(inputStream, target); } return target; } }
747
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Optional.java
package software.amazon.jsii; import java.lang.annotation.*; /** * Denotes an optional member from the TypeScript model for the API. * * Annotated methods have a default implementation that throws {@link UnsupportedOperationException} when invoked. * In a similar way that they have to in TypeScript, implementors need to actively opt into supporting the * functionality by providing a custom implementation for the member. */ @Documented @Target({ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) public @interface Optional {}
748
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Builder.java
package software.amazon.jsii; /** * A superinterface common to instance builders. */ @FunctionalInterface public interface Builder<T> { /** * Builds the instance given the current builder configuration. * * @return the built instance. */ T build(); }
749
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Internal.java
package software.amazon.jsii; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates API elements that are intended for jsii's internal use only. Such APIs elements are not public by design * and likely to be removed or renamed, have their signature change, or have their access level decreased in future * versions of the library without notice. * * Annotated elements are eligible for immediate modification or removal and are not subject to semantic versioning. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) public @interface Internal { }
750
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java
package software.amazon.jsii; import software.amazon.jsii.api.Callback; import software.amazon.jsii.api.GetRequest; import software.amazon.jsii.api.InvokeRequest; import software.amazon.jsii.api.JsiiOverride; import software.amazon.jsii.api.SetRequest; import com.fasterxml.jackson.databind.JsonNode; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.*; import java.util.*; import static software.amazon.jsii.Util.isJavaPropertyMethod; import static software.amazon.jsii.Util.javaPropertyToJSProperty; import static software.amazon.jsii.Util.javaScriptPropertyToJavaPropertyName; /** * The javascript engine which supports jsii objects. */ @Internal public final class JsiiEngine implements JsiiCallbackHandler { /** * The singleton instance. */ private static JsiiEngine INSTANCE = null; /** * The suffix for interface proxy classes. */ private static final String INTERFACE_PROXY_CLASS_NAME = "Jsii$Proxy"; /** * A map that associates value instances with the {@link JsiiEngine} that * created them or which first interacted with them. Using a weak hash map * so that {@link JsiiEngine} instances can be garbage collected after all * instances they are assigned to are themselves collected. */ private static Map<Object, JsiiEngine> engineAssociations = new WeakHashMap<>(); /** * Object cache. */ private final Map<String, Object> objects = new HashMap<>(); /** * The jsii-server child process. */ private final JsiiRuntime runtime = new JsiiRuntime(); /** * The set of modules we already loaded into the VM. */ private Map<String, JsiiModule> loadedModules = new HashMap<>(); /** * A map that associates value instances with the {@link JsiiObjectRef} that * represents them across the jsii process boundary. Using a weak hash map * so that {@link JsiiObjectRef} instances can be garbage collected after * all instances they are assigned to are themselves collected. */ private Map<Object, JsiiObjectRef> objectRefs = new WeakHashMap<>(); /** * @return The singleton instance. */ public static JsiiEngine getInstance() { if (INSTANCE == null) { INSTANCE = new JsiiEngine(); } return INSTANCE; } /** * Retrieves the {@link JsiiEngine} associated with the provided instance. If none was assigned yet, the current * value of {@link JsiiEngine#getInstance()} will be assigned then returned. * * @param instance The object instance for which a {@link JsiiEngine} is requested. * * @return a {@link JsiiEngine} instance. */ static JsiiEngine getEngineFor(final Object instance) { return JsiiEngine.getEngineFor(instance, null); } /** * Retrieves the {@link JsiiEngine} associated with the provided instance. If none was assigned yet, the current * value of {@code defaultEngine} will be assigned then returned. If {@code instance} is a {@link JsiiObject} * instance, then the value will be recorded on the instance itself (the responsibility of this process is on the * {@link JsiiObject} constructors). * * @param instance The object instance for which a {@link JsiiEngine} is requested. * @param defaultEngine The engine to use if none was previously assigned. If {@code null}, the value of * {@link #getInstance()} is used instead. * * @return a {@link JsiiEngine} instance. */ static JsiiEngine getEngineFor(final Object instance, @Nullable final JsiiEngine defaultEngine) { Objects.requireNonNull(instance, "instance is required"); if (instance instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) instance; if (jsiiObject.jsii$engine != null) { return jsiiObject.jsii$engine; } return defaultEngine != null ? defaultEngine : JsiiEngine.getInstance(); } return engineAssociations.computeIfAbsent( instance, (_k) -> defaultEngine != null ? defaultEngine : JsiiEngine.getInstance() ); } /** * Resets the singleton instance of JsiiEngine. This will cause a new process to be spawned (the previous process * will terminate itself). This method is intended to be used by compliance tests to ensure a complete and * reproductible kernel trace is obtained. */ static void reset() throws InterruptedException, IOException { final JsiiEngine toTerminate = INSTANCE; INSTANCE = null; if (toTerminate != null) { toTerminate.runtime.terminate(); } } /** * Silences any error and warning logging from the Engine. Useful when testing. * * @param value whether to silence the logs or not. */ public static void setQuietMode(boolean value) { getInstance().quietMode = value; } private boolean quietMode = true; /** * @return The jsii-server HTTP client. */ public JsiiClient getClient() { return runtime.getClient(); } /** * Initializes the engine. */ private JsiiEngine() { runtime.setCallbackHandler(this); } /** * Loads a JavaScript module into the remote jsii-server. * No-op if the module is already loaded. * @param moduleClass The jsii module class. */ public void loadModule(final Class<? extends JsiiModule> moduleClass) { if (!JsiiModule.class.isAssignableFrom(moduleClass)) { throw new JsiiError("Invalid module class " + moduleClass.getName() + ". It must be derived from JsiiModule"); } JsiiModule module; try { module = moduleClass.getConstructor().newInstance(); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new JsiiError(e); } if (this.loadedModules.containsKey(module.getModuleName())) { return; } // Load dependencies for (Class<? extends JsiiModule> dep: module.getDependencies()) { loadModule(dep); } this.getClient().loadModule(module); // indicate that it was loaded this.loadedModules.put(module.getModuleName(), module); } /** * Returns the native java object for a given jsii object reference. * If it already exists in our native objects cache, we return it. * * If we can't find the object in the cache, it means it was created in javascript-land, so we need * to create a native wrapper with the correct type and add it to cache. * * @param objRef The object reference. * @return The jsii object the represents this remote object. */ public Object nativeFromObjRef(final JsiiObjectRef objRef) { Object obj = this.objects.get(objRef.getObjId()); if (obj == null) { obj = createNativeProxy(objRef.getFqn(), objRef); this.registerObject(objRef, obj); } return obj; } /** * Assigns a {@link JsiiObjectRef} to a given instance. * * @param objRef The object reference to be assigned. * @param instance The instance to which the JsiiObjectRef is to be linked. * * @throws IllegalStateException if another {@link JsiiObjectRef} was * previously assigned to {@code instance}. */ final void registerObject(final JsiiObjectRef objRef, final Object instance) { Objects.requireNonNull(instance, "instance is required"); Objects.requireNonNull(objRef, "objRef is required"); final JsiiObjectRef assigned; if (instance instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) instance; if (jsiiObject.jsii$objRef == null) { jsiiObject.jsii$objRef = objRef; } assigned = jsiiObject.jsii$objRef; } else { assigned = this.objectRefs.computeIfAbsent( instance, (key) -> objRef ); } if (!assigned.equals(objRef)) { throw new IllegalStateException("Another object reference was previously assigned to this instance!"); } this.objects.put(assigned.getObjId(), instance); } /** * Returns the jsii object reference given a native object. If the object * does not have one yet, a new object reference is requested from the jsii * kernel, and gets assigned to the instance before being returned. * * @param nativeObject The native object to obtain the reference for * * @return A jsii object reference */ public JsiiObjectRef nativeToObjRef(final Object nativeObject) { if (nativeObject instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) nativeObject; if (jsiiObject.jsii$objRef == null) { jsiiObject.jsii$objRef = this.createNewObject(jsiiObject); } return jsiiObject.jsii$objRef; } return this.objectRefs.computeIfAbsent( nativeObject, (_k) -> this.createNewObject(nativeObject) ); } /** * Gets an object by reference. Throws if the object cannot be found. * * @param objRef The object reference * @return a JsiiObject * @throws JsiiError If the object is not found. */ public Object getObject(final JsiiObjectRef objRef) { Object obj = this.objects.get(objRef.getObjId()); if (obj == null) { throw new JsiiError("Cannot find jsii object: " + objRef.getObjId()); } return obj; } /** * Given an obj ref, returns a Java object that represents it. * A new object proxy object will be allocated if needed. * @param objRefNode The objref * @return A Java object */ public Object getObject(final JsonNode objRefNode) { return this.getObject(JsiiObjectRef.parse(objRefNode)); } /** * Given a jsii FQN, returns the Java class for it. * * @param fqn The FQN. * * @return The Java class name. */ Class<?> resolveJavaClass(final String fqn) { if ("Object".equals(fqn)) { return JsiiObject.class; } String[] parts = fqn.split("\\."); if (parts.length < 2) { throw new JsiiError("Malformed FQN: " + fqn); } String moduleName = parts[0]; JsonNode names = this.getClient().getModuleNames(moduleName); if (!names.has("java")) { throw new JsiiError("No java name for module " + moduleName); } final JsiiModule module = this.loadedModules.get(moduleName); if (module == null) { throw new JsiiError("No loaded module is named " + moduleName); } try { return module.resolveClass(fqn); } catch (final ClassNotFoundException cfne) { throw new JsiiError(cfne); } } /** * Given a jsii FQN, instantiates a Java JsiiObject. * * NOTE: if a the Java class cannot be found, we will simply return a {@link JsiiObject}. * * @param fqn The jsii FQN of the type * @return An object derived from JsiiObject. */ private JsiiObject createNativeProxy(final String fqn, final JsiiObjectRef objRef) { try { Class<?> klass = resolveJavaClass(fqn); if (klass.isInterface() || Modifier.isAbstract(klass.getModifiers())) { // "$" is used to represent inner classes in Java klass = Class.forName(klass.getCanonicalName() + "$" + INTERFACE_PROXY_CLASS_NAME); } try { Constructor<? extends Object> ctor = klass.getDeclaredConstructor(JsiiObjectRef.class); ctor.setAccessible(true); JsiiObject newObj = (JsiiObject) ctor.newInstance(objRef); ctor.setAccessible(false); return newObj; } catch (NoSuchMethodException e) { throw new JsiiError("Cannot create native object of type " + klass.getName() + " without a constructor that accepts an InitializationMode argument", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new JsiiError("Unable to instantiate a new object for FQN " + fqn + ": " + e.getMessage(), e); } } catch (ClassNotFoundException e) { this.log("WARNING: Cannot find the class: %s. Defaulting to JsiiObject", fqn); return new JsiiObject(objRef); } } /** * Given a jsii enum ref in the form "fqn/member" returns the Java enum value for it. * @param enumRef The jsii enum ref. * @return The java enum value. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Enum<?> findEnumValue(final String enumRef) { int sep = enumRef.lastIndexOf('/'); if (sep == -1) { throw new JsiiError("Malformed enum reference: " + enumRef); } String typeName = enumRef.substring(0, sep); String valueName = enumRef.substring(sep + 1); Class klass = resolveJavaClass(typeName); return Enum.valueOf(klass, valueName); } /** * Dequeues and processes pending jsii callbacks until there are no more callbacks to process. */ public void processAllPendingCallbacks() { while (true) { List<Callback> callbacks = this.getClient().pendingCallbacks(); if (callbacks.size() == 0) { break; } callbacks.forEach(this::processCallback); } } /** * Invokes a local callback and returns the result/error. * @param callback The callback to invoke. * @return The return value * @throws JsiiError if the callback failed. */ public JsonNode handleCallback(final Callback callback) { if (callback.getInvoke() != null) { return invokeCallbackMethod(callback.getInvoke(), callback.getCookie()); } else if (callback.getGet() != null) { return invokeCallbackGet(callback.getGet()); } else if (callback.getSet() != null) { return invokeCallbackSet(callback.getSet()); } throw new JsiiError("Unrecognized callback type: get/set/invoke"); } /** * Invokes an override for a property getter. * @param req The get request * @return The override's return value. */ private JsonNode invokeCallbackGet(final GetRequest req) { Object obj = this.getObject(req.getObjref()); String methodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty()); Method getter = this.findCallbackGetter(obj.getClass(), methodName); return JsiiObjectMapper.valueToTree(invokeMethod(obj, getter)); } /** * Invokes an override for a property setter. * @param req The set request * @return The setter return value (an empty object) */ private JsonNode invokeCallbackSet(final SetRequest req) { final Object obj = this.getObject(req.getObjref()); final String getterMethodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty()); final Method getter = this.findCallbackGetter(obj.getClass(), getterMethodName); // Turns "get" into "set"! final String setterMethodName = getterMethodName.replaceFirst("g", "s"); final Method setter = this.findCallbackSetter(obj.getClass(), setterMethodName, getter.getReturnType()); final Object arg = JsiiObjectMapper.treeToValue(req.getValue(), NativeType.forType(setter.getGenericParameterTypes()[0])); return JsiiObjectMapper.valueToTree(invokeMethod(obj, setter, arg)); } /** * Invokes an override for a method. * @param req The request * @param cookie The cookie * @return The method's return value */ private JsonNode invokeCallbackMethod(final InvokeRequest req, final String cookie) { Object obj = this.getObject(req.getObjref()); Method method = this.findCallbackMethod(obj.getClass(), cookie); final Type[] argTypes = method.getGenericParameterTypes(); final Object[] args = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { args[i] = JsiiObjectMapper.treeToValue(req.getArgs().get(i), NativeType.forType(argTypes[i])); } return JsiiObjectMapper.valueToTree(invokeMethod(obj, method, args)); } /** * Invokes a Java method, even if the method is protected. * @param obj The object * @param method The method * @param args Method arguments * @return The return value */ private Object invokeMethod(final Object obj, final Method method, final Object... args) { // turn method to accessible. otherwise, we won't be able to callback to methods // on non-public classes. boolean accessibility = method.isAccessible(); method.setAccessible(true); try { try { return method.invoke(obj, args); } catch (Exception e) { final StringWriter sw = new StringWriter(); try (final PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); } this.log("Error while invoking %s with %s: %s", method, Arrays.toString(args), sw.toString()); throw e; } } catch (InvocationTargetException e) { if (e.getTargetException() instanceof JsiiError){ throw (JsiiError)(e.getTargetException()); } else if (e.getTargetException() instanceof RuntimeException) { // can rethrow without wrapping here throw (RuntimeException)(e.getTargetException()); } else { // Can't just throw a checked error without wrapping it :( throw new RuntimeException(e.getTargetException()); } } catch (IllegalAccessException e) { throw new JsiiError(e); } finally { // revert accessibility. method.setAccessible(accessibility); } } /** * Process a single callback by invoking the native method it refers to. * @param callback The callback to process. */ private void processCallback(final Callback callback) { try { JsonNode result = handleCallback(callback); this.getClient().completeCallback(callback, null, null, result); } catch (Exception e) { String name = e instanceof JsiiException ? JsiiException.Type.JSII_FAULT.toString() : JsiiException.Type.RUNTIME_ERROR.toString(); this.getClient().completeCallback(callback, e.getMessage(), name, null); } } /** * Finds the Java method that implements a callback. * @param klass The java class. * @param signature Method signature * @return a {@link Method}. */ private Method findCallbackMethod(final Class<?> klass, final String signature) { for (Method method : klass.getDeclaredMethods()) { if (method.toString().equals(signature)) { // found! return method; } } if (klass.getSuperclass() != null) { // Try to check parent class at this point return findCallbackMethod(klass.getSuperclass(), signature); } throw new JsiiError("Unable to find callback method with signature: " + signature); } /** * Tries to locate the getter method for a property * @param klass is the type on which the getter is to be searched for * @param methodName is the name of the getter method * @return the found Method * @throws JsiiError if no such method is found */ private Method findCallbackGetter(final Class<?> klass, final String methodName) { try { return klass.getDeclaredMethod(methodName); } catch (final NoSuchMethodException nsme) { if (klass.getSuperclass() != null) { try { return findCallbackGetter(klass.getSuperclass(), methodName); } catch (final JsiiException _ignored) { // Ignored! } } throw new JsiiError(nsme); } } /** * Tries to locate the setter method for a property * @param klass is the type on which the setter is to be searched for * @param methodName is the name of the setter method * @param valueType is the type of the argument the setter accepts * @return the found Method * @throws JsiiError if no such method is found */ private Method findCallbackSetter(final Class<?> klass, final String methodName, final Class<?> valueType) { try { return klass.getDeclaredMethod(methodName, valueType); } catch (final NoSuchMethodException nsme) { if (klass.getSuperclass() != null) { try { return findCallbackSetter(klass.getSuperclass(), methodName, valueType); } catch (final JsiiException _ignored) { // Ignored! } } throw new JsiiError(nsme); } } /** * Given an uninitialized native object instance, reads the @Jsii annotations to determine * the jsii module and FQN, and creates a JS object. * * Any methods implemented on the native object are passed in as "overrides", which are overridden * in the javascript side to call-back to the native method. * * @param uninitializedNativeObject An uninitialized native object * @param args Initializer arguments * @return An object reference for the new object. */ public JsiiObjectRef createNewObject(final Object uninitializedNativeObject, final Object... args) { Class<? extends Object> klass = uninitializedNativeObject.getClass(); Jsii jsii = tryGetJsiiAnnotation(klass, true); String fqn = "Object"; // if we can't determine FQN, we just create an empty JS object if (jsii != null) { fqn = jsii.fqn(); loadModule(jsii.module()); } Collection<JsiiOverride> overrides = discoverOverrides(klass); Collection<String> interfaces = discoverInterfaces(klass); JsiiObjectRef objRef = this.getClient().createObject(fqn, Arrays.asList(args), overrides, interfaces); registerObject(objRef, uninitializedNativeObject); return objRef; } /** * Prepare a list of methods which are overridden by Java classes. * @param classToInspect The java class to inspect for * @return A list of method names that should be overridden. */ private static Collection<JsiiOverride> discoverOverrides(final Class<?> classToInspect) { Map<String, JsiiOverride> overrides = new HashMap<>(); Class<?> klass = classToInspect; // if we reached a generated jsii class or Object, we should stop collecting those overrides since // all the rest of the hierarchy is generated all the way up to JsiiObject and java.lang.Object. while (klass != null && klass.getDeclaredAnnotationsByType(Jsii.class).length == 0 && klass != Object.class && klass != JsiiObject.class) { // add all the methods in the current class for (Method method : klass.getDeclaredMethods()) { if (Modifier.isPrivate(method.getModifiers())) { continue; } String methodName = method.getName(); // check if this is a property ("getXXX" or "setXXX", oh java!) if (isJavaPropertyMethod(method)) { String propertyName = javaPropertyToJSProperty(method); // skip if this property is already in the overrides list if (overrides.containsKey(propertyName)) { continue; } JsiiOverride override = new JsiiOverride(); override.setProperty(propertyName); overrides.put(propertyName, override); } else { // if this method is already overridden, skip it if (overrides.containsKey(methodName)) { continue; } // we use the method's .toString() as a cookie, which will later be used to identify the // method when it is called back. JsiiOverride override = new JsiiOverride(); override.setMethod(methodName); override.setCookie(method.toString()); overrides.put(methodName, override); } } klass = klass.getSuperclass(); } return overrides.values(); } /** * Crawls up the inheritance tree of {@code classToInspect} in order to determine the jsii-visible * interfaces that are implemented. * * @param classToInspect the class for which interfaces are needed * * @return the list of jsii FQNs of interfaces implemented by {@code classToInspect} */ private Collection<String> discoverInterfaces(final Class<?> classToInspect) { // If {@classToInspect} has the @Jsii annotation, it's a jsii well-known type final Jsii declaredAnnotation = classToInspect.getDeclaredAnnotation(Jsii.class); if (declaredAnnotation != null) { // If it's an interface, then we can return a singleton set with that! if (classToInspect.isInterface()) { // Ensure the interface's module has been loaded... loadModule(declaredAnnotation.module()); return Collections.singleton(declaredAnnotation.fqn()); } // If it was NOT an interface, then this type already "implies" all interfaces -- nothing to declare. return Collections.emptySet(); } // If this wasn't an @Jsii well-known type, browse up the interface declarations, and collect results final Set<String> interfaces = new HashSet<>(); for (final Class<?> iface : classToInspect.getInterfaces()) { interfaces.addAll(discoverInterfaces(iface)); } return interfaces; } private void log(final String format, final Object... args) { if (!this.quietMode) { System.err.println(String.format(format, args)); } } /** * Attempts to find the @Jsii annotation from a type. * @param type The type. * @param inherited If 'true' will look for the annotation up the class hierarchy. * @return The annotation or null. */ static Jsii tryGetJsiiAnnotation(final Class<?> type, final boolean inherited) { Jsii[] ann; if (inherited) { ann = (Jsii[]) type.getAnnotationsByType(Jsii.class); } else { ann = (Jsii[]) type.getDeclaredAnnotationsByType(Jsii.class); } if (ann.length == 0) { return null; } return ann[0]; } /** * Given a java class that extends a Jsii proxy, loads the corresponding jsii module * and returns the FQN of the jsii type. * @param nativeClass The java class. * @return The FQN. */ String loadModuleForClass(Class<?> nativeClass) { final Jsii jsii = tryGetJsiiAnnotation(nativeClass, true); if (jsii == null) { throw new JsiiError("Unable to find @Jsii annotation for class"); } this.loadModule(jsii.module()); return jsii.fqn(); } }
751
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Configuration.java
package software.amazon.jsii; /** * Runtime configuration flags available for the Java jsii runtime. */ public final class Configuration { private static boolean runtimeTypeChecking = true; /** * Determines whether runtime type checking will be performed in places where * APIs accept {@link java.lang.Object} but the underlying model actually * uses a type union. * * Disabling this configuration allows to stop paying the runtime cost of type * checking, however it will produce degraded error messages in case of a * developer error. */ public static boolean getRuntimeTypeChecking() { return Configuration.runtimeTypeChecking; } /** * Specifies whether runtime type checking will be performed in places where * APIs accept {@link java.lang.Object} but the underlying model actually * uses a type union. * * Disabling this configuration allows to stop paying the runtime cost of type * checking, however it will produce degraded error messages in case of a * developer error. */ public void setRuntimeTypeChecking(final boolean value) { Configuration.runtimeTypeChecking = value; } private Configuration(){ throw new UnsupportedOperationException(); } }
752
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectMapper.java
package software.amazon.jsii; import java.io.IOException; import java.time.Instant; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.deser.ResolvableDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.module.SimpleSerializers; import com.fasterxml.jackson.databind.type.MapLikeType; import com.fasterxml.jackson.databind.type.MapType; import org.jetbrains.annotations.Nullable; /** * Provides a correctly configured JSON processor for handling JSII requests and responses. */ @Internal public final class JsiiObjectMapper { /** * An ObjectMapper that can be used to serialize and deserialize JSII requests and responses. */ public static final ObjectMapper INSTANCE = new JsiiObjectMapper().getObjectMapper(); /** * Similar to calling JsiiObjectMapper.INSTANCE.treeToValue, but handles a null JsonNode argument * well, and throws JsiiError instead of JsonProcessingException. * * @param tree the JSON object to parse * @param valueType the expected type value type * @param <T> expected type * @return the deserialized value */ public static <T> T treeToValue(final JsonNode tree, final NativeType<T> valueType) { if (tree == null) { return null; } final Object result = INSTANCE.convertValue(tree, valueType.getJavaType()); return valueType.transform(result); } /** * Similar to calling JsiiObjectMapper.INSTANCE.valueToTree, but handles a null argument well by * returning null. * * @param value the value to serialize * @param <T> expected JSON type * @return the JSON object */ public static <T extends JsonNode> T valueToTree(final Object value) { if (value == null) { return null; } return INSTANCE.valueToTree(value); } private static final String TOKEN_REF = JsiiObjectRef.TOKEN_REF; private static final String TOKEN_DATE = "$jsii.date"; private static final String TOKEN_ENUM = "$jsii.enum"; private static final String TOKEN_MAP = "$jsii.map"; private final ObjectMapper objectMapper; @Nullable private final JsiiEngine jsiiEngine; private JsiiObjectMapper() { this(null); } JsiiObjectMapper(@Nullable final JsiiEngine jsiiEngine) { this.jsiiEngine = jsiiEngine; this.objectMapper = new ObjectMapper(); this.objectMapper.setSerializationInclusion(Include.NON_NULL); final SimpleModule module = new SimpleModule("JSII", Version.unknownVersion()); module.setDeserializerModifier(new JsiiDeserializerModifier()); module.setSerializers(new JsiiSerializers()); module.addSerializer(Enum.class, new EnumSerializer()); module.addSerializer(Instant.class, new InstantSerializer()); module.addSerializer(JsiiSerializable.class, new JsiiSerializer()); this.objectMapper.findAndRegisterModules(); this.objectMapper.registerModule(module); } ObjectMapper getObjectMapper() { return this.objectMapper; } private JsiiEngine getEngine() { if (this.jsiiEngine != null) { return this.jsiiEngine; } return JsiiEngine.getInstance(); } /** * A JsonDeserializer designed to correctly handle JSII "magic objects" that are used to remodel "pass-by-reference" * values, dates, and enum constants. */ private final class JsiiDeserializer extends StdDeserializer<Object> implements ContextualDeserializer, ResolvableDeserializer{ public static final long serialVersionUID = 1L; private final JsonDeserializer<?> standardDeserializer; /** * @param standardDeserializer a standard Jackson deserialize that can be delegated to in case the object is not a * JSII "magic object". */ public JsiiDeserializer(final JsonDeserializer<?> standardDeserializer) { super(Object.class); this.standardDeserializer = standardDeserializer; } @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { final JsonNode node = p.readValueAsTree(); if (node.isObject()) { if (node.has(TOKEN_DATE)) { return Instant.parse(node.get(TOKEN_DATE).textValue()); } if (node.has(TOKEN_ENUM)) { return getEngine().findEnumValue(node.get(TOKEN_ENUM).textValue()); } if (node.has(TOKEN_REF)) { return getEngine().nativeFromObjRef(JsiiObjectRef.parse(node)); } if (node.has(TOKEN_MAP)) { return getObjectMapper().treeToValue(node.get(TOKEN_MAP), Map.class); } } final JsonParser nodeParser = node.traverse(p.getCodec()); nodeParser.nextToken(); return standardDeserializer.deserialize(nodeParser, ctxt); } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { if (this.standardDeserializer instanceof ContextualDeserializer) { return new JsiiDeserializer(((ContextualDeserializer)this.standardDeserializer).createContextual(ctxt, property)); } return this; } @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { if (this.standardDeserializer instanceof ResolvableDeserializer) { ((ResolvableDeserializer)this.standardDeserializer).resolve(ctxt); } } } public final class JsiiDeserializerModifier extends BeanDeserializerModifier { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { return new JsiiDeserializer(deserializer); } @Override public JsonDeserializer<?> modifyEnumDeserializer(DeserializationConfig config, JavaType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { return new JsiiDeserializer(deserializer); } @Override public JsonDeserializer<?> modifyMapDeserializer(DeserializationConfig config, MapType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { return new JsiiDeserializer(deserializer); } @Override public JsonDeserializer<?> modifyMapLikeDeserializer(DeserializationConfig config, MapLikeType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { return new JsiiDeserializer(deserializer); } } /** * Serializer for classes that extend JsiiObject and any other class that implements a jsii interface. * We use the JsiiSerializable interface as a way to identify "anything jsii-able". */ private final class JsiiSerializer extends JsonSerializer<JsiiSerializable> { @Override public void serialize(final JsiiSerializable o, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { // First, ensure the relevant interfaces' modules have been loaded (in case "o" is a struct instance) for (final Class<?> iface : o.getClass().getInterfaces()) { final Jsii jsii = JsiiEngine.tryGetJsiiAnnotation(iface, true); if (jsii != null) { getEngine().loadModule(jsii.module()); } } // Then dump the JSON out jsonGenerator.writeTree(o.$jsii$toJson()); } } /** * Serializer for enum values. */ @SuppressWarnings("rawtypes") private static final class EnumSerializer extends JsonSerializer<Enum> { @Override public void serialize(final Enum value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { Jsii jsii = this.tryGetJsiiAnnotation(value.getClass()); if (jsii == null) { throw new JsiiError("Cannot serialize non-jsii enums"); } else { gen.writeStartObject(); gen.writeStringField(TOKEN_ENUM, jsii.fqn() + "/" + value.toString()); gen.writeEndObject(); } } private Jsii tryGetJsiiAnnotation(final Class<?> type) { final Jsii[] ann = type.getDeclaredAnnotationsByType(Jsii.class); if (ann.length == 0) { return null; } return ann[0]; } } /** * Serializer for Instants. */ private static final class InstantSerializer extends JsonSerializer<Instant> { @Override public void serialize(final Instant value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField(TOKEN_DATE, value.toString()); gen.writeEndObject(); } } private static final class JsiiSerializers extends SimpleSerializers { @Override public JsonSerializer<?> findMapSerializer(SerializationConfig config, MapType type, BeanDescription beanDesc, JsonSerializer<Object> keySerializer, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) { final JsonSerializer<?> standard = super.findMapSerializer(config, type, beanDesc, keySerializer, elementTypeSerializer, elementValueSerializer); return new JsiiMapSerializer<>(standard); } } private static final class JsiiMapSerializer<T> extends JsonSerializer<T> { private final JsonSerializer<T> delegate; JsiiMapSerializer(final JsonSerializer<T> delegate) { this.delegate = delegate; } @Override @SuppressWarnings("unchecked") public void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeFieldName(TOKEN_MAP); if (this.delegate != null) { this.delegate.serialize(value, gen, serializers); } else { gen.writeStartObject(); for (final Map.Entry<String, Object> entry : ((Map<String, Object>)value).entrySet()) { serializers.defaultSerializeField(entry.getKey(), entry.getValue(), gen); } gen.writeEndObject(); } gen.writeEndObject(); } } }
753
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectRef.java
package software.amazon.jsii; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.jetbrains.annotations.VisibleForTesting; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Represents a remote jsii object reference. */ @Internal public final class JsiiObjectRef { /** * The JSON key used to represent an object reference. */ static final String TOKEN_REF = "$jsii.byref"; /** * The JSON key used to represent an interface list. */ static final String TOKEN_INTERFACES = "$jsii.interfaces"; /** * The JSON node. */ private JsonNode node; /** * The object ID. */ private String objId; /** * The FQN of the object's type as parsed from the object ID. */ private String fqn; private Set<String> interfaces; /** * Private constructor. * @param objId The object id. * @param node The JSON node that includes the objref. */ private JsiiObjectRef(final String objId, final JsonNode node) { this(objId, node.has(TOKEN_INTERFACES) ? parseInterfaces(node.get(TOKEN_INTERFACES)) : Collections.emptySet(), node); } @VisibleForTesting JsiiObjectRef(final String objId, final Set<String> interfaces) { this(objId, interfaces, JsiiObjectRef.makeJson(objId, interfaces)); } private JsiiObjectRef(final String objId, final Set<String> interfaces, final JsonNode node) { this.objId = objId; int fqnDelimiter = this.objId.lastIndexOf("@"); this.fqn = this.objId.substring(0, fqnDelimiter); this.interfaces = interfaces; this.node = node; } /** * Creates an object reference. * @param objRef The object reference. * @return A {@link JsiiObjectRef} object. */ public static JsiiObjectRef parse(final JsonNode objRef) { if (!objRef.has(TOKEN_REF)) { throw new JsiiError("Malformed object reference. Expecting " + TOKEN_REF); } return new JsiiObjectRef(objRef.get(TOKEN_REF).textValue(), objRef); } /** * Creates an object ref from an object ID. * @param objId Object ID. * @return The new object ref. */ public static JsiiObjectRef fromObjId(final String objId) { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put(TOKEN_REF, objId); return new JsiiObjectRef(objId, node); } JsiiObjectRef withInterface(final String fqn) { final Set<String> interfaces = new HashSet<>(this.interfaces); interfaces.add(fqn); return new JsiiObjectRef(this.objId, interfaces); } private static JsonNode makeJson(final String objId, final Set<String> interfaces) { final ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put(TOKEN_REF, objId); final ArrayNode jsonInterfaces = JsonNodeFactory.instance.arrayNode(); for (final String iface : interfaces) { jsonInterfaces.add(JsonNodeFactory.instance.textNode(iface)); } node.set(TOKEN_INTERFACES, jsonInterfaces); return node; } private static Set<String> parseInterfaces(final JsonNode node) { if (!node.isArray()) { throw new Error(String.format("Invalid value for %s. Expected array but received %s", TOKEN_INTERFACES, node)); } final Set<String> result = new HashSet<>(); node.forEach(entry -> { if (!entry.isTextual()) { throw new Error(String.format("Invalid entry in %s. Expected only strings, but received %s", TOKEN_INTERFACES, entry)); } result.add(entry.asText()); }); return Collections.unmodifiableSet(result); } /** * @return The jsii FQN (fully qualified name) of the object's type. */ public String getFqn() { return fqn; } /** * @return The JSON node for this objref. */ public JsonNode toJson() { return node; } /** * @return The object ID. */ public String getObjId() { return objId; } /** * @return the lsit of interfaces implemented by the object */ public Set<String> getInterfaces() { return interfaces; } @Override public String toString() { return objId; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof JsiiObjectRef)) { return false; } final JsiiObjectRef other = (JsiiObjectRef) obj; return this.objId.equals(other.objId); } @Override public int hashCode() { return this.objId.hashCode(); } }
754
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/NativeType.java
package software.amazon.jsii; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.type.TypeFactory; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Internal public abstract class NativeType<T> { protected static final JavaType[] NO_TYPE_PARAMS = {}; /** * A {@link NativeType} representation for `void`. */ public static final NativeType<Void> VOID = NativeType.forClass(Void.class); /** * Creates a {@link NativeType} representation for classes that are neither {@link List} nor {@link Map} subclasses. * * @param simpleType the Java class to be represented. * @param <T> the static type of {@code simpleType}. * * @return a new {@link NativeType} instance. * * @throws IllegalArgumentException if a {@link List} or {@link Map} subclass is passed as an argument. */ public static <T> NativeType<T> forClass(final Class<T> simpleType) { return new SimpleNativeType<>(simpleType); } /** * Creates a {@link NativeType} representation for a {@link List} of some {@code elementType}. * * @param elementType the type of elements in the {@link List}. * @param <T> the static type of the elements in the {@link List}. * * @return a new {@link NativeType} instance. */ public static <T> NativeType<List<T>> listOf(final NativeType<T> elementType) { return new ListNativeType<>(elementType); } /** * Creates a {@link NativeType} representation for a {@link Map} of {@link String} to some {@code elementType}. * * @param elementType the type of values in the {@link Map}. * @param <T> the static type of the values in the {@link Map}. * * @return a new {@link NativeType} instance. */ public static <T> NativeType<Map<String, T>> mapOf(final NativeType<T> elementType) { return new MapNativeType<>(elementType); } /** * Creates a {@link NativeType} for the given Java type description. This particular API is unsafe and should not be * used if any of the other APIs can be. * * @param type the {@link Type} to be represented. It can be any type, including a {@link Class} reference, however * when a {@link Class} instance is available, the caller should use {@link #forClass(Class)}, * {@link #listOf(NativeType)} and {@link #mapOf(NativeType)} appropriately instead, as this operation * is not checked at runtime. * @param <T> the static type of the represented type. This operation is not checked, leaving the caller responsible * for ensuring the correct type is specified. * * @return a new {@link NativeType} instance. */ @SuppressWarnings("unchecked") public static <T> NativeType<T> forType(final Type type) { if (type instanceof ParameterizedType) { final ParameterizedType genericType = (ParameterizedType)type; final Class<?> rawType = (Class<?>)genericType.getRawType(); // Provided List<T>, we abide by the value of T if (List.class.isAssignableFrom(rawType)) { return (NativeType<T>)listOf(forType(genericType.getActualTypeArguments()[0])); } // Provided Map<?, T>, we abide by the value of T if (Map.class.isAssignableFrom(rawType)) { return (NativeType<T>)mapOf(forType(genericType.getActualTypeArguments()[1])); } } // If it's not a List<T> or Map<String, T>, it MUST be a Class, or we don't know how to handle it if (!(type instanceof Class<?>)) { throw new IllegalArgumentException(String.format("Unsupported type: %s", type)); } // Provided the raw class List, interpret it as List<Object> if (List.class.isAssignableFrom((Class<?>)type)) { return (NativeType<T>)listOf(forClass(Object.class)); } // Provided the raw class Map, interpret it as Map<String, Object> if (Map.class.isAssignableFrom((Class<?>)type)) { return (NativeType<T>)mapOf(forClass(Object.class)); } // Anything else... return (NativeType<T>) forClass((Class<?>)type); } private static Class<?> wireFor(final Class<?> type) { if (JsiiObject.class.isAssignableFrom(type)) { return JsiiObject.class; } return type; } private final JavaType javaType; protected NativeType(final JavaType javaType) { this.javaType = javaType; } final JavaType getJavaType() { return javaType; } abstract T transform(final Object value); private static final class SimpleNativeType<T> extends NativeType<T> { private final Class<T> type; SimpleNativeType(final Class<T> simpleType) { super(TypeFactory.defaultInstance() .constructSimpleType(wireFor(simpleType), NO_TYPE_PARAMS)); this.type = simpleType; if (List.class.isAssignableFrom(this.type)) { throw new IllegalArgumentException(String.format( "Illegal attempt to create a SimpleNativeType with a List type: %s", this.type.getCanonicalName())); } if (Map.class.isAssignableFrom(this.type)) { throw new IllegalArgumentException(String.format( "Illegal attempt to create a SimpleNativeType with a Map type: %s", this.type.getCanonicalName())); } } Class<T> getType() { return type; } @Override @SuppressWarnings("unchecked") T transform(Object value) { if (value != null && this.getType().isInterface() && value instanceof JsiiObject) { if (!this.getType().isAssignableFrom(value.getClass()) && this.getType().isAnnotationPresent(Jsii.Proxy.class)) { final Jsii.Proxy annotation = this.getType().getAnnotation(Jsii.Proxy.class); return (T) ((JsiiObject)value).asInterfaceProxy(annotation.value()); } } return (T) value; } } private static final class ListNativeType<T> extends NativeType<List<T>> { private final NativeType<T> elementType; ListNativeType(final NativeType<T> elementType) { super(TypeFactory.defaultInstance() .constructCollectionType(List.class, elementType.getJavaType())); this.elementType = elementType; } NativeType<T> getElementType() { return elementType; } @Override List<T> transform(Object value) { final List<?> original = (List<?>)value; return original.stream() .map(this.getElementType()::transform) .collect(Collectors.toList()); } } private static final class MapNativeType<T> extends NativeType<Map<String, T>> { private static final JavaType STRING_JAVA_TYPE = TypeFactory.defaultInstance() .constructSimpleType(String.class, NO_TYPE_PARAMS); private final NativeType<T> elementType; MapNativeType(final NativeType<T> elementType) { super(TypeFactory.defaultInstance() .constructMapType(Map.class, STRING_JAVA_TYPE, elementType.getJavaType())); this.elementType = elementType; } NativeType<T> getElementType() { return elementType; } @Override Map<String, T> transform(Object value) { @SuppressWarnings("unchecked") final Map<String, ?> original = (Map<String, ?>)value; return original.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> this.getElementType().transform(entry.getValue()), // We don't map keys, so there will never be a conflict (existing, replacement) -> existing, // Using LinkedHashMap to preserve ordering of elements LinkedHashMap::new )); } } }
755
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiModule.java
package software.amazon.jsii; import java.util.Collections; import java.util.List; /** * Represents a jsii JavaScript module. */ @Internal public abstract class JsiiModule { /** * The module class. */ private final Class<? extends JsiiModule> moduleClass; /** * The name of the module. */ private final String moduleName; /** * The version of this module. */ private final String moduleVersion; /** * The module's resource name. */ private final String bundleResourceName; /** * Creates a module. * @param moduleName The name of the module. * @param moduleVersion The version of the module. * @param moduleClass The module class. * @param bundleResourceName The name of the bundle resource. */ public JsiiModule(final String moduleName, final String moduleVersion, final Class<? extends JsiiModule> moduleClass, final String bundleResourceName) { this.moduleName = moduleName; this.moduleClass = moduleClass; this.bundleResourceName = bundleResourceName; this.moduleVersion = moduleVersion; } /** * @return The URL of the code bundle. */ public final Class<? extends JsiiModule> getModuleClass() { return this.moduleClass; } /** * @return The name of the bundle resource. */ public final String getBundleResourceName() { return this.bundleResourceName; } /** * @return The name of the module. */ public final String getModuleName() { return this.moduleName; } /** * @return The version of this module. */ public final String getModuleVersion() { return this.moduleVersion; } /** * @return A list of all classes for module dependencies. */ protected List<Class<? extends JsiiModule>> getDependencies() { return Collections.emptyList(); } /** * Resolves a class of this module given it's jsii Fully Qualified Name (FQN) * * @param fqn the jsii FQN of the class being looked up. * * @return the Java class that correspons to the FQN. * * @throws ClassNotFoundException if the requested jsii FQN does not correspond to a known class. */ protected abstract Class<?> resolveClass(final String fqn) throws ClassNotFoundException; }
756
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiSerializable.java
package software.amazon.jsii; import com.fasterxml.jackson.core.TreeNode; /** * Marks a class as serializable from native to javascript. * {@link JsiiObject} implements this as well as all generated jsii interfaces. * The actual metadata needed for serialization is defined by the @Jsii annotations attached to these * types, but Jackson doesn't support selecting serializers by annotations, so we needed a type as a marker. * See {@link JsiiObjectMapper} for details. */ @Internal public interface JsiiSerializable { /** * Serializes this object to JSON. The default behavior is to return an object reference. * However, builders implement this method by emitting an actual JSON object of the key/values. * @return the jsii/JSON representation of this object */ @Internal default TreeNode $jsii$toJson() { JsiiObjectRef objRef = JsiiEngine.getInstance().nativeToObjRef(this); return objRef.toJson(); } }
757
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiPromise.java
package software.amazon.jsii; /** * Represents a promise to a result of an async method execution. */ public final class JsiiPromise { /** * The ID of the promise. */ private String promiseId; /** * Creates a promise. * @param promiseId The ID of the promise. */ public JsiiPromise(final String promiseId) { this.promiseId = promiseId; } /** * @return The ID of the promise. */ public String getPromiseId() { return promiseId; } }
758
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Kernel.java
package software.amazon.jsii; import com.fasterxml.jackson.databind.JsonNode; import org.jetbrains.annotations.Nullable; /** * A static helper to interact with the kernel in a "simple" way. */ @Internal public final class Kernel { /** * Calls an async method on the object. * * @param receiver the receiver for the method call. * @param method The name of the method. * @param nativeType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * * @return A return value. */ @Nullable @Internal public static <T> T asyncCall(final Object receiver, final String method, final NativeType<T> nativeType, @Nullable final Object... args) { final JsiiEngine engine = JsiiEngine.getEngineFor(receiver); final JsiiObjectRef objRef = engine.nativeToObjRef(receiver); final JsiiClient client = engine.getClient(); final JsiiPromise promise = client.beginAsyncMethod(objRef, method, JsiiObjectMapper.valueToTree(args)); engine.processAllPendingCallbacks(); return JsiiObjectMapper.treeToValue(client.endAsyncMethod(promise), nativeType); } /** * Calls a JavaScript method on a receiver. * * @param receiver the receiver for the method call * @param method The name of the method. * @param nativeType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * * @return A return value. */ @Nullable @Internal public static <T> T call(final Object receiver, final String method, final NativeType<T> nativeType, @Nullable final Object... args) { final JsiiEngine engine = JsiiEngine.getEngineFor(receiver); final JsiiObjectRef objRef = engine.nativeToObjRef(receiver); final JsonNode result = engine.getClient().callMethod(objRef, method, JsiiObjectMapper.valueToTree(args)); return JsiiObjectMapper.treeToValue(result, nativeType); } /** * Gets a property value from the object. * * @param receiver The receiver of the property access. * @param property The property name. * @param type The Java type of the property. * @param <T> The Java type of the property. * * @return The property value. */ @Nullable @Internal public static <T> T get(final Object receiver, final String property, final NativeType<T> type) { final JsiiEngine engine = JsiiEngine.getEngineFor(receiver); final JsiiObjectRef objRef = engine.nativeToObjRef(receiver); final JsonNode result = engine.getClient().getPropertyValue(objRef, property); return JsiiObjectMapper.treeToValue(result, type); } /** * Sets a property value of an object. * * @param receiver The receiver of the property access. * @param property The name of the property. * @param value The property value. */ @Internal public static void set(final Object receiver, final String property, @Nullable final Object value) { final JsiiEngine engine = JsiiEngine.getEngineFor(receiver); final JsiiObjectRef objRef = engine.nativeToObjRef(receiver); engine.getClient().setPropertyValue(objRef, property, JsiiObjectMapper.valueToTree(value)); } private Kernel() { throw new UnsupportedOperationException(); } }
759
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiObject.java
package software.amazon.jsii; import com.fasterxml.jackson.databind.JsonNode; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; /** * Represents a JavaScript object in the Java world. */ public class JsiiObject implements JsiiSerializable { /** * The interface-proxies that this object can also be represented as. */ private final Map<Class<? extends JsiiObject>, JsiiObject> proxies = new HashMap<>(); /** * The jsii engine used by this object. */ final JsiiEngine jsii$engine; /** * The underlying {@link JsiiObjectRef} instance. */ @Nullable @Internal JsiiObjectRef jsii$objRef; /** * A special constructor that allows creating wrapper objects while bypassing the normal constructor * chain. This is used when an object was created in javascript-land and just needs a wrapper in native-land. * * @param initializationMode Must always be set to "JSII". */ protected JsiiObject(final InitializationMode initializationMode) { this(null, initializationMode); } /** * A special constructor that allows creating wrapper objects while bypassing the normal constructor * chain. This is used when an object was created in javascript-land and just needs a wrapper in native-land. * * This constructor is meant to be used only in unit tests. * * @param engine The {@link JsiiEngine} to use. * @param initializationMode Must always be set to "JSII". */ @Internal JsiiObject(@Nullable final JsiiEngine engine, final InitializationMode initializationMode) { this.jsii$engine = JsiiEngine.getEngineFor(this, engine); if (initializationMode != InitializationMode.JSII) { throw new JsiiError("The only supported initialization mode is '" + InitializationMode.JSII + "'"); } } /** * Used to construct a JSII object with a reference to an existing managed JSII node object. * * @param objRef Reference to existing managed JSII node object. */ @Internal protected JsiiObject(final JsiiObjectRef objRef) { this(null, objRef); } /** * Used to construct a JSII object with a reference to an existing managed JSII node object. * * This constructor is meant to be used only in unit tests. * * @param engine the {@link JsiiEngine} to use. * @param objRef Reference to existing managed JSII node object. */ @Internal JsiiObject(@Nullable final JsiiEngine engine, @Nullable final JsiiObjectRef objRef) { this.jsii$engine = JsiiEngine.getEngineFor(this, engine); this.jsii$objRef = objRef; this.jsii$engine.registerObject(objRef, this); } /** * Used as a marker for bypassing native ctor chain. */ public enum InitializationMode { /** * Used as a way to bypass the the native constructor chain to allow classes that do not extend * JsiiObject directly to perform the initialization logic in javascript instead of natively. */ JSII; } /** * Calls a JavaScript method on the object. * * @param method The name of the method. * @param returnType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * @return A return value. * * @deprecated use {@link Kernel#call(Object, String, NativeType, Object...)} instead */ @Nullable @Deprecated @Internal protected final <T> T jsiiCall(final String method, final Class<T> returnType, @Nullable final Object... args) { return jsiiCall(method, NativeType.forType(returnType), args); } /** * Calls a JavaScript method on the object. * * @param method The name of the method. * @param nativeType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * @return A return value. * * @deprecated use {@link Kernel#call(Object, String, NativeType, Object...)} instead */ @Nullable @Deprecated @Internal protected final <T> T jsiiCall(final String method, final NativeType<T> nativeType, @Nullable final Object... args) { return Kernel.call(this, method, nativeType, args); } /** * Calls a static method. * * @param nativeClass The java class. * @param method The method to call. * @param returnType The return type. * @param args The method arguments. * @param <T> Return type. * @return Return value. * * @deprecated use {@link #jsiiStaticCall(Class, String, NativeType, Object...)} instead */ @Nullable @Deprecated @Internal protected static <T> T jsiiStaticCall(final Class<?> nativeClass, final String method, final Class<T> returnType, @Nullable final Object... args) { return jsiiStaticCall(nativeClass, method, NativeType.forType(returnType), args); } /** * Calls a static method. * * @param nativeClass The java class. * @param method The method to call. * @param nativeType The return type. * @param args The method arguments. * @param <T> Return type. * * @return Return value. */ @Nullable @Internal protected static <T> T jsiiStaticCall(final Class<?> nativeClass, final String method, final NativeType<T> nativeType, @Nullable final Object... args) { return jsiiStaticCall(JsiiEngine.getInstance(), nativeClass, method, nativeType, args); } /** * Calls a static method. * * This method is meant to be used only in unit tests. * * @param engine The JsiiEngine to use. * @param nativeClass The java class. * @param method The method to call. * @param nativeType The return type. * @param args The method arguments. * @param <T> Return type. * * @return Return value. */ @Nullable @Internal static <T> T jsiiStaticCall(final JsiiEngine engine, final Class<?> nativeClass, final String method, final NativeType<T> nativeType, @Nullable final Object... args) { final String fqn = engine.loadModuleForClass(nativeClass); final JsonNode result = engine.getClient().callStaticMethod(fqn, method, JsiiObjectMapper.valueToTree(args)); return JsiiObjectMapper.treeToValue(result, nativeType); } /** * Calls an async method on the object. * * @param method The name of the method. * @param returnType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * @return A return value. * * @deprecated use {@link Kernel#asyncCall(Object, String, NativeType, Object...)} instead */ @Nullable @Deprecated @Internal protected final <T> T jsiiAsyncCall(final String method, final Class<T> returnType, @Nullable final Object... args) { return jsiiAsyncCall(method, NativeType.forType(returnType), args); } /** * Calls an async method on the object. * @param method The name of the method. * @param nativeType The return type. * @param args Method arguments. * @param <T> Java type for the return value. * * @return A return value. * * @deprecated Use {@link Kernel#asyncCall(Object, String, NativeType, Object...)} instead */ @Nullable @Internal protected final <T> T jsiiAsyncCall(final String method, final NativeType<T> nativeType, @Nullable final Object... args) { return Kernel.asyncCall(this, method, nativeType, args); } /** * Gets a property value from the object. * * @param property The property name. * @param type The Java type of the property. * @param <T> The Java type of the property. * * @return The property value. * * @deprecated use {@link Kernel#get(Object, String, NativeType)} instead */ @Nullable @Deprecated @Internal protected final <T> T jsiiGet(final String property, final Class<T> type) { return jsiiGet(property, NativeType.forType(type)); } /** * Gets a property value from the object. * * @param property The property name. * @param type The Java type of the property. * @param <T> The Java type of the property. * * @return The property value. * * @deprecated use {@link Kernel#get(Object, String, NativeType)} instead */ @Nullable @Deprecated @Internal protected final <T> T jsiiGet(final String property, final NativeType<T> type) { return Kernel.get(this, property, type); } /** * Returns the value of a static property. * * @param nativeClass The java class. * @param property The name of the property. * @param type The expected java return type. * @param <T> Return type * * @return Return value * * @deprecated use {@link #jsiiStaticGet(Class, String, NativeType)} instead */ @Nullable @Deprecated @Internal protected static <T> T jsiiStaticGet(final Class<?> nativeClass, final String property, final Class<T> type) { return jsiiStaticGet(nativeClass, property, NativeType.forType(type)); } /** * Returns the value of a static property. * * @param nativeClass The java class. * @param property The name of the property. * @param type The expected java return type. * @param <T> Return type * * @return Return value */ @Nullable @Internal protected static <T> T jsiiStaticGet(final Class<?> nativeClass, final String property, final NativeType<T> type) { return jsiiStaticGet(JsiiEngine.getInstance(), nativeClass, property, type); } /** * Returns the value of a static property. * * This method is meant to be used only in unit tests. * * @param engine The JsiiEngine to use. * @param nativeClass The java class. * @param property The name of the property. * @param type The expected java return type. * @param <T> Return type * * @return Return value */ @Nullable @Internal static <T> T jsiiStaticGet(final JsiiEngine engine, final Class<?> nativeClass, final String property, final NativeType<T> type) { final String fqn = engine.loadModuleForClass(nativeClass); final JsonNode result = engine.getClient().getStaticPropertyValue(fqn, property); return JsiiObjectMapper.treeToValue(result, type); } /** * Sets a property value of an object. * * @param property The name of the property. * @param value The property value. * * @deprecated Use {@link Kernel#set(Object, String, Object)} instead */ @Deprecated @Internal protected final void jsiiSet(final String property, @Nullable final Object value) { Kernel.set(this, property, value); } /** * Sets a value for a static property. * * @param nativeClass The java class. * @param property The name of the property * @param value The value */ @Internal protected static void jsiiStaticSet(final Class<?> nativeClass, final String property, @Nullable final Object value) { jsiiStaticSet(JsiiEngine.getInstance(), nativeClass, property, value); } /** * Sets a value for a static property. * * This method is meant to be used only in unit tests. * * @param engine The JsiiEngine to use. * @param nativeClass The java class. * @param property The name of the property * @param value The value */ @Internal protected static void jsiiStaticSet(final JsiiEngine engine, final Class<?> nativeClass, final String property, @Nullable final Object value) { final String fqn = engine.loadModuleForClass(nativeClass); engine.getClient().setStaticPropertyValue(fqn, property, JsiiObjectMapper.valueToTree(value)); } /** * Create a view of this {@link JsiiObject} as the implementation of an interface. * * @param proxyClass the {@code $JsiiProxy} class for the desired interface. * @param <T> the interface type that the new vew must implement. * * @return a view on the same {@link JsiiObject}. */ @Internal final <T extends JsiiObject> T asInterfaceProxy(final Class<? extends T> proxyClass) { if (!this.proxies.containsKey(proxyClass)) { try { final Constructor<? extends JsiiObject> constructor = proxyClass.getDeclaredConstructor(JsiiObjectRef.class); @SuppressWarnings("deprecated") final boolean oldAccessible = constructor.isAccessible(); try { constructor.setAccessible(true); final JsiiObject proxyInstance = constructor.newInstance(this.jsii$engine.nativeToObjRef(this)); this.proxies.put(proxyClass, proxyInstance); } finally { constructor.setAccessible(oldAccessible); } } catch(final NoSuchMethodException nsme) { throw new JsiiError("Unable to find interface proxy constructor on " + proxyClass.getCanonicalName(), nsme); } catch (final InvocationTargetException | InstantiationException e) { throw new JsiiError("Unable to initialize interface proxy " + proxyClass.getCanonicalName(), e); } catch (final IllegalAccessException iae) { throw new JsiiError("Unable to invoke constructor of " + proxyClass.getCanonicalName(), iae); } } @SuppressWarnings("unchecked") final T result = (T)this.proxies.get(proxyClass); return result; } }
760
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/Stability.java
package software.amazon.jsii; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Documents the stability of an API. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) public @interface Stability { /** * @return The stability level of the annotated API. */ Level value(); /** * Stability level of an API, similar to the Node.js stability index. * * @see <a href="https://nodejs.org/api/documentation.html#documentation_stability_index">https://nodejs.org/api/documentation.html#documentation_stability_index</a> */ public enum Level { /** * The API is not subject to Semantic Versioning rules. Non-backward compatible changes or removal may occur in any * future release. Use of the API is not recommended in production environments. */ Experimental, /** * The API is subject to Sematic Versining rules. It may not change in non-backward compatible ways in a subsequent * patch or feature version. */ Stable, /** * The API may emit warnings. Backward compatibility is not guaranteed. APIs annotated with the {@code Deprecated} * level should also be annotated with the standard {@link Deprecated} annotation. */ Deprecated, /** * This API is an representation of an API managed elsewhere and follows * the other API's versioning model. */ External } }
761
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiError.java
package software.amazon.jsii; /** * A nonrecoverable error from the jsii runtime, * usually the kernel. */ public final class JsiiError extends JsiiException { public static final long serialVersionUID = 1L; /** * Creates an exception. * @param message The error message */ JsiiError(final String message) { super(message); } /** * Creates an exception. * @param e The error that caused this exception */ JsiiError(final Throwable e) { super(e); } /** * Creates an exception. * @param message The error message * @param e The error that caused this exception */ JsiiError(final String message, final Throwable e) { super(message, e); } }
762
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiClient.java
package software.amazon.jsii; import software.amazon.jsii.api.Callback; import software.amazon.jsii.api.CreateRequest; import software.amazon.jsii.api.JsiiOverride; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static software.amazon.jsii.Util.extractResource; /** * HTTP client for jsii-server. */ @Internal public final class JsiiClient { /** * JSON node factory. */ private static final JsonNodeFactory JSON = JsonNodeFactory.instance; /** * TCP port to connect to (always "localhost"). */ private final JsiiRuntime runtime; /** * Creates a new jsii-runtime client. * @param runtime The {@link JsiiRuntime}. */ public JsiiClient(final JsiiRuntime runtime) { this.runtime = runtime; } /** * Loads a JavaScript module into the remote sandbox. * @param module The module to load */ public void loadModule(final JsiiModule module) { try { Path tarball = extractResource(module.getModuleClass(), module.getBundleResourceName(), null); try { ObjectNode req = makeRequest("load"); req.put("tarball", tarball.toString()); req.put("name", module.getModuleName()); req.put("version", module.getModuleVersion()); this.runtime.requestResponse(req); } finally { Files.delete(tarball); Files.delete(tarball.getParent()); } } catch (IOException e) { throw new JsiiError("Unable to extract resource " + module.getBundleResourceName(), e); } } /** * Creates a remote jsii object. * @param fqn The fully-qualified-name of the class. * @param initializerArgs Constructor arguments. * @param overrides A list of async methods to override. If a method is defined as an override, a callback * will be scheduled when it is called, and the promise it returns will only be fulfilled * when the callback is completed. * @return A jsii object reference. */ public JsiiObjectRef createObject(final String fqn, final Collection<Object> initializerArgs, final Collection<JsiiOverride> overrides, final Collection<String> interfaces) { CreateRequest request = new CreateRequest(); request.setFqn(fqn); request.setArgs(initializerArgs); request.setOverrides(overrides); request.setInterfaces(interfaces); ObjectNode req = JsiiObjectMapper.valueToTree(request); req.put("api", "create"); JsonNode resp = this.runtime.requestResponse(req); return JsiiObjectRef.parse(resp); } /** * Deletes a remote object. * @param objRef The object reference. */ public void deleteObject(final JsiiObjectRef objRef) { ObjectNode req = makeRequest("del", objRef); this.runtime.requestResponse(req); } /** * Gets a value for a property from a remote object. * @param objRef The remote object reference. * @param property The property name. * @return The value of the property. */ public JsonNode getPropertyValue(final JsiiObjectRef objRef, final String property) { ObjectNode req = makeRequest("get", objRef); req.put("property", property); return this.runtime.requestResponse(req).get("value"); } /** * Sets a value for a property in a remote object. * @param objRef The remote object reference. * @param property The name of the property. * @param value The new property value. */ public void setPropertyValue(final JsiiObjectRef objRef, final String property, final JsonNode value) { ObjectNode req = makeRequest("set", objRef); req.put("property", property); req.set("value", value); this.runtime.requestResponse(req); } /** * Gets a value of a static property. * @param fqn The FQN of the class * @param property The name of the static property * @return The value of the static property */ public JsonNode getStaticPropertyValue(final String fqn, final String property) { ObjectNode req = makeRequest("sget"); req.put("fqn", fqn); req.put("property", property); return this.runtime.requestResponse(req).get("value"); } /** * Sets the value of a mutable static property. * @param fqn The FQN of the class * @param property The property name * @param value The new value */ public void setStaticPropertyValue(final String fqn, final String property, final JsonNode value) { ObjectNode req = makeRequest("sset"); req.put("fqn", fqn); req.put("property", property); req.set("value", value); this.runtime.requestResponse(req); } /** * Invokes a static method. * @param fqn The FQN of the class. * @param method The method name. * @param args The method arguments. * @return The return value. */ public JsonNode callStaticMethod(final String fqn, final String method, final ArrayNode args) { ObjectNode req = makeRequest("sinvoke"); req.put("fqn", fqn); req.put("method", method); req.set("args", args); JsonNode resp = this.runtime.requestResponse(req); return resp.get("result"); } /** * Calls a method on a remote object. * @param objRef The remote object reference. * @param method The name of the method. * @param args Method arguments. * @return The return value of the method. */ public JsonNode callMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) { ObjectNode req = makeRequest("invoke", objRef); req.put("method", method); req.set("args", args); JsonNode resp = this.runtime.requestResponse(req); return resp.get("result"); } /** * Begins the execution of an async method. * @param objRef The object reference. * @param method The name of the async method. * @param args Arguments for the method. * @return A {@link JsiiPromise} which represents this method. */ public JsiiPromise beginAsyncMethod(final JsiiObjectRef objRef, final String method, final ArrayNode args) { ObjectNode req = this.makeRequest("begin", objRef); req.put("method", method); req.set("args", args); JsonNode resp = this.runtime.requestResponse(req); return new JsiiPromise(resp.get("promiseid").asText()); } /** * Ends the execution of an async method. * @param promise The promise returned by beginAsyncMethod. * @return The method return value. */ public JsonNode endAsyncMethod(final JsiiPromise promise) { ObjectNode req = makeRequest("end"); req.put("promiseid", promise.getPromiseId()); JsonNode resp = this.runtime.requestResponse(req); if (resp == null) { return null; // result is null } return resp.get("result"); } /** * Dequques all the currently pending callbacks. * @return A list of all pending callbacks. */ public List<Callback> pendingCallbacks() { ObjectNode req = makeRequest("callbacks"); JsonNode resp = this.runtime.requestResponse(req); JsonNode callbacksResp = resp.get("callbacks"); if (callbacksResp == null || !callbacksResp.isArray()) { throw new JsiiError("Expecting a 'callbacks' key with an array in response"); } ArrayNode callbacksArray = (ArrayNode) callbacksResp; List<Callback> result = new ArrayList<>(); callbacksArray.forEach(node -> { result.add(JsiiObjectMapper.treeToValue(node, NativeType.forClass(Callback.class))); }); return result; } /** * Completes a callback. * @param callback The callback to complete. * @param error Error information (or null). * @param name Error type (or null). * @param result Result (or null). */ public void completeCallback(final Callback callback, final String error, final String name, final JsonNode result) { ObjectNode req = makeRequest("complete"); req.put("cbid", callback.getCbid()); req.put("err", error); req.put("name", name); req.set("result", result); this.runtime.requestResponse(req); } /** * Returns all names for a jsii module. * @param moduleName The name of the module. * @return The result (map from "lang" to language configuration). */ public JsonNode getModuleNames(final String moduleName) { ObjectNode req = makeRequest("naming"); req.put("assembly", moduleName); JsonNode resp = this.runtime.requestResponse(req); return resp.get("naming"); } /** * Returns a request object for a specific API call. * @param api The api call (i.e "create", "del", "load", ....) * @return A JSON object */ private ObjectNode makeRequest(final String api) { ObjectNode req = JSON.objectNode(); req.put("api", api); return req; } /** * Returns a new request object for a specific API and a specific object. * @param api The API call * @param objRef The object reference * @return A JSON object */ private ObjectNode makeRequest(final String api, final JsiiObjectRef objRef) { ObjectNode req = makeRequest(api); req.set("objref", objRef.toJson()); return req; } }
763
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/MessageInspector.java
package software.amazon.jsii; import com.fasterxml.jackson.databind.JsonNode; interface MessageInspector { void inspect(final JsonNode message, final MessageType type); enum MessageType { Request, Response; } }
764
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/package-info.java
/** * jsii Runtime for Java. */ package software.amazon.jsii;
765
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/InvokeRequest.java
package software.amazon.jsii.api; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.List; import software.amazon.jsii.Internal; /** * Represents a method invocation jsii-runtime request. */ @Internal public class InvokeRequest { /** * The object reference. */ private ObjectNode objref; /** * The method to invoke. */ private String method; /** * Method arguments. */ private List<JsonNode> args; /** * @return The object reference. */ public ObjectNode getObjref() { return objref; } /** * @param objref The object reference. */ public void setObjref(final ObjectNode objref) { this.objref = objref; } /** * @return The method to invoke. */ public String getMethod() { return method; } /** * @param method The method to invoke. */ public void setMethod(final String method) { this.method = method; } /** * @return Method arguments. */ public List<JsonNode> getArgs() { return args; } /** * @param args Method arguments. */ public void setArgs(final List<JsonNode> args) { this.args = args; } }
766
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/JsiiOverride.java
package software.amazon.jsii.api; import software.amazon.jsii.Internal; /** * Represents an override. */ @Internal public class JsiiOverride { /** * The name of the overridden method (or null if this is property override). */ private String method; /** * The name of the overridden property (or null if this is a method override). */ private String property; /** * The cookie. */ private String cookie; /** * @return The name of the overridden method (or null if this is property). */ public String getMethod() { return method; } /** * @param method The name of the overridden method (or null if this is property). */ public void setMethod(final String method) { this.method = method; } /** * @return The name of the overridden property (or null if this is a method override). */ public String getProperty() { return property; } /** * @param property The name of the overridden property (or null if this is a method override). */ public void setProperty(final String property) { this.property = property; } /** * @return The cookie. */ public String getCookie() { return cookie; } /** * @param cookie The cookie. */ public void setCookie(final String cookie) { this.cookie = cookie; } }
767
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/GetRequest.java
package software.amazon.jsii.api; import com.fasterxml.jackson.databind.node.ObjectNode; import software.amazon.jsii.Internal; /** * Represents a "get property" jsii-runtime request. */ @Internal public class GetRequest { /** * The object reference. */ private ObjectNode objref; /** * The name of the property. */ private String property; /** * @return The name of the property. */ public String getProperty() { return property; } /** * @param property The name of the property */ public void setProperty(final String property) { this.property = property; } /** * @return The object reference. */ public ObjectNode getObjref() { return objref; } /** * @param objref The object reference. */ public void setObjref(final ObjectNode objref) { this.objref = objref; } }
768
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/Callback.java
package software.amazon.jsii.api; import software.amazon.jsii.Internal; /** * The "callback" struct. */ @Internal public class Callback { /** * Callback ID. */ private String cbid; /** * Callback cookie. */ private String cookie; /** * Invoke request (can be null). */ private InvokeRequest invoke; /** * Get request (can be null). */ private GetRequest get; /** * Set request (can be null). */ private SetRequest set; /** * @return Callback ID. */ public String getCbid() { return cbid; } /** * Sets the callback ID. * @param cbid The callback ID. */ public void setCbid(final String cbid) { this.cbid = cbid; } /** * @return The callback cookie. */ public String getCookie() { return cookie; } /** * Sets the callback cookie. * @param cookie The cookie */ public void setCookie(final String cookie) { this.cookie = cookie; } /** * @return The invoke request. */ public InvokeRequest getInvoke() { return invoke; } /** * Sets the invoke request. * @param invoke The invoke request. */ public void setInvoke(final InvokeRequest invoke) { this.invoke = invoke; } /** * @return The get request. */ public GetRequest getGet() { return get; } /** * Sets the "get" request. * @param get The "get" request */ public void setGet(final GetRequest get) { this.get = get; } /** * @return The "set" request. */ public SetRequest getSet() { return set; } /** * Sets the "set" request. * @param set The "set" request */ public void setSet(final SetRequest set) { this.set = set; } }
769
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/CreateRequest.java
package software.amazon.jsii.api; import java.util.Collection; import software.amazon.jsii.Internal; /** * Represents a "create" jsii-runtime request. */ @Internal public class CreateRequest { /** * The FQN of the class to create. */ private String fqn; /** * A collection of initializer arguments. */ private Collection<Object> args; /** * A collection of native overrides. */ private Collection<JsiiOverride> overrides; /** * A collection of interfaces implemented by this object. */ private Collection<String> interfaces; /** * @return The class's FQN. */ public String getFqn() { return fqn; } /** * Sets the class's FQN. * @param fqn The FQN. */ public void setFqn(final String fqn) { this.fqn = fqn; } /** * @return Initializer arguments. */ public Collection<Object> getArgs() { return args; } /** * Sets initializer arguments. * @param args Arguments. */ public void setArgs(final Collection<Object> args) { this.args = args; } /** * @return Overrides. */ public Collection<JsiiOverride> getOverrides() { return overrides; } /** * Sets the overrides. * @param overrides Overrides */ public void setOverrides(final Collection<JsiiOverride> overrides) { this.overrides = overrides; } /** * @return Interfaces */ public Collection<String> getInterfaces() { return interfaces; } /** * Sets the interfaces * @param interfaces Interfaces */ public void setInterfaces(Collection<String> interfaces) { this.interfaces = interfaces; } }
770
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/SetRequest.java
package software.amazon.jsii.api; import com.fasterxml.jackson.databind.JsonNode; import software.amazon.jsii.Internal; /** * Represents a "set property" jsii-runtime request. */ @Internal public class SetRequest { /** * The jsii object reference. */ private JsonNode objref; /** * The name of the property to set. */ private String property; /** * The new value. */ private JsonNode value; /** * @return The jsii object reference. */ public JsonNode getObjref() { return objref; } /** * @param objref The jsii object reference. */ public void setObjref(final JsonNode objref) { this.objref = objref; } /** * @return The name of the property to set. */ public String getProperty() { return property; } /** * @param property The name of the property to set. */ public void setProperty(final String property) { this.property = property; } /** * @return The new value. */ public JsonNode getValue() { return value; } /** * @param value The new value. */ public void setValue(final JsonNode value) { this.value = value; } }
771
0
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/api/package-info.java
/** * jsii-runtime API. */ package software.amazon.jsii.api;
772
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/JsiiVersionTest.java
package software.amazon.jsii; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static software.amazon.jsii.JsiiVersion.JSII_RUNTIME_VERSION; public final class JsiiVersionTest { @Test public void compatibleVersions() { JsiiRuntime.assertVersionCompatible("0.7.0", "0.7.0"); JsiiRuntime.assertVersionCompatible("0.7.0", "0.7.0+abcd"); JsiiRuntime.assertVersionCompatible("0.7.0+cdfe0", "0.7.0+abcd"); JsiiRuntime.assertVersionCompatible("0.7.0+cdfe0", "0.7.0+abcd111"); } @Test public void incompatibleVersions_1() { assertThrows(JsiiException.class, () -> JsiiRuntime.assertVersionCompatible("0.7.0", "0.7.1")); } @Test public void incompatibleVersions_2() { assertThrows(JsiiException.class, () -> JsiiRuntime.assertVersionCompatible("0.7.0", "0.7")); } @Test public void incompatibleVersions_3() { assertThrows(JsiiException.class, () -> JsiiRuntime.assertVersionCompatible("0.7.0+abcd", "1.2.0+abcd")); } @Test public void versionIsDefined() { assertNotNull(JSII_RUNTIME_VERSION); assertNotEquals("", JSII_RUNTIME_VERSION); } }
773
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/ComplianceSuiteHarness.java
package software.amazon.jsii; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class ComplianceSuiteHarness implements BeforeEachCallback, AfterEachCallback, AfterAllCallback { private final ObjectMapper objectMapper = new ObjectMapper(); private final ObjectNode result = objectMapper.createObjectNode(); private final Map<String, List<String>> kernelTraces = new HashMap<>(); @Override public void beforeEach(final ExtensionContext extensionContext) throws Exception { final List<String> trace = new ArrayList<>(); kernelTraces.put(extensionContext.getUniqueId(), trace); JsiiRuntime.messageInspector.set((message, type) -> { final String prefix = type == MessageInspector.MessageType.Request ? "<" : ">"; try { trace.add(String.format("%s %s%n", prefix, objectMapper.writeValueAsString(message))); } catch (final IOException e) { throw new UncheckedIOException(e); } }); JsiiEngine.reset(); } @Override public void afterEach(final ExtensionContext extensionContext) { JsiiRuntime.messageInspector.remove(); final ObjectNode entry = result.putObject(extensionContext.getRequiredTestMethod().getName()); entry.put("status", extensionContext.getExecutionException().isPresent() ? "failure" : "success"); entry.putPOJO("kernelTrace", kernelTraces.remove(extensionContext.getUniqueId())); } @Override public void afterAll(final ExtensionContext extensionContext) throws IOException { final File file = new File("./compliance-report.json"); try (final OutputStream os = new FileOutputStream(file)) { this.objectMapper.writer(new DefaultPrettyPrinter().withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE)).writeValue(os, this.result); } catch (IOException ioe) { System.err.println("Failed writing test report: " + ioe.getMessage()); throw ioe; } } }
774
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/ReloadingClassLoader.java
package software.amazon.jsii; import java.io.File; import java.lang.management.ManagementFactory; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.util.stream.Stream; /** * This wonderful utility can be used to reload classes regardless of whether it was already loaded by the current * ClassLoader or not. This is particularly useful when a test needs to go through the burden of checking static * initialization is happening as designed. * * It leverages black magic in the form of shameless down-casting of classloaders to URLClassLoader and may or may not * spectacularly blow up on new JVM major versions. * * THIS IS A DRAGONS LAIR AND YOU SHOULD TREAD CAREFULLY, SO AS NOT TO STEP ON A DRAGON'S TAIL. */ public final class ReloadingClassLoader extends URLClassLoader { /** * Reloads one or more classes, returning the newly loaded version of the first one. * * @param parent is the parent ClassLoader to use for classes that do not need to be re-loaded. * @param clazz is the first class that needs to be reloaded. * @param others a list of any other class that also needs to be reloaded. * @param <T> the static type of the reloaded {@code class}. * * @return the reloaded version of {@code class}. */ @SuppressWarnings("unchecked") public static <T> Class<T> reload(final ClassLoader parent, final Class<T> clazz, final Class<?> ...others) { final ClassLoader cl = new ReloadingClassLoader(parent, Stream.concat(Stream.of(clazz), Stream.of(others)).toArray(Class[]::new)); try { return (Class<T>)cl.loadClass(binaryNameOf(clazz)); } catch (final ClassNotFoundException cnfe) { // This is theoretically impossible! throw new RuntimeException(cnfe); } } /** * Obtains the "binary name" of a class. This is needed because ClassLoaders expect a binary name, and not a * canonical class name. Binary names have the pesky "$" separator instead of a "." for member classes. * * @param clazz the class which binary name is needed. * * @return {@code clazz}' binary name. */ private static String binaryNameOf(final Class<?> clazz) { if (!clazz.isMemberClass()) { return clazz.getCanonicalName(); } final Class<?> declaringClass = clazz.getDeclaringClass(); return String.format("%s$%s", binaryNameOf(declaringClass), clazz.getSimpleName()); } private final Class<?>[] toReload; private ReloadingClassLoader(final ClassLoader parent, final Class<?> ...toReload) { super( Stream.of(toReload) .flatMap(clazz -> urlsFromClassLoader(clazz.getClassLoader())) .toArray(URL[]::new), parent ); this.toReload = toReload; } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (Stream.of(this.toReload).map(ReloadingClassLoader::binaryNameOf).noneMatch(clazz -> clazz.equals(name))) { // Not to be reloaded - delegate to the standard flow. return super.loadClass(name, resolve); } // Class is to be reloaded. Conveniently, "findClass" does just that! final Class<?> result = this.findClass(name); if (resolve) { this.resolveClass(result); } return result; } private static Stream<URL> urlsFromClassLoader(final ClassLoader classLoader) { if (classLoader instanceof URLClassLoader) { return Stream.of(((URLClassLoader)classLoader).getURLs()); } // In java >= 9, class loaders may not always be URLClassLoaders, so we need this: return Stream .of(ManagementFactory.getRuntimeMXBean() .getClassPath() .split(File.pathSeparator)) .map(ReloadingClassLoader::toURL); } private static URL toURL(final String classPathEntry) { try { return new File(classPathEntry).toURI().toURL(); } catch (final MalformedURLException ex) { throw new IllegalArgumentException("URL could not be obtained from " + classPathEntry, ex); } } }
775
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/testing/TypeCheckingTest.java
package software.amazon.jsii.testing; import org.junit.jupiter.api.Test; import software.amazon.jsii.JsiiException; import software.amazon.jsii.JsiiObject; import software.amazon.jsii.tests.calculator.*; import software.amazon.jsii.tests.calculator.anonymous.*; import software.amazon.jsii.tests.calculator.anonymous.UseOptions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; public class TypeCheckingTest { private static class StructAImplementer implements StructA, StructB { public String requiredString; StructAImplementer(String param) { requiredString = param; } public void setRequiredString(String param) { requiredString = param; } public String getRequiredString() { return requiredString; } } @Test public void constructor() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("good", new StructAImplementer("present")); map.put("bad", "Not a StructA or StructB"); ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); list.add(map); Exception e = assertThrows(IllegalArgumentException.class, () -> { new ClassWithCollectionOfUnions(list); }); assertEquals("Expected unionProperty.get(0).get(\"bad\") to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.String", e.getMessage()); } @Test public void anonymousObjectIsValid() { Object anonymousObject = UseOptions.provide("A"); assertEquals(JsiiObject.class, anonymousObject.getClass()); assertEquals("A", UseOptions.consume(anonymousObject)); } @Test public void nestedUnion() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { ArrayList<Object> list = new ArrayList<Object>(); list.add(1337.42); new ClassWithNestedUnion(list); }); assertEquals("Expected unionProperty.get(0) to be one of: java.util.Map<java.lang.String, java.lang.Object>, java.util.List<java.lang.Object>; received class java.lang.Double", e.getMessage()); e = assertThrows(IllegalArgumentException.class, () -> { ArrayList<Object> list = new ArrayList<Object>(); ArrayList<Object> nestedList = new ArrayList<Object>(); nestedList.add(new StructAImplementer("required")); nestedList.add(1337.42); list.add(nestedList); new ClassWithNestedUnion(list); }); assertEquals("Expected unionProperty.get(0).get(1) to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.Double", e.getMessage()); e = assertThrows(IllegalArgumentException.class, () -> { HashMap<String, Object> map = new HashMap<String, Object>(); ArrayList<Object> list = new ArrayList<Object>(); map.put("good", new StructAImplementer("present")); map.put("bad", "Not a StructA or StructB"); list.add(map); new ClassWithNestedUnion(list); }); assertEquals("Expected unionProperty.get(0).get(\"bad\") to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.String", e.getMessage()); } @Test public void keysAreTypeChecked() { HashMap<Object, Object> map = new HashMap<Object, Object>(); ArrayList<Object> list = new ArrayList<Object>(); map.put("good", new StructAImplementer("present")); map.put(1337.42, new StructAImplementer("present")); list.add(map); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new ClassWithNestedUnion(list); }); assertEquals("Expected unionProperty.get(0).keySet() to contain class String; received class java.lang.Double", e.getMessage()); } @Test public void variadic() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { new VariadicTypeUnion(new StructAImplementer("present"), 1337.42); }); assertEquals("Expected union[1] to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.Double", e.getMessage()); } @Test public void setter() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("good", new StructAImplementer("present")); map.put("bad", "Not a StructA or StructB"); ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); ClassWithCollectionOfUnions subject = new ClassWithCollectionOfUnions(list); list.add(map); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { subject.setUnionProperty(list); }); assertEquals("Expected value.get(0).get(\"bad\") to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.String", e.getMessage()); } @Test public void staticMethod() { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> { StructUnionConsumer.isStructA("Not a StructA"); }); assertEquals("Expected struct to be one of: software.amazon.jsii.tests.calculator.StructA, software.amazon.jsii.tests.calculator.StructB; received class java.lang.String", e.getMessage()); } }
776
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/testing/JsiiClientTest.java
package software.amazon.jsii.testing; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.jsii.JsiiClient; import software.amazon.jsii.JsiiException; import software.amazon.jsii.JsiiObjectMapper; import software.amazon.jsii.JsiiObjectRef; import software.amazon.jsii.JsiiPromise; import software.amazon.jsii.JsiiRuntime; import software.amazon.jsii.JsiiSerializable; import software.amazon.jsii.api.Callback; import software.amazon.jsii.api.JsiiOverride; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class JsiiClientTest { private ObjectMapper OM = new ObjectMapper(); private JsonNodeFactory JSON = JsonNodeFactory.instance; private JsiiClient client; private JsiiRuntime jsiiRuntime; @BeforeEach public void setUp() { jsiiRuntime = new JsiiRuntime(); this.client = jsiiRuntime.getClient(); this.client.loadModule(new software.amazon.jsii.tests.calculator.baseofbase.$Module()); this.client.loadModule(new software.amazon.jsii.tests.calculator.base.$Module()); this.client.loadModule(new software.amazon.jsii.tests.calculator.lib.$Module()); this.client.loadModule(new software.amazon.jsii.tests.calculator.$Module()); } @Test public void initialTest() { JsiiObjectRef obj = client.createObject("@scope/jsii-calc-lib.Number", Collections.singletonList(42), Arrays.asList(), Arrays.asList()); assertEquals(84, fromSandbox(client.getPropertyValue(obj, "doubleValue"))); assertEquals("Number", fromSandbox(client.callMethod(obj, "typeName", toSandboxArray()))); ObjectNode calculatorProps = JSON.objectNode(); calculatorProps.set("initialValue", JSON.numberNode(100)); JsiiObjectRef calculator = client.createObject("jsii-calc.Calculator", Collections.singletonList(calculatorProps), Arrays.asList(), Arrays.asList()); assertNull(fromSandbox(client.callMethod(calculator, "add", toSandboxArray(50)))); JsiiObjectRef add = JsiiObjectRef.parse(client.getPropertyValue(calculator, "curr")); assertEquals(150, fromSandbox(client.getPropertyValue(add, "value"))); JsonNode names = client.getModuleNames("@scope/jsii-calc-lib"); assertEquals("software.amazon.jsii.tests.calculator.lib", names.get("java").get("package").textValue()); JsonNode names2 = client.getModuleNames("jsii-calc"); assertEquals("software.amazon.jsii.tests.calculator", names2.get("java").get("package").textValue()); client.deleteObject(calculator); boolean thrown = false; try { client.getPropertyValue(calculator, "curr"); } catch (JsiiException e) { thrown = true; } assertTrue(thrown); } @Test public void asyncMethods() { JsiiObjectRef obj = client.createObject("jsii-calc.AsyncVirtualMethods", Arrays.asList(), Arrays.asList(), Arrays.asList()); // begin will return a promise JsiiPromise promise = client.beginAsyncMethod(obj, "callMe", toSandboxArray()); assertFalse(promise.getPromiseId().isEmpty()); // end will return the result JsonNode result = client.endAsyncMethod(promise); assertEquals(128, result.asInt()); } private Collection<JsiiOverride> methodOverride(final String methodName, final String cookie) { JsiiOverride override = new JsiiOverride(); override.setMethod(methodName); override.setCookie(cookie); return Arrays.asList(override); } @Test public void asyncMethodOverrides() { JsiiObjectRef obj = client.createObject("jsii-calc.AsyncVirtualMethods", Arrays.asList(), methodOverride("overrideMe", "myCookie"), Arrays.asList()); // begin will return a promise JsiiPromise promise = client.beginAsyncMethod(obj, "callMe", toSandboxArray()); assertFalse(promise.getPromiseId().isEmpty()); // now we expect to see a callback to "overrideMe" in the pending callbacks queue List<Callback> callbacks = client.pendingCallbacks(); assertEquals(1, callbacks.size()); Callback first = callbacks.get(0); assertEquals("overrideMe", first.getInvoke().getMethod()); assertEquals("myCookie", first.getCookie()); assertEquals(1, first.getInvoke().getArgs().size()); assertEquals(JsiiObjectMapper.valueToTree(10), first.getInvoke().getArgs().get(0)); assertEquals(obj.getObjId(), JsiiObjectRef.parse(first.getInvoke().getObjref()).getObjId()); // now complete the callback with some override value client.completeCallback(first, null, null, toSandbox(999)); // end the async invocation, but now we expect the value to be different since we override the method. JsonNode result = client.endAsyncMethod(promise); assertEquals(1007, result.asInt()); } @Test public void asyncMethodOverridesThrow() { JsiiObjectRef obj = client.createObject("jsii-calc.AsyncVirtualMethods", Arrays.asList(), methodOverride("overrideMe", "myCookie"), Arrays.asList()); // begin will return a promise JsiiPromise promise = client.beginAsyncMethod(obj, "callMe", toSandboxArray()); assertFalse(promise.getPromiseId().isEmpty()); // now we expect to see a callback to "overrideMe" in the pending callbacks queue List<Callback> callbacks = client.pendingCallbacks(); assertEquals(1, callbacks.size()); Callback first = callbacks.get(0); assertEquals("overrideMe", first.getInvoke().getMethod()); assertEquals("myCookie", first.getCookie()); assertEquals(1, first.getInvoke().getArgs().size()); assertEquals(JsiiObjectMapper.valueToTree(10), first.getInvoke().getArgs().get(0)); assertEquals(obj.getObjId(), JsiiObjectRef.parse(first.getInvoke().getObjref()).getObjId()); // now complete the callback with an error client.completeCallback(first, "Hello, Error", null, null); // end the async invocation, but now we expect the value to be different since we override the method. boolean thrown = false; try { client.endAsyncMethod(promise); } catch (RuntimeException e) { assertEquals(RuntimeException.class, e.getClass()); assertTrue(e.getMessage().contains("Hello, Error")); thrown = true; } assertTrue(thrown); } @Test public void asyncMethodOverridesThrowWithFault() { JsiiObjectRef obj = client.createObject("jsii-calc.AsyncVirtualMethods", Arrays.asList(), methodOverride("overrideMe", "myCookie"), Arrays.asList()); // begin will return a promise JsiiPromise promise = client.beginAsyncMethod(obj, "callMe", toSandboxArray()); assertFalse(promise.getPromiseId().isEmpty()); // now we expect to see a callback to "overrideMe" in the pending callbacks queue List<Callback> callbacks = client.pendingCallbacks(); assertEquals(1, callbacks.size()); Callback first = callbacks.get(0); assertEquals("overrideMe", first.getInvoke().getMethod()); assertEquals("myCookie", first.getCookie()); assertEquals(1, first.getInvoke().getArgs().size()); assertEquals(JsiiObjectMapper.valueToTree(10), first.getInvoke().getArgs().get(0)); assertEquals(obj.getObjId(), JsiiObjectRef.parse(first.getInvoke().getObjref()).getObjId()); // now complete the callback with an error client.completeCallback(first, "Hello, Fault", "@jsii/kernel.Fault", null); // end the async invocation, but now we expect the value to be different since we override the method. boolean thrown = false; try { client.endAsyncMethod(promise); } catch (JsiiException e) { assertTrue(e.getMessage().contains("Hello, Fault")); thrown = true; } assertTrue(thrown); } @Test public void syncVirtualMethods() { JsiiObjectRef obj = client.createObject("jsii-calc.SyncVirtualMethods", Arrays.asList(), methodOverride("virtualMethod","myCookie"), Arrays.asList()); jsiiRuntime.setCallbackHandler(callback -> { assertEquals(obj.getObjId(), JsiiObjectRef.parse(callback.getInvoke().getObjref()).getObjId()); assertEquals("virtualMethod", callback.getInvoke().getMethod()); assertEquals(JsiiObjectMapper.valueToTree(10), callback.getInvoke().getArgs().get(0)); assertEquals("myCookie", callback.getCookie()); // interact with jsii from inside the callback JsiiObjectRef num = client.createObject("@scope/jsii-calc-lib.Number", Arrays.asList(42), Arrays.asList(), Arrays.asList()); assertEquals(84, fromSandbox(client.getPropertyValue(num, "doubleValue"))); return JSON.numberNode(898); }); assertEquals(898, client.callMethod(obj, "callerIsMethod", JSON.arrayNode()).numberValue()); // just for fun, change the return value from the callback and observe that we got the new value jsiiRuntime.setCallbackHandler(callback -> JSON.numberNode(111)); assertEquals(111, client.callMethod(obj, "callerIsMethod", JSON.arrayNode()).numberValue()); // verify that sync callbacks are invoked from a property assertEquals(111, client.getPropertyValue(obj, "callerIsProperty").numberValue()); // verify that sync callbacks are invoked from an async methods jsiiRuntime.setCallbackHandler(callback -> JSON.numberNode(222)); JsiiPromise promise = client.beginAsyncMethod(obj, "callerIsAsync", JSON.arrayNode()); List<Callback> pending = client.pendingCallbacks(); assertEquals(0, pending.size()); assertEquals(222, client.endAsyncMethod(promise).numberValue()); } @Test public void staticProperties() { final String fqn = "jsii-calc.Statics"; assertEquals("hello", client.getStaticPropertyValue(fqn, "Foo").textValue()); JsonNode defaultInstance = client.getStaticPropertyValue(fqn, "instance"); assertEquals("default", client.getPropertyValue(JsiiObjectRef.parse(defaultInstance), "value").textValue()); JsiiObjectRef newValue = client.createObject(fqn, Arrays.asList("NewValue"), Arrays.asList(), Arrays.asList()); client.setStaticPropertyValue(fqn, "instance", newValue.toJson()); JsonNode newInstance = client.getStaticPropertyValue(fqn, "instance"); assertEquals("NewValue", client.getPropertyValue(JsiiObjectRef.parse(newInstance), "value").textValue()); } @Test public void staticMethods() { final String fqn = "jsii-calc.Statics"; JsonNode result = client.callStaticMethod(fqn, "staticMethod", JSON.arrayNode().add("Foo")); assertEquals("hello ,Foo!", result.textValue()); } /** * If a JsiiSerializable object has a method named "$jsii$toJson", it will be * used to serialize the object instead of the normal */ @Test public void serializeViaJsiiToJsonIfExists() { JsonNode result = JsiiObjectMapper.INSTANCE.valueToTree(new JsiiSerializable() { public JsonNode $jsii$toJson() { ObjectNode node = JSON.objectNode(); node.set("foo", OM.valueToTree("bar")); node.set("hey", OM.valueToTree(42)); return node; } }); assertEquals("{\"foo\":\"bar\",\"hey\":42}", result.toString()); } private ArrayNode toSandboxArray(final Object... values) { return OM.valueToTree(values); } private JsonNode toSandbox(Object value) { return OM.valueToTree(value); } private Object fromSandbox(JsonNode value) { if (value == null) { return null; } try { return OM.treeToValue(value, Object.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
777
0
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii
Create_ds/jsii/packages/@jsii/java-runtime-test/project/src/test/java/software/amazon/jsii/testing/ComplianceTest.java
package software.amazon.jsii.testing; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import software.amazon.jsii.ComplianceSuiteHarness; import software.amazon.jsii.JsiiEngine; import software.amazon.jsii.JsiiException; import software.amazon.jsii.ReloadingClassLoader; import software.amazon.jsii.tests.calculator.*; import software.amazon.jsii.tests.calculator.baseofbase.StaticConsumer; import software.amazon.jsii.tests.calculator.cdk16625.Cdk16625; import software.amazon.jsii.tests.calculator.cdk22369.AcceptsPath; import software.amazon.jsii.tests.calculator.composition.CompositeOperation; import software.amazon.jsii.tests.calculator.custom_submodule_name.NestingClass.NestedStruct; import software.amazon.jsii.tests.calculator.lib.deprecation_removal.InterfaceFactory; import software.amazon.jsii.tests.calculator.lib.EnumFromScopedModule; import software.amazon.jsii.tests.calculator.lib.IFriendly; import software.amazon.jsii.tests.calculator.lib.MyFirstStruct; import software.amazon.jsii.tests.calculator.lib.Number; import software.amazon.jsii.tests.calculator.lib.NumericValue; import software.amazon.jsii.tests.calculator.lib.StructWithOnlyOptionals; import software.amazon.jsii.tests.calculator.submodule.child.OuterClass; import java.io.IOException; import java.lang.reflect.Constructor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("deprecated") @ExtendWith(ComplianceSuiteHarness.class) public class ComplianceTest { @Test public void useNestedStruct() { StaticConsumer.consume( new NestedStruct.Builder() .name("Bond, James Bond") .build() ); } /** * Verify that we can marshal and unmarshal objects without type information. */ @Test public void primitiveTypes() throws IOException { AllTypes types = new AllTypes(); // boolean types.setBooleanProperty(true); assertEquals(true, types.getBooleanProperty()); // string types.setStringProperty("foo"); assertEquals("foo", types.getStringProperty()); // number types.setNumberProperty(1234); assertEquals(1234, types.getNumberProperty()); // date types.setDateProperty(Instant.ofEpochMilli(123)); assertEquals(Instant.ofEpochMilli(123), types.getDateProperty()); // json types.setJsonProperty((ObjectNode) new ObjectMapper().readTree("{ \"Foo\": { \"Bar\": 123 } }")); assertEquals(123, types.getJsonProperty().get("Foo").get("Bar").numberValue()); } @Test public void dates() { AllTypes types = new AllTypes(); // strong type types.setDateProperty(Instant.ofEpochMilli(123)); assertEquals(Instant.ofEpochMilli(123), types.getDateProperty()); // weak type types.setAnyProperty(Instant.ofEpochSecond(999)); assertEquals(Instant.ofEpochSecond(999), types.getAnyProperty()); } @Test public void collectionTypes() { AllTypes types = new AllTypes(); // array types.setArrayProperty(Arrays.asList("Hello", "World")); assertEquals("World", types.getArrayProperty().get(1)); // map Map<String, Number> map = new HashMap<>(); map.put("Foo", new Number(123)); types.setMapProperty(map); } @Test public void dynamicTypes() throws IOException { AllTypes types = new AllTypes(); // boolean types.setAnyProperty(false); assertEquals(false, types.getAnyProperty()); // string types.setAnyProperty("String"); assertEquals("String", types.getAnyProperty()); // number types.setAnyProperty(12); assertEquals(12, types.getAnyProperty()); // date types.setAnyProperty(Instant.ofEpochSecond(1234)); assertEquals(Instant.ofEpochSecond(1234), types.getAnyProperty()); // json (notice that when deserialized, it is deserialized as a map). types.setAnyProperty(Collections.singletonMap("Goo", Arrays.asList("Hello", Collections.singletonMap("World", 123)))); assertEquals(123, ((Map<?, ?>)((List<?>)((Map<?, ?>)types.getAnyProperty()).get("Goo")).get(1)).get("World")); // array types.setAnyProperty(Arrays.asList("Hello", "World")); assertEquals("Hello", ((List<?>)types.getAnyProperty()).get(0)); assertEquals("World", ((List<?>)types.getAnyProperty()).get(1)); // array of any types.setAnyArrayProperty(Arrays.asList("Hybrid", new Number(12), 123, false)); assertEquals(123, types.getAnyArrayProperty().get(2)); // map Map<String, Object> map = new HashMap<>(); map.put("MapKey", "MapValue"); types.setAnyProperty(map); assertEquals("MapValue", ((Map<?, ?>)types.getAnyProperty()).get("MapKey")); // map of any map.put("Goo", 19289812); types.setAnyMapProperty(map); assertEquals(19289812, types.getAnyMapProperty().get("Goo")); // classes Multiply mult = new Multiply(new Number(10), new Number(20)); types.setAnyProperty(mult); assertSame(types.getAnyProperty(), mult); assertTrue(types.getAnyProperty() instanceof Multiply); assertEquals(200, ((Multiply) types.getAnyProperty()).getValue()); } @Test public void unionTypes() { AllTypes types = new AllTypes(); // single valued property types.setUnionProperty(1234); assertEquals(1234, types.getUnionProperty()); types.setUnionProperty("Hello"); assertEquals("Hello", types.getUnionProperty()); types.setUnionProperty(new Multiply(new Number(2), new Number(12))); assertEquals(24, ((Multiply)types.getUnionProperty()).getValue()); // NOTE: union collections are untyped in Java (java.lang.Object) // map Map<String, Object> map = new HashMap<>(); map.put("Foo", new Number(99)); types.setUnionMapProperty(map); // array types.setUnionArrayProperty(Arrays.asList(123, new Number(33))); assertEquals(33, ((Number)((List<?>)types.getUnionArrayProperty()).get(1)).getValue()); } @Test public void createObjectAndCtorOverloads() { new Calculator(); new Calculator(CalculatorProps.builder().maximumValue(10).build()); } @Test public void getSetPrimitiveProperties() { Number number = new Number(20); assertEquals(20, number.getValue()); assertEquals(40, number.getDoubleValue()); assertEquals(-30, new Negate(new Add(new Number(20), new Number(10))).getValue()); assertEquals(20, new Multiply(new Add(new Number(5), new Number(5)), new Number(2)).getValue()); assertEquals(3 * 3 * 3 * 3, new Power(new Number(3), new Number(4)).getValue()); assertEquals(999, new Power(new Number(999), new Number(1)).getValue()); assertEquals(1, new Power(new Number(999), new Number(0)).getValue()); } @Test public void callMethods() { Calculator calc = new Calculator(); calc.add(10); assertEquals(10, calc.getValue()); calc.mul(2); assertEquals(20, calc.getValue()); calc.pow(5); assertEquals(20 * 20 * 20 * 20 * 20, calc.getValue()); calc.neg(); assertEquals(-3200000, calc.getValue()); } @Test public void unmarshallIntoAbstractType() { Calculator calc = new Calculator(); calc.add(120); NumericValue value = calc.getCurr(); assertEquals(120, value.getValue()); } @Test public void getAndSetNonPrimitiveProperties() { Calculator calc = new Calculator(); calc.add(3200000); calc.neg(); calc.setCurr(new Multiply(new Number(2), calc.getCurr())); assertEquals(-6400000, calc.getValue()); } @Test public void getAndSetEnumValues() { Calculator calc = new Calculator(); calc.add(9); calc.pow(3); assertEquals(CompositeOperation.CompositionStringStyle.NORMAL, calc.getStringStyle()); calc.setStringStyle(CompositeOperation.CompositionStringStyle.DECORATED); assertEquals(CompositeOperation.CompositionStringStyle.DECORATED, calc.getStringStyle()); assertEquals("<<[[{{(((1 * (0 + 9)) * (0 + 9)) * (0 + 9))}}]]>>", calc.toString()); } @Test public void useEnumFromScopedModule() { ReferenceEnumFromScopedPackage obj = new ReferenceEnumFromScopedPackage(); assertEquals(EnumFromScopedModule.VALUE2, obj.getFoo()); obj.setFoo(EnumFromScopedModule.VALUE1); assertEquals(EnumFromScopedModule.VALUE1, obj.loadFoo()); obj.saveFoo(EnumFromScopedModule.VALUE2); assertEquals(EnumFromScopedModule.VALUE2, obj.getFoo()); } @Test public void undefinedAndNull() { Calculator calculator = new Calculator(); assertNull(calculator.getMaxValue()); calculator.setMaxValue(null); } @Test public void arrays() { Sum sum = new Sum(); sum.setParts(Arrays.asList(new Number(5), new Number(10), new Multiply(new Number(2), new Number(3)))); assertEquals(10 + 5 + (2 * 3), sum.getValue()); assertEquals(5, sum.getParts().get(0).getValue()); assertEquals(6, sum.getParts().get(2).getValue()); assertEquals("(((0 + 5) + 10) + (2 * 3))", sum.toString()); } @Test public void maps() { Calculator calc2 = new Calculator(); // Initializer overload (props is optional) calc2.add(10); calc2.add(20); calc2.mul(2); assertEquals(2, calc2.getOperationsMap().get("add").size()); assertEquals(1, calc2.getOperationsMap().get("mul").size()); assertEquals(30, calc2.getOperationsMap().get("add").get(1).getValue()); } @Test public void fluentApi() { final Calculator calc3 = new Calculator(CalculatorProps.builder() .initialValue(20) .maximumValue(30) .build()); calc3.add(3); assertEquals(23, calc3.getValue()); } @Test public void unionPropertiesWithBuilder() throws Exception { // verify we have a withXxx overload for each union type UnionProperties.Builder builder = UnionProperties.builder(); assertNotNull(builder.getClass().getMethod("bar", java.lang.Number.class)); assertNotNull(builder.getClass().getMethod("bar", String.class)); assertNotNull(builder.getClass().getMethod("bar", AllTypes.class)); assertNotNull(builder.getClass().getMethod("foo", String.class)); assertNotNull(builder.getClass().getMethod("foo", java.lang.Number.class)); UnionProperties obj1 = UnionProperties.builder() .bar(12) .foo("Hello") .build(); assertEquals(12, obj1.getBar()); assertEquals("Hello", obj1.getFoo()); UnionProperties obj2 = UnionProperties.builder() .bar("BarIsString") .build(); assertEquals("BarIsString", obj2.getBar()); assertNull(obj2.getFoo()); AllTypes allTypes = new AllTypes(); UnionProperties obj3 = UnionProperties.builder() .bar(allTypes) .foo(999) .build(); assertSame(allTypes, obj3.getBar()); assertEquals(999, obj3.getFoo()); } @Test public void exceptions() { final Calculator calc3 = new Calculator(CalculatorProps.builder() .initialValue(20) .maximumValue(30).build()); calc3.add(3); assertEquals(23, calc3.getValue()); boolean thrown = false; try { calc3.add(10); } catch (JsiiException e) { // We expect a RuntimeException that is NOT a JsiiException. throw e; } catch (RuntimeException e) { thrown = true; } assertTrue(thrown); calc3.setMaxValue(40); calc3.add(10); assertEquals(33, calc3.getValue()); } @Test public void unionProperties() { Calculator calc3 = new Calculator(); calc3.setUnionProperty(new Multiply(new Number(9), new Number(3))); assertTrue(calc3.getUnionProperty() instanceof Multiply); assertEquals(9 * 3, calc3.readUnionValue()); calc3.setUnionProperty(new Power(new Number(10), new Number(3))); assertTrue(calc3.getUnionProperty() instanceof Power); } @Test public void subclassing() { Calculator calc = new Calculator(); calc.setCurr(new AddTen(33)); calc.neg(); assertEquals(-43, calc.getValue()); } @Test public void testJSObjectLiteralToNative() { JSObjectLiteralToNative obj = new JSObjectLiteralToNative(); JSObjectLiteralToNativeClass obj2 = obj.returnLiteral(); assertEquals("Hello", obj2.getPropA()); assertEquals(102, obj2.getPropB()); } @Test public void testFluentApiWithDerivedClasses() { // make sure that fluent API can be assigned to objects from derived classes DerivedFromAllTypes obj = new DerivedFromAllTypes(); obj.setStringProperty("Hello"); obj.setNumberProperty(12); assertEquals("Hello", obj.getStringProperty()); assertEquals(12, obj.getNumberProperty()); } /** * See that we can create a native object, pass it JS and then unmarshal * back without type information. */ @Test @SuppressWarnings("deprecated") public void creationOfNativeObjectsFromJavaScriptObjects() { AllTypes types = new AllTypes(); Number jsObj = new Number(44); types.setAnyProperty(jsObj); Object unmarshalledJSObj = types.getAnyProperty(); assertEquals(Number.class, unmarshalledJSObj.getClass()); AddTen nativeObj = new AddTen(10); types.setAnyProperty(nativeObj); Object result1 = types.getAnyProperty(); assertSame(nativeObj, result1); MulTen nativeObj2 = new MulTen(20); types.setAnyProperty(nativeObj2); Object unmarshalledNativeObj = types.getAnyProperty(); assertEquals(MulTen.class, unmarshalledNativeObj.getClass()); assertSame(nativeObj2, unmarshalledNativeObj); } @Test public void asyncOverrides_callAsyncMethod() { AsyncVirtualMethods obj = new AsyncVirtualMethods(); assertEquals(128, obj.callMe()); assertEquals(528, obj.overrideMe(44)); } @Test public void asyncOverrides_overrideAsyncMethod() { OverrideAsyncMethods obj = new OverrideAsyncMethods(); assertEquals(4452, obj.callMe()); } @Test public void asyncOverrides_overrideAsyncMethodByParentClass() { OverrideAsyncMethodsByBaseClass obj = new OverrideAsyncMethodsByBaseClass(); assertEquals(4452, obj.callMe()); } @Test public void asyncOverrides_overrideCallsSuper() { OverrideCallsSuper obj = new OverrideCallsSuper(); assertEquals(1441, obj.overrideMe(12)); assertEquals(1209, obj.callMe()); } @Test public void asyncOverrides_twoOverrides() { TwoOverrides obj = new TwoOverrides(); assertEquals(684, obj.callMe()); } @Test public void asyncOverrides_overrideThrows() { AsyncVirtualMethods obj = new AsyncVirtualMethods() { public java.lang.Number overrideMe(java.lang.Number mult) { throw new RuntimeException("Thrown by native code"); } }; boolean thrown = false; try { obj.callMe(); } catch (JsiiException e) { throw e; } catch (RuntimeException e) { assertTrue(e.getMessage().contains( "Thrown by native code")); thrown = true; } assertTrue(thrown); } @Test public void syncOverrides() { SyncOverrides obj = new SyncOverrides(); assertEquals(10 * 5, obj.callerIsMethod()); // affect the result obj.multiplier = 5; assertEquals(10 * 5 * 5, obj.callerIsMethod()); // verify callbacks are invoked from a property assertEquals(10 * 5 * 5, obj.getCallerIsProperty()); } /** * Allow overriding property getters and setters. */ @Test public void propertyOverrides_get_set() { SyncOverrides so = new SyncOverrides(); assertEquals("I am an override!", so.retrieveValueOfTheProperty()); so.modifyValueOfTheProperty("New Value"); assertEquals("New Value", so.anotherTheProperty); } @Test public void propertyOverrides_get_calls_super() { SyncVirtualMethods so = new SyncVirtualMethods() { public String getTheProperty() { String superValue = super.getTheProperty(); return "super:" + superValue; } }; assertEquals("super:initial value", so.retrieveValueOfTheProperty()); assertEquals("super:initial value", so.getTheProperty()); } @Test public void propertyOverrides_set_calls_super() { SyncVirtualMethods so = new SyncVirtualMethods() { @Override public void setTheProperty(String value) { super.setTheProperty(value + ":by override"); } }; so.modifyValueOfTheProperty("New Value"); assertEquals("New Value:by override", so.getTheProperty()); } @Test public void propertyOverrides_get_throws() { SyncVirtualMethods so = new SyncVirtualMethods() { public String getTheProperty() { throw new RuntimeException("Oh no, this is bad"); } }; boolean thrown = false; try { so.retrieveValueOfTheProperty(); } catch (JsiiException e) { throw e; } catch (RuntimeException e) { assertTrue(e.getMessage().contains("Oh no, this is bad")); thrown = true; } assertTrue(thrown); } @Test public void propertyOverrides_set_throws() { SyncVirtualMethods so = new SyncVirtualMethods() { public void setTheProperty(String value) { throw new RuntimeException("Exception from overloaded setter"); } }; boolean thrown = false; try { so.modifyValueOfTheProperty("Hii"); } catch (JsiiException e) { throw e; } catch (RuntimeException e) { assertTrue(e.getMessage().contains("Exception from overloaded setter")); thrown = true; } assertTrue(thrown); } @Test public void propertyOverrides_interfaces() { IInterfaceWithProperties obj = new IInterfaceWithProperties() { private String x; @Override public String getReadOnlyString() { return "READ_ONLY_STRING"; } @Override public String getReadWriteString() { return x + "?"; } @Override public void setReadWriteString(String value) { this.x = value + "!"; } }; UsesInterfaceWithProperties interact = new UsesInterfaceWithProperties(obj); assertEquals("READ_ONLY_STRING", interact.justRead()); assertEquals("Hello!?", interact.writeAndRead("Hello")); } @Test public void interfaceBuilder() { IInterfaceWithProperties obj = new IInterfaceWithProperties() { private String value = "READ_WRITE"; @Override public String getReadOnlyString() { return "READ_ONLY"; } @Override public String getReadWriteString() { return value; } @Override public void setReadWriteString(String value) { this.value = value; } }; UsesInterfaceWithProperties interact = new UsesInterfaceWithProperties(obj); assertEquals("READ_ONLY", interact.justRead()); assertEquals("Hello", interact.writeAndRead("Hello")); } @Test public void syncOverrides_callsSuper() { SyncOverrides obj = new SyncOverrides(); assertEquals(10 * 5, obj.getCallerIsProperty()); obj.returnSuper = true; // js code returns n * 2 assertEquals(10 * 2, obj.getCallerIsProperty()); } @Test public void fail_syncOverrides_callsDoubleAsync_method() { assertThrows(JsiiException.class, () -> { try { JsiiEngine.setQuietMode(true); SyncOverrides obj = new SyncOverrides(); obj.callAsync = true; obj.callerIsMethod(); } finally { JsiiEngine.setQuietMode(false); } }); } @Test public void fail_syncOverrides_callsDoubleAsync_propertyGetter() { assertThrows(JsiiException.class, () -> { SyncOverrides obj = new SyncOverrides(); obj.callAsync = true; obj.getCallerIsProperty(); }); } @Test public void fail_syncOverrides_callsDoubleAsync_propertySetter() { assertThrows(JsiiException.class, () -> { SyncOverrides obj = new SyncOverrides(); obj.callAsync = true; obj.setCallerIsProperty(12); }); } @Test public void testInterfaces() { IFriendly friendly; IFriendlier friendlier; IRandomNumberGenerator randomNumberGenerator; IFriendlyRandomGenerator friendlyRandomGenerator; Add add = new Add(new Number(10), new Number(20)); friendly = add; // friendlier = add // <-- shouldn't compile since Add implements IFriendly assertEquals("Hello, I am a binary operation. What's your name?", friendly.hello()); Multiply multiply = new Multiply(new Number(10), new Number(30)); friendly = multiply; friendlier = multiply; randomNumberGenerator = multiply; // friendlyRandomGenerator = multiply; // <-- shouldn't compile assertEquals("Hello, I am a binary operation. What's your name?", friendly.hello()); assertEquals("Goodbye from Multiply!", friendlier.goodbye()); assertEquals(89, randomNumberGenerator.next()); friendlyRandomGenerator = new DoubleTrouble(); assertEquals("world", friendlyRandomGenerator.hello()); assertEquals(12, friendlyRandomGenerator.next()); Polymorphism poly = new Polymorphism(); assertEquals("oh, Hello, I am a binary operation. What's your name?", poly.sayHello(friendly)); assertEquals("oh, world", poly.sayHello(friendlyRandomGenerator)); assertEquals("oh, SubclassNativeFriendlyRandom", poly.sayHello(new SubclassNativeFriendlyRandom())); assertEquals("oh, I am a native!", poly.sayHello(new PureNativeFriendlyRandom())); } /** * This test verifies that native objects passed to jsii code as interfaces will remain "stable" * across invocation. For native objects that derive from JsiiObject, that's natural, because the objref * is stored at the JsiiObject level. But for "pure" native objects, which are not part of the JsiiObject * hierarchy, there's some magic going on: when the pure object is first passed to jsii, an empty javascript * object is created for it (extends Object.prototype) and any native method overrides are assigned (like any * other jsii object). The resulting objref is stored at the engine level (in "objects"). * * We verify two directions: * 1. objref => obj: when .getGenerator() is called, we get back an objref and we assert that it is the *same* * as the one we originally passed. * 2. obj => objref: when we call .isSameGenerator(x) we pass the pure native object back to jsii and we expect * that a new object is not created again. */ @Test public void testNativeObjectsWithInterfaces() { // create a pure and native object, not part of the jsii hierarchy, only implements a jsii interface PureNativeFriendlyRandom pureNative = new PureNativeFriendlyRandom(); SubclassNativeFriendlyRandom subclassedNative = new SubclassNativeFriendlyRandom(); NumberGenerator generatorBoundToPSubclassedObject = new NumberGenerator(subclassedNative); assertSame(subclassedNative, generatorBoundToPSubclassedObject.getGenerator()); generatorBoundToPSubclassedObject.isSameGenerator(subclassedNative); assertEquals(10000, generatorBoundToPSubclassedObject.nextTimes100()); // when we invoke nextTimes100 again, it will use the objref and call into the same object. assertEquals(20000, generatorBoundToPSubclassedObject.nextTimes100()); NumberGenerator generatorBoundToPureNative = new NumberGenerator(pureNative); assertSame(pureNative, generatorBoundToPureNative.getGenerator()); generatorBoundToPureNative.isSameGenerator(pureNative); assertEquals(100000, generatorBoundToPureNative.nextTimes100()); assertEquals(200000, generatorBoundToPureNative.nextTimes100()); } @Test public void testLiteralInterface() { JSObjectLiteralForInterface obj = new JSObjectLiteralForInterface(); IFriendly friendly = obj.giveMeFriendly(); assertEquals("I am literally friendly!", friendly.hello()); IFriendlyRandomGenerator gen = obj.giveMeFriendlyGenerator(); assertEquals("giveMeFriendlyGenerator", gen.hello()); assertEquals(42, gen.next()); } @Test public void testInterfaceParameter() { JSObjectLiteralForInterface obj = new JSObjectLiteralForInterface(); IFriendly friendly = obj.giveMeFriendly(); assertEquals("I am literally friendly!", friendly.hello()); GreetingAugmenter greetingAugmenter = new GreetingAugmenter(); String betterGreeting = greetingAugmenter.betterGreeting(friendly); assertEquals("I am literally friendly! Let me buy you a drink!", betterGreeting); } @Test public void structs_stepBuilders() { Instant someInstant = Instant.now(); DoubleTrouble nonPrim = new DoubleTrouble(); DerivedStruct s = new DerivedStruct.Builder() .nonPrimitive(nonPrim) .bool(false) .anotherRequired(someInstant) .astring("Hello") .anumber(1234) .firstOptional(Arrays.asList("Hello", "World")) .build(); assertSame(nonPrim, s.getNonPrimitive()); assertEquals(false, s.getBool()); assertEquals(someInstant, s.getAnotherRequired()); assertEquals("Hello", s.getAstring()); assertEquals(1234, s.getAnumber()); assertEquals("World", s.getFirstOptional().get(1)); assertNull(s.getAnotherOptional()); assertNull(s.getOptionalArray()); MyFirstStruct myFirstStruct = new MyFirstStruct.Builder() .astring("Hello") .anumber(12) .build(); assertEquals("Hello", myFirstStruct.getAstring()); assertEquals(12, myFirstStruct.getAnumber()); StructWithOnlyOptionals onlyOptionals1 = new StructWithOnlyOptionals.Builder() .optional1("Hello") .optional2(1) .build(); assertEquals("Hello", onlyOptionals1.getOptional1()); assertEquals(1, onlyOptionals1.getOptional2()); assertNull(onlyOptionals1.getOptional3()); StructWithOnlyOptionals onlyOptionals2 = new StructWithOnlyOptionals.Builder().build(); assertNull(onlyOptionals2.getOptional1()); assertNull(onlyOptionals2.getOptional2()); assertNull(onlyOptionals2.getOptional3()); } @Test public void structs_withDiamondInheritance_correctlyDedupeProperties() { DiamondInheritanceTopLevelStruct struct = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("base") .firstMidLevelProperty("mid1") .secondMidLevelProperty("mid2") .topLevelProperty("top") .build(); assertEquals("base", struct.getBaseLevelProperty()); assertEquals("mid1", struct.getFirstMidLevelProperty()); assertEquals("mid2", struct.getSecondMidLevelProperty()); assertEquals("top", struct.getTopLevelProperty()); } @Test public void structs_nonOptionalequals() { StableStruct structA = StableStruct.builder() .readonlyProperty("one") .build(); StableStruct structB = StableStruct.builder() .readonlyProperty("one") .build(); StableStruct structC = StableStruct.builder() .readonlyProperty("two") .build(); assertTrue(structA.equals(structB)); assertFalse(structA.equals(structC)); } @Test public void structs_nonOptionalhashCode() { StableStruct structA = StableStruct.builder() .readonlyProperty("one") .build(); StableStruct structB = StableStruct.builder() .readonlyProperty("one") .build(); StableStruct structC = StableStruct.builder() .readonlyProperty("two") .build(); assertTrue(structA.hashCode() == structB.hashCode()); assertFalse(structA.hashCode() == structC.hashCode()); } @Test public void structs_optionalEquals() { OptionalStruct structA = OptionalStruct.builder() .field("one") .build(); OptionalStruct structB = OptionalStruct.builder() .field("one") .build(); OptionalStruct structC = OptionalStruct.builder() .field("two") .build(); OptionalStruct structD = OptionalStruct.builder() .build(); assertTrue(structA.equals(structB)); assertFalse(structA.equals(structC)); assertFalse(structA.equals(structD)); } @Test public void structs_optionalHashCode() { OptionalStruct structA = OptionalStruct.builder() .field("one") .build(); OptionalStruct structB = OptionalStruct.builder() .field("one") .build(); OptionalStruct structC = OptionalStruct.builder() .field("two") .build(); OptionalStruct structD = OptionalStruct.builder() .build(); assertTrue(structA.hashCode() == structB.hashCode()); assertFalse(structA.hashCode() == structC.hashCode()); assertFalse(structA.hashCode() == structD.hashCode()); } @Test public void structs_multiplePropertiesEquals() { DiamondInheritanceTopLevelStruct structA = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("three") .topLevelProperty("four") .build(); DiamondInheritanceTopLevelStruct structB = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("three") .topLevelProperty("four") .build(); DiamondInheritanceTopLevelStruct structC = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("different") .topLevelProperty("four") .build(); assertTrue(structA.equals(structB)); assertFalse(structA.equals(structC)); } @Test public void structs_multiplePropertiesHashCode() { DiamondInheritanceTopLevelStruct structA = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("three") .topLevelProperty("four") .build(); DiamondInheritanceTopLevelStruct structB = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("three") .topLevelProperty("four") .build(); DiamondInheritanceTopLevelStruct structC = DiamondInheritanceTopLevelStruct.builder() .baseLevelProperty("one") .firstMidLevelProperty("two") .secondMidLevelProperty("different") .topLevelProperty("four") .build(); assertTrue(structA.hashCode() == structB.hashCode()); assertFalse(structA.hashCode() == structC.hashCode()); } @Test public void structs_containsNullChecks() { assertThrows(NullPointerException.class, () -> new MyFirstStruct.Builder().build()); } @Test public void structs_serializeToJsii() { MyFirstStruct firstStruct = MyFirstStruct.builder() .astring("FirstString") .anumber(999) .firstOptional(Arrays.asList("First", "Optional")) .build(); DoubleTrouble doubleTrouble = new DoubleTrouble(); DerivedStruct derivedStruct = DerivedStruct.builder() .nonPrimitive(doubleTrouble) .bool(false) .anotherRequired(Instant.now()) .astring("String") .anumber(1234) .firstOptional(Arrays.asList("one", "two")) .build(); GiveMeStructs gms = new GiveMeStructs(); assertEquals(999, gms.readFirstNumber(firstStruct)); assertEquals(1234, gms.readFirstNumber(derivedStruct)); // since derived inherits from first assertSame(doubleTrouble, gms.readDerivedNonPrimitive(derivedStruct)); StructWithOnlyOptionals literal = gms.getStructLiteral(); assertEquals("optional1FromStructLiteral", literal.getOptional1()); assertEquals(false, literal.getOptional3()); assertNull(literal.getOptional2()); } @Test public void structs_returnedLiteralEqualsNativeBuilt() { GiveMeStructs gms = new GiveMeStructs(); StructWithOnlyOptionals returnedLiteral = gms.getStructLiteral(); StructWithOnlyOptionals nativeBuilt = StructWithOnlyOptionals.builder() .optional1("optional1FromStructLiteral") .optional3(false) .build(); assertEquals(nativeBuilt.getOptional1(), returnedLiteral.getOptional1()); assertEquals(nativeBuilt.getOptional2(), returnedLiteral.getOptional2()); assertEquals(nativeBuilt.getOptional3(), returnedLiteral.getOptional3()); assertEquals(nativeBuilt, returnedLiteral); assertEquals(returnedLiteral, nativeBuilt); assertEquals(nativeBuilt.hashCode(), returnedLiteral.hashCode()); } @Test public void statics() { assertEquals("hello ,Yoyo!", Statics.staticMethod("Yoyo")); assertEquals("default", Statics.getInstance().getValue()); Statics newStatics = new Statics("new value"); Statics.setInstance(newStatics); assertSame(Statics.getInstance(), newStatics); assertEquals(Statics.getInstance().getValue(), "new value"); assertEquals(100, Statics.getNonConstStatic()); } @Test @SuppressWarnings("unchecked") public void consts() throws Exception { /* * Here be dragons: "consts" are actually pre-fetched when the class gets loaded, and they are static final * properties (so we cannot reset those). Since those tests need to run with a new Engine process, what was * loaded at this point may have been loaded by an engine that was long since disposed of. So we need to * actually run this code through a classloader that'll get a brand _new_ instance of the class. * * This whole process relies on ClassLoader black magic because I don't know a better way. */ final Class<ConstTestRunner> reloadedClass = ReloadingClassLoader.reload(this.getClass().getClassLoader(), ConstTestRunner.class, Statics.class); final Constructor<ConstTestRunner> constructor = reloadedClass.getConstructor(); constructor.setAccessible(true); final Runnable runnable = constructor.newInstance(); runnable.run(); } private static final class ConstTestRunner implements Runnable { public ConstTestRunner() {} public final void run() { assertEquals("hello", Statics.FOO); DoubleTrouble obj = Statics.CONST_OBJ; assertEquals("world", obj.hello()); assertEquals(1234, Statics.BAR); assertEquals("world", Statics.ZOO_BAR.get("hello")); } } @Test public void reservedKeywordsAreSlugifiedInMethodNames() { JavaReservedWords obj = new JavaReservedWords(); obj.doImport(); obj.doConst(); assertEquals("hello", obj.getWhileValue()); // properties should also be 'slugified' } @Test public void reservedKeywordsAreSlugifiedInStructProperties() { StructWithJavaReservedWords struct = StructWithJavaReservedWords.builder() .assertValue("one") .defaultValue("two") .build(); assertEquals("one", struct.getAssertValue()); assertEquals("two", struct.getDefaultValue()); } @Test public void reservedKeywordsAreSlugifiedInClassProperties() { ClassWithJavaReservedWords obj = new ClassWithJavaReservedWords("one"); String result = obj.doImport("two"); assertEquals("onetwo", result); } @Test public void hashCodeIsResistantToPropertyShadowingResultVariable() { StructWithJavaReservedWords first = StructWithJavaReservedWords.builder().defaultValue("one").build(); StructWithJavaReservedWords second = StructWithJavaReservedWords.builder().defaultValue("one").build(); StructWithJavaReservedWords third = StructWithJavaReservedWords.builder().defaultValue("two").build(); assertEquals(first.hashCode(), second.hashCode()); assertNotEquals(first.hashCode(), third.hashCode()); } @Test public void equalsIsResistantToPropertyShadowingResultVariable() { StructWithJavaReservedWords first = StructWithJavaReservedWords.builder().defaultValue("one").build(); StructWithJavaReservedWords second = StructWithJavaReservedWords.builder().defaultValue("one").build(); StructWithJavaReservedWords third = StructWithJavaReservedWords.builder().defaultValue("two").build(); assertEquals(first, second); assertNotEquals(first, third); } @Test public void nodeStandardLibrary() { NodeStandardLibrary obj = new NodeStandardLibrary(); assertEquals("Hello, resource!", obj.fsReadFile()); assertEquals("Hello, resource! SYNC!", obj.fsReadFileSync()); assertTrue(obj.getOsPlatform().length() > 0); assertEquals("6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50", obj.cryptoSha256()); } @Test public void returnAbstract() { AbstractClassReturner obj = new AbstractClassReturner(); AbstractClass obj2 = obj.giveMeAbstract(); assertEquals("Hello, John!!", obj2.abstractMethod("John")); assertEquals("propFromInterfaceValue", obj2.getPropFromInterface()); assertEquals(42, obj2.nonAbstractMethod()); IInterfaceImplementedByAbstractClass iface = obj.giveMeInterface(); assertEquals("propFromInterfaceValue", iface.getPropFromInterface()); assertEquals("hello-abstract-property", obj.getReturnAbstractFromProperty().getAbstractProperty()); } @Test public void doNotOverridePrivates_method_public() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") public String privateMethod() { return "privateMethod-Override"; } }; assertEquals("privateMethod", obj.privateMethodValue()); } @Test public void doNotOverridePrivates_method_private() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") private String privateMethod() { return "privateMethod-Override"; } }; assertEquals("privateMethod", obj.privateMethodValue()); } @Test public void doNotOverridePrivates_property_by_name_private() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") private String privateProperty() { return "privateProperty-Override"; } }; assertEquals("privateProperty", obj.privatePropertyValue()); } @Test public void doNotOverridePrivates_property_by_name_public() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") public String privateProperty() { return "privateProperty-Override"; } }; assertEquals("privateProperty", obj.privatePropertyValue()); } @Test public void doNotOverridePrivates_property_getter_public() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") public String getPrivateProperty() { return "privateProperty-Override"; } @SuppressWarnings("unused") public void setPrivateProperty(String value) { throw new RuntimeException("Boom"); } }; assertEquals("privateProperty", obj.privatePropertyValue()); // verify the setter override is not invoked. obj.changePrivatePropertyValue("MyNewValue"); assertEquals("MyNewValue", obj.privatePropertyValue()); } @Test public void doNotOverridePrivates_property_getter_private() { DoNotOverridePrivates obj = new DoNotOverridePrivates() { @SuppressWarnings("unused") private String getPrivateProperty() { return "privateProperty-Override"; } @SuppressWarnings("unused") public void setPrivateProperty(String value) { throw new RuntimeException("Boom"); } }; assertEquals("privateProperty", obj.privatePropertyValue()); // verify the setter override is not invoked. obj.changePrivatePropertyValue("MyNewValue"); assertEquals("MyNewValue", obj.privatePropertyValue()); } @Test public void classWithPrivateConstructorAndAutomaticProperties() { ClassWithPrivateConstructorAndAutomaticProperties obj = ClassWithPrivateConstructorAndAutomaticProperties.create("Hello", "Bye"); assertEquals("Bye", obj.getReadWriteString()); obj.setReadWriteString("Hello"); assertEquals("Hello", obj.getReadOnlyString()); } @Test public void nullShouldBeTreatedAsUndefined() { NullShouldBeTreatedAsUndefined obj = new NullShouldBeTreatedAsUndefined("hello", null); obj.giveMeUndefined(null); obj.giveMeUndefinedInsideAnObject(NullShouldBeTreatedAsUndefinedData.builder() .thisShouldBeUndefined(null) .arrayWithThreeElementsAndUndefinedAsSecondArgument(Arrays.asList("hello", null, "boom")) .build()); obj.setChangeMeToUndefined(null); obj.verifyPropertyIsUndefined(); } @Test public void testJsiiAgent() { assertEquals("Java/" + System.getProperty("java.version"), JsiiAgent.getValue()); } /** * @see https://github.com/aws/jsii/issues/320 */ @Test public void receiveInstanceOfPrivateClass() { assertTrue(new ReturnsPrivateImplementationOfInterface().getPrivateImplementation().getSuccess()); } @Test public void objRefsAreLabelledUsingWithTheMostCorrectType() { final PublicClass classRef = Constructors.makeClass(); final IPublicInterface ifaceRef = Constructors.makeInterface(); assertTrue(classRef instanceof InbetweenClass); assertNotNull(ifaceRef); } /** * Verifies that data values that are not set are recognized as unset keys * in JavaScript-land. See https://github.com/aws/jsii/issues/375 */ @Test public void eraseUnsetDataValues() { EraseUndefinedHashValuesOptions opts = EraseUndefinedHashValuesOptions.builder() .option1("option1") .build(); assertTrue(EraseUndefinedHashValues.doesKeyExist(opts, "option1")); assertFalse(EraseUndefinedHashValues.doesKeyExist(opts, "option2")); assertEquals("{prop2=value2}", EraseUndefinedHashValues.prop1IsNull().toString()); assertEquals("{prop1=value1}", EraseUndefinedHashValues.prop2IsUndefined().toString()); } @Test public void objectIdDoesNotGetReallocatedWhenTheConstructorPassesThisOut() { final PartiallyInitializedThisConsumer reflector = new PartiallyInitializedThisConsumerImpl(); new ConstructorPassesThisOut(reflector); } @Test public void variadicMethodCanBeInvoked() { final VariadicMethod variadicMethod = new VariadicMethod(1); final List<java.lang.Number> result = variadicMethod.asArray(3, 4, 5, 6); assertEquals(Arrays.asList(1, 3, 4, 5, 6), result); } @Test public void callbacksCorrectlyDeserializeArguments() { final DataRenderer renderer = new DataRenderer() { public final String renderMap(final Map<String, Object> map) { return super.renderMap(map); } }; assertEquals("{\n \"anumber\": 42,\n \"astring\": \"bazinga!\"\n}", renderer.render()); } @Test public void canLoadEnumValues() { assertNotNull(EnumDispenser.randomStringLikeEnum()); assertNotNull(EnumDispenser.randomIntegerLikeEnum()); } public void listInClassCannotBeModified() { List<String> modifiableList = Arrays.asList("one", "two"); ClassWithCollections classWithCollections = new ClassWithCollections(Collections.emptyMap(), modifiableList); assertThrows(UnsupportedOperationException.class, () -> classWithCollections.getArray().add("three")); } @Test public void listInClassCanBeReadCorrectly() { List<String> modifiableList = Arrays.asList("one", "two"); ClassWithCollections classWithCollections = new ClassWithCollections(Collections.emptyMap(), modifiableList); assertThat(classWithCollections.getArray(), contains("one", "two")); } @Test public void mapInClassCannotBeModified() { Map<String, String> modifiableMap = new HashMap<>(); modifiableMap.put("key", "value"); ClassWithCollections classWithCollections = new ClassWithCollections(modifiableMap, Collections.emptyList()); assertThrows(UnsupportedOperationException.class, () -> classWithCollections.getMap().put("keyTwo", "valueTwo")); } @Test public void mapInClassCanBeReadCorrectly() { Map<String, String> modifiableMap = new HashMap<>(); modifiableMap.put("key", "value"); ClassWithCollections classWithCollections = new ClassWithCollections(modifiableMap, Collections.emptyList()); Map<String, String> result = classWithCollections.getMap(); assertThat(result, hasEntry("key", "value")); assertThat(result.size(), is(1)); } @Test public void staticListInClassCannotBeModified() { assertThrows(UnsupportedOperationException.class, () -> ClassWithCollections.getStaticArray().add("three")); } @Test public void staticListInClassCanBeReadCorrectly() { assertThat(ClassWithCollections.getStaticArray(), contains("one", "two")); } @Test public void staticMapInClassCannotBeModified() { assertThrows(UnsupportedOperationException.class, () -> ClassWithCollections.getStaticMap().put("keyTwo", "valueTwo")); } @Test public void staticMapInClassCanBeReadCorrectly() { Map<String, String> result = ClassWithCollections.getStaticMap(); assertThat(result, hasEntry("key1", "value1")); assertThat(result, hasEntry("key2", "value2")); assertThat(result.size(), is(2)); } @Test public void arrayReturnedByMethodCannotBeModified() { assertThrows(UnsupportedOperationException.class, () -> ClassWithCollections.createAList().add("three")); } @Test public void arrayReturnedByMethodCanBeRead() { assertThat(ClassWithCollections.createAList(), contains("one", "two")); } @Test public void mapReturnedByMethodCannotBeModified() { assertThrows(UnsupportedOperationException.class, () -> ClassWithCollections.createAMap().put("keyThree", "valueThree")); } @Test public void mapReturnedByMethodCanBeRead() { Map<String, String> result = ClassWithCollections.createAMap(); assertThat(result, hasEntry("key1", "value1")); assertThat(result, hasEntry("key2", "value2")); assertThat(result.size(), is(2)); } @Test public void canOverrideProtectedMethod() { final String challenge = "Cthulhu Fhtagn!"; final OverridableProtectedMember overridden = new OverridableProtectedMember() { @Override protected String overrideMe() { return challenge; } }; assertEquals(challenge, overridden.valueFromProtected()); } @Test public void canOverrideProtectedGetter() { final String challenge = "Cthulhu Fhtagn!"; final OverridableProtectedMember overridden = new OverridableProtectedMember() { @Override protected String getOverrideReadOnly() { return "Cthulhu "; } @Override protected String getOverrideReadWrite() { return "Fhtagn!"; } }; assertEquals(challenge, overridden.valueFromProtected()); } @Test public void canOverrideProtectedSetter() { final String challenge = "Bazzzzzzzzzzzaar..."; final OverridableProtectedMember overridden = new OverridableProtectedMember() { @Override protected void setOverrideReadWrite(String value) { super.setOverrideReadWrite("zzzzzzzzz" + value); } }; overridden.switchModes(); assertEquals(challenge, overridden.valueFromProtected()); } @Test public void canLeverageIndirectInterfacePolymorphism() { final IAnonymousImplementationProvider provider = new AnonymousImplementationProvider(); assertEquals(1337, provider.provideAsClass().getValue()); assertEquals(1337, provider.provideAsInterface().getValue()); assertEquals("to implement", provider.provideAsInterface().verb()); } @Test public void correctlyDeserializesStructUnions() { final StructA a0 = StructA.builder() .requiredString("Present!") .optionalString("Bazinga!") .build(); final StructA a1 = StructA.builder() .requiredString("Present!") .optionalNumber(1337) .build(); final StructB b0 = StructB.builder() .requiredString("Present!") .optionalBoolean(true) .build(); final StructB b1 = StructB.builder() .requiredString("Present!") .optionalStructA(a1) .build(); assertTrue(StructUnionConsumer.isStructA(a0)); assertTrue(StructUnionConsumer.isStructA(a1)); assertFalse(StructUnionConsumer.isStructA(b0)); assertFalse(StructUnionConsumer.isStructA(b1)); assertFalse(StructUnionConsumer.isStructB(a0)); assertFalse(StructUnionConsumer.isStructB(a1)); assertTrue(StructUnionConsumer.isStructB(b0)); assertTrue(StructUnionConsumer.isStructB(b1)); } @Test public void returnSubclassThatImplementsInterface976() { IReturnJsii976 obj = SomeTypeJsii976.returnReturn(); assertEquals(obj.getFoo(), 333); } @Test public void testStructsCanBeDowncastedToParentType() { assertNotNull(Demonstrate982.takeThis()); assertNotNull(Demonstrate982.takeThisToo()); } @Test public void testNullIsAValidOptionalList() { assertNull(DisappointingCollectionSource.MAYBE_LIST); } @Test public void testNullIsAValidOptionalMap() { assertNull(DisappointingCollectionSource.MAYBE_MAP); } static class PartiallyInitializedThisConsumerImpl extends PartiallyInitializedThisConsumer { @Override public String consumePartiallyInitializedThis(final ConstructorPassesThisOut obj, final Instant dt, final AllTypesEnum en) { assertNotNull(obj); assertEquals(Instant.EPOCH, dt); assertEquals(AllTypesEnum.THIS_IS_GREAT, en); return "OK"; } } static class MulTen extends Multiply { public MulTen(final int value) { super(new Number(value), new Number(10)); } } static class AddTen extends Add { public AddTen(final int value) { super(new Number(value), new Number(10)); } } static class DerivedFromAllTypes extends AllTypes { } static class OverrideAsyncMethods extends AsyncVirtualMethods { @Override public java.lang.Number overrideMe(java.lang.Number mult) { return this.foo() * 2; } /** * Implement another method, which doesn't override anything in the base class. * This should obviously be possible. */ public int foo() { return 2222; } } static class OverrideAsyncMethodsByBaseClass extends OverrideAsyncMethods { } static class OverrideCallsSuper extends AsyncVirtualMethods { @Override public java.lang.Number overrideMe(java.lang.Number mult) { java.lang.Number superRet = super.overrideMe(mult); return superRet.intValue() * 10 + 1; } } static class TwoOverrides extends AsyncVirtualMethods { @Override public java.lang.Number overrideMe(java.lang.Number mult) { return 666; } @Override public java.lang.Number overrideMeToo() { return 10; } } static class SyncOverrides extends SyncVirtualMethods { int multiplier = 1; boolean returnSuper = false; boolean callAsync = false; @Override public java.lang.Number virtualMethod(java.lang.Number n) { if (returnSuper) { return super.virtualMethod(n); } if (callAsync) { OverrideAsyncMethods obj = new OverrideAsyncMethods(); return obj.callMe(); } return 5 * n.intValue() * multiplier; } @Override public String getTheProperty() { return "I am an override!"; } @Override public void setTheProperty(String value) { this.anotherTheProperty = value; } /** * Used by the test that verifies that it is possible to override a property setter. */ public String anotherTheProperty; } /** * In this case, the class does not derive from the JsiiObject hierarchy. It means * that when we pass it along to javascript, we won't have an objref. This should result * in creating a new empty javascript object and applying the overrides. * * The newly created objref will need to be stored somewhere (in the engine's object map) * so that subsequent calls won't create a new object every time. */ class PureNativeFriendlyRandom implements IFriendlyRandomGenerator { private int nextNumber = 1000; @Override public java.lang.Number next() { int n = this.nextNumber; this.nextNumber += 1000; return n; } @Override public String hello() { return "I am a native!"; } } class SubclassNativeFriendlyRandom extends Number implements IFriendly, IRandomNumberGenerator { private int nextNumber; public SubclassNativeFriendlyRandom() { super(908); this.nextNumber = 100; } @Override public String hello() { return "SubclassNativeFriendlyRandom"; } @Override public java.lang.Number next() { int next = this.nextNumber; this.nextNumber += 100; return next; } } @Test public void canUseInterfaceSetters() { final IObjectWithProperty obj = ObjectWithPropertyProvider.provide(); obj.setProperty("New Value"); assertTrue(obj.wasSet()); } @Test public void structsAreUndecoratedOntheWayToKernel() throws IOException { final ObjectMapper om = new ObjectMapper(); final String json = JsonFormatter.stringify(StructB.builder().requiredString("Bazinga!").optionalBoolean(false).build()); final JsonNode actual = om.readTree(json); final ObjectNode expected = om.createObjectNode(); expected.put("requiredString", "Bazinga!"); expected.put("optionalBoolean", Boolean.FALSE); assertEquals(expected, actual); } @Test public void canObtainReferenceWithOverloadedSetter() { assertNotNull(ConfusingToJackson.makeInstance()); } @Test public void canObtainStructReferenceWithOverloadedSetter() { assertNotNull(ConfusingToJackson.makeStructInstance()); } @Test public void pureInterfacesCanBeUsedTransparently() { final StructB expected = StructB.builder() .requiredString("It's Britney b**ch!") .build(); final IStructReturningDelegate delegate = new IStructReturningDelegate() { public StructB returnStruct() { return expected; } }; final ConsumePureInterface consumer = new ConsumePureInterface(delegate); assertEquals(expected, consumer.workItBaby()); } @Test public void pureInterfacesCanBeUsedTransparently_WhenTransitivelyImplementing() { final StructB expected = StructB.builder() .requiredString("It's Britney b**ch!") .build(); final IStructReturningDelegate delegate = new IndirectlyImplementsStructReturningDelegate(expected); final ConsumePureInterface consumer = new ConsumePureInterface(delegate); assertEquals(expected, consumer.workItBaby()); } private static final class IndirectlyImplementsStructReturningDelegate extends ImplementsStructReturningDelegate { public IndirectlyImplementsStructReturningDelegate(final StructB struct) { super(struct); } } private static class ImplementsStructReturningDelegate implements IStructReturningDelegate { private final StructB struct; protected ImplementsStructReturningDelegate(final StructB struct) { this.struct = struct; } public StructB returnStruct() { return this.struct; } } @Test public void interfacesCanBeUsedTransparently_WhenAddedToJsiiType() { final StructB expected = StructB.builder() .requiredString("It's Britney b**ch!") .build(); final IStructReturningDelegate delegate = new ImplementsAdditionalInterface(expected); final ConsumePureInterface consumer = new ConsumePureInterface(delegate); assertEquals(expected, consumer.workItBaby()); } private static final class ImplementsAdditionalInterface extends AllTypes implements IStructReturningDelegate { private final StructB struct; public ImplementsAdditionalInterface(final StructB struct) { this.struct = struct; } public StructB returnStruct() { return this.struct; } } @Test public void liftedKwargWithSameNameAsPositionalArg() { // This is a replication of a test that mostly affects languages with keyword arguments (e.g: Python, Ruby, ...) final Bell bell = new Bell(); final AmbiguousParameters amb = AmbiguousParameters.Builder.create(bell).scope("Driiiing!").build(); assertEquals(bell, amb.getScope()); assertEquals(StructParameterType.builder().scope("Driiiing!").build(), amb.getProps()); } @Test public void abstractMembersAreCorrectlyHandled() { final AbstractSuite abstractSuite = new AbstractSuite() { private String property; @Override protected String someMethod(String str) { return String.format("Wrapped<%s>", str); } @Override protected String getProperty() { return this.property; } @Override protected void setProperty(String value) { this.property = String.format("String<%s>", value); } }; assertEquals("Wrapped<String<Oomf!>>", abstractSuite.workItAll("Oomf!")); } @Test public void collectionOfInterfaces_ListOfStructs() { for (final Object obj : InterfaceCollections.listOfStructs()) { assertTrue(obj instanceof StructA, () -> obj + " is an instance of " + StructA.class.getCanonicalName()); } } @Test public void collectionOfInterfaces_ListOfInterfaces() { for (final Object obj : InterfaceCollections.listOfInterfaces()) { assertTrue(obj instanceof IBell, () -> obj + " is an instance of " + IBell.class.getCanonicalName()); } } @Test public void collectionOfInterfaces_MapOfStructs() { for (final Object obj : InterfaceCollections.mapOfStructs().values()) { assertTrue(obj instanceof StructA, () -> obj + " is an instance of " + StructA.class.getCanonicalName()); } } @Test public void collectionOfInterfaces_MapOfInterfaces() { for (final Object obj : InterfaceCollections.mapOfInterfaces().values()) { assertTrue(obj instanceof IBell, () -> obj + " is an instance of " + IBell.class.getCanonicalName()); } } @Test public void classesCanSelfReferenceDuringClassInitialization() { final OuterClass outerClass = new OuterClass(); assertNotNull(outerClass.getInnerClass()); } @Test public void iso8601DoesNotDeserializeToDate() { final TimeZone tz = TimeZone.getTimeZone("UTC"); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); final String nowAsISO = df.format(new Date()); final IWallClock wallClock = new IWallClock() { @NotNull @Override public String iso8601Now() { return nowAsISO; } }; final Entropy entropy = new Entropy(wallClock) { @NotNull @Override public String repeat(@NotNull final String word) { return word; } }; assertEquals(nowAsISO, entropy.increase()); } @Test public void classCanBeUsedWhenNotExpressedlyLoaded() { final Cdk16625 subject = new Cdk16625() { @NotNull @Override protected java.lang.Number unwrap(final IRandomNumberGenerator rng) { return rng.next(); } }; subject.test(); } @Test public void strippedDeprecatedMemberCanBeReceived() { assertNotNull(InterfaceFactory.create()); } @Test public void exceptionMessage() { boolean thrown = false; try { AcceptsPath.Builder.create() .sourcePath("A Bad Path") .build(); } catch (final RuntimeException e) { assertTrue(e.getMessage().startsWith("Cannot find asset")); thrown = true; } assertTrue(thrown); } }
778
0
Create_ds/gradle-template/template-server/src/main/java/com/netflix/template
Create_ds/gradle-template/template-server/src/main/java/com/netflix/template/server/TalkServer.java
package com.netflix.template.server; import com.netflix.template.common.Conversation; import com.netflix.template.common.Sentence; import javax.ws.rs.GET; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/talk") public class TalkServer implements Conversation { @GET @Produces(MediaType.APPLICATION_XML) public Sentence greeting() { return new Sentence("Hello"); } @DELETE @Produces(MediaType.APPLICATION_XML) public Sentence farewell() { return new Sentence("Goodbye"); } }
779
0
Create_ds/gradle-template/template-client/src/test/java/com/netflix/template
Create_ds/gradle-template/template-client/src/test/java/com/netflix/template/common/ExampleTest.java
package com.netflix.template.common; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; public class ExampleTest { @Test public void canaryTest(TestInfo testinfo) { assertEquals(1/*expected*/, 1/*result from your code*/, "canary test 1 should equal 1"); } }
780
0
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template/common/Sentence.java
package com.netflix.template.common; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Container for words going back and forth. * @author jryan * */ @XmlRootElement public class Sentence { private String whole; @SuppressWarnings("unused") private Sentence() { }; /** * Initialize sentence. * @param whole */ public Sentence(String whole) { this.whole = whole; } /** * whole getter. * @return */ @XmlElement public String getWhole() { return whole; } public void setWhole(String whole) { this.whole = whole; } }
781
0
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template/common/Conversation.java
package com.netflix.template.common; /** * Hold a conversation. * @author jryan * */ public interface Conversation { /** * Initiates a conversation. * @return Sentence words from geeting */ Sentence greeting(); /** * End the conversation. * @return */ Sentence farewell(); }
782
0
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template
Create_ds/gradle-template/template-client/src/main/java/com/netflix/template/client/TalkClient.java
package com.netflix.template.client; import com.netflix.template.common.Conversation; import com.netflix.template.common.Sentence; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.LoggingFilter; import javax.ws.rs.core.MediaType; /** * Delegates to remote TalkServer over REST. * @author jryan * */ public class TalkClient implements Conversation { private WebResource webResource; /** * Instantiate client. * * @param location URL to the base of resources, e.g. http://localhost:8080/template-server/rest */ public TalkClient(String location) { Client client = Client.create(); client.addFilter(new LoggingFilter(System.out)); webResource = client.resource(location + "/talk"); } @Override public Sentence greeting() { Sentence s = webResource.accept(MediaType.APPLICATION_XML).get(Sentence.class); return s; } @Override public Sentence farewell() { Sentence s = webResource.accept(MediaType.APPLICATION_XML).delete(Sentence.class); return s; } /** * Tests out client. * @param args Not applicable */ public static void main(String[] args) { TalkClient remote = new TalkClient("http://localhost:8080/template-server/rest"); System.out.println(remote.greeting().getWhole()); System.out.println(remote.farewell().getWhole()); } }
783
0
Create_ds/paris/paris/src/testDebug/java/com/airbnb/paris/views
Create_ds/paris/paris/src/testDebug/java/com/airbnb/paris/views/java/WithStyleableChildView.java
package com.airbnb.paris.views.java; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.airbnb.paris.R2; import com.airbnb.paris.annotations.Styleable; import com.airbnb.paris.annotations.StyleableChild; @Styleable("Test_WithStyleableChildView") public class WithStyleableChildView extends View { @StyleableChild(R2.styleable.Test_WithStyleableChildView_test_arbitraryStyle) public View arbitrarySubView; public WithStyleableChildView(Context context) { super(context); init(); } public WithStyleableChildView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public WithStyleableChildView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { arbitrarySubView = new View(getContext()); } }
784
0
Create_ds/paris/paris/src/testDebug/java/com/airbnb/paris/views
Create_ds/paris/paris/src/testDebug/java/com/airbnb/paris/views/java/WithStyleFieldView.java
package com.airbnb.paris.views.java; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.airbnb.paris.annotations.Style; import com.airbnb.paris.annotations.Styleable; @Styleable public class WithStyleFieldView extends View { @Style public static final com.airbnb.paris.styles.Style testStyle = new WithStyleFieldViewStyleApplier.StyleBuilder().build(); public WithStyleFieldView(Context context) { super(context); } public WithStyleFieldView(Context context, AttributeSet attrs) { super(context, attrs); } public WithStyleFieldView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
785
0
Create_ds/paris/paris/src/main/java/com/airbnb/paris
Create_ds/paris/paris/src/main/java/com/airbnb/paris/utils/StyleBuilderFunction.java
package com.airbnb.paris.utils; import com.airbnb.paris.StyleBuilder; import androidx.annotation.NonNull; public interface StyleBuilderFunction<T extends StyleBuilder> { void invoke(@NonNull T builder); }
786
0
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr/input/PackageInfo.java
package com.airbnb.paris.test.styleable_in_other_module; import com.airbnb.paris.annotations.ParisConfig; @ParisConfig(rClass = com.airbnb.paris.test.R.class) class PackageInfo { }
787
0
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr/input/MyView.java
package com.airbnb.paris.test; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.airbnb.paris.annotations.Attr; import com.airbnb.paris.annotations.Styleable; @Styleable("MyLibView") public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Attr(com.airbnb.paris.test.lib.R2.styleable.MyLibView_title) public void setTitle(String title) { } }
788
0
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr/output/MyViewStyleApplier.java
package com.airbnb.paris.test; import android.content.Context; import android.content.res.Resources; import android.view.ViewStyleApplier; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.annotation.UiThread; import com.airbnb.paris.StyleApplier; import com.airbnb.paris.styles.Style; import com.airbnb.paris.test.lib.R; import com.airbnb.paris.typed_array_wrappers.TypedArrayWrapper; import java.lang.Override; import java.lang.String; @UiThread public final class MyViewStyleApplier extends StyleApplier<MyView, MyView> { public MyViewStyleApplier(MyView view) { super(view); } @Override protected void applyParent(Style style) { ViewStyleApplier applier = new ViewStyleApplier(getView()); applier.setDebugListener(getDebugListener()); applier.apply(style); } @Override protected int[] attributes() { return R.styleable.MyLibView; } @Override protected void processStyleableFields(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); } @Override protected void processAttributes(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); if (a.hasValue(R.styleable.MyLibView_title)) { getProxy().setTitle(a.getString(R.styleable.MyLibView_title)); } } public StyleBuilder builder() { return new StyleBuilder(this); } /** * Empty style. */ public void applyDefault() { } /** * For debugging */ public static void assertStylesContainSameAttributes(Context context) { } public abstract static class BaseStyleBuilder<B extends BaseStyleBuilder<B, A>, A extends StyleApplier<?, ?>> extends ViewStyleApplier.BaseStyleBuilder<B, A> { public BaseStyleBuilder(A applier) { super(applier); } public BaseStyleBuilder() { } /** * @see MyView#setTitle(String) */ public B title(@Nullable String value) { getBuilder().put(R.styleable.MyLibView[R.styleable.MyLibView_title], value); return (B) this; } /** * @see MyView#setTitle(String) */ public B titleRes(@StringRes int resId) { getBuilder().putRes(R.styleable.MyLibView[R.styleable.MyLibView_title], resId); return (B) this; } public B applyTo(MyView view) { new MyViewStyleApplier(view).apply(build()); return (B) this; } } @UiThread public static final class StyleBuilder extends BaseStyleBuilder<StyleBuilder, MyViewStyleApplier> { public StyleBuilder(MyViewStyleApplier applier) { super(applier); } public StyleBuilder() { } /** * Empty style. */ public StyleBuilder addDefault() { return this; } } }
789
0
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr
Create_ds/paris/paris-test/src/test/resources/styleable_in_other_module_single_attr/output/Paris.java
package com.airbnb.paris.test; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroupStyleApplier; import android.view.ViewStyleApplier; import android.widget.ImageView; import android.widget.ImageViewStyleApplier; import android.widget.TextView; import android.widget.TextViewStyleApplier; import com.airbnb.paris.spannables.SpannableBuilder; public final class Paris { public static ImageViewStyleApplier style(ImageView view) { return new ImageViewStyleApplier(view); } public static ImageViewStyleApplier.StyleBuilder styleBuilder(ImageView view) { return new ImageViewStyleApplier.StyleBuilder(new ImageViewStyleApplier(view)); } public static MyOtherViewStyleApplier style(MyOtherView view) { return new MyOtherViewStyleApplier(view); } public static MyOtherViewStyleApplier.StyleBuilder styleBuilder(MyOtherView view) { return new MyOtherViewStyleApplier.StyleBuilder(new MyOtherViewStyleApplier(view)); } public static MyViewStyleApplier style(MyView view) { return new MyViewStyleApplier(view); } public static MyViewStyleApplier.StyleBuilder styleBuilder(MyView view) { return new MyViewStyleApplier.StyleBuilder(new MyViewStyleApplier(view)); } public static TextViewStyleApplier style(TextView view) { return new TextViewStyleApplier(view); } public static TextViewStyleApplier.StyleBuilder styleBuilder(TextView view) { return new TextViewStyleApplier.StyleBuilder(new TextViewStyleApplier(view)); } public static ViewGroupStyleApplier style(ViewGroup view) { return new ViewGroupStyleApplier(view); } public static ViewGroupStyleApplier.StyleBuilder styleBuilder(ViewGroup view) { return new ViewGroupStyleApplier.StyleBuilder(new ViewGroupStyleApplier(view)); } public static ViewStyleApplier style(View view) { return new ViewStyleApplier(view); } public static ViewStyleApplier.StyleBuilder styleBuilder(View view) { return new ViewStyleApplier.StyleBuilder(new ViewStyleApplier(view)); } public static SpannableBuilder spannableBuilder() { return new SpannableBuilder(); } /** * For debugging */ public static void assertStylesContainSameAttributes(Context context) { ImageViewStyleApplier.assertStylesContainSameAttributes(context); MyOtherViewStyleApplier.assertStylesContainSameAttributes(context); MyViewStyleApplier.assertStylesContainSameAttributes(context); TextViewStyleApplier.assertStylesContainSameAttributes(context); ViewGroupStyleApplier.assertStylesContainSameAttributes(context); ViewStyleApplier.assertStylesContainSameAttributes(context); } }
790
0
Create_ds/paris/paris-test/src/test/resources/at_style_style_field
Create_ds/paris/paris-test/src/test/resources/at_style_style_field/input/PackageInfo.java
package com.airbnb.paris.test; import com.airbnb.paris.annotations.ParisConfig; @ParisConfig(rClass = com.airbnb.paris.test.R.class) class PackageInfo { }
791
0
Create_ds/paris/paris-test/src/test/resources/at_style_style_field
Create_ds/paris/paris-test/src/test/resources/at_style_style_field/input/MyView.java
package com.airbnb.paris.test; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.airbnb.paris.annotations.Attr; import com.airbnb.paris.annotations.Style; import com.airbnb.paris.annotations.Styleable; import com.airbnb.paris.test.MyViewStyleApplier; @Styleable("MyView") public class MyView extends View { @Style static final com.airbnb.paris.styles.Style myStyle = new MyViewStyleApplier.StyleBuilder().build(); public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
792
0
Create_ds/paris/paris-test/src/test/resources/at_style_style_field
Create_ds/paris/paris-test/src/test/resources/at_style_style_field/output/MyViewStyleApplier.java
package com.airbnb.paris.test; import android.content.Context; import android.content.res.Resources; import android.view.ViewStyleApplier; import androidx.annotation.UiThread; import com.airbnb.paris.StyleApplier; import com.airbnb.paris.StyleApplierUtils; import com.airbnb.paris.styles.Style; import com.airbnb.paris.typed_array_wrappers.TypedArrayWrapper; import java.lang.Override; @UiThread public final class MyViewStyleApplier extends StyleApplier<MyView, MyView> { public MyViewStyleApplier(MyView view) { super(view); } @Override protected void applyParent(Style style) { ViewStyleApplier applier = new ViewStyleApplier(getView()); applier.setDebugListener(getDebugListener()); applier.apply(style); } @Override protected int[] attributes() { return R.styleable.MyView; } @Override protected void processStyleableFields(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); } @Override protected void processAttributes(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); } public StyleBuilder builder() { return new StyleBuilder(this); } /** * @see MyView#myStyle */ public void applyMy() { apply(MyView.myStyle); } /** * Empty style. */ public void applyDefault() { } /** * For debugging */ public static void assertStylesContainSameAttributes(Context context) { MyView MyView = new MyView(context); StyleApplierUtils.Companion.assertSameAttributes(new MyViewStyleApplier(MyView), new StyleBuilder().addMy().build(), new StyleBuilder().addDefault().build()); } public abstract static class BaseStyleBuilder<B extends BaseStyleBuilder<B, A>, A extends StyleApplier<?, ?>> extends ViewStyleApplier.BaseStyleBuilder<B, A> { public BaseStyleBuilder(A applier) { super(applier); } public BaseStyleBuilder() { } public B applyTo(MyView view) { new MyViewStyleApplier(view).apply(build()); return (B) this; } } @UiThread public static final class StyleBuilder extends BaseStyleBuilder<StyleBuilder, MyViewStyleApplier> { public StyleBuilder(MyViewStyleApplier applier) { super(applier); } public StyleBuilder() { } /** * @see MyView#myStyle */ public StyleBuilder addMy() { add(MyView.myStyle); return this; } /** * Empty style. */ public StyleBuilder addDefault() { return this; } } }
793
0
Create_ds/paris/paris-test/src/test/resources/at_style_style_field
Create_ds/paris/paris-test/src/test/resources/at_style_style_field/output/Paris.java
package com.airbnb.paris.test; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroupStyleApplier; import android.view.ViewStyleApplier; import android.widget.ImageView; import android.widget.ImageViewStyleApplier; import android.widget.TextView; import android.widget.TextViewStyleApplier; import com.airbnb.paris.spannables.SpannableBuilder; public final class Paris { public static ImageViewStyleApplier style(ImageView view) { return new ImageViewStyleApplier(view); } public static ImageViewStyleApplier.StyleBuilder styleBuilder(ImageView view) { return new ImageViewStyleApplier.StyleBuilder(new ImageViewStyleApplier(view)); } public static MyOtherViewStyleApplier style(MyOtherView view) { return new MyOtherViewStyleApplier(view); } public static MyOtherViewStyleApplier.StyleBuilder styleBuilder(MyOtherView view) { return new MyOtherViewStyleApplier.StyleBuilder(new MyOtherViewStyleApplier(view)); } public static MyViewStyleApplier style(MyView view) { return new MyViewStyleApplier(view); } public static MyViewStyleApplier.StyleBuilder styleBuilder(MyView view) { return new MyViewStyleApplier.StyleBuilder(new MyViewStyleApplier(view)); } public static TextViewStyleApplier style(TextView view) { return new TextViewStyleApplier(view); } public static TextViewStyleApplier.StyleBuilder styleBuilder(TextView view) { return new TextViewStyleApplier.StyleBuilder(new TextViewStyleApplier(view)); } public static ViewGroupStyleApplier style(ViewGroup view) { return new ViewGroupStyleApplier(view); } public static ViewGroupStyleApplier.StyleBuilder styleBuilder(ViewGroup view) { return new ViewGroupStyleApplier.StyleBuilder(new ViewGroupStyleApplier(view)); } public static ViewStyleApplier style(View view) { return new ViewStyleApplier(view); } public static ViewStyleApplier.StyleBuilder styleBuilder(View view) { return new ViewStyleApplier.StyleBuilder(new ViewStyleApplier(view)); } public static SpannableBuilder spannableBuilder() { return new SpannableBuilder(); } /** * For debugging */ public static void assertStylesContainSameAttributes(Context context) { ImageViewStyleApplier.assertStylesContainSameAttributes(context); MyOtherViewStyleApplier.assertStylesContainSameAttributes(context); MyViewStyleApplier.assertStylesContainSameAttributes(context); TextViewStyleApplier.assertStylesContainSameAttributes(context); ViewGroupStyleApplier.assertStylesContainSameAttributes(context); ViewStyleApplier.assertStylesContainSameAttributes(context); } }
794
0
Create_ds/paris/paris-test/src/test/resources/error_private_style_field
Create_ds/paris/paris-test/src/test/resources/error_private_style_field/input/PackageInfo.java
package com.airbnb.paris.test; import com.airbnb.paris.annotations.ParisConfig; @ParisConfig(rClass = com.airbnb.paris.test.R.class) class PackageInfo { }
795
0
Create_ds/paris/paris-test/src/test/resources/error_private_style_field
Create_ds/paris/paris-test/src/test/resources/error_private_style_field/input/MyView.java
package com.airbnb.paris.test; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.airbnb.paris.annotations.Attr; import com.airbnb.paris.annotations.Style; import com.airbnb.paris.annotations.Styleable; import com.airbnb.paris.test.MyViewStyleApplier; @Styleable("MyView") public class MyView extends View { @Style private static final com.airbnb.paris.styles.Style myStyle = new MyViewStyleApplier.StyleBuilder().build(); public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
796
0
Create_ds/paris/paris-test/src/test/resources/styleable_fields
Create_ds/paris/paris-test/src/test/resources/styleable_fields/input/PackageInfo.java
package com.airbnb.paris.test; import com.airbnb.paris.annotations.ParisConfig; @ParisConfig(rClass = com.airbnb.paris.test.R.class) class PackageInfo { }
797
0
Create_ds/paris/paris-test/src/test/resources/styleable_fields
Create_ds/paris/paris-test/src/test/resources/styleable_fields/input/MyView.java
package com.airbnb.paris.test; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.airbnb.paris.annotations.Styleable; import com.airbnb.paris.annotations.StyleableChild; @Styleable("MyView") public class MyView extends View { @StyleableChild(R2.styleable.MyView_titleStyle) TextView title; @StyleableChild(R2.styleable.MyView_subtitleStyle) TextView subtitle; @StyleableChild(R2.styleable.MyView_dividerStyle) View divider; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
798
0
Create_ds/paris/paris-test/src/test/resources/styleable_fields
Create_ds/paris/paris-test/src/test/resources/styleable_fields/output/MyViewStyleApplier.java
package com.airbnb.paris.test; import android.content.Context; import android.content.res.Resources; import android.view.ViewStyleApplier; import android.widget.TextViewStyleApplier; import androidx.annotation.StyleRes; import androidx.annotation.UiThread; import com.airbnb.paris.StyleApplier; import com.airbnb.paris.styles.Style; import com.airbnb.paris.typed_array_wrappers.TypedArrayWrapper; import com.airbnb.paris.utils.StyleBuilderFunction; import java.lang.Override; @UiThread public final class MyViewStyleApplier extends StyleApplier<MyView, MyView> { public MyViewStyleApplier(MyView view) { super(view); } @Override protected void applyParent(Style style) { ViewStyleApplier applier = new ViewStyleApplier(getView()); applier.setDebugListener(getDebugListener()); applier.apply(style); } @Override protected int[] attributes() { return R.styleable.MyView; } @Override protected void processStyleableFields(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); if (a.hasValue(R.styleable.MyView_titleStyle)) { title().apply(a.getStyle(R.styleable.MyView_titleStyle)); } if (a.hasValue(R.styleable.MyView_subtitleStyle)) { subtitle().apply(a.getStyle(R.styleable.MyView_subtitleStyle)); } if (a.hasValue(R.styleable.MyView_dividerStyle)) { divider().apply(a.getStyle(R.styleable.MyView_dividerStyle)); } } @Override protected void processAttributes(Style style, TypedArrayWrapper a) { Context context = getView().getContext(); Resources res = context.getResources(); } public StyleBuilder builder() { return new StyleBuilder(this); } public TextViewStyleApplier title() { TextViewStyleApplier subApplier = new TextViewStyleApplier(getProxy().title); subApplier.setDebugListener(getDebugListener()); return subApplier; } public TextViewStyleApplier subtitle() { TextViewStyleApplier subApplier = new TextViewStyleApplier(getProxy().subtitle); subApplier.setDebugListener(getDebugListener()); return subApplier; } public ViewStyleApplier divider() { ViewStyleApplier subApplier = new ViewStyleApplier(getProxy().divider); subApplier.setDebugListener(getDebugListener()); return subApplier; } /** * Empty style. */ public void applyDefault() { } /** * For debugging */ public static void assertStylesContainSameAttributes(Context context) { } public abstract static class BaseStyleBuilder<B extends BaseStyleBuilder<B, A>, A extends StyleApplier<?, ?>> extends ViewStyleApplier.BaseStyleBuilder<B, A> { public BaseStyleBuilder(A applier) { super(applier); } public BaseStyleBuilder() { } public B titleStyle(@StyleRes int resId) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_titleStyle], resId); return (B) this; } public B titleStyle(Style style) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_titleStyle], style); return (B) this; } public B titleStyle(StyleBuilderFunction<TextViewStyleApplier.StyleBuilder> function) { TextViewStyleApplier.StyleBuilder subBuilder = new TextViewStyleApplier.StyleBuilder(); function.invoke(subBuilder); getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_titleStyle], subBuilder.build()); return (B) this; } public B subtitleStyle(@StyleRes int resId) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_subtitleStyle], resId); return (B) this; } public B subtitleStyle(Style style) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_subtitleStyle], style); return (B) this; } public B subtitleStyle(StyleBuilderFunction<TextViewStyleApplier.StyleBuilder> function) { TextViewStyleApplier.StyleBuilder subBuilder = new TextViewStyleApplier.StyleBuilder(); function.invoke(subBuilder); getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_subtitleStyle], subBuilder.build()); return (B) this; } public B dividerStyle(@StyleRes int resId) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_dividerStyle], resId); return (B) this; } public B dividerStyle(Style style) { getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_dividerStyle], style); return (B) this; } public B dividerStyle(StyleBuilderFunction<ViewStyleApplier.StyleBuilder> function) { ViewStyleApplier.StyleBuilder subBuilder = new ViewStyleApplier.StyleBuilder(); function.invoke(subBuilder); getBuilder().putStyle(R.styleable.MyView[R.styleable.MyView_dividerStyle], subBuilder.build()); return (B) this; } public B applyTo(MyView view) { new MyViewStyleApplier(view).apply(build()); return (B) this; } } @UiThread public static final class StyleBuilder extends BaseStyleBuilder<StyleBuilder, MyViewStyleApplier> { public StyleBuilder(MyViewStyleApplier applier) { super(applier); } public StyleBuilder() { } /** * Empty style. */ public StyleBuilder addDefault() { return this; } } }
799