@Override
  public void generateAngularGlobalEntity(GrailsDomainClass grailsDomainClass, String destDir)
      throws IOException {
    Assert.hasText(destDir, "Argument [destdir] not specified");

    /* Get global template list */
    File viewsDir = new File(destDir, "web-app/js/app");
    if (!viewsDir.exists()) {
      viewsDir.mkdirs();
    }

    for (String name : getTemplateNamesFromPath("js/entity")) {
      File viewsEntityDir =
          new File(viewsDir.getAbsolutePath() + "/" + grailsDomainClass.getPropertyName());
      if (!viewsEntityDir.exists()) {
        viewsEntityDir.mkdirs();
      }
      generateText(
          grailsDomainClass,
          name,
          viewsDir.getAbsolutePath() + "/" + grailsDomainClass.getPropertyName(),
          "js/entity",
          "js");
    }
  }
  public void testInsertableUpdateableHibernateMapping() throws Exception {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestInsertableUpdateableDomain {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String testString1 \n"
                    + "    String testString2 \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "       testString1 insertable:false, updateable:false \n"
                    + "       testString2 updateable:false, insertable:false \n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestInsertableUpdateableDomain");

    Property property1 = persistentClass.getProperty("testString1");
    assertEquals(false, property1.isInsertable());
    assertEquals(false, property1.isUpdateable());

    Property property2 = persistentClass.getProperty("testString2");
    assertEquals(false, property2.isUpdateable());
    assertEquals(false, property2.isInsertable());
  }
  public void testForeignKeyColumnBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    String description \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestManySide");

    Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
  public void generateView(GrailsDomainClass domainClass, String viewName, Writer out)
      throws IOException {
    String templateText =
        getTemplateTextView(
            viewName + ".gsp", "/WEB-INF/templates/angular-scaffolding/views/", "views");

    if (!StringUtils.hasLength(templateText)) {
      return;
    }

    GrailsDomainClassProperty multiPart = null;
    for (GrailsDomainClassProperty property : domainClass.getProperties()) {
      if (property.getType() == Byte[].class || property.getType() == byte[].class) {
        multiPart = property;
        break;
      }
    }

    String packageName =
        StringUtils.hasLength(domainClass.getPackageName())
            ? "<%@ page import=\"" + domainClass.getFullName() + "\" %>"
            : "";
    Map<String, Object> binding = createBinding(domainClass);
    binding.put("packageName", packageName);
    binding.put("multiPart", multiPart);
    binding.put("propertyName", getPropertyName(domainClass));

    generate(templateText, binding, out);
  }
  public void testDefaultNamingStrategy() {

    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String fooName \n"
                    + "    String barDescriPtion \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestOneSide");
    assertEquals("test_one_side", persistentClass.getTable().getName());

    Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next();
    assertEquals("foo_name", column.getName());

    column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next();
    assertEquals("bar_descri_ption", column.getName());

    persistentClass = config.getClassMapping("TestManySide");
    assertEquals("test_many_side", persistentClass.getTable().getName());

    column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
  public void testDomainClassBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "public class BinderTestClass {\n"
                    + "    Long id; \n"
                    + "    Long version; \n"
                    + "\n"
                    + "    String firstName; \n"
                    + "    String lastName; \n"
                    + "    String comment; \n"
                    + "    Integer age;\n"
                    + "    boolean active = true"
                    + "\n"
                    + "    static constraints = {\n"
                    + "        firstName(nullable:true,size:4..15)\n"
                    + "        lastName(nullable:false)\n"
                    + "        age(nullable:true)\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config = getDomainConfig(cl, cl.getLoadedClasses());

    // Test database mappings
    PersistentClass persistentClass = config.getClassMapping("BinderTestClass");
    assertTrue(
        "Property [firstName] must be optional in db mapping",
        persistentClass.getProperty("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be required in db mapping",
        persistentClass.getProperty("lastName").isOptional());
    // Property must be required by default
    assertFalse(
        "Property [comment] must be required in db mapping",
        persistentClass.getProperty("comment").isOptional());

    // Test properties
    assertTrue(
        "Property [firstName] must be optional",
        domainClass.getPropertyByName("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be optional",
        domainClass.getPropertyByName("lastName").isOptional());
    assertFalse(
        "Property [comment] must be required",
        domainClass.getPropertyByName("comment").isOptional());
    assertTrue(
        "Property [age] must be optional", domainClass.getPropertyByName("age").isOptional());
  }
  /* (non-Javadoc)
   * @see org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfiguration#addDomainClass(org.codehaus.groovy.grails.commons.GrailsDomainClass)
   */
  public GrailsDomainConfiguration addDomainClass(GrailsDomainClass domainClass) {
    if (domainClass.getMappingStrategy().equalsIgnoreCase(GrailsDomainClass.GORM)) {
      domainClasses.add(domainClass);
    }

    return this;
  }
 private Class<?> getReferencedTypeForCollection(String name, Object target) {
   final GrailsApplication grailsApplication = ApplicationHolder.getApplication();
   if (grailsApplication != null) {
     GrailsDomainClass dc =
         (GrailsDomainClass)
             grailsApplication.getArtefact(
                 DomainClassArtefactHandler.TYPE, target.getClass().getName());
     if (dc != null) {
       GrailsDomainClassProperty domainProperty = dc.getPropertyByName(name);
       if (domainProperty != null) {
         return domainProperty.getReferencedPropertyType();
       }
     }
   }
   return null;
 }
  public void generateViews(GrailsDomainClass domainClass, String destDir) throws IOException {
    Assert.hasText(destDir, "Argument [destdir] not specified");

    File viewsDir = new File(destDir, "web-app/partials/" + domainClass.getPropertyName());
    if (!viewsDir.exists()) {
      viewsDir.mkdirs();
    }

    for (String name : getTemplateNamesFromPath("views")) {
      if (log.isInfoEnabled()) {
        log.info(
            "Generating [" + name + "] view for domain class [" + domainClass.getFullName() + "]");
      }
      generateView(domainClass, name, viewsDir.getAbsolutePath());
    }
  }
  /** Overrides the default behaviour to including binding of Grails domain classes. */
  @Override
  protected void secondPassCompile() throws MappingException {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader originalContextLoader = currentThread.getContextClassLoader();
    if (!configLocked) {
      if (LOG.isDebugEnabled())
        LOG.debug(
            "[GrailsAnnotationConfiguration] ["
                + domainClasses.size()
                + "] Grails domain classes to bind to persistence runtime");

      // do Grails class configuration
      DefaultGrailsDomainConfiguration.configureDomainBinder(grailsApplication, domainClasses);

      for (GrailsDomainClass domainClass : domainClasses) {

        final String fullClassName = domainClass.getFullName();

        String hibernateConfig = fullClassName.replace('.', '/') + ".hbm.xml";
        final ClassLoader loader = originalContextLoader;
        // don't configure Hibernate mapped classes
        if (loader.getResource(hibernateConfig) != null) continue;

        final Mappings mappings = super.createMappings();
        if (!GrailsHibernateUtil.usesDatasource(domainClass, dataSourceName)) {
          continue;
        }

        LOG.debug(
            "[GrailsAnnotationConfiguration] Binding persistent class [" + fullClassName + "]");

        Mapping m = binder.getMapping(domainClass);
        mappings.setAutoImport(m == null || m.getAutoImport());
        binder.bindClass(domainClass, mappings, sessionFactoryBeanName);
      }
    }

    try {
      currentThread.setContextClassLoader(grailsApplication.getClassLoader());
      super.secondPassCompile();
      createSubclassForeignKeys();
    } finally {
      currentThread.setContextClassLoader(originalContextLoader);
    }

    configLocked = true;
  }
Beispiel #11
0
 /**
  * Returns the class type of the searchable property
  *
  * @param grailsDomainClass
  * @param propertyName
  * @param searchableGrailsDomainClasses
  * @return
  */
 public static Class getSearchablePropertyAssociatedClass(
     GrailsDomainClass grailsDomainClass,
     String propertyName,
     Collection searchableGrailsDomainClasses) {
   Assert.notNull(grailsDomainClass, "grailsDomainClass cannot be null");
   Assert.notNull(propertyName, "propertyName cannot be null");
   return getSearchablePropertyAssociatedClass(
       grailsDomainClass.getPropertyByName(propertyName), searchableGrailsDomainClasses);
 }
Beispiel #12
0
 /**
  * Is the given class an emebedded property of another domain class?
  *
  * @param grailsDomainClass the GrailsDomainClass to check as n embedded property
  * @param grailsDomainClasses all GrailsDomainClasses
  * @return true if the given class is an embedded property of another class
  */
 public static boolean isEmbeddedPropertyOfOtherDomainClass(
     GrailsDomainClass grailsDomainClass, Collection grailsDomainClasses) {
   for (Iterator iter = grailsDomainClasses.iterator(); iter.hasNext(); ) {
     GrailsDomainClass other = (GrailsDomainClass) iter.next();
     if (grailsDomainClass == other) {
       continue;
     }
     GrailsDomainClassProperty[] domainClassProperties = other.getProperties();
     for (int i = 0; i < domainClassProperties.length; i++) {
       GrailsDomainClass referencedDomainClass =
           domainClassProperties[i].getReferencedDomainClass();
       if (referencedDomainClass != null
           && referencedDomainClass == grailsDomainClass
           && domainClassProperties[i].isEmbedded()) {
         return true;
       }
     }
   }
   return false;
 }
  /*
   * Test method for 'org.codehaus.groovy.grails.validation.metaclass.ConstraintsDynamicProperty.get(Object)'
   */
  @SuppressWarnings("rawtypes")
  public void testGet() throws Exception {
    GroovyClassLoader gcl = new GroovyClassLoader();
    Class<?> groovyClass =
        gcl.parseClass(
            "package org.codehaus.groovy.grails.validation\n"
                + "class Test {\n"
                + "   Long id\n"
                + // WE NEED this even though GORM 2 doesn't, as we're not a "domain" class within
                  // grails-app
                "   Long version\n"
                + // WE NEED this even though GORM 2 doesn't, as we're not a "domain" class within
                  // grails-app
                " String name\n"
                + "}");

    GrailsDomainClass domainClass = new DefaultGrailsDomainClass(groovyClass);

    Map constraints = domainClass.getConstrainedProperties();

    assertNotNull(constraints);
    assertFalse(constraints.isEmpty());
  }
  @SuppressWarnings("deprecation")
  protected Map<String, Object> createBinding(GrailsDomainClass domainClass) {
    boolean hasHibernate =
        pluginManager.hasGrailsPlugin("hibernate") || pluginManager.hasGrailsPlugin("hibernate4");

    Map<String, Object> binding = new HashMap<String, Object>();
    binding.put("pluginManager", pluginManager);
    binding.put("domainClass", domainClass);
    binding.put("className", domainClass.getShortName());
    binding.put("renderEditor", getRenderEditor());
    binding.put("applicationName", grailsApplication.getMetadata().get("app.name"));
    binding.put(
        "comparator",
        hasHibernate
            ? DomainClassPropertyComparator.class
            : SimpleDomainClassPropertyComparator.class);
    return binding;
  }
 @SuppressWarnings("unchecked")
 private Map resolveConstrainedProperties(Object object, GrailsDomainClass dc) {
   Map constrainedProperties = null;
   if (dc != null) {
     constrainedProperties = dc.getConstrainedProperties();
   } else {
     // is this dead code? , didn't remove in case it's used somewhere
     MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
     MetaProperty metaProp = mc.getMetaProperty(CONSTRAINTS_PROPERTY);
     if (metaProp != null) {
       Object constrainedPropsObj = getMetaPropertyValue(metaProp, object);
       if (constrainedPropsObj instanceof Map) {
         constrainedProperties = (Map) constrainedPropsObj;
       }
     }
   }
   return constrainedProperties;
 }
  public void initialize() {
    if (domainClass.getIdentifier() != null) {
      identifier = new GrailsDomainClassPersistentProperty(this, domainClass.getIdentifier());
      propertiesByName.put(identifier.getName(), identifier);
    }
    if (domainClass.getVersion() != null) {
      version = new GrailsDomainClassPersistentProperty(this, domainClass.getVersion());
      propertiesByName.put(version.getName(), version);
    }

    mappingContext.addEntityValidator(this, domainClass.getValidator());

    final GrailsDomainClassProperty[] persistentProperties = domainClass.getPersistentProperties();
    for (GrailsDomainClassProperty grailsDomainClassProperty : persistentProperties) {
      PersistentProperty persistentProperty;
      if (grailsDomainClassProperty.isAssociation()) {
        if (grailsDomainClassProperty.isEmbedded()) {
          persistentProperty = createEmbedded(mappingContext, grailsDomainClassProperty);
        } else if (grailsDomainClassProperty.isOneToMany()) {
          persistentProperty = createOneToMany(mappingContext, grailsDomainClassProperty);
        } else if (grailsDomainClassProperty.isHasOne()) {
          persistentProperty = createOneToOne(mappingContext, grailsDomainClassProperty);
        } else if (grailsDomainClassProperty.isOneToOne()) {
          persistentProperty = createOneToOne(mappingContext, grailsDomainClassProperty);
        } else if (grailsDomainClassProperty.isManyToOne()) {
          persistentProperty = createManyToOne(mappingContext, grailsDomainClassProperty);
        } else if (grailsDomainClassProperty.isManyToMany()) {
          persistentProperty = createManyToMany(mappingContext, grailsDomainClassProperty);
        } else {
          persistentProperty =
              new GrailsDomainClassPersistentProperty(this, grailsDomainClassProperty);
        }
      } else if (grailsDomainClassProperty.isBasicCollectionType()) {
        persistentProperty = createBasicCollection(mappingContext, grailsDomainClassProperty);
      } else {
        persistentProperty =
            new GrailsDomainClassPersistentProperty(this, grailsDomainClassProperty);
      }
      propertiesByName.put(grailsDomainClassProperty.getName(), persistentProperty);
      properties.add(persistentProperty);

      if (persistentProperty instanceof Association) {
        associations.add((Association) persistentProperty);
      }
    }
    initialized = true;
  }
 public boolean isInstance(Object obj) {
   return domainClass.getClazz().isInstance(obj);
 }
 public Class getJavaClass() {
   return domainClass.getClazz();
 }
 public String getName() {
   return domainClass.getFullName();
 }
  public void testCustomNamingStrategy() throws Exception {

    // somewhat artificial in that it doesn't test that setting the property
    // in DataSource.groovy works, but that's handled in DataSourceConfigurationTests
    GrailsDomainBinder.configureNamingStrategy(CustomNamingStrategy.class);

    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String fooName \n"
                    + "    String barDescriPtion \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestOneSide");
    assertEquals("table_TestOneSide", persistentClass.getTable().getName());

    Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("col_id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("col_version", column.getName());

    column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next();
    assertEquals("col_fooName", column.getName());

    column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next();
    assertEquals("col_barDescriPtion", column.getName());

    persistentClass = config.getClassMapping("TestManySide");
    assertEquals("table_TestManySide", persistentClass.getTable().getName());

    column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("col_id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("col_version", column.getName());

    column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
 public boolean hasProperty(String name, Class type) {
   return domainClass.hasProperty(name);
 }
 public boolean isOwningEntity(PersistentEntity owner) {
   return domainClass.isOwningClass(owner.getJavaClass());
 }
 public Object newInstance() {
   return domainClass.newInstance();
 }
 protected String getPropertyName(GrailsDomainClass domainClass) {
   return domainClass.getPropertyName() + domainSuffix;
 }
 public String getDecapitalizedName() {
   return domainClass.getLogicalPropertyName();
 }
 private boolean shouldMapWithGorm(GrailsDomainClass domainClass) {
   return !AnnotationDomainClassArtefactHandler.isJPADomainClass(domainClass.getClazz())
       && domainClass.getMappingStrategy().equalsIgnoreCase(GrailsDomainClass.GORM);
 }
 public boolean isRoot() {
   return domainClass.isRoot();
 }
Beispiel #28
0
 /**
  * Get the given domain class's searchable property value, if any
  *
  * @param grailsDomainClass the Grails domain class
  * @return the searchable property value, or null
  */
 public static Object getSearchablePropertyValue(GrailsDomainClass grailsDomainClass) {
   return GrailsClassUtils.getStaticPropertyValue(
       grailsDomainClass.getClazz(), SEARCHABLE_PROPERTY_NAME);
 }
 public boolean isIdentityName(String propertyName) {
   return domainClass.getIdentifier().getName().equals(propertyName);
 }
 /**
  * Is the given GrailsDomainClass a root mapped class in Compass
  *
  * @param domainClass the GrailsDomainClass
  * @param compass Compass
  * @return true if there is a root mapping for the class in Compass
  */
 public static boolean isRootMappedClass(GrailsDomainClass domainClass, Compass compass) {
   return ((InternalCompass) compass).getMapping().getRootMappingByClass(domainClass.getClazz())
       != null;
 }