Example usage for org.hibernate.cfg Configuration configure

List of usage examples for org.hibernate.cfg Configuration configure

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration configure.

Prototype

public Configuration configure() throws HibernateException 

Source Link

Document

Use the mappings and properties specified in an application resource named hibernate.cfg.xml.

Usage

From source file:de.xwic.sandbox.server.installer.InstallationManager.java

License:Apache License

/**
 * Create a hibernate configuration.//from ww w  .j  a  v  a  2s. co  m
 * 
 * @return
 * @throws IOException
 */
private Configuration createHibernateConfiguration() {

    log.info("Creating hibernate configuration.");
    Configuration cfg = new Configuration();
    cfg.configure();
    // read and apply hibernate.properties
    File file = findFile("hibernate.properties");

    if (file != null) {
        log.info("Found " + file.getPath());
        Properties prop = new Properties();
        FileInputStream inStream = null;
        try {
            inStream = new FileInputStream(file);
            prop.load(inStream);
            cfg.setProperties(prop);
        } catch (IOException e) {
            log.warn("Error reading properties - trying without", e);
        } finally {
            closeStream(inStream);
        }
    }
    return cfg;
}

From source file:de.xwic.sandbox.server.ServletLifecycleListener.java

License:Apache License

@Override
public void contextInitialized(ServletContextEvent event) {
    HibernateDAOProvider hbnDP = new HibernateDAOProvider();

    DAOFactory factory = CommonConfiguration.createCommonDaoFactory(hbnDP);

    DAOSystem.setDAOFactory(factory);/*from  www.ja  v  a  2 s.c o  m*/
    DAOSystem.setSecurityManager(new ServerSecurityManager());
    DAOSystem.setUseCaseService(new DefaultUseCaseService(hbnDP));
    DAOSystem.setFileHandler(new HbnFileOracleFixDAO());

    SandboxModelConfig.register(factory);
    StartModelConfig.register(factory);

    DemoAppModelConfig.register(factory);

    final ServletContext context = event.getServletContext();
    SandboxModelConfig.setWebRootDirectory(new File(context.getRealPath("/")));

    final String rootPath = context.getRealPath("");

    final File path = new File(rootPath + "/config");
    Setup setup;
    try {
        setup = XmlConfigLoader.loadSetup(path.toURI().toURL());
    } catch (Exception e) {
        log.error("Error loading product configuration", e);
        throw new RuntimeException("Error loading product configuration: " + e, e);
    }
    ConfigurationManager.setSetup(setup);

    if (!HibernateUtil.isInitialized()) {
        Configuration configuration = new Configuration();
        configuration.configure(); // load configuration settings from hbm file.
        // load properties
        Properties prop = new Properties();
        InputStream in = context.getResourceAsStream("WEB-INF/hibernate.properties");
        if (in == null) {
            in = context.getResourceAsStream("/WEB-INF/hibernate.properties");
        }
        if (in != null) {
            try {
                prop.load(in);
                configuration.setProperties(prop);
            } catch (IOException e) {
                log.error("Error loading hibernate.properties. Skipping this step! : " + e);
            }
        }
        HibernateUtil.initialize(configuration);
    }

    File prefStorePath = new File(new File(rootPath), "WEB-INF/prefstore");
    if (!prefStorePath.exists() && !prefStorePath.mkdirs()) {
        throw new IllegalStateException("Error initializing preference store: can not create directory "
                + prefStorePath.getAbsolutePath());
    }
    Platform.initialize(new StorageProvider(prefStorePath), new UserContextPreferenceProvider());

}

From source file:dms.Persist.java

private void setUp() {
    Configuration c = new Configuration();
    c.configure();
    sf = c.buildSessionFactory();
}

From source file:eds.component.data.HibernateUtil.java

/**
 * Singleton factory method/*from  ww w. j  a  va 2s.  c om*/
 * @return 
 */
public SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        Configuration cfg = this.createJNDIConfig();
        cfg.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
    }
    return sessionFactory;
}

From source file:edu.ku.brc.specify.tools.SpecifySchemaGenerator.java

License:Open Source License

/**
 * Creates the Schema./*  w w w .j  a  v a2  s. c  o m*/
 * @param driverInfo the driver info to use
 * @param connectionStr the connection string for creating or opening a database
 * @param hostname the hostname (localhost)
 * @param databaseName the database name
 * @param user the username
 * @param passwd the password (clear text)
 * @param doUpdate tells it to update the schema instead of creating it
 */
protected static void doGenSchema(final DatabaseDriverInfo driverInfo, final String connectionStr, // might be a create or an open connection string
        final String user, final String passwd, final boolean doUpdate) {
    // setup the Hibernate configuration
    Configuration hibCfg = new AnnotationConfiguration();
    hibCfg.setProperties(getHibernateProperties(driverInfo, connectionStr, user, passwd, doUpdate));
    hibCfg.configure();

    if (doUpdate) {
        SchemaUpdate schemaUpdater = new SchemaUpdate(hibCfg);

        log.info("Updating schema");
        //System.exit(0);
        boolean doScript = false;
        log.info("Updating the DB schema");
        schemaUpdater.execute(doScript, true);

        log.info("DB schema Updating completed");

        // log the exceptions that occurred
        List<?> exceptions = schemaUpdater.getExceptions();
        for (Object o : exceptions) {
            Exception e = (Exception) o;
            log.error(e.getMessage());
        }
    } else {
        SchemaExport schemaExporter = new SchemaExport(hibCfg);
        schemaExporter.setDelimiter(";");

        log.info("Generating schema");
        //System.exit(0);
        boolean printToScreen = false;
        boolean exportToDb = true;
        boolean justDrop = false;
        boolean justCreate = true;
        log.info("Creating the DB schema");
        schemaExporter.execute(printToScreen, exportToDb, justDrop, justCreate);

        log.info("DB schema creation completed");

        // log the exceptions that occurred
        List<?> exceptions = schemaExporter.getExceptions();
        for (Object o : exceptions) {
            Exception e = (Exception) o;
            log.error(e.getMessage());
        }
    }
}

From source file:edu.temple.tutrucks.HibernateUtil.java

/**
 * Builds Hibernate's Session Factory. Required by Hibernate
 * @return the session factory for Hibernate
 *///from   w  ww  .  j  ava 2 s  .c  om
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        return configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed.");
        System.err.println(ex.getMessage());
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:edu.ucdenver.bios.jasyptsvc.hibernate.SessionContext.java

License:Open Source License

/**
 * Instantiates a new session context.//from  w ww  . j  av a  2s  . c  om
 *
 * @throws SessionContextException
 *             the session context exception
 */
private SessionContext() throws SessionContextException {
    /*
     * Build a SessionFactory object from session-factory configuration
     * defined in the hibernate.cfg.xml file. In this file we register the
     * JDBC connection information, connection pool, the hibernate dialect
     * that we used and the mapping to our hbm.xml file for each POJO (Plain
     * Old Java Object).
     */
    try {
        /* Begin : Jasypt Chnages */
        /*StandardPBEStringEncryptor strongEncryptor = new StandardPBEStringEncryptor();
        strongEncryptor.setAlgorithm("PBEWithMD5AndDES");           
        strongEncryptor.setPassword("password");
        HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
        registry.registerPBEStringEncryptor("configurationHibernateEncryptor", strongEncryptor);*/

        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        config.setPasswordEnvName("ENV_VARIABLE");

        StandardPBEStringEncryptor strongEncryptor = new StandardPBEStringEncryptor();
        strongEncryptor.setAlgorithm("PBEWithMD5AndDES");
        strongEncryptor.setConfig(config);

        HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
        registry.registerPBEStringEncryptor("configurationHibernateEncryptor", strongEncryptor);

        /* End : Jasypt Chnages */
        Configuration configuration = new Configuration();
        sessionFactory = configuration.configure().buildSessionFactory();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:edu.ucdenver.bios.webservice.common.hibernate.SessionContext.java

License:Open Source License

/**
 * Instantiates a new session context.//from   w  w  w. j  a v a2s.  com
 *
 * @throws SessionContextException
 *             the session context exception
 */
private SessionContext() throws SessionContextException {
    /*
     * Build a SessionFactory object from session-factory configuration
     * defined in the hibernate.cfg.xml file. In this file we register the
     * JDBC connection information, connection pool, the hibernate dialect
     * that we used and the mapping to our hbm.xml file for each POJO (Plain
     * Old Java Object).
     */
    try {
        /* Begin : Jasypt Chnages */
        /*StandardPBEStringEncryptor strongEncryptor = new StandardPBEStringEncryptor();
        strongEncryptor.setAlgorithm("PBEWithMD5AndDES");           
        strongEncryptor.setPassword("password");
        HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
        registry.registerPBEStringEncryptor("configurationHibernateEncryptor", strongEncryptor);*/

        /*EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        config.setPasswordEnvName("ENV_VARIABLE");
                
        StandardPBEStringEncryptor strongEncryptor = new StandardPBEStringEncryptor();
        strongEncryptor.setAlgorithm("PBEWithMD5AndDES");
        strongEncryptor.setConfig(config);
                
        HibernatePBEEncryptorRegistry registry =  HibernatePBEEncryptorRegistry.getInstance();
        registry.registerPBEStringEncryptor("configurationHibernateEncryptor", strongEncryptor);*/

        /* End : Jasypt Chnages */
        Configuration configuration = new Configuration();
        sessionFactory = configuration.configure().buildSessionFactory();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:edu.upenn.cis.ppod.persistence.SessionFactoryProvider.java

License:Apache License

public SessionFactory get() {
    logger.debug("building session factory...");
    final Configuration cfg = new Configuration();
    cfg.setNamingStrategy(new ImprovedNamingStrategy());

    // Read hibernate.cfg.xml (has to be present)
    cfg.configure();
    final SessionFactory sf = cfg.buildSessionFactory();
    logger.debug("...done");
    return sf;//from   www  . j a va  2 s  . c  o  m
}

From source file:Entidades.BaseDAO.java

public static Session openSession() throws Exception {
    Configuration configuration = new Configuration();
    configuration.configure();
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(standardRegistry);
    Session session = sessionFactory.openSession();
    return session;
}