List of usage examples for org.hibernate.cfg Configuration getProperty
public String getProperty(String propertyName)
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
public static SessionFactory loadSessionFactory(String fileName, HttpSession sess) throws CSConfigurationException { FileLoader fileLoader = FileLoader.getInstance(); InputStream stream = fileLoader.getFileAsStream(fileName); SessionFactory sessionFactory = null; try {/* w ww . j a v a 2 s. co m*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(stream); //File file = new File(url.toURI()); //AnnotationConfiguration configuration = new AnnotationConfiguration().configure(doc); Configuration configuration = new Configuration().configure(doc); if (configuration.getProperty("hibernate.cache.use_second_level_cache") == null || configuration.getProperty("cache.use_second_level_cache") == null) { configuration.setProperty("hibernate.cache.use_second_level_cache", "false"); configuration.setProperty("cache.use_second_level_cache", "false"); } JDBCHelper.testConnectionHibernate(configuration); sessionFactory = configuration.buildSessionFactory(); } catch (CacheException e) { e.printStackTrace(); ClassPathLoader.releaseJarsFromClassPath(sess); throw new CSConfigurationException( "Error in loading the Session Factory from the Hibernate File." + e.getMessage()); } catch (Exception exception) { exception.printStackTrace(); throw new CSConfigurationException( "Error in loading the Session Factory from the Hibernate File." + exception.getMessage()); } if (null == sessionFactory) throw new CSConfigurationException("Error in loading the Session Factory from the Hibernate File"); else { Session session = null; try { session = sessionFactory.openSession(); } catch (Exception exception) { exception.printStackTrace(); throw new CSConfigurationException("Error in creating a Session from the Loaded Session Factory"); } if (null == session) throw new CSConfigurationException("Error in creating a Session from the Loaded Session Factory"); } return sessionFactory; }
From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java
License:Open Source License
private void doBootstrap() { // do everything in a transaction Session session = getSessionFactory().openSession(); try {/*from www . j a v a 2s . com*/ // make sure that we AUTO-COMMIT Connection connection = session.connection(); connection.setAutoCommit(true); // DoQui workaround: getConfiguration() solleverebbe una IllegalStateException() Configuration cfg = localSessionFactory.getConfigurationOverride(); // Check and dump the dialect being used Dialect dialect = Dialect.getDialect(cfg.getProperties()); Class<?> dialectClazz = dialect.getClass(); LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_DIALECT_USED, dialectClazz.getName()); if (dialectClazz.equals(MySQLDialect.class) || dialectClazz.equals(MySQL5Dialect.class)) { LogUtil.warn( logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + WARN_DIALECT_UNSUPPORTED, dialectClazz.getName()); } if (dialectClazz.equals(HSQLDialect.class)) { logger.info("[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + I18NUtil.getMessage(WARN_DIALECT_HSQL)); } // Ensure that our static connection provider is used String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER); cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName()); SchemaBootstrapConnectionProvider.setBootstrapConnection(connection); // update the schema, if required if (updateSchema) { // Check and record that the bootstrap has started setBootstrapStarted(connection); // Allocate buffer for executed statements executedStatementsThreadLocal.set(new StringBuilder(1024)); updateSchema(cfg, session, connection); // Copy the executed statements to the output file File schemaOutputFile = null; if (schemaOuputFilename != null) { schemaOutputFile = new File(schemaOuputFilename); } else { schemaOutputFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-All_Statements-", ".sql"); } String executedStatements = executedStatementsThreadLocal.get().toString(); if (executedStatements.length() == 0) { LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_NO_CHANGES); } else { FileContentWriter writer = new FileContentWriter(schemaOutputFile); writer.setEncoding("UTF-8"); writer.putContent(executedStatements); LogUtil.info( logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_ALL_STATEMENTS, schemaOutputFile.getPath()); } // verify that all patches have been applied correctly checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false); // check scripts checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, false); // check scripts checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, false); // check scripts // Remove the flag indicating a running bootstrap setBootstrapCompleted(connection); } else { LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_BYPASSING_SCHEMA_UPDATE); } // Reset the configuration cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass); // all done successfully } catch (Throwable e) { LogUtil.error(logger, e, ERR_UPDATE_FAILED); if (updateSchema) { throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e); } else { throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e); } } finally { // Remove the connection reference from the threadlocal boostrap SchemaBootstrapConnectionProvider.setBootstrapConnection(null); } }
From source file:javahibernate2.JavaHibernate2.java
public SessionFactory initHibernate() { try {/*w ww . j a v a 2 s . com*/ final Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); LOG.info("Connection to hibernate URL = " + config.getProperty("hibernate.connection.url")); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); return config.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.out.println(e.toString()); return null; } }
From source file:main.java.edu.isistan.genCom.redSocial.dao.HibernateUtil.java
License:Open Source License
private static SessionFactory buildSessionFactory() { try {/*from w w w .jav a 2s.c o m*/ // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.setNamingStrategy(DefaultNamingStrategy.INSTANCE); configuration.configure(); myConnectionUrl = configuration.getProperty("hibernate.connection.url"); myUserName = configuration.getProperty("hibernate.connection.username"); myPassword = configuration.getProperty("hibernate.connection.password"); sessionFactory = configuration.buildSessionFactory(); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:model.Data_Handler.java
private SessionFactory getSessionFactory() { try {/* w w w .jav a 2 s .com*/ final Configuration config = new Configuration(); config.configure("mealsHibernate.cfg.xml"); LOG.info("Connection to hibernate URL = " + config.getProperty("hibernate.connection.url")); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); return config.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.out.println(e.getMessage()); return null; } }
From source file:myrmidia.Database.Connector.java
License:Open Source License
/** * This mehtod is used to override a hard-coded parameter in the * hibernate.cfg.xml file to give a the application a limited altered * configuration. Used to permit hibernate to create non-existing tables. * @param file URL the url path to the hibernate.cfg.xml file * @throws InitializingException/* w w w . j a va 2s .c om*/ */ public void initOverwriteFromXMLFile(URL file) throws InitializingException { try { 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"); } hbconfig.setProperty("hibernate.hbm2ddl.auto", "update"); String currentProperty = hbconfig.getProperty("hibernate.connection.url"); currentProperty += ";create=true"; hbconfig.setProperty("hibernate.connection.url", currentProperty); sessionFactory = hbconfig.buildSessionFactory(); } catch (Throwable ex) { throw new InitializingException(ex); } }
From source file:net.krotscheck.jersey2.hibernate.factory.HibernateConfigurationFactoryTest.java
License:Apache License
/** * Test provide and dispose.//from w w w .ja v a 2 s . c o m */ @Test public void testProvideDispose() { HibernateConfigurationFactory factory = new HibernateConfigurationFactory(); Configuration config = factory.provide(); Assert.assertEquals("org.hibernate.dialect.H2Dialect", config.getProperty("hibernate.dialect")); // This shouldn't actually do anything, but is included here for // coverage. factory.dispose(config); }
From source file:net.krotscheck.jersey2.hibernate.factory.HibernateConfigurationFactoryTest.java
License:Apache License
/** * Test the application binder.//from ww w. j a v a 2s.co m */ @Test public void testBinder() { ResourceConfig config = new ResourceConfig(); config.register(TestFeature.class); // Make sure it's registered Assert.assertTrue(config.isRegistered(TestFeature.class)); // Create a fake application. ApplicationHandler handler = new ApplicationHandler(config); Configuration appConfig = handler.getServiceLocator().getService(Configuration.class); Assert.assertNotNull(appConfig); // Make sure it's reading from the same place. Assert.assertEquals("org.hibernate.dialect.H2Dialect", appConfig.getProperty("hibernate.dialect")); // Make sure it's a singleton... Configuration appConfig2 = handler.getServiceLocator().getService(Configuration.class); Assert.assertSame(appConfig, appConfig2); }
From source file:org.alfresco.hibernate.DialectFactoryBean.java
License:Open Source License
/** * Substitute the dialect with an alternative, if possible. * // w w w . ja va 2 s . c o m * @param cfg * the configuration * @param dialect * the dialect * @return the dialect */ private Dialect changeDialect(Configuration cfg, Dialect dialect) { String dialectName = cfg.getProperty(Environment.DIALECT); if (dialectName == null || dialectName.length() == 0) { // Fix the dialect property to match the detected dialect cfg.setProperty(Environment.DIALECT, dialect.getClass().getName()); } return dialect; // TODO: https://issues.alfresco.com/jira/browse/ETHREEOH-679 // else if (dialectName.equals(Oracle9Dialect.class.getName())) // { // String subst = AlfrescoOracle9Dialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQLDialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQL5Dialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } }
From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java
License:Open Source License
/** * Count applied patches. This fails if multiple applied patch tables are found, * which normally indicates that the schema view needs to be limited. * /*w ww . j a v a 2 s . c om*/ * @param cfg The Hibernate config * @param connection a valid database connection * @return Returns the number of applied patches * @throws NoSchemaException if the table of applied patches can't be found */ private int countAppliedPatches(Configuration cfg, Connection connection) throws Exception { String defaultSchema = dbSchemaName != null ? dbSchemaName : databaseMetaDataHelper.getSchema(connection); if (defaultSchema != null && defaultSchema.length() == 0) { defaultSchema = null; } String defaultCatalog = cfg.getProperty("hibernate.default_catalog"); if (defaultCatalog != null && defaultCatalog.length() == 0) { defaultCatalog = null; } DatabaseMetaData dbMetadata = connection.getMetaData(); ResultSet tableRs = dbMetadata.getTables(defaultCatalog, defaultSchema, "%", null); boolean newPatchTable = false; boolean oldPatchTable = false; try { boolean multipleSchemas = false; while (tableRs.next()) { String tableName = tableRs.getString("TABLE_NAME"); if (tableName.equalsIgnoreCase("applied_patch")) { if (oldPatchTable || newPatchTable) { // Found earlier multipleSchemas = true; } oldPatchTable = true; } else if (tableName.equalsIgnoreCase("alf_applied_patch")) { if (oldPatchTable || newPatchTable) { // Found earlier multipleSchemas = true; } newPatchTable = true; } } // We go through all the tables so that multiple visible schemas are detected if (multipleSchemas) { throw new AlfrescoRuntimeException(ERR_MULTIPLE_SCHEMAS); } } finally { try { tableRs.close(); } catch (Throwable e) { e.printStackTrace(); } } if (newPatchTable) { Statement stmt = connection.createStatement(); try { ResultSet rs = stmt.executeQuery("select count(id) from alf_applied_patch"); rs.next(); int count = rs.getInt(1); return count; } catch (SQLException e) { // This should work at least and is probably an indication of the user viewing multiple schemas throw new AlfrescoRuntimeException(ERR_MULTIPLE_SCHEMAS); } finally { try { stmt.close(); } catch (Throwable e) { } } } else if (oldPatchTable) { // found the old style table name Statement stmt = connection.createStatement(); try { ResultSet rs = stmt.executeQuery("select count(id) from applied_patch"); rs.next(); int count = rs.getInt(1); return count; } finally { try { stmt.close(); } catch (Throwable e) { } } } else { // The applied patches table is not present throw new NoSchemaException(); } }