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

@Deprecated
public Configuration configure(org.w3c.dom.Document document) throws HibernateException 

Source Link

Usage

From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java

License:CDDL license

/**
 * Constructor which accepts an entityName and a Hibernate configuration
 * resource. The current implementation instantiates a SessionFactory per
 * instance (implying one instance per CacheStore-backed NamedCache).
 *
 * @param sEntityName   Hibernate entity (i.e. the HQL table name)
 * @param sResource     Hibernate config classpath resource (e.g. hibernate.cfg.xml)
 *///from  www.  j  ava 2s .  c om
public HibernateCacheLoader(String sEntityName, String sResource) {
    m_sEntityName = sEntityName;

    /*
    If we start caching these we need to be aware that the resource may
    be relative (and so we should not key the cache by resource name).
    */
    Configuration configuration = new Configuration();
    configuration.configure(sResource);

    m_sessionFactory = configuration.buildSessionFactory();
}

From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java

License:CDDL license

/**
 * Constructor which accepts an entityName and a Hibernate configuration
 * resource. The current implementation instantiates a SessionFactory per
 * instance (implying one instance per CacheStore-backed NamedCache).
 *
 * @param sEntityName       Hibernate entity (i.e. the HQL table name)
 * @param configurationFile Hibernate config file (e.g. hibernate.cfg.xml)
 *//*from  ww  w  .  j av a  2 s  .  com*/
public HibernateCacheLoader(String sEntityName, File configurationFile) {
    m_sEntityName = sEntityName;

    /*
    If we start caching these we should cache by canonical file name.
    */
    Configuration configuration = new Configuration();
    configuration.configure(configurationFile);

    m_sessionFactory = configuration.buildSessionFactory();
}

From source file:com.payment.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        HttpSession session = request.getSession();

        Calendar cal = Calendar.getInstance();
        String month = new SimpleDateFormat("MMM").format(cal.getTime());
        String concept = request.getParameter("concept");
        String flat = (String) session.getAttribute("flat");
        // String month =  request.getParameter("month");
        int amount = Integer.parseInt(request.getParameter("amount"));

        Pay pay = new Pay();
        pay.setAmount(amount);/*from ww w .  j  a  v a  2  s  .  c  om*/
        pay.setConcept(concept);
        pay.setFlat(flat);
        pay.setMonth(month);
        String email = (String) session.getAttribute("email");
        paymentmail pxx = new paymentmail();
        int n = pxx.send(email, amount, month);

        if (n == 0) {
            Configuration cfg = new Configuration();
            cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
            SessionFactory factory = cfg.buildSessionFactory();
            Session session1 = factory.openSession();
            Transaction t = session1.beginTransaction();
            session1.persist(pay);
            t.commit();
            session1.close();

            request.setAttribute("success", "suc");
            RequestDispatcher rd = request.getRequestDispatcher("account.jsp");
            rd.forward(request, response);

        } else {
            request.setAttribute("success", "err");
            RequestDispatcher rd = request.getRequestDispatcher("account.jsp");
            rd.forward(request, response);
        }

    }

    catch (Exception e) {

    }
}

From source file:com.project.hibernate.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {// w w w .ja  v  a  2  s.  c o  m
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        System.out.println("Hibernate Configuration loaded");

        // apply configuration property settings to StandardServiceRegistryBuilder
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        System.out.println("Hibernate serviceRegistry created");

        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        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:com.rdsic.pcm.common.HibernateUtil.java

public static void createSchema(String source_filename, String target_filename) {
    org.hibernate.cfg.Configuration cfg = new AnnotationConfiguration();
    cfg.configure(source_filename);
    new SchemaExport(cfg).setDelimiter(";").setOutputFile(target_filename).create(false, false);
}

From source file:com.referencelogic.xmlormupload.main.XmlormuploadMain.java

License:Open Source License

public void run() {
    try {//from   w  ww . j  a v  a 2 s  .c o m
        XMLConfiguration config = new XMLConfiguration(configFileName);
        String sourceDir = config.getString("source.path");
        List allowedExtensions = config.getList("source.extensions");
        int poolSize = config.getInt("threadpool.size");

        String groovySourceDir = config.getString("domainclasses.path");
        List groovyAllowedExtensions = config.getList("domainclasses.extensions");

        if (isDebugging) {
            log.debug("Loaded configuration successfully. Reading groovy class list from: " + groovySourceDir
                    + " with allowed extensions " + groovyAllowedExtensions);
        }

        if (isDebugging) {
            log.debug("Loaded configuration successfully. Reading file list from: " + sourceDir
                    + " with allowed extensions " + allowedExtensions);
        }
        Iterator iter = FileUtils.iterateFiles(new File(sourceDir),
                (String[]) allowedExtensions.toArray(new String[allowedExtensions.size()]), true);
        if (poolSize < 1) {
            poolSize = 5;
        }

        exec = Executors.newFixedThreadPool(poolSize);

        GroovyClassLoader gcl = new GroovyClassLoader();

        ClassLoader ojcl = Thread.currentThread().getContextClassLoader();

        boolean allFilesResolved = false;
        while (!allFilesResolved) {
            Iterator groovyIter = FileUtils.iterateFiles(new File(groovySourceDir),
                    (String[]) groovyAllowedExtensions.toArray(new String[groovyAllowedExtensions.size()]),
                    true);

            allFilesResolved = true;

            while (groovyIter.hasNext()) {
                File groovyFile = (File) groovyIter.next();
                log.info("Trying to parse file " + groovyFile);
                try {
                    Class clazz = gcl.parseClass(groovyFile);
                } catch (IOException ioe) {
                    log.error("Unable to read file " + groovyFile + " to parse class ", ioe);
                } catch (Exception e) {
                    log.error("Unable to parse file " + groovyFile + " ex:" + e);
                    allFilesResolved = false;
                }
            }

        }

        Thread.currentThread().setContextClassLoader(gcl);

        Configuration hibernateConfig = new Configuration();

        SessionFactory sf;
        if (!matchRegex) {
            sf = hibernateConfig.configure(new File("hibernate.config.xml")).buildSessionFactory();
        } else {
            sf = hibernateConfig.configure(new File("hibernate.update.config.xml")).buildSessionFactory();
        }

        log.info("Opened session");

        while (iter.hasNext()) {
            File file = (File) iter.next();
            String filePath = "";
            try {
                filePath = file.getCanonicalPath();
                log.debug("Canonical path being processed is: " + filePath);
            } catch (IOException ioe) {
                log.warn("Unable to get canonical path from file", ioe);
            }
            log.debug("Is matchRegex true? " + matchRegex);
            log.debug("Does filePath match regexStr?" + filePath.matches(matchRegexStr));
            if ((!matchRegex) || (matchRegex && filePath.matches(matchRegexStr))) {
                exec.execute(new Xmlormuploader(file, config, gcl, sf));
            }
        }

        exec.shutdown();
        try {
            while (!exec.isTerminated()) {
                exec.awaitTermination(30, TimeUnit.SECONDS);
            }
        } catch (InterruptedException ie) {
            // Do nothing, going to close database connection anyway        
        }

        sf.close();

    } catch (ConfigurationException cex) {
        log.fatal("Unable to load config file " + configFileName + " to determine configuration.", cex);
    }
}

From source file:com.reg.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String city = request.getParameter("city");
    String state = request.getParameter("state");
    String zip = request.getParameter("zip");
    String country = request.getParameter("country");
    String mob = request.getParameter("mob");
    String org = request.getParameter("mem");
    String total_pr = request.getParameter("total");
    int personCount = Integer.parseInt(total_pr);
    Date date = new Date();
    User u = new User();
    u.setCity(city);/*from  w w w. j a v  a  2  s .  c  o m*/
    u.setCountry(country);
    u.setD(date);
    u.setMobile(mob);
    u.setOrganization(org);
    u.setState(state);
    u.setZipcode(zip);
    u.setPersonCount(personCount);

    try {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        session.persist(u);
        t.commit();
        session.close();

        request.setAttribute("sendSuccess", "block");
        RequestDispatcher rd = request.getRequestDispatcher("Main.jsp");
        rd.forward(request, response);
    }

    catch (Exception e) {

        request.setAttribute("dbError", "block");
        RequestDispatcher rd = request.getRequestDispatcher("Main.jsp");
        rd.forward(request, response);

    }

}

From source file:com.sakadream.sql.SQLConfigJson.java

License:MIT License

/**
 * Get Hibernate Configuration Properties using Hibernate API
 * @param pkgLocation hibernate.cfg.xml's folder location
 * @return SQLConfig SQLConfig object//from  ww w.  j  a  v a2 s  .com
 */
public static SQLConfig getHibernateCfg(String pkgLocation) {
    Configuration config = new Configuration();
    config.configure(pkgLocation + "hibernate.cfg.xml");
    String username = config.getProperty("hibernate.connection.username");
    String password = config.getProperty("hibernate.connection.password");
    String url = config.getProperty("hibernate.connection.url");

    SQLConfig sqlconfig = new SQLConfig();
    sqlconfig.setDialect(dl.getDialectByUrl(url));
    sqlconfig.setUsername(username);
    sqlconfig.setPassword(password);
    sqlconfig.setHibernateConfig(true);

    return sqlconfig;
}

From source file:com.sakadream.sql.SQLConfigJson.java

License:MIT License

/**
 * Set hibernate.cfg.xml properties from SQLConfig object
 * @param config SQLConfig object//from  w w w  .jav  a 2  s  .c  o m
 * @param pkgLocation hibernate.cfg.xml's folder location
 */
public static void setHibernateCfg(SQLConfig config, String pkgLocation) {
    String url = "";
    if (config.getUrl() == null) {
        url = config.generateURL();
    } else {
        url = config.getUrl();
    }

    Configuration HBMconfig = new Configuration();
    HBMconfig.configure(pkgLocation + "hibernate.cfg.xml");
    HBMconfig.setProperty("hibernate.connection.username", config.getUsername());
    HBMconfig.setProperty("hibernate.connection.password", config.getPassword());
    HBMconfig.setProperty("hibernate.connection.url", url);
}

From source file:com.sam.moca.db.hibernate.HibernateTools.java

License:Open Source License

synchronized public static SessionFactory getSessionFactory(final MocaContext ctx) {
    if (_factory == null) {
        Configuration cfg = new Configuration();

        // First, load up default properties stored in MOCA 
        Properties props = new Properties();
        try {/* www .ja va2  s. co  m*/
            _loadProperties(props, HibernateTools.class.getResourceAsStream("resources/hibernate.properties"));
        } catch (IOException e) {
            ctx.logWarning("Unable to load hibernate properties: " + e);
            _sqlLogger.debug("Unable to load hibernate properties", e);
        }

        // Next, default the database dialect, based on MOCA's idea
        // of the database type.
        String dbType = ctx.getDb().getDbType();

        if (dbType.equals("ORACLE")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        } else if (dbType.equals("MSSQL")) {
            props.setProperty("hibernate.dialect", "com.sam.moca.db.hibernate.UnicodeSQLServerDialect");
        } else if (dbType.equals("H2")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        }

        SystemContext systemContext = ServerUtils.globalContext();

        // We get the data files in reverse.
        File[] files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.properties")) {
                    return true;
                }
                return false;
            }

        }, true);

        // For each directory in the list, look for a
        // hibernate.properties file.
        for (File propFile : files) {
            if (propFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading Properties file: " + propFile);
                    _loadProperties(props, new FileInputStream(propFile));
                } catch (IOException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                }
            }
        }

        cfg.setProperties(props);

        // We get the data files in reverse.
        files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.cfg.xml")) {
                    return true;
                }
                return false;
            }

        }, true);

        // Now look for hibernate config files in each mappings directory.
        for (File xmlFile : files) {
            if (xmlFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading config file: " + xmlFile);
                    cfg.configure(xmlFile);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load config file " + xmlFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate config", e);
                }
            }
        }

        _factory = cfg.buildSessionFactory();

        StatisticsService statsMBean = new StatisticsService();
        statsMBean.setSessionFactory(_factory);

        Exception excp = null;
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics"));
        } catch (InstanceAlreadyExistsException e) {
            excp = e;
        } catch (MBeanRegistrationException e) {
            excp = e;
        } catch (NotCompliantMBeanException e) {
            excp = e;
        } catch (MalformedObjectNameException e) {
            excp = e;
        }

        if (excp != null) {
            _sqlLogger.warn("Failed to export Hibernate Statistics "
                    + "Service.  Runtime statistics will not be viewable " + "from MBeans!", excp);
        }
    }

    return _factory;

}