Example usage for org.hibernate.cfg Configuration getProperties

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

Introduction

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

Prototype

public Properties getProperties() 

Source Link

Document

Get all properties

Usage

From source file:org.vibur.dbcp.util.HibernateTestUtils.java

License:Apache License

private static SessionFactory buildSessionFactory(String configFileName) {
    try {/*from  w  w w  . j a v a2s. c  om*/
        Configuration cfg = new Configuration().configure(configFileName);
        cfg.addAnnotatedClass(Actor.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        return cfg.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        throw new ExceptionInInitializerError(e);
    }
}

From source file:org.wattdepot.server.depository.impl.hibernate.Manager.java

License:Open Source License

/**
 * @param properties The ServerProperties that contain the database
 *        configuration.//from   w  ww  . j  a  v a 2  s.  co m
 * @return The singleton SessionFactory.
 */
public static SessionFactory getFactory(ServerProperties properties) {
    if (sessionFactory == null) {
        Configuration cfg = new Configuration()
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.CollectorProcessDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.DepositoryImpl.class)
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.DepositorySensorContribution.class)
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.MeasurementPruningDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementTypeImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.PropertyImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.RowCount.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorGroupImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorModelImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.OrganizationImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserInfoImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserPasswordImpl.class)
                .setProperty("hibernate.connection.driver_class",
                        properties.get(ServerProperties.DB_CONNECTION_DRIVER))
                .setProperty("hibernate.connection.url", properties.get(ServerProperties.DB_CONNECTION_URL))
                .setProperty("hibernate.connection.username", properties.get(ServerProperties.DB_USER_NAME))
                .setProperty("hibernate.connection.password", properties.get(ServerProperties.DB_PASSWORD))
                .setProperty("hibernate.c3p0.min_size", "5").setProperty("hibernate.c3p0.max_size", "20")
                .setProperty("hibernate.c3p0.timeout", "1800")
                .setProperty("hibernate.c3p0.max_statements", "50")
                .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")
                .setProperty("hibernate.show_sql", properties.get(ServerProperties.DB_SHOW_SQL))
                .setProperty("hibernate.hbm2ddl.auto", properties.get(ServerProperties.DB_TABLE_UPDATE));
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        // A SessionFactory is set up once for an application
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);

        // // A SessionFactory is set up once for an application
        //       sessionFactory = new Configuration().configure() // configures settings
        //       // from
        //       // hibernate.cfg.xml
        //       .buildSessionFactory();

    }
    return sessionFactory;
}

From source file:org.wattdepot.server.depository.impl.hibernate.Manager.java

License:Open Source License

/**
 * @param properties The ServerProperties that contain the database
 *        configuration.//w w w  .  j av a  2  s  .  c  om
 * @return The singleton SessionFactory.
 */
public static SessionFactory getValidateFactory(ServerProperties properties) {
    if (validateFactory == null) {
        Configuration cfg = new Configuration()
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.CollectorProcessDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.DepositoryImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementTypeImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.PropertyImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorGroupImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorModelImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.OrganizationImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserInfoImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserPasswordImpl.class)
                .setProperty("hibernate.connection.driver_class",
                        properties.get(ServerProperties.DB_CONNECTION_DRIVER))
                .setProperty("hibernate.connection.url", properties.get(ServerProperties.DB_CONNECTION_URL))
                .setProperty("hibernate.connection.username", properties.get(ServerProperties.DB_USER_NAME))
                .setProperty("hibernate.connection.password", properties.get(ServerProperties.DB_PASSWORD))
                .setProperty("hibernate.c3p0.min_size", "5").setProperty("hibernate.c3p0.max_size", "20")
                .setProperty("hibernate.c3p0.timeout", "1800")
                .setProperty("hibernate.c3p0.max_statements", "50")
                .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")
                .setProperty("hibernate.show_sql", properties.get(ServerProperties.DB_SHOW_SQL))
                .setProperty("hibernate.hbm2ddl.auto", "validate");
        validateRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        // A SessionFactory is set up once for an application
        validateFactory = cfg.buildSessionFactory(validateRegistry);

    }
    return validateFactory;
}

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 {// ww  w . j a  va  2  s  .c om

        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. java  2s  .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));
    }

}

From source file:org.wildfly.extras.db_bootstrap.DbBootstrapScanDetectorProcessor.java

License:Apache License

/**
 * Create a {@link Session} based on the provided configuration file.
 *
 * @param bootstrapDatabaseAnnotation - bootstrap configuration source
 * @param classLoader - class loader to use with the session factory
 * @return {@link Session}//from   ww  w  .j  a  v  a2  s . c  o m
 * @throws Exception
 */
private Session createSession(final BootstrapDatabase bootstrapDatabaseAnnotation,
        final ClassLoader classLoader) throws Exception {
    URL resource = classLoader.getResource(bootstrapDatabaseAnnotation.hibernateCfg());
    DbBootstrapLogger.ROOT_LOGGER.tracef("Using hibernate configuration file %s",
            bootstrapDatabaseAnnotation.hibernateCfg());
    Configuration configuration = new Configuration();
    configuration.configure(resource); // configures settings from hibernate.cfg.xml
    configureSettingsFromSystemProperties(bootstrapDatabaseAnnotation, configuration);
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory.openSession();
}

From source file:org.wso2.appserver.hibernate.jndi.sample.listener.HibernateSessionFactoryListener.java

License:Open Source License

public void contextInitialized(ServletContextEvent servletContextEvent) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    logger.info("Hibernate Configuration created successfully");

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    logger.info("ServiceRegistry created successfully");
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    logger.info("SessionFactory created successfully");

    servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory);
    logger.info("Hibernate SessionFactory Configured successfully");
}

From source file:org.yawlfoundation.yawl.util.HibernateEngine.java

License:Open Source License

/** initialises hibernate and the required tables */
private void initialise(Set<Class> classes, Properties props) throws HibernateException {
    try {//from w  w  w . j  av a 2  s .com
        Configuration _cfg = new Configuration();

        // if props supplied, use them instead of hibernate.properties
        if (props != null) {
            _cfg.setProperties(props);
        }

        // add each persisted class to config
        for (Class persistedClass : classes) {
            _cfg.addClass(persistedClass);
        }

        // get a session context
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(_cfg.getProperties()).build();
        _factory = _cfg.buildSessionFactory(serviceRegistry);

        // check tables exist and are of a matching format to the persisted objects
        new SchemaUpdate(_cfg).execute(false, true);

    } catch (MappingException me) {
        _log.error("Could not initialise database connection.", me);
    }
}

From source file:org.yourorg.yourapp.support.HibernateUtil4.java

/**
 * This will pass back a Singleton instance of SessionFactory
 *
 * @return//  www  .ja v a  2s .  co  m
 */
public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        try {
            // loads configuration and mappings
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

            //configuration.setProperty("hibernate.connection.password", "@ChangeMe123");
            if (debug) {
                System.out.println("*** Hibernate Configuration loaded");
            }

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

            if (debug) {
                System.out.println("*** Hibernate serviceRegistry created");
            }

            sessionFactory = configuration.buildSessionFactory(serviceRegistry);

            if (debug) {
                System.out.println("*** Hibernate sessionFactory created");
            }

        } catch (Exception ex) {
            StringBuilder sb = new StringBuilder();
            sb.append(ex.getMessage());
            System.out.println(sb.toString());
        }
    }

    if (sessionFactory != null && debug) {
        System.out.println("\n*** Hibernate: sessionFactory returned.\n");
    }
    return sessionFactory;
}

From source file:orm.ORM.java

public static void main(String[] args) throws FileNotFoundException, NoSuchAlgorithmException, IOException {
    // TODO code application logic here
    MessageDigest md = MessageDigest.getInstance("MD5");
    FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");

    byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);//from   w  w  w .  j a  v a2 s  .c o  m
    }
    ;
    byte[] mdbytes = md.digest();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    System.out.println("Digest(in hex format):: " + sb.toString());

    String checksum;

    checksum = sb.toString();

    /// Hibernate Mapping starts here....

    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    //creating configuration object  
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
    //creating seession factory object  

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
            .build();
    SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);

    //creating session object  
    Session session = factory.openSession();

    Transaction t = session.beginTransaction();
    file e1 = new file();
    e1.setID(115);
    e1.setName("something");
    e1.setHashValue(checksum);
    session.persist(e1);//persisting the object  
    t.commit();//transaction is commited  
    session.close();

    boolean a;
    a = ask_user();

    if (a == true) {
        Scanner o = new Scanner(System.in);
        String s;

        System.out.print("Enter the filename");
        s = o.nextline();

        String hql = "SELECT" + s + "FROM file e";
        String new_check;

        Query query = session.createQuery(hql);
        List results;
        results = query.list();

        hql2 = "SELECT file hash FROM file WHERE Name like " + o;
        Query query2 = session.createQuery(hql2);
        List results2 = query2.list();
        String new_check;
        new_check = checksum_cal(o);

        if (new_check.equals(old_check)) {

            System.out.println("No change");
        }
    } else {

        System.out.println("Change in file");

    }

}