Exemplo n.º 1
0
  @Test
  public void nestedSelfRefsInStringContentWithoutParentFile()
      throws NoSuchMethodException, ClassNotFoundException, IOException {

    String schemaContents =
        IOUtils.toString(
            CodeGenerationHelper.class.getResource("/schema/ref/nestedSelfRefsReadAsString.json"));
    JCodeModel codeModel = new JCodeModel();
    new SchemaMapper().generate(codeModel, "NestedSelfRefsInString", "com.example", schemaContents);

    codeModel.build(schemaRule.getGenerateDir());

    ClassLoader classLoader = schemaRule.compile();

    Class<?> nestedSelfRefs = classLoader.loadClass("com.example.NestedSelfRefsInString");
    assertThat(
        nestedSelfRefs.getMethod("getThings").getReturnType().getSimpleName(), equalTo("List"));

    Class<?> listEntryType =
        (Class<?>)
            ((ParameterizedType) nestedSelfRefs.getMethod("getThings").getGenericReturnType())
                .getActualTypeArguments()[0];
    assertThat(listEntryType.getName(), equalTo("com.example.Thing"));

    Class<?> thingClass = classLoader.loadClass("com.example.Thing");
    assertThat(
        thingClass.getMethod("getNamespace").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(thingClass.getMethod("getName").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(
        thingClass.getMethod("getVersion").getReturnType().getSimpleName(), equalTo("String"));
  }
 static KeyStore getKeystore() throws Exception {
   ClassLoader loader = SecureClientDriverTest.class.getClassLoader();
   byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("keystore.jks"));
   KeyStore keyStore = KeyStore.getInstance("JKS");
   keyStore.load(new ByteArrayInputStream(binaryContent), "password".toCharArray());
   return keyStore;
 }
Exemplo n.º 3
0
  @Test
  @SuppressWarnings("rawtypes")
  public void wordDelimitersCausesCamelCase()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile(
            "/schema/properties/propertiesWithWordDelimiters.json",
            "com.example",
            config("usePrimitives", true, "propertyWordDelimiters", "_ -"));

    Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("propertyWithUnderscores", generatedType)
        .getWriteMethod()
        .invoke(instance, "a_b_c");
    new PropertyDescriptor("propertyWithHyphens", generatedType)
        .getWriteMethod()
        .invoke(instance, "a-b-c");
    new PropertyDescriptor("propertyWithMixedDelimiters", generatedType)
        .getWriteMethod()
        .invoke(instance, "a b_c-d");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertThat(jsonified.has("property_with_underscores"), is(true));
    assertThat(jsonified.has("property-with-hyphens"), is(true));
    assertThat(jsonified.has("property_with mixed-delimiters"), is(true));
  }
  @BeforeClass
  public static void generateAndCompileEnum() throws ClassNotFoundException {

    ClassLoader fragmentRefsClassLoader =
        generateAndCompile("/schema/ref/fragmentRefs.json", "com.example");

    fragmentRefsClass = fragmentRefsClassLoader.loadClass("com.example.FragmentRefs");
  }
Exemplo n.º 5
0
  @BeforeClass
  public static void generateAndCompileEnum() throws ClassNotFoundException {

    ClassLoader selfRefsClassLoader =
        classSchemaRule.generateAndCompile("/schema/ref/selfRefs.json", "com.example");

    selfRefsClass = selfRefsClassLoader.loadClass("com.example.SelfRefs");
  }
Exemplo n.º 6
0
  @Test
  public void propertyCalledClassCanBeSerialized()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/propertyCalledClass.json", "com.example");

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.PropertyCalledClass");

    String valuesAsJsonString = "{\"class\":\"a\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("class").asText(), is("a"));
  }
 @Test
 public void say_valid() {
   IHelloService target = new HelloValidationService();
   String responseXml =
       target.say(ClassLoader.getSystemResourceAsStream("hello-validation-valid.xml"));
   assertThat(extract(responseXml, "/helloValidationResponse/message/text()"), is("Hello, JAXB!"));
 }
    public void execute(WorkerProcessContext workerProcessContext) {
      // Check environment
      assertThat(System.getProperty("test.system.property"), equalTo("value"));
      assertThat(System.getenv().get("TEST_ENV_VAR"), equalTo("value"));

      // Check ClassLoaders
      ClassLoader antClassLoader = Project.class.getClassLoader();
      ClassLoader thisClassLoader = getClass().getClassLoader();
      ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

      assertThat(antClassLoader, not(sameInstance(systemClassLoader)));
      assertThat(thisClassLoader, not(sameInstance(systemClassLoader)));
      assertThat(antClassLoader.getParent(), equalTo(systemClassLoader.getParent()));
      try {
        assertThat(
            thisClassLoader.loadClass(Project.class.getName()),
            sameInstance((Object) Project.class));
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }

      // Send some messages
      TestListenerInterface sender =
          workerProcessContext.getServerConnection().addOutgoing(TestListenerInterface.class);
      sender.send("message 1", 1);
      sender.send("message 2", 2);
    }
Exemplo n.º 9
0
  @Test
  public void propertyNamesThatAreJavaKeywordsCanBeSerialized()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/propertiesThatAreJavaKeywords.json", "com.example");

    Class<?> generatedType =
        resultsClassLoader.loadClass("com.example.PropertiesThatAreJavaKeywords");

    String valuesAsJsonString =
        "{\"public\":\"a\",\"void\":\"b\",\"enum\":\"c\",\"abstract\":\"d\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("public").asText(), is("a"));
    assertThat(valueAsJsonNode.path("void").asText(), is("b"));
    assertThat(valueAsJsonNode.path("enum").asText(), is("c"));
    assertThat(valueAsJsonNode.path("abstract").asText(), is("d"));
  }
Exemplo n.º 10
0
  @Test
  @SuppressWarnings("rawtypes")
  public void propertiesWithNullValuesAreOmittedWhenSerialized()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/nullProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.NullProperties");
    Object instance = generatedType.newInstance();

    Method setter = new PropertyDescriptor("property", generatedType).getWriteMethod();
    setter.invoke(instance, "value");

    assertThat(mapper.valueToTree(instance).toString(), containsString("property"));

    setter.invoke(instance, (Object) null);

    assertThat(mapper.valueToTree(instance).toString(), not(containsString("property")));
  }
 /**
  * 指定のクラスローダーからクラスをロードし、そのクラスのインスタンスを生成して返す。
  *
  * @param loader クラスローダー
  * @param name クラスの名前
  * @param arguments 引数の一覧
  * @return 生成したインスタンス
  */
 protected Object create(ClassLoader loader, Name name, Object... arguments) {
   try {
     Class<?> loaded = loader.loadClass(name.toNameString());
     for (Constructor<?> ctor : loaded.getConstructors()) {
       if (ctor.getParameterTypes().length == arguments.length) {
         return ctor.newInstance(arguments);
       }
     }
     throw new AssertionError();
   } catch (Exception e) {
     throw new AssertionError(e);
   }
 }
Exemplo n.º 12
0
  @Test
  @SuppressWarnings("rawtypes")
  public void propertiesAreSerializedInCorrectOrder()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/orderedProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.OrderedProperties");
    Object instance = generatedType.newInstance();

    new PropertyDescriptor("type", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("id", generatedType).getWriteMethod().invoke(instance, "2");
    new PropertyDescriptor("name", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("hastickets", generatedType).getWriteMethod().invoke(instance, true);
    new PropertyDescriptor("starttime", generatedType).getWriteMethod().invoke(instance, "4");

    String serialized = mapper.valueToTree(instance).toString();

    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("type"),
        is(lessThan(serialized.indexOf("id"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("id"),
        is(lessThan(serialized.indexOf("name"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("name"),
        is(lessThan(serialized.indexOf("hastickets"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("hastickets"),
        is(lessThan(serialized.indexOf("starttime"))));
  }
Exemplo n.º 13
0
  @Test
  @SuppressWarnings("rawtypes")
  public void usePrimitivesArgumentCausesPrimitiveTypes()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile(
            "/schema/properties/primitiveProperties.json",
            "com.example",
            config("usePrimitives", true));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    assertThat(
        new PropertyDescriptor("a", generatedType).getReadMethod().getReturnType().getName(),
        is("int"));
    assertThat(
        new PropertyDescriptor("b", generatedType).getReadMethod().getReturnType().getName(),
        is("double"));
    assertThat(
        new PropertyDescriptor("c", generatedType).getReadMethod().getReturnType().getName(),
        is("boolean"));
  }
Exemplo n.º 14
0
 @Test(expected = RuntimeException.class)
 public void say_invalid() {
   IHelloService target = new HelloValidationService();
   target.say(ClassLoader.getSystemResourceAsStream("hello-validation-invalid.xml"));
 }