示例#1
1
 public <T extends AbstractTask> T createTask(Class<T> type, Project project, String name) {
   Task task =
       TASK_FACTORY.createTask(
           (ProjectInternal) project, GUtil.map(Task.TASK_TYPE, type, Task.TASK_NAME, name));
   assertTrue(type.isAssignableFrom(task.getClass()));
   return type.cast(task);
 }
  @Test
  public void selfRefUsedInAPropertyIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = selfRefsClass.getMethod("getChildOfSelf").getReturnType();

    assertThat(aClass.getName(), is("com.example.SelfRefs"));
  }
  @Test
  public void refToFragmentOfAnotherSchemaIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfA").getReturnType();

    assertThat(aClass.getName(), is("com.example.AdditionalPropertyValue"));
  }
示例#4
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));
  }
  @Test
  public void detectsFindAllWithSortParameterOnSortingRepository() throws Exception {

    Class<RepositoryWithCustomSortingFindAll> type = RepositoryWithCustomSortingFindAll.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class));
    assertSaveMethodPresent(type, false);
  }
 @Test
 public void addPluginWithoutId() {
   Class<? extends Plugin> type = getPluginWithoutId().getClass();
   Plugin addedPlugin = addWithType(type);
   assertThat(getPluginWithoutId(), sameInstance(addedPlugin));
   assertThat(addedPlugin, sameInstance((Plugin) addWithType(type)));
   assertThat(addedPlugin, sameInstance(getPluginContainer().findByName(type.getName())));
 }
示例#7
0
 @Test
 public void testGetExceptionConstructorFindStringConstructor() {
   Constructor<?> constructor = new ExceptionFactory().getExceptionConstructor(Exception.class);
   assertThat(constructor, not(nullValue()));
   assertThat(constructor.getParameterTypes().length, equalTo(1));
   Class<?> parameterType = constructor.getParameterTypes()[0];
   assertThat(parameterType.equals(String.class), equalTo(true));
 }
  @Test
  public void stringToInt() throws Throwable {
    Method str_to_int = moduleClass.getMethod("str_to_int");
    assertThat((Integer) str_to_int.invoke(null), is(42));

    Method str_to_integer = moduleClass.getMethod("str_to_integer");
    assertThat((Integer) str_to_integer.invoke(null), is(42));
  }
  @Test
  public void stringFormat() throws Throwable {
    Method str_format1 = moduleClass.getMethod("str_format1");
    assertThat((String) str_format1.invoke(null), is("plop"));

    Method str_format2 = moduleClass.getMethod("str_format2");
    assertThat((String) str_format2.invoke(null), is("plop da plop"));
  }
  @Test
  public void refToFragmentOfSelfIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfSelf").getReturnType();

    assertThat(aClass.getName(), is("com.example.A"));
    assertThat(aClass.getMethods(), hasItemInArray(hasProperty("name", equalTo("getPropertyOfA"))));
  }
示例#11
0
  @Test
  public void selfRefUsedAsArrayItemsIsReadSuccessfully() throws NoSuchMethodException {

    Type listOfAType = selfRefsClass.getMethod("getArrayOfSelf").getGenericReturnType();
    Class<?> listEntryClass =
        (Class<?>) ((ParameterizedType) listOfAType).getActualTypeArguments()[0];

    assertThat(listEntryClass.getName(), is("com.example.SelfRefs"));
  }
  /** @see DATACMNS-393 */
  @Test
  public void detectsOverloadedMethodsCorrectly() throws Exception {

    Class<RepositoryWithAllCrudMethodOverloaded> type = RepositoryWithAllCrudMethodOverloaded.class;
    assertFindOneMethodOn(type, type.getDeclaredMethod("findOne", Long.class));
    assertDeleteMethodOn(type, type.getDeclaredMethod("delete", Long.class));
    assertSaveMethodOn(type, type.getDeclaredMethod("save", Domain.class));
    assertFindAllMethodOn(type, type.getDeclaredMethod("findAll"));
  }
  @Test
  public void detectsMethodsOnPagingAndSortingRepository() throws Exception {

    Class<DomainPagingAndSortingRepository> type = DomainPagingAndSortingRepository.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class));
    assertDeleteMethodOn(type, type.getMethod("delete", Serializable.class));
    assertSaveMethodPresent(type, true);
  }
  /**
   * input/output simple records.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void simple_record() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Simple");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Simple");
    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));

    object.set("sid", 1L);
    object.set("value", new Text("hello"));
    modelOut.write(object.unwrap());

    object.set("sid", 2L);
    object.set("value", new Text("world"));
    modelOut.write(object.unwrap());

    object.set("sid", 3L);
    object.set("value", null);
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Simple");

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 1L));
    assertThat(copy.get("value"), is((Object) new Text("hello")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 2L));
    assertThat(copy.get("value"), is((Object) new Text("world")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 3L));
    assertThat(copy.getOption("value").isNull(), is(true));

    assertThat(input.read(), is(-1));
    modelIn.close();
  }
 @Test
 public void hasAndFindForPluginWithoutId() {
   Plugin plugin = getPluginWithoutId();
   Class<? extends Plugin> pluginType = plugin.getClass();
   addWithType(pluginType);
   assertThat(getPluginContainer().hasPlugin(pluginType.getName()), equalTo(true));
   assertThat(getPluginContainer().hasPlugin(pluginType), equalTo(true));
   assertThat(getPluginContainer().findPlugin(pluginType), sameInstance(plugin));
   assertThat(getPluginContainer().findPlugin(pluginType.getName()), sameInstance(plugin));
 }
示例#16
0
  @Test
  public void selfRefUsedForAdditionalPropertiesIsReadSuccessfully() throws NoSuchMethodException {

    Type additionalPropertiesType =
        selfRefsClass.getMethod("getAdditionalProperties").getGenericReturnType();
    Class<?> mapEntryClass =
        (Class<?>) ((ParameterizedType) additionalPropertiesType).getActualTypeArguments()[1];

    assertThat(mapEntryClass.getName(), is("com.example.SelfRefs"));
  }
  @Test
  public void detectsMethodsOnCustomRepository() throws Exception {

    Class<RepositoryWithCustomSortingAndPagingFindAll> type =
        RepositoryWithCustomSortingAndPagingFindAll.class;
    assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class));

    Class<RepositoryWithIterableDeleteOnly> type1 = RepositoryWithIterableDeleteOnly.class;
    assertDeleteMethodOn(type1, type1.getMethod("delete", Iterable.class));
  }
  /** @see DATACMNS-393 */
  @Test
  public void selectsFindAllWithSortParameterOnRepositoryAmongUnsuitableAlternatives()
      throws Exception {

    Class<RepositoryWithInvalidPagingFallbackToSortFindAll> type =
        RepositoryWithInvalidPagingFallbackToSortFindAll.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class));
    assertSaveMethodPresent(type, false);
  }
示例#19
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"));
  }
示例#20
0
 @Test
 public void testGetCheckedConstructorReturnConstructor() {
   Constructor<?> constructor =
       new ExceptionFactory().getCheckedConstructor(Throwable.class, String.class);
   assertThat(constructor, not(nullValue()));
   Class<?> declaringClass = constructor.getDeclaringClass();
   assertThat(declaringClass.equals(Throwable.class), equalTo(true));
   assertThat(constructor.getParameterTypes().length, equalTo(1));
   Class<?> parameterType = constructor.getParameterTypes()[0];
   assertThat(parameterType.equals(String.class), equalTo(true));
 }
  @Test
  public void bindings() throws Throwable {
    Method lbind = moduleClass.getMethod("lbind");
    MethodHandle mh = (MethodHandle) lbind.invoke(null);
    Integer result = (Integer) mh.invokeWithArguments(2);
    assertThat(result, is(8));

    Method rbind = moduleClass.getMethod("rbind");
    mh = (MethodHandle) rbind.invoke(null);
    result = (Integer) mh.invokeWithArguments(2);
    assertThat(result, is(-8));
  }
 /**
  * 指定のクラスローダーからクラスをロードし、そのクラスのインスタンスを生成して返す。
  *
  * @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);
   }
 }
  @Test
  public void getMergedAnnotationAttributesWithAliasedValueComposedAnnotation() {
    Class<?> element = AliasedValueComposedContextConfigClass.class;
    String name = ContextConfig.class.getName();
    AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);

    assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes);
    assertArrayEquals("locations", asArray("test.xml"), attributes.getStringArray("locations"));
    assertArrayEquals("value", asArray("test.xml"), attributes.getStringArray("value"));

    // Verify contracts between utility methods:
    assertTrue(isAnnotated(element, name));
  }
  /**
   * all primitive types.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void primitives() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Primitives");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Primitives");

    object.set("type_boolean", true);
    object.set("type_byte", (byte) 64);
    object.set("type_short", (short) 256);
    object.set("type_int", 100);
    object.set("type_long", 200L);
    object.set("type_float", 300.f);
    object.set("type_double", 400.d);
    object.set("type_decimal", new BigDecimal("1234.567"));
    object.set("type_text", new Text("Hello, world!"));
    object.set("type_date", new Date(2011, 3, 31));
    object.set("type_datetime", new DateTime(2011, 3, 31, 23, 30, 1));

    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Primitives");
    modelIn.readTo(copy.unwrap());
    assertThat(object.unwrap(), equalTo(copy.unwrap()));
    assertThat(input.read(), is(-1));
    modelIn.close();
  }
示例#25
0
 private static Properties loadProperties(Class clazz, String resourcePath) throws IOException {
   InputStream is = clazz.getResourceAsStream(resourcePath);
   Properties prop = new Properties();
   prop.load(is);
   is.close();
   return prop;
 }
 @Test
 public void lists_reduce() throws Throwable {
   Method lists_reduce = moduleClass.getMethod("lists_reduce");
   Object result = lists_reduce.invoke(null);
   assertThat(result, instanceOf(Integer.class));
   assertThat((Integer) result, is(10));
 }
 @Test
 public void sets_each() throws Throwable {
   Method sets_each = moduleClass.getMethod("sets_each");
   Object result = sets_each.invoke(null);
   assertThat(result, instanceOf(Integer.class));
   assertThat((Integer) result, is(10));
 }
 @Test
 public void chaining() throws Throwable {
   Method chaining = moduleClass.getMethod("chaining");
   MethodHandle mh = (MethodHandle) chaining.invoke(null);
   Integer result = (Integer) mh.invokeWithArguments(4);
   assertThat(result, is(-500));
 }
 @Test
 public void method_handle_to() throws Throwable {
   Method method_handle_to = moduleClass.getMethod("method_handle_to");
   Object result = method_handle_to.invoke(null);
   assertThat(result, instanceOf(Callable.class));
   Callable<?> callable = (Callable<?>) result;
   assertThat((String) callable.call(), is("ok"));
 }
  @Test
  public void getMergedAnnotationWithImplicitAliasesInMetaAnnotationOnComposedAnnotation() {
    Class<?> element = ComposedImplicitAliasesContextConfigClass.class;
    String name = ImplicitAliasesContextConfig.class.getName();
    ImplicitAliasesContextConfig config =
        getMergedAnnotation(element, ImplicitAliasesContextConfig.class);
    String[] expected = asArray("A.xml", "B.xml");

    assertNotNull(
        "Should find @ImplicitAliasesContextConfig on " + element.getSimpleName(), config);
    assertArrayEquals("groovyScripts", expected, config.groovyScripts());
    assertArrayEquals("xmlFiles", expected, config.xmlFiles());
    assertArrayEquals("locations", expected, config.locations());
    assertArrayEquals("value", expected, config.value());

    // Verify contracts between utility methods:
    assertTrue(isAnnotated(element, name));
  }