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.archiviststoolkit.plugin.dbdialog.RemoteDBConnectDialogLight.java

/**
 * Connect to the AT database at the given location. This does not check database version
 * so the it should be able to work with version 1.5 and 1.5.7
 *///w  w  w  .ja va2  s  .  com
private boolean connectToDatabase2() {
    // based on the database type set the driver and hibernate dialect
    String databaseType = (String) comboBox2.getSelectedItem();
    String driverClass = "";
    String hibernateDialect = "";

    if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
        driverClass = "com.mysql.jdbc.Driver";
        hibernateDialect = "org.hibernate.dialect.MySQLInnoDBDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_MICROSOFT_SQL_SERVER)) {
        driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        hibernateDialect = "org.hibernate.dialect.SQLServerDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
        driverClass = "oracle.jdbc.OracleDriver";
        hibernateDialect = "org.hibernate.dialect.Oracle10gDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_INTERNAL)) {
        driverClass = "org.hsqldb.jdbcDriver";
        hibernateDialect = "org.hibernate.dialect.HSQLDialect";
    } else { // should never get here
        System.out.println("Unknown database type : " + databaseType);
        return false;
    }

    // now attempt to build the session factory
    String databaseUrl = (String) connectionUrl.getSelectedItem();
    String userName = textField1.getText();
    String password = new String(passwordField1.getPassword());

    try {
        connectionMessage = "Connecting to: " + databaseUrl;
        System.out.println(connectionMessage);

        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    databaseUrl + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", databaseUrl);
        }
        //deal with oracle specific settings
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", userName);
        properties.setProperty("hibernate.connection.password", password);
        properties.setProperty("hibernate.dialect", hibernateDialect);
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();

        //test the session factory to make sure it is working
        testHibernate();

        session = sessionFactory.openSession();

        connectionMessage += "\nSuccess ...\n\n";
        System.out.println("Success ...");

        return true; // connected successfully so return true
    } catch (Exception hibernateException) {
        hibernateException.printStackTrace();

        JOptionPane.showMessageDialog(this, "Failed to start hibernate engine ...", "Hibernate Error",
                JOptionPane.ERROR_MESSAGE);

        return false;
    }
}

From source file:org.beangle.commons.orm.hibernate.ddl.DdlGenerator.java

License:Open Source License

public void gen(String dialect, String fileName) throws HibernateException, IOException {
    Configuration configuration = new OverrideConfiguration();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            DdlGenerator.class.getClassLoader());

    configuration.getProperties().put(Environment.DIALECT, dialect);

    // config naming strategy
    DefaultTableNamingStrategy tableNamingStrategy = new DefaultTableNamingStrategy();
    for (Resource resource : resolver.getResources("classpath*:META-INF/beangle/table.properties"))
        tableNamingStrategy.addConfig(resource.getURL());
    RailsNamingStrategy namingStrategy = new RailsNamingStrategy();
    namingStrategy.setTableNamingStrategy(tableNamingStrategy);
    configuration.setNamingStrategy(namingStrategy);

    for (Resource resource : resolver.getResources("classpath*:META-INF/hibernate.cfg.xml"))
        configuration.configure(resource.getURL());
    SchemaExport export = new SchemaExport(configuration);
    export.setOutputFile(fileName);//from www . ja v  a  2s .c om
    export.execute(false, false, false, true);
}

From source file:org.bonitasoft.engine.persistence.HibernatePersistenceIT.java

License:Open Source License

protected void executeSearch(final boolean enableWordSearch, final int expectedResults)
        throws ClassNotFoundException, SPersistenceException, SBonitaReadException {
    // Setup Hibernate and extract SessionFactory
    final Configuration configuration = new Configuration().configure();
    final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).buildServiceRegistry();
    SessionFactory sessionFactory;//from   w ww.  j  a va  2s.com
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    //
    final List<Class<? extends PersistentObject>> classMapping = Arrays
            .<Class<? extends PersistentObject>>asList(Book.class);
    final Map<String, String> classAliasMappings = Collections.singletonMap(Book.class.getName(), "book");
    final PlatformHibernatePersistenceService persistenceService = new PlatformHibernatePersistenceService(
            sessionFactory, classMapping, classAliasMappings, enableWordSearch, Collections.<String>emptySet(),
            mock(TechnicalLoggerService.class));

    Session session;
    session = persistenceService.getSession(true);
    session.beginTransaction();
    try {
        Book book;
        book = new Book();
        book.setId(1);
        book.setTitle("lieues");
        book.setAuthor("Laurent");
        persistenceService.insert(book);

        book = new Book();
        book.setId(2);
        book.setTitle("Vingt mille lieues");
        book.setAuthor("Nicolas");
        persistenceService.insert(book);

    } finally {
        session.getTransaction().commit();
    }

    final QueryOptions queryOptions = buildQueryOptions("lieues", "ipsum");

    session = persistenceService.getSession(true);
    session.beginTransaction();
    try {
        final List<Book> allBooks = persistenceService
                .selectList(new SelectListDescriptor<Book>("getAllBooks", null, Book.class, queryOptions));
        assertThat(allBooks).isEqualTo(expectedResults);
    } finally {
        session.getTransaction().commit();
    }
}

From source file:org.compass.gps.device.hibernate.embedded.CompassEventListener.java

License:Apache License

private CompassHolder initCompassHolder(Configuration cfg) {
    Properties compassProperties = new Properties();
    //noinspection unchecked
    Properties props = cfg.getProperties();
    for (Map.Entry entry : props.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }/*from   w w w.ja  va 2  s .  c  o  m*/
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties defined, disabling Compass");
        }
        return null;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return null;
    }

    processCollections = compassProperties.getProperty(COMPASS_PROCESS_COLLECTIONS, "true")
            .equalsIgnoreCase("true");

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    boolean atleastOneClassAdded = false;
    for (Iterator it = cfg.getClassMappings(); it.hasNext();) {
        PersistentClass clazz = (PersistentClass) it.next();
        Class<?> mappedClass = clazz.getMappedClass();
        for (Iterator propIt = clazz.getPropertyIterator(); propIt.hasNext();) {
            Property prop = (Property) propIt.next();
            Value value = prop.getValue();
            if (value instanceof Component) {
                Component component = (Component) value;
                try {
                    atleastOneClassAdded |= compassConfiguration.tryAddClass(
                            ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader()));
                } catch (ClassNotFoundException e) {
                    log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e);
                }
            }
        }
        Value idValue = clazz.getIdentifierProperty().getValue();
        if (idValue instanceof Component) {
            Component component = (Component) idValue;
            try {
                atleastOneClassAdded |= compassConfiguration.tryAddClass(
                        ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader()));
            } catch (ClassNotFoundException e) {
                log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e);
            }
        }
        atleastOneClassAdded |= compassConfiguration.tryAddClass(mappedClass);
    }
    if (!atleastOneClassAdded) {
        if (log.isDebugEnabled()) {
            log.debug("No searchable class mappings found in Hibernate class mappings, disabling Compass");
        }
        return null;
    }

    CompassHolder compassHolder = new CompassHolder();
    compassHolder.compassProperties = compassProperties;

    compassHolder.commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    if (transactionFactory == null) {
        String hibernateTransactionStrategy = cfg.getProperty(Environment.TRANSACTION_STRATEGY);
        if (CMTTransactionFactory.class.getName().equals(hibernateTransactionStrategy)
                || JTATransactionFactory.class.getName().equals(hibernateTransactionStrategy)) {
            // hibernate is configured with JTA, automatically configure Compass to use its JTASync (by default)
            compassHolder.hibernateControlledTransaction = false;
            compassConfiguration.setSetting(CompassEnvironment.Transaction.FACTORY,
                    JTASyncTransactionFactory.class.getName());
        } else {
            // Hibernate JDBC transaction manager, let Compass use the local transaction manager
            compassHolder.hibernateControlledTransaction = true;
            // if the settings is configured to use local transaciton, disable thread bound setting since
            // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals
            if (settings
                    .getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
                settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION,
                        true);
            }
        }
    } else if (LocalTransactionFactory.class.getName().equals(transactionFactory)) {
        compassHolder.hibernateControlledTransaction = true;
        // if the settings is configured to use local transaciton, disable thread bound setting since
        // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals
        if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
            settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION,
                    true);
        }
    } else {
        // Hibernate is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with Hibernate transaction listeners
        compassHolder.hibernateControlledTransaction = false;
    }

    compassHolder.indexSettings = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassHolder.indexSettings.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    String mirrorFilterClass = compassHolder.compassProperties.getProperty(COMPASS_MIRROR_FILTER);
    if (mirrorFilterClass != null) {
        try {
            compassHolder.mirrorFilter = (HibernateMirrorFilter) ClassUtils
                    .forName(mirrorFilterClass, compassConfiguration.getSettings().getClassLoader())
                    .newInstance();
        } catch (Exception e) {
            throw new CompassException("Failed to create mirror filter [" + mirrorFilterClass + "]", e);
        }
    }

    compassHolder.compass = compassConfiguration.buildCompass();

    return compassHolder;
}

From source file:org.dspace.app.cris.util.UpdateSchemaTool.java

private SchemaUpdate getSchemaUpdate(Configuration cfg) throws HibernateException, IOException {
    Properties properties = new Properties();
    properties.putAll(cfg.getProperties());
    if (propertiesFile == null) {
        properties.putAll(getProject().getProperties());
    } else {/*from  w w  w .jav  a2  s  . c  o m*/
        properties.load(new FileInputStream(propertiesFile));
    }
    cfg.setProperties(properties);
    SchemaUpdate su = new SchemaUpdate(cfg);
    su.setOutputFile(outputFile.getPath());
    su.setDelimiter(delimiter);
    su.setHaltOnError(haltOnError);
    return su;
}

From source file:org.dt.bsa.util.HibernateUtil.java

License:Open Source License

public static void init() {
    try {/*from ww w .j a  va2 s  . c  o m*/
        Configuration configuration = new Configuration();
        configuration.setNamingStrategy(ImprovedNamingStrategy.INSTANCE);
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        log.error("HibernateUtil:init error:" + ex.getMessage());
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.dynamise.sample.hibernate.DataAccessBundle.java

License:Apache License

@Signal(LifecycleEvent.START)
public void start(ServiceContext serviceCtx) {

    this.logger.info("Building session factory");

    // Pre-loading driver class
    String driverClass = this.properties.getString("db.driver");
    try {/*w w  w  .  j a  va  2  s  .co  m*/
        Class.forName(driverClass);
    } catch (ClassNotFoundException e) {
        throw new BundleException("Driver not found", e);
    }

    // Prepare config
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(Book.class);
    configuration.setProperty("connection.driver_class", driverClass);
    configuration.setProperty("hibernate.connection.url", this.properties.getString("db.url"));
    configuration.setProperty("hibernate.connection.username", this.properties.getString("db.username"));
    configuration.setProperty("hibernate.connection.password", this.properties.getString("db.password"));
    configuration.setProperty("dialect", this.properties.getString("db.hDialect"));
    configuration.setProperty("hibernate.hbm2ddl.auto", this.properties.getString("db.hbm2ddl.auto"));

    try {

        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        this.sessionFactory = configuration.buildSessionFactory(builder.build());

        serviceCtx.put(Constants.KEY_SESSION_FACTORY, this.sessionFactory);

    } catch (HibernateException e) {
        throw new BundleException(e);
    }

}

From source file:org.easybatch.extensions.hibernate.DatabaseUtil.java

License:Open Source License

public static void initializeSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure("/org/easybatch/extensions/hibernate/hibernate.cfg.xml");

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

From source file:org.easybatch.integration.hibernate.DatabaseUtil.java

License:Open Source License

public static void initializeSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure("/org/easybatch/integration/hibernate/hibernate.cfg.xml");

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

From source file:org.exoplatform.services.organization.idm.CustomHibernateServiceImpl.java

License:Open Source License

protected SessionFactory buildSessionFactory() {
    Configuration conf = getHibernateConfiguration();

    BootstrapServiceRegistry bootstrapRegistry = createHibernateBootstrapServiceRegistry();

    final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder(bootstrapRegistry)
            .applySettings(conf.getProperties()).buildServiceRegistry();
    conf.setSessionFactoryObserver(new SessionFactoryObserver() {
        @Override/*from w  w w .j a v a  2s  . c om*/
        public void sessionFactoryCreated(SessionFactory factory) {
        }

        @Override
        public void sessionFactoryClosed(SessionFactory factory) {
            ((StandardServiceRegistryImpl) serviceRegistry).destroy();
        }
    });

    final ClassLoader old = SecurityHelper.doPrivilegedAction(new PrivilegedAction<ClassLoader>() {
        public ClassLoader run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });

    try {
        SecurityHelper.doPrivilegedAction(new PrivilegedAction<Void>() {
            public Void run() {
                DelegatingClassLoader cl = new DelegatingClassLoader(old,
                        org.picketlink.idm.api.IdentitySessionFactory.class.getClassLoader());
                Thread.currentThread().setContextClassLoader(cl);
                return null;
            }
        });
        return conf.buildSessionFactory(serviceRegistry);
    } finally {
        if (old != null) {
            SecurityHelper.doPrivilegedAction(new PrivilegedAction<Void>() {
                public Void run() {
                    Thread.currentThread().setContextClassLoader(old);
                    return null;
                }
            });
        }
    }
}