Search in sources :

Example 16 with ClassData

use of org.motechproject.mds.domain.ClassData in project motech by motech.

the class JarGeneratorServiceImpl method generate.

@Override
public File generate(SchemaHolder schemaHolder) throws IOException {
    Path tempDir = Files.createTempDirectory("mds");
    Path tempFile = Files.createTempFile(tempDir, "mds-entities", ".jar");
    java.util.jar.Manifest manifest = createManifest();
    StringBuilder entityNamesSb = new StringBuilder();
    StringBuilder historyEntitySb = new StringBuilder();
    try (FileOutputStream fileOutput = new FileOutputStream(tempFile.toFile());
        JarOutputStream output = new JarOutputStream(fileOutput, manifest)) {
        List<EntityInfo> information = new ArrayList<>();
        for (ClassData classData : MotechClassPool.getEnhancedClasses(false)) {
            String className = classData.getClassName();
            // insert entity class, only for EUDE, note that this can also be a generated enum class
            if (!classData.isDDE()) {
                addEntry(output, JavassistUtil.toClassPath(className), classData.getBytecode());
            }
            // insert history and trash classes, these classes will not be present for enums
            ClassData historyClassData = MotechClassPool.getHistoryClassData(className);
            if (historyClassData != null) {
                addEntry(output, JavassistUtil.toClassPath(historyClassData.getClassName()), historyClassData.getBytecode());
                historyEntitySb.append(className).append('\n');
            }
            ClassData trashClassData = MotechClassPool.getTrashClassData(className);
            if (trashClassData != null) {
                addEntry(output, JavassistUtil.toClassPath(trashClassData.getClassName()), trashClassData.getBytecode());
            }
            if (!classData.isEnumClassData()) {
                EntityDto entity = schemaHolder.getEntityByClassName(classData.getClassName());
                List<FieldDto> fields = schemaHolder.getFields(entity);
                AdvancedSettingsDto advancedSettings = schemaHolder.getAdvancedSettings(entity);
                EntityInfo info = buildEntityInfo(entity, fields, advancedSettings);
                // we keep the name to construct a file containing all entity names
                // the file is required for schema generation
                entityNamesSb.append(className).append('\n');
                // insert repository
                String repositoryName = MotechClassPool.getRepositoryName(className);
                if (addClass(output, repositoryName)) {
                    info.setRepository(repositoryName);
                }
                // insert service implementation
                String serviceClass = MotechClassPool.getServiceImplName(className);
                if (addClass(output, serviceClass)) {
                    info.setServiceClass(serviceClass);
                    info.setServiceName(ClassName.getServiceName(className));
                }
                // insert the interface
                String interfaceName = MotechClassPool.getInterfaceName(className);
                if (MotechClassPool.isServiceInterfaceRegistered(className)) {
                    // we import the service interface
                    info.setInterfaceName(interfaceName);
                } else {
                    // we generated the service interface from scratch and include it in the bundle
                    if (addClass(output, interfaceName)) {
                        info.setInterfaceName(interfaceName);
                    }
                }
                information.add(info);
            }
        }
        String blueprint = mergeTemplate(information, BLUEPRINT_TEMPLATE);
        String context = mergeTemplate(information, MDS_ENTITIES_CONTEXT_TEMPLATE);
        String channel = mergeTemplate(information, MDS_CHANNEL_TEMPLATE);
        jdoListenerRegistryService.updateEntityNames();
        jdoListenerRegistryService.removeInactiveListeners(entityNamesSb.toString());
        String entityWithListenersNames = jdoListenerRegistryService.getEntitiesListenerStr();
        addEntries(output, blueprint, context, channel, entityNamesSb.toString(), historyEntitySb.toString(), entityWithListenersNames);
        addEntityInfoFiles(output, information);
        return tempFile.toFile();
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) JarOutputStream(java.util.jar.JarOutputStream) EntityDto(org.motechproject.mds.dto.EntityDto) ClassData(org.motechproject.mds.domain.ClassData) EntityInfo(org.motechproject.mds.entityinfo.EntityInfo) FileOutputStream(java.io.FileOutputStream) AdvancedSettingsDto(org.motechproject.mds.dto.AdvancedSettingsDto) FieldDto(org.motechproject.mds.dto.FieldDto)

Example 17 with ClassData

use of org.motechproject.mds.domain.ClassData in project motech by motech.

the class JarGeneratorServiceImpl method getImports.

private String getImports() throws IOException {
    // first load the standard imports
    String stdImports = loadResourceAsString(BUNDLE_IMPORTS).replaceAll("\\r|\\n", "");
    // we want to prevent duplicate imports
    StringBuilder sb = new StringBuilder(stdImports);
    Set<String> alreadyImported = new HashSet<>();
    Collections.addAll(alreadyImported, split(stdImports, ","));
    // add imports for DDE classes
    for (ClassData classData : MotechClassPool.getEnhancedClasses(true)) {
        if (classData.isDDE()) {
            String pkg = ClassName.getPackage(classData.getClassName());
            if (!alreadyImported.contains(pkg)) {
                sb.append(',').append(pkg);
                alreadyImported.add(pkg);
            }
        }
    }
    for (String enumName : MotechClassPool.registeredEnums()) {
        String pkg = ClassName.getPackage(enumName);
        if (!alreadyImported.contains(pkg)) {
            sb.append(',').append(pkg);
            alreadyImported.add(pkg);
        }
    }
    return sb.toString();
}
Also used : ClassData(org.motechproject.mds.domain.ClassData) HashSet(java.util.HashSet)

Example 18 with ClassData

use of org.motechproject.mds.domain.ClassData in project motech by motech.

the class JarGeneratorServiceImpl method getExports.

private String getExports() {
    Set<String> exports = new HashSet<>();
    exports.add(PackagesGenerated.ENTITY);
    exports.add(PackagesGenerated.SERVICE);
    for (ClassData enhancedClass : MotechClassPool.getEnhancedClasses(false)) {
        if (enhancedClass.isEnumClassData()) {
            String pkg = ClassName.getPackage(enhancedClass.getClassName());
            exports.add(pkg);
        }
        if (!MotechClassPool.isServiceInterfaceRegistered(enhancedClass.getClassName()) && enhancedClass.isDDE()) {
            String pkg = ClassName.getPackage(enhancedClass.getClassName()).concat(".mdsservice");
            exports.add(pkg);
        }
    }
    return createExportPackage(exports);
}
Also used : ClassData(org.motechproject.mds.domain.ClassData) HashSet(java.util.HashSet)

Example 19 with ClassData

use of org.motechproject.mds.domain.ClassData in project motech by motech.

the class EntityBuilderTest method shouldNotAddVersionFieldToTheHistoryClass.

@Test(expected = NoSuchFieldException.class)
public void shouldNotAddVersionFieldToTheHistoryClass() throws Exception {
    FieldDto versionField = fieldDto("version", Long.class);
    versionField.addMetadata(new MetadataDto(Constants.MetadataKeys.VERSION_FIELD, "true"));
    fields.addAll(asList(fieldDto("id", Long.class), versionField, fieldDto("count", Integer.class), fieldDto("str", String.class)));
    ClassData classData = entityBuilder.buildHistory(entity, fields);
    assertEquals("xx.yy.history.BuilderTest__History", classData.getClassName());
    Class<?> clazz = mdsClassLoader.safeDefineClass(classData.getClassName(), classData.getBytecode());
    assertNotNull(clazz);
    try {
        assertField(clazz, "id", Long.class);
        assertField(clazz, "count", Integer.class);
        assertField(clazz, "str", String.class);
    } catch (NoSuchFieldException e) {
        LOGGER.error("Cannot find field in the history class", e);
        fail();
    }
    assertField(clazz, "version", Long.class);
}
Also used : ClassData(org.motechproject.mds.domain.ClassData) MetadataDto(org.motechproject.mds.dto.MetadataDto) FieldDto(org.motechproject.mds.dto.FieldDto) Test(org.junit.Test)

Example 20 with ClassData

use of org.motechproject.mds.domain.ClassData in project motech by motech.

the class EntityBuilderTest method shouldBuildEnhancedDDE.

@Test
public void shouldBuildEnhancedDDE() throws Exception {
    FieldDto strField = fieldDto("testStr", String.class);
    FieldDto boolField = fieldDto("testBool", Boolean.class);
    strField.setReadOnly(true);
    boolField.setReadOnly(true);
    fields.addAll(asList(strField, boolField, fieldDto("fromUser", DateTime.class)));
    when(entity.getClassName()).thenReturn(EntBuilderTestClass.class.getName());
    ClassData classData = entityBuilder.buildDDE(entity, fields, bundle);
    Class<?> builtClass = MDSClassLoader.getStandaloneInstance().defineClass(classData.getClassName(), classData.getBytecode());
    assertField(builtClass, "testStr", String.class, "defValForTestStr");
    assertField(builtClass, "testBool", boolean.class, false, "is");
    assertField(builtClass, "fromUser", DateTime.class);
    // check annotations
    assertNotNull(builtClass.getAnnotation(PersistenceCapable.class));
    java.lang.reflect.Field field = builtClass.getDeclaredField("testStr");
    assertNotNull(field.getAnnotation(Unique.class));
}
Also used : EntBuilderTestClass(org.motechproject.mds.testutil.EntBuilderTestClass) ClassData(org.motechproject.mds.domain.ClassData) PersistenceCapable(javax.jdo.annotations.PersistenceCapable) Unique(javax.jdo.annotations.Unique) FieldDto(org.motechproject.mds.dto.FieldDto) Test(org.junit.Test)

Aggregations

ClassData (org.motechproject.mds.domain.ClassData)28 Test (org.junit.Test)9 FieldDto (org.motechproject.mds.dto.FieldDto)7 CtClass (javassist.CtClass)6 ArrayList (java.util.ArrayList)5 EntityDto (org.motechproject.mds.dto.EntityDto)5 IOException (java.io.IOException)4 CannotCompileException (javassist.CannotCompileException)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 HashSet (java.util.HashSet)2 ByteArrayClassPath (javassist.ByteArrayClassPath)2 ComboboxHolder (org.motechproject.mds.domain.ComboboxHolder)2 MetadataDto (org.motechproject.mds.dto.MetadataDto)2 TypeDto (org.motechproject.mds.dto.TypeDto)2 EntityCreationException (org.motechproject.mds.exception.entity.EntityCreationException)2 EntBuilderTestClass (org.motechproject.mds.testutil.EntBuilderTestClass)2 MDSClassLoader (org.motechproject.mds.util.MDSClassLoader)2 Bundle (org.osgi.framework.Bundle)2 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1