Search in sources :

Example 1 with JavaCodeBase

use of com.manydesigns.portofino.code.JavaCodeBase in project Portofino by ManyDesigns.

the class SessionFactoryBuilder method buildSessionFactory.

public SessionFactoryAndCodeBase buildSessionFactory(FileObject root) throws Exception {
    List<Table> mappableTables = database.getAllTables();
    mappableTables.removeIf(this::checkInvalidPrimaryKey);
    List<Table> externallyMappedTables = mappableTables.stream().filter(t -> {
        boolean externallyMapped = t.getActualJavaClass() != null;
        if (externallyMapped) {
            logger.debug("Skipping table explicitly mapped with {}", t.getActualJavaClass());
        }
        return externallyMapped;
    }).collect(Collectors.toList());
    mappableTables.removeAll(externallyMappedTables);
    // Use a new classloader as scratch space for Javassist
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader scratchClassLoader = new URLClassLoader(new URL[0], contextClassLoader);
    Thread.currentThread().setContextClassLoader(scratchClassLoader);
    try {
        CtClass baseClass = generateBaseClass();
        FileObject databaseDir = root.resolveFile(database.getDatabaseName());
        databaseDir.deleteAll();
        databaseDir.createFolder();
        FileObject baseClassFile = databaseDir.resolveFile("BaseEntity.class");
        try (OutputStream outputStream = baseClassFile.getContent().getOutputStream()) {
            outputStream.write(baseClass.toBytecode());
        }
        for (Table table : mappableTables) {
            generateClass(table);
        }
        for (Table table : mappableTables) {
            mapRelationships(table);
        }
        for (Table table : mappableTables) {
            byte[] classFile = getClassFile(table);
            FileObject location = getEntityLocation(root, table);
            try (OutputStream outputStream = location.getContent().getOutputStream()) {
                outputStream.write(classFile);
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
    return buildSessionFactory(new JavaCodeBase(root), mappableTables, externallyMappedTables);
}
Also used : ConstPool(javassist.bytecode.ConstPool) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) SequenceGenerator(com.manydesigns.portofino.model.database.SequenceGenerator) TableGenerator(com.manydesigns.portofino.model.database.TableGenerator) URLClassLoader(java.net.URLClassLoader) PersistentClass(org.hibernate.mapping.PersistentClass) Column(com.manydesigns.portofino.model.database.Column) MultiTenancyImplementation(com.manydesigns.portofino.persistence.hibernate.multitenancy.MultiTenancyImplementation) Method(java.lang.reflect.Method) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) javassist(javassist) Immutable(org.hibernate.annotations.Immutable) PersistentDateTime(org.jadira.usertype.dateandtime.joda.PersistentDateTime) FileSystemException(org.apache.commons.vfs2.FileSystemException) Collectors(java.util.stream.Collectors) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase) MetadataSources(org.hibernate.boot.MetadataSources) Serializable(java.io.Serializable) Nullable(org.jetbrains.annotations.Nullable) ForeignKey(com.manydesigns.portofino.model.database.ForeignKey) javassist.bytecode.annotation(javassist.bytecode.annotation) FileName(org.apache.commons.vfs2.FileName) Modifier(java.lang.reflect.Modifier) NotNull(org.jetbrains.annotations.NotNull) TypeDefs(org.hibernate.annotations.TypeDefs) Types(java.sql.Types) BootstrapServiceRegistryBuilder(org.hibernate.boot.registry.BootstrapServiceRegistryBuilder) java.util(java.util) javax.persistence(javax.persistence) AvailableSettings(org.hibernate.cfg.AvailableSettings) CodeBase(com.manydesigns.portofino.code.CodeBase) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) VFS(org.apache.commons.vfs2.VFS) Table(com.manydesigns.portofino.model.database.Table) OutputStream(java.io.OutputStream) Updatable(com.manydesigns.elements.annotations.Updatable) Logger(org.slf4j.Logger) ClassFile(javassist.bytecode.ClassFile) EntityMode(org.hibernate.EntityMode) ClassLoaderServiceImpl(org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl) MultiTenancyStrategy(org.hibernate.MultiTenancyStrategy) BootstrapServiceRegistry(org.hibernate.boot.registry.BootstrapServiceRegistry) DateTime(org.joda.time.DateTime) DatabasePlatform(com.manydesigns.portofino.model.database.platforms.DatabasePlatform) IOException(java.io.IOException) com.manydesigns.portofino.model.database(com.manydesigns.portofino.model.database) FileObject(org.apache.commons.vfs2.FileObject) GenericGenerator(org.hibernate.annotations.GenericGenerator) ServiceRegistry(org.hibernate.service.ServiceRegistry) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) Configuration(org.apache.commons.configuration2.Configuration) MetadataBuilder(org.hibernate.boot.MetadataBuilder) Component(org.hibernate.mapping.Component) TypeDef(org.hibernate.annotations.TypeDef) Table(com.manydesigns.portofino.model.database.Table) URLClassLoader(java.net.URLClassLoader) OutputStream(java.io.OutputStream) URLClassLoader(java.net.URLClassLoader) FileObject(org.apache.commons.vfs2.FileObject) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase)

Example 2 with JavaCodeBase

use of com.manydesigns.portofino.code.JavaCodeBase in project Portofino by ManyDesigns.

the class JavaResourceResolver method resolveJavaFile.

protected Class resolveJavaFile(final FileObject fileObject) throws ClassNotFoundException, IOException {
    try {
        JavaType<?> result = Roaster.parse(fileObject.getContent().getInputStream());
        String className = result.getQualifiedName();
        return new JavaCodeBase(fileObject.getParent(), codeBase).loadJavaFile(fileObject, className);
    } finally {
        fileObject.close();
    }
}
Also used : JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase)

Example 3 with JavaCodeBase

use of com.manydesigns.portofino.code.JavaCodeBase in project Portofino by ManyDesigns.

the class DispatcherInitializer method createCodeBase.

protected CodeBase createCodeBase() throws IOException {
    // TODO auto discovery?
    FileObject codeBaseRoot = getCodeBaseRoot();
    JavaCodeBase javaCodeBase = new JavaCodeBase(codeBaseRoot, null, getClass().getClassLoader());
    CodeBase codeBase = javaCodeBase;
    try {
        Class<?> gcb = Class.forName("com.manydesigns.portofino.code.GroovyCodeBase");
        Constructor<?> gcbConstructor = gcb.getConstructor(FileObject.class, CodeBase.class);
        codeBase = (CodeBase) gcbConstructor.newInstance(codeBaseRoot, javaCodeBase);
        logger.info("Groovy is available");
    } catch (Exception e) {
        logger.debug("Groovy not available", e);
    }
    return codeBase;
}
Also used : FileObject(org.apache.commons.vfs2.FileObject) CodeBase(com.manydesigns.portofino.code.CodeBase) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase) FileSystemException(org.apache.commons.vfs2.FileSystemException) IOException(java.io.IOException) ConfigurationException(org.apache.commons.configuration2.ex.ConfigurationException) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase)

Example 4 with JavaCodeBase

use of com.manydesigns.portofino.code.JavaCodeBase in project Portofino by ManyDesigns.

the class TestJavaResourceResolver method testCodebase.

@Test
public void testCodebase() throws Exception {
    ResourceResolver resourceResolver = getResourceResolver(new JavaCodeBase(VFS.getManager().resolveFile("res:java-codebase")));
    FileObject root = getRoot();
    // A.java
    Class<?> c = resourceResolver.resolve(root.resolveFile("codebase"), Class.class);
    assertEquals("Test", c.getName());
    Field string = c.getField("string");
    Object a = c.newInstance();
    assertEquals("it works!", string.get(a));
}
Also used : Field(java.lang.reflect.Field) JavaResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.JavaResourceResolver) FileObject(org.apache.commons.vfs2.FileObject) FileObject(org.apache.commons.vfs2.FileObject) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase) Test(org.testng.annotations.Test)

Example 5 with JavaCodeBase

use of com.manydesigns.portofino.code.JavaCodeBase in project Portofino by ManyDesigns.

the class GrizzlyMain method main.

public static void main(String[] args) throws Exception {
    File currentDirectory = new File("");
    FileSystemManager manager = VFS.getManager();
    if (manager instanceof DefaultFileSystemManager) {
        ((DefaultFileSystemManager) manager).setBaseFile(currentDirectory);
    }
    String rootPath = currentDirectory.getAbsolutePath();
    if (args.length > 0) {
        rootPath = args[0];
    }
    FileObject codeBaseRoot;
    try {
        codeBaseRoot = VFS.getManager().resolveFile("res:");
    } catch (Exception e) {
        codeBaseRoot = VFS.getManager().resolveFile("res:com/manydesigns/portofino/dispatcher/main/GrizzlyMain.class").getParent().getParent().getParent().getParent().getParent().getParent();
    }
    CodeBase codeBase = new JavaCodeBase(codeBaseRoot);
    codeBase = new GroovyCodeBase(codeBaseRoot, codeBase);
    ResourceResolvers resourceResolver = new ResourceResolvers();
    resourceResolver.resourceResolvers.add(new JavaResourceResolver(codeBase));
    resourceResolver.resourceResolvers.add(new GroovyResourceResolver(codeBase));
    FileObject root = manager.resolveFile(rootPath);
    logger.info("Codebase rootFactory: " + codeBaseRoot.getURL());
    logger.info("Root path: " + root.getURL());
    DocumentedApiRoot.setRootFactory(() -> Root.get(root, resourceResolver));
    String host = System.getProperty("portofino.web.host", "0.0.0.0");
    String port = System.getProperty("portofino.web.port", "8090");
    ResourceConfig config = new ResourceConfig(ApplicationRoot.class, OpenApiResource.class);
    config.property(ServletProperties.FILTER_FORWARD_ON_404, true);
    try {
        config.register(Class.forName("org.glassfish.jersey.jackson.JacksonFeature"));
        ResourceResolver jacksonRR = (ResourceResolver) Class.forName("com.manydesigns.portofino.dispatcher.resolvers.JacksonResourceResolver").newInstance();
        resourceResolver.resourceResolvers.add(new CachingResourceResolver(jacksonRR));
    } catch (ClassNotFoundException e) {
    // Jackson not available
    }
    try {
        config.register(Class.forName("com.manydesigns.portofino.dispatcher.security.ShiroResourceFilter"));
    } catch (ClassNotFoundException e) {
    // Shiro not available
    }
    /* TODO
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setSchemes(new String[]{"http"});
        beanConfig.setHost(host + ":" + port);
        beanConfig.setBasePath("/");
        beanConfig.setResourcePackage(ApplicationRoot.class.getPackage().getName());
        beanConfig.setScan(true);*/
    URI uri = URI.create("http://" + host + ":" + port + "/");
    HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, config);
    // https://scalajamsession.wordpress.com/2015/06/27/how-to-serve-static-files-with-jerseygrizzly-setup-and-control-access-to-static-content/
    ClassLoader loader = GrizzlyMain.class.getClassLoader();
    CLStaticHttpHandler webjarsHandler = new CLStaticHttpHandler(loader, "META-INF/resources/webjars/");
    httpServer.getServerConfiguration().addHttpHandler(webjarsHandler, "/webjars/");
    httpServer.start();
}
Also used : CLStaticHttpHandler(org.glassfish.grizzly.http.server.CLStaticHttpHandler) ResourceResolvers(com.manydesigns.portofino.dispatcher.resolvers.ResourceResolvers) JavaResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.JavaResourceResolver) CodeBase(com.manydesigns.portofino.code.CodeBase) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase) GroovyCodeBase(com.manydesigns.portofino.code.GroovyCodeBase) DefaultFileSystemManager(org.apache.commons.vfs2.impl.DefaultFileSystemManager) FileSystemManager(org.apache.commons.vfs2.FileSystemManager) URI(java.net.URI) CachingResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.CachingResourceResolver) GroovyResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.GroovyResourceResolver) GroovyCodeBase(com.manydesigns.portofino.code.GroovyCodeBase) ResourceResolver(com.manydesigns.portofino.dispatcher.ResourceResolver) GroovyResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.GroovyResourceResolver) CachingResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.CachingResourceResolver) JavaResourceResolver(com.manydesigns.portofino.dispatcher.resolvers.JavaResourceResolver) HttpServer(org.glassfish.grizzly.http.server.HttpServer) DefaultFileSystemManager(org.apache.commons.vfs2.impl.DefaultFileSystemManager) FileObject(org.apache.commons.vfs2.FileObject) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) File(java.io.File) JavaCodeBase(com.manydesigns.portofino.code.JavaCodeBase)

Aggregations

JavaCodeBase (com.manydesigns.portofino.code.JavaCodeBase)5 FileObject (org.apache.commons.vfs2.FileObject)4 CodeBase (com.manydesigns.portofino.code.CodeBase)3 JavaResourceResolver (com.manydesigns.portofino.dispatcher.resolvers.JavaResourceResolver)2 IOException (java.io.IOException)2 FileSystemException (org.apache.commons.vfs2.FileSystemException)2 Updatable (com.manydesigns.elements.annotations.Updatable)1 GroovyCodeBase (com.manydesigns.portofino.code.GroovyCodeBase)1 ResourceResolver (com.manydesigns.portofino.dispatcher.ResourceResolver)1 CachingResourceResolver (com.manydesigns.portofino.dispatcher.resolvers.CachingResourceResolver)1 GroovyResourceResolver (com.manydesigns.portofino.dispatcher.resolvers.GroovyResourceResolver)1 ResourceResolvers (com.manydesigns.portofino.dispatcher.resolvers.ResourceResolvers)1 com.manydesigns.portofino.model.database (com.manydesigns.portofino.model.database)1 Column (com.manydesigns.portofino.model.database.Column)1 ForeignKey (com.manydesigns.portofino.model.database.ForeignKey)1 SequenceGenerator (com.manydesigns.portofino.model.database.SequenceGenerator)1 Table (com.manydesigns.portofino.model.database.Table)1 TableGenerator (com.manydesigns.portofino.model.database.TableGenerator)1 DatabasePlatform (com.manydesigns.portofino.model.database.platforms.DatabasePlatform)1 MultiTenancyImplementation (com.manydesigns.portofino.persistence.hibernate.multitenancy.MultiTenancyImplementation)1