Example usage for org.hibernate.cfg Configuration addResource

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

Introduction

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

Prototype

public Configuration addResource(String resourceName) throws MappingException 

Source Link

Document

Read mappings as a application resourceName (i.e.

Usage

From source file:myrmidia.Database.Connector.java

License:Open Source License

@Override
public void initFromXMLfile(URL file) throws InitializingException {
    try {/* ww w . jav  a2s .co  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(file.openStream());

        String hcf = document.getElementsByTagName("HibernateConfigFile").item(0).getTextContent();

        String descriptionMapFile = document.getElementsByTagName("DescriptionMappingFile").item(0)
                .getTextContent();
        descriptionClassName = document.getElementsByTagName("DescriptionClassName").item(0).getTextContent();

        Configuration hbconfig = new Configuration();
        hbconfig.configure(FileIO.findFile(hcf));
        hbconfig.addURL(FileIO.findFile(descriptionMapFile));

        try {
            String solutionMapFile = document.getElementsByTagName("SolutionMappingFile").item(0)
                    .getTextContent();
            solutionClassName = document.getElementsByTagName("SolutionClassName").item(0).getTextContent();
            hbconfig.addResource(solutionMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have solution");
        }

        try {
            String justOfSolutionMapFile = document.getElementsByTagName("JustificationOfSolutionMappingFile")
                    .item(0).getTextContent();
            justOfSolutionClassName = document.getElementsByTagName("JustificationOfSolutionClassName").item(0)
                    .getTextContent();
            hbconfig.addResource(justOfSolutionMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have justification of the solution");
        }

        try {
            String resultMapFile = document.getElementsByTagName("ResultMappingFile").item(0).getTextContent();
            resultClassName = document.getElementsByTagName("ResultClassName").item(0).getTextContent();
            hbconfig.addResource(resultMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have result");
        }
        sessionFactory = hbconfig.buildSessionFactory();
    } catch (Throwable ex) {
        throw new InitializingException(ex);
    }
}

From source file:net.sf.hibernate.jconsole.tester.HibernateSessions.java

License:Open Source License

private static void doInitSessionFactory() throws Exception {
    Configuration cfg = new Configuration();
    cfg.addResource("net/sf/hibernate/jconsole/tester/test-message-entity.hbm.xml");
    cfg.setProperties(System.getProperties());

    cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:mymemdb");
    cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver");
    cfg.setProperty("hibernate.connection.username", "SA");
    cfg.setProperty("hibernate.hbm2ddl.auto", "create-drop");

    sessionFactory = cfg.buildSessionFactory();
    mBeanServer = ManagementFactory.getPlatformMBeanServer();
    HibernateJmxBinding binding = new HibernateJmxBinding(mBeanServer, sessionFactory);
    binding.registerJmxBinding();//from   ww w  .  j ava2  s .c o  m
}

From source file:OpenRate.customerinterface.webservices.HibernateUtil.java

License:Open Source License

/**
 * Return the current session factory/*from w  w w.  ja  v  a2  s  .  c  o m*/
 *
 * @return
 */
private static SessionFactory getSessionFactory(boolean useBeansList) {
    try {
        if (sessionFactory == null) {
            if (useBeansList) {
                // use the J2EE type beans list
                Configuration configuration = new Configuration();

                // load all beans
                InputStream is = HibernateUtil.class.getResourceAsStream("hibernateBeans.lst");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line;

                while ((line = reader.readLine()) != null) {
                    configuration.addResource(line);
                }

                Properties properties = new Properties();

                properties.load(HibernateUtil.class.getResourceAsStream("hibernate.properties"));
                configuration.setProperties(properties);
                sessionFactory = configuration.buildSessionFactory();
            } else {
                // Use the plain old session factory
                sessionFactory = new Configuration().configure().buildSessionFactory();
            }
        }
    } catch (Throwable ex) {
        log.error("Initial SessionFactory creation failed.", ex);

        throw new ExceptionInInitializerError(ex);
    }

    return sessionFactory;
}

From source file:org.apache.ignite.cache.store.hibernate.CacheHibernateBlobStore.java

License:Apache License

/**
 * Initializes store./*from  w  ww. j  ava 2s  . c  om*/
 *
 * @throws IgniteException If failed to initialize.
 */
private void init() throws IgniteException {
    if (initGuard.compareAndSet(false, true)) {
        if (log.isDebugEnabled())
            log.debug("Initializing cache store.");

        try {
            if (sesFactory != null)
                // Session factory has been provided - nothing to do.
                return;

            if (!F.isEmpty(hibernateCfgPath)) {
                try {
                    URL url = new URL(hibernateCfgPath);

                    sesFactory = new Configuration().configure(url).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using URL: " + url);

                    // Session factory has been successfully initialized.
                    return;
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Caught malformed URL exception: " + e.getMessage());
                }

                // Provided path is not a valid URL. File?
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists()) {
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using file: " + hibernateCfgPath);

                    // Session factory has been successfully initialized.
                    return;
                }

                // Provided path is not a file. Classpath resource?
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
            } else {
                if (hibernateProps == null) {
                    U.warn(log, "No Hibernate configuration has been provided for store (will use default).");

                    hibernateProps = new Properties();

                    hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
                    hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
                    hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
                }

                Configuration cfg = new Configuration();

                cfg.setProperties(hibernateProps);

                assert resourceAvailable(MAPPING_RESOURCE) : MAPPING_RESOURCE;

                cfg.addResource(MAPPING_RESOURCE);

                sesFactory = cfg.buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using properties: " + hibernateProps);
            }
        } catch (HibernateException e) {
            throw new IgniteException("Failed to initialize store.", e);
        } finally {
            initLatch.countDown();
        }
    } else if (initLatch.getCount() > 0) {
        try {
            U.await(initLatch);
        } catch (IgniteInterruptedCheckedException e) {
            throw new IgniteException(e);
        }
    }

    if (sesFactory == null)
        throw new IgniteException("Cache store was not properly initialized.");
}

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

License:Open Source License

protected Configuration buildConfiguration(final Properties properties,
        final HibernateResourcesConfigurationProvider hibernateResourcesConfigurationProvider) {
    final Configuration configuration = new Configuration();
    configuration.addProperties(properties);
    for (final String resource : hibernateResourcesConfigurationProvider.getResources()) {
        configuration.addResource(resource);
    }//from www  . j  av a 2 s. c  om
    configuration.buildMappings();
    return configuration;
}

From source file:org.codehaus.griffon.runtime.hibernate3.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyMappings(final Configuration config) {
    ServiceLoaderUtils.load(application.getApplicationClassLoader().get(), "META-INF/types",
            Hibernate3Mapping.class, new ServiceLoaderUtils.LineProcessor() {
                @Override//from  w  ww  .  j ava 2  s.c om
                public void process(ClassLoader classLoader, Class<?> type, String line) {
                    line = line.trim();
                    if (isBlank(line))
                        return;
                    line = line.replace('.', '/');
                    LOG.debug("Registering {} as hibernate resource", line + HBM_XML_SUFFIX);
                    config.addResource(line + HBM_XML_SUFFIX);
                }
            });

    for (String mapping : getConfigValue(sessionConfig, "mappings", Collections.<String>emptyList())) {
        mapping = mapping.replace('.', '/');
        if (!mapping.endsWith(HBM_XML_SUFFIX)) {
            mapping = mapping + HBM_XML_SUFFIX;
        }
        LOG.debug("Registering {} as hibernate resource", mapping);
        config.addResource(mapping);
    }
}

From source file:org.codehaus.griffon.runtime.hibernate4.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyMappings(final Configuration config) {
    ServiceLoaderUtils.load(application.getApplicationClassLoader().get(), "META-INF/types",
            Hibernate4Mapping.class, new ServiceLoaderUtils.LineProcessor() {
                @Override//  w w  w.j a  v a  2 s.co m
                public void process(ClassLoader classLoader, Class<?> type, String line) {
                    line = line.trim();
                    if (isBlank(line))
                        return;
                    line = line.replace('.', '/');
                    LOG.debug("Registering {} as hibernate resource", line + HBM_XML_SUFFIX);
                    config.addResource(line + HBM_XML_SUFFIX);
                }
            });

    for (String mapping : getConfigValue(sessionConfig, "mappings", Collections.<String>emptyList())) {
        mapping = mapping.replace('.', '/');
        if (!mapping.endsWith(HBM_XML_SUFFIX)) {
            mapping = mapping + HBM_XML_SUFFIX;
        }
        LOG.debug("Registering {} as hibernate resource", mapping);
        config.addResource(mapping);
    }
}

From source file:org.codehaus.griffon.runtime.hibernate5.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyMappings(final Configuration config) {
    final Object mapClasses = getConfigValue(sessionConfig, MAP_CLASSES_PATTERN, Pattern.compile(".*"));
    ServiceLoaderUtils.load(application.getApplicationClassLoader().get(), "META-INF/types",
            Hibernate5Mapping.class, new ServiceLoaderUtils.LineProcessor() {
                @Override/*from  w w w.j  a  v a  2s  .  c o  m*/
                public void process(ClassLoader classLoader, Class<?> type, String line) {
                    String originalName = line.trim();

                    if (isBlank(originalName) || !matchMapClassPattern(mapClasses, originalName))
                        return;
                    line = originalName.replace('.', '/');
                    LOG.debug("Registering {} as hibernate resource", line + HBM_XML_SUFFIX);
                    if (classLoader.getResource(line + HBM_XML_SUFFIX) != null)
                        config.addResource(line + HBM_XML_SUFFIX);
                    else {
                        addAnnotatedClass(config, classLoader, originalName);
                    }

                }
            });

    for (String mapping : getConfigValue(sessionConfig, "mappings", Collections.<String>emptyList())) {
        mapping = mapping.replace('.', '/');
        if (!mapping.endsWith(HBM_XML_SUFFIX)) {
            mapping = mapping + HBM_XML_SUFFIX;
        }
        LOG.debug("Registering {} as hibernate resource", mapping);
        config.addResource(mapping);
    }
}

From source file:org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStore.java

License:Open Source License

/**
 * Initializes store./* w w w.j av a 2  s. co m*/
 *
 * @throws GridException If failed to initialize.
 */
private void init() throws GridException {
    if (initGuard.compareAndSet(false, true)) {
        if (log.isDebugEnabled())
            log.debug("Initializing cache store.");

        try {
            if (sesFactory != null)
                // Session factory has been provided - nothing to do.
                return;

            if (!F.isEmpty(hibernateCfgPath)) {
                try {
                    URL url = new URL(hibernateCfgPath);

                    sesFactory = new Configuration().configure(url).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using URL: " + url);

                    // Session factory has been successfully initialized.
                    return;
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Caught malformed URL exception: " + e.getMessage());
                }

                // Provided path is not a valid URL. File?
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists()) {
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using file: " + hibernateCfgPath);

                    // Session factory has been successfully initialized.
                    return;
                }

                // Provided path is not a file. Classpath resource?
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
            } else {
                if (hibernateProps == null) {
                    U.warn(log, "No Hibernate configuration has been provided for store (will use default).");

                    hibernateProps = new Properties();

                    hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
                    hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
                    hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
                }

                Configuration cfg = new Configuration();

                cfg.setProperties(hibernateProps);

                assert resourceAvailable(MAPPING_RESOURCE) : MAPPING_RESOURCE;

                cfg.addResource(MAPPING_RESOURCE);

                sesFactory = cfg.buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using properties: " + hibernateProps);
            }
        } catch (HibernateException e) {
            throw new GridException("Failed to initialize store.", e);
        } finally {
            initLatch.countDown();
        }
    } else if (initLatch.getCount() > 0)
        U.await(initLatch);

    if (sesFactory == null)
        throw new GridException("Cache store was not properly initialized.");
}

From source file:org.jbpm.examples.taskinstance.CustomTaskInstanceTest.java

License:Open Source License

protected JbpmConfiguration getJbpmConfiguration() {
    if (jbpmConfiguration == null) {
        // the jbpm.cfg.xml file is modified to add the CustomTaskInstanceFactory
        // so we will read in the file from the config directory of this example
        jbpmConfiguration = JbpmConfiguration.parseResource("taskinstance/jbpm.cfg.xml");
        DbPersistenceServiceFactory factory = (DbPersistenceServiceFactory) jbpmConfiguration
                .getServiceFactory(Services.SERVICENAME_PERSISTENCE);

        Configuration configuration = factory.getConfiguration();
        configuration.addResource("taskinstance/CustomTaskInstance.hbm.xml");

        JbpmSchema jbpmSchema = new JbpmSchema(configuration);
        jbpmSchema.updateTable("JBPM_TASKINSTANCE");
    }/*from   w w w.  ja v  a 2s .  c o  m*/
    return jbpmConfiguration;
}