Example usage for org.hibernate.tool.hbm2ddl SchemaExport getExceptions

List of usage examples for org.hibernate.tool.hbm2ddl SchemaExport getExceptions

Introduction

In this page you can find the example usage for org.hibernate.tool.hbm2ddl SchemaExport getExceptions.

Prototype

public List getExceptions() 

Source Link

Document

Returns a List of all Exceptions which occurred during the export.

Usage

From source file:org.bonitasoft.engine.business.data.impl.SchemaManagerUpdate.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<Exception> drop(final Set<String> managedClasses) {
    final SchemaExport export = new SchemaExport(buildConfiguration(managedClasses));
    export.drop(Target.EXPORT);//from   w ww.j a  va  2  s . c  o  m
    return export.getExceptions();
}

From source file:org.codehaus.mojo.hibernate3.exporter.Hbm2DDLExporterMojo.java

License:Apache License

/**
 * Overrides the default implementation of executing this goal.
 *
 * @throws MojoExecutionException if there is an error executing the goal
 *//*  ww w  . j  a va 2s  . c  o  m*/
protected void doExecute() throws MojoExecutionException {
    boolean scriptToConsole = getComponentProperty("console", true);
    boolean exportToDatabase = getComponentProperty("export", true);
    boolean haltOnError = getComponentProperty("haltonerror", false);
    boolean drop = getComponentProperty("drop", false);
    boolean create = getComponentProperty("create", true);
    String implementation = getComponentProperty("implementation", getComponent().getImplementation());

    Configuration configuration = getComponentConfiguration(implementation).getConfiguration(this);

    if (getComponentProperty("update", false)) {
        SchemaUpdate update = new SchemaUpdate(configuration);
        update.execute(scriptToConsole, exportToDatabase);
    } else {
        SchemaExport export = new SchemaExport(configuration);
        export.setDelimiter(getComponentProperty("delimiter", ";"));
        export.setHaltOnError(haltOnError);
        export.setFormat(getComponentProperty("format", false));

        String outputFilename = getComponentProperty("outputfilename");
        if (outputFilename != null) {
            File outputFile = HibernateUtils.prepareFile(
                    new File(getProject().getBasedir(), getComponent().getOutputDirectory()), outputFilename,
                    "outputfilename");
            export.setOutputFile(outputFile.toString());
        }

        if (drop && create) {
            export.create(scriptToConsole, exportToDatabase);
        } else {
            export.execute(scriptToConsole, exportToDatabase, drop, create);
        }

        if (export.getExceptions().size() > 0) {
            Iterator iterator = export.getExceptions().iterator();
            int cnt = 1;
            getLog().warn(export.getExceptions().size() + " errors occurred while performing <hbm2ddl>.");
            while (iterator.hasNext()) {
                getLog().error("Error #" + cnt + ": " + iterator.next().toString());
            }
            if (haltOnError) {
                throw new MojoExecutionException("Errors while performing <hbm2ddl>");
            }
        }
    }
}

From source file:org.eclipsetrader.repository.hibernate.HibernateRepository.java

License:Open Source License

public void startUp(IProgressMonitor monitor) {
    properties.put("hibernate.query.factory_class", "org.hibernate.hql.classic.ClassicQueryTranslatorFactory");
    properties.put("hibernate.connection.pool_size", "5");
    properties.put("hibernate.jdbc.batch_size", "20");
    properties.put("hibernate.show_sql", "false");

    // Build suitable defaults for file-based databases (Apache Derby and HSQL)
    if (!properties.containsKey("hibernate.connection.url") && Activator.getDefault() != null) {
        if ("org.apache.derby.jdbc.EmbeddedDriver"
                .equals(properties.get("hibernate.connection.driver_class"))) {
            properties.put("hibernate.connection.url", "jdbc:derby:"
                    + Activator.getDefault().getStateLocation().toOSString() + "/.derby;create=true");
        }/*from   w  ww .  j  a  va 2s.  co  m*/
        if ("org.hsqldb.jdbcDriver".equals(properties.get("hibernate.connection.driver_class"))) {
            properties.put("hibernate.connection.url",
                    "jdbc:hsqldb:file:" + Activator.getDefault().getStateLocation().toOSString() + "/.hsqldb");
        }
    }

    AnnotationConfiguration cfg = buildConfiguration();
    try {
        initializeDatabase(cfg);
    } catch (Exception e) {
        String message = NLS.bind("Error initializing repository '{1}' ({0})", new Object[] { schema, name });
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, message, e);
        Activator.log(status);

        int userChoice = new RepositoryValidator(name, cfg).validate();

        switch (userChoice) {
        case RepositoryValidator.UPDATE_ID:
            SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);
            schemaUpdate.execute(true, true);
            if (schemaUpdate.getExceptions().size() != 0) {
                MultiStatus multiStatus = new MultiStatus(Activator.PLUGIN_ID, 0, new IStatus[0], ERROR_MESSAGE,
                        null);
                for (Object o : schemaUpdate.getExceptions()) {
                    multiStatus.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, null, (Exception) o));
                }
                Activator.log(multiStatus);
            }
            break;
        case RepositoryValidator.CREATE_ID:
            SchemaExport schemaExport = new SchemaExport(cfg);
            schemaExport.create(true, true);
            if (schemaExport.getExceptions().size() != 0) {
                MultiStatus multiStatus = new MultiStatus(Activator.PLUGIN_ID, 0, new IStatus[0], ERROR_MESSAGE,
                        null);
                for (Object o : schemaExport.getExceptions()) {
                    multiStatus.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, null, (Exception) o));
                }
                Activator.log(multiStatus);
            }
            break;
        }
    }
    initializeDatabase(cfg);
}

From source file:org.glite.security.voms.admin.persistence.deployer.SchemaDeployer.java

License:Apache License

private void doUndeploy() {

    checkVoExistence();//from  w w  w .  j  a  v a  2s .  com

    log.info("Undeploying voms database...");

    int existingDB = checkDatabaseExistence();

    if (existingDB == 1) {
        log.error(
                "This tool cannot undeploy voms-admin 1.2.x database! Please upgrade to voms-admin 2 or use voms-admin-configure 1.2.x tools to undeploy this database.");
        System.exit(-1);
    }

    if (existingDB == 2) {

        log.error(
                "This tool cannot undeploy voms-admin 2.0.x databases! Please either upgrade the database to voms-admin 2.5 (using this tool) or use voms-admin-configure 2.0.x"
                        + " tools to undeploy this database");

        System.exit(-1);
    }
    if (existingDB < 0) {

        log.error("No voms-admin database found!");
        System.exit(-1);
    }

    checkDatabaseWritable();

    SchemaExport export = new SchemaExport();

    EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.DATABASE);

    Metadata md = getHibernateMetadataSources().getMetadataBuilder().build();
    export.drop(targetTypes, md);

    @SuppressWarnings("rawtypes")
    List l = export.getExceptions();

    if (!l.isEmpty()) {
        log.error("Error undeploying voms database!");
        printExceptions(l);
        System.exit(2);
    }

    log.info("Database undeployed correctly!");

}

From source file:org.glite.security.voms.admin.persistence.deployer.SchemaDeployer.java

License:Apache License

private void doDeploy() {

    checkVoExistence();/*from ww  w .j  av a  2s  .com*/

    int existingDb = checkDatabaseExistence();

    if (existingDb > 0) {
        final String adminDbVersion = VOMSVersionDAO.instance().getVersion().getAdminVersion().trim();

        log.warn("Existing voms database found. Will not overwrite " + "the database! (admin db version: {})",
                adminDbVersion);
        System.exit(0);
    }

    checkDatabaseWritable();

    SchemaExport exporter = new SchemaExport();

    EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.DATABASE);
    exporter.createOnly(targetTypes, HibernateFactory.getMetadata());

    log.info("Deploying voms database...");

    @SuppressWarnings("rawtypes")
    List l = exporter.getExceptions();

    if (!l.isEmpty()) {
        log.error("Error deploying voms database!");
        printExceptions(l);
        System.exit(2);

    }

    // This is needed as the version of hibernate we are using
    // does not support defining indexes on join table columns
    // See: https://hibernate.atlassian.net/browse/HHH-4263
    CreateAuditEventDataIndexes createIndexTask = new CreateAuditEventDataIndexes(
            HibernateFactory.getSession());

    HibernateFactory.beginTransaction();

    createIndexTask.run();

    CreateAttributeValueIndex avIndexTask = new CreateAttributeValueIndex(HibernateFactory.getSession());

    avIndexTask.run();

    UpdateCATask caTask = new UpdateCATask();
    caTask.run();

    DatabaseSetupTask task = DatabaseSetupTask.instance();
    task.run();

    HibernateFactory.commitTransaction();
    log.info("Database deployed correctly!");

}

From source file:org.jasig.portlet.announcements.SchemaCreator.java

License:Apache License

private int create() {

    /*//  w ww  .  ja v a  2s  . c o  m
     * We will need to provide a Configuration and a Connection;  both should be properly
     * managed by the Spring ApplicationContext.
     */

    final LocalSessionFactoryBean sessionFactoryBean = applicationContext.getBean(SESSION_FACTORY_BEAN_NAME,
            LocalSessionFactoryBean.class);
    final DataSource dataSource = applicationContext.getBean(DATA_SOURCE_BEAN_NAME, DataSource.class);

    try (final Connection conn = dataSource.getConnection()) {
        final Configuration cfg = sessionFactoryBean.getConfiguration();
        final SchemaExport schemaExport = new SchemaExport(cfg, conn);
        schemaExport.execute(true, true, false, false);

        final List<Exception> exceptions = schemaExport.getExceptions();
        if (exceptions.size() != 0) {
            logger.error("Schema Create Failed;  see below for details");
            for (Exception e : exceptions) {
                logger.error("Exception from Hibernate Tools SchemaExport", e);
            }
            return 1;
        }
    } catch (SQLException sqle) {
        logger.error("Failed to initialize & invoke the SchemaExport tool", sqle);
        return 1;
    }

    return 0;

}

From source file:org.siberia.binding.impl.db.hibernate.HibernateBindingManager.java

License:Open Source License

/** drop all databases tables */
public void dropAllTables() {
    SchemaExport export = new SchemaExport(this.configuration);
    export.drop(false, true);//from  w ww  .j a  va2  s.  c  o m

    List exceptions = export.getExceptions();
    if (exceptions != null) {
        for (int i = 0; i < exceptions.size(); i++) {
            Object current = exceptions.get(i);

            if (current instanceof Throwable) {
                logger.error("exception occured while droping tables", (Throwable) current);
            }
        }
    }
}

From source file:org.web4thejob.module.JobletInstallerImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <E extends Exception> List<E> install(List<Joblet> joblets) {
    List<E> exceptions = new ArrayList<E>();

    try {//from  w w  w  .j a v  a 2s  .c o m

        final Configuration configuration = new Configuration();
        configuration.setProperty(AvailableSettings.DIALECT,
                connInfo.getProperty(DatasourceProperties.DIALECT));
        configuration.setProperty(AvailableSettings.DRIVER, connInfo.getProperty(DatasourceProperties.DRIVER));
        configuration.setProperty(AvailableSettings.URL, connInfo.getProperty(DatasourceProperties.URL));
        configuration.setProperty(AvailableSettings.USER, connInfo.getProperty(DatasourceProperties.USER));
        configuration.setProperty(AvailableSettings.PASS, connInfo.getProperty(DatasourceProperties.PASSWORD));

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

        if (StringUtils.hasText(connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX))) {
            String schemaSyntax = connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX);
            Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection();

            for (Joblet joblet : joblets) {
                for (String schema : joblet.getSchemas()) {
                    Statement statement = connection.createStatement();
                    statement.executeUpdate(schemaSyntax.replace("%s", schema));
                    statement.close();
                }
            }

            if (!connection.getAutoCommit()) {
                connection.commit();
            }
        }

        for (Joblet joblet : joblets) {
            for (Resource resource : joblet.getResources()) {
                configuration.addInputStream(resource.getInputStream());
            }
        }

        SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration);
        schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE);
        exceptions.addAll(schemaExport.getExceptions());

    } catch (Exception e) {
        exceptions.add((E) e);
    }

    return exceptions;

}

From source file:org.web4thejob.orm.CreateSchemaTest.java

License:Open Source License

@Test
public void schemaExportTest() throws IOException, SQLException {

    Log4jConfigurer.initLogging("classpath:org/web4thejob/conf/log4j.xml");

    Properties datasource = new Properties();
    datasource.load(new ClassPathResource(DatasourceProperties.PATH).getInputStream());

    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.DIALECT, datasource.getProperty(DatasourceProperties.DIALECT));
    configuration.setProperty(AvailableSettings.DRIVER, datasource.getProperty(DatasourceProperties.DRIVER));
    configuration.setProperty(AvailableSettings.URL, "jdbc:hsqldb:mem:mydb");
    configuration.setProperty(AvailableSettings.USER, datasource.getProperty(DatasourceProperties.USER));
    configuration.setProperty(AvailableSettings.PASS, datasource.getProperty(DatasourceProperties.PASSWORD));

    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();

    Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection();
    Statement statement = connection.createStatement();
    statement.executeUpdate("CREATE SCHEMA w4tj;");
    statement.close();//from   w  w w .j a va  2 s  .c o m

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        for (Resource resource : resolver.getResources("classpath*:org/web4thejob/orm/**/*.hbm.xml")) {

            if (resource.getFile().getName().equals("AuxiliaryDatabaseObjects.hbm.xml"))
                continue;

            configuration.addFile(resource.getFile());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration);
    schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException((Throwable) schemaExport.getExceptions().get(0));
    }

}