Search in sources :

Example 1 with JDOEnhancer

use of javax.jdo.JDOEnhancer in project tests by datanucleus.

the class DynamicEnhanceSchemaToolTest method testEnhance.

public void testEnhance() throws Exception {
    // Create an in-memory class
    String className = "test.Client";
    NucleusLogger.PERSISTENCE.info(">> Creating class in-memory");
    byte[] classBytes = createClass(className);
    // Add it to a CustomClassLoader
    DynamicEnhanceSchemaToolClassLoader workCL = new DynamicEnhanceSchemaToolClassLoader(Thread.currentThread().getContextClassLoader());
    workCL.defineClass("test.Client", classBytes);
    // Write the class to disk (debugging)
    NucleusLogger.PERSISTENCE.info(">> Writing in-memory class to target/generated/Client.class");
    File file = new File("target/generated");
    if (!file.exists()) {
        file.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream("target/generated/Client.class");
    fos.write(classBytes);
    fos.close();
    // Create an enhancer (JDO, ASM)
    JDOEnhancer enhancer = JDOHelper.getEnhancer();
    enhancer.setClassLoader(workCL);
    // Create MetaData for the in-memory class and register it with the enhancer
    JDOMetadata jdomd = enhancer.newMetadata();
    createMetadata(jdomd);
    enhancer.registerMetadata(jdomd);
    enhancer.addClass(className, classBytes);
    // Enhance the in-memory bytes and obtain the enhanced bytes
    NucleusLogger.PERSISTENCE.info(">> Enhancing test.Client inmemory bytes");
    enhancer.enhance();
    byte[] enhancedBytes = enhancer.getEnhancedBytes(className);
    // Write the enhanced class to disk (debugging)
    NucleusLogger.PERSISTENCE.info(">> Writing enhanced in-memory class to target/enhancedClient.class");
    file = new File("target/enhanced");
    if (!file.exists()) {
        file.mkdirs();
    }
    fos = new FileOutputStream("target/enhanced/Client.class");
    fos.write(enhancedBytes);
    fos.close();
    // Create our runtime class loader, and load the enhanced class into it
    DynamicEnhanceSchemaToolClassLoader runtimeCL = new DynamicEnhanceSchemaToolClassLoader(Thread.currentThread().getContextClassLoader());
    runtimeCL.defineClass(className, enhancedBytes);
    // SchemaTool
    NucleusLogger.PERSISTENCE.info(">> Schema creation for dynamic type");
    schemaCreate(runtimeCL);
    // Persist an object of the new type
    NucleusLogger.PERSISTENCE.info(">> Persisting an object of dynamic type");
    persist(runtimeCL);
}
Also used : JDOEnhancer(javax.jdo.JDOEnhancer) FileOutputStream(java.io.FileOutputStream) JDOMetadata(javax.jdo.metadata.JDOMetadata) File(java.io.File)

Aggregations

File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 JDOEnhancer (javax.jdo.JDOEnhancer)1 JDOMetadata (javax.jdo.metadata.JDOMetadata)1