Example usage for org.hibernate.cfg Configuration Configuration

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

Introduction

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

Prototype

public Configuration() 

Source Link

Usage

From source file:com.querydsl.jpa.codegen.JPADomainExporterTest.java

License:Apache License

@Test
public void Execute_Multiple2() throws IOException {
    FileUtils.delete(new File("target/jpagen4"));
    Configuration config = new Configuration();
    for (Class<?> cl : Domain2.classes) {
        config.addAnnotatedClass(cl);// w w  w  .  j  a v  a  2  s  .  c o  m
    }
    JPADomainExporter exporter = new JPADomainExporter("Q", new File("target/jpagen4"), serializerConfig,
            convert(config));
    exporter.execute();

    List<String> failures = new ArrayList<String>();
    for (File file : new File("target/jpagen4/com/querydsl/jpa/domain2").listFiles()) {
        String result1 = Files.toString(file, Charsets.UTF_8);
        String result2 = Files.toString(
                new File("../querydsl-jpa/target/generated-test-sources/java/com/querydsl/jpa/domain2",
                        file.getName()),
                Charsets.UTF_8);
        if (!result1.equals(result2)) {
            System.err.println(file.getName());
            failures.add(file.getName());
        }
    }

    if (!failures.isEmpty()) {
        fail("Failed with " + failures.size() + " failures");
    }

}

From source file:com.querydsl.jpa.codegen.JPADomainExporterTest.java

License:Apache License

@Test
@Ignore // FIXME/*from w  w  w.  j  av a 2 s .c  o  m*/
public void Execute_Store() throws IOException {
    FileUtils.delete(new File("target/jpagen5"));
    File contact = new File("src/test/resources/store.hbm.xml");
    Configuration config = new Configuration();
    config.addFile(contact);
    JPADomainExporter exporter = new JPADomainExporter("Q", new File("target/jpagen5"), convert(config));
    exporter.execute();

    File targetFile = new File("target/jpagen5/com/querydsl/jpa/domain3/QStore.java");
    assertContains(targetFile, "StringPath code", "StringPath address");

    targetFile = new File("target/jpagen5/com/querydsl/jpa/domain3/QHardwareStore.java");
    assertContains(targetFile, "StringPath code = _super.code;", "StringPath address");
}

From source file:com.querydsl.jpa.testutil.HibernateTestRunner.java

License:Apache License

private void start() throws Exception {
    Configuration cfg = new Configuration();
    for (Class<?> cl : Domain.classes) {
        cfg.addAnnotatedClass(cl);/*www .j  a v  a  2s .  co m*/
    }
    String mode = Mode.mode.get() + ".properties";
    isDerby = mode.contains("derby");
    if (isDerby) {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    }
    Properties props = new Properties();
    InputStream is = HibernateTestRunner.class.getResourceAsStream(mode);
    if (is == null) {
        throw new IllegalArgumentException("No configuration available at classpath:" + mode);
    }
    props.load(is);
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(props).build();
    cfg.setProperties(props);
    sessionFactory = cfg.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();
    session.beginTransaction();
}

From source file:com.quix.aia.cn.imo.database.HibernateFactory.java

License:Open Source License

public static SessionFactory buildSessionFactory() throws HibernateException {
    if (sessionFactory != null) {
        closeFactory();/*from  w  w w  .j  a  v  a2 s  .c  om*/
    }

    Configuration configuration = new Configuration();
    configuration.configure();
    sessionFactory = configuration.buildSessionFactory();

    return sessionFactory;
}

From source file:com.quix.aia.cn.imo.database.HibernateFactory.java

License:Open Source License

public static SessionFactory buildIfNeeded() throws HibernateException {
    if (sessionFactory == null) {
        //Configuration configuration = new Configuration();
        // configuration.configure();
        //sessionFactory = configuration.buildSessionFactory();
        //sessionFactory = new Configuration().configure("com\\xml\\hibernate.cfg.xml").buildSessionFactory();
        sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
    } else {/*from  w  w w .j  a v  a  2 s. c  o m*/
        // sessionFactory = buildSessionFactory();
    }
    return sessionFactory;
}

From source file:com.r573.enfili.common.resource.db.hibernate.HibernateManager.java

License:Apache License

public static void init() {
    sessionFactory = new Configuration().configure().buildSessionFactory();
}

From source file:com.rapid.develop.core.system.dal.SessionFactoryBuilder.java

License:Apache License

/**
 * System.//from www.  j  a  v  a2s . co  m
 *
 * <p>Javassit??</p>
 *
 * @return SessionFactory
 */
public synchronized SessionFactory getEntitySessionFactory() {
    if (this.entitySessionFactory == null) {
        URL url = SessionFactoryBuilder.class.getResource(AppConfigure.HIBERNATE_CFG_XML);
        Configuration configuration = new Configuration().configure(url);
        AppConfigure appConfigure = AppConfigure.loadConfig();
        for (String key : appConfigure.getConfigurationValues().keySet()) {
            configuration.setProperty(key, appConfigure.getConfigurationValues().get(key));
        }
        configuration.setProperty("hibernate.hbm2ddl.auto", "create");
        configuration.addAnnotatedClass(Application.class);
        configuration.addAnnotatedClass(AppPlugin.class);
        configuration.addAnnotatedClass(AppPluginConfig.class);
        configuration.addAnnotatedClass(AppRestService.class);
        configuration.addAnnotatedClass(AppServiceClass.class);
        configuration.addAnnotatedClass(EntityDefination.class);
        configuration.addAnnotatedClass(FieldDefination.class);
        entitySessionFactory = configuration.buildSessionFactory();
    }
    return this.entitySessionFactory;
}

From source file:com.redhat.rhn.common.hibernate.ConnectionManager.java

License:Open Source License

/**
 * Create a SessionFactory, loading the hbm.xml files from the specified
 * location.//  w w w.  j  a  v  a2 s.  c  o  m
 * @param packageNames Package name to be searched.
 */
private void createSessionFactory() {
    if (sessionFactory != null && !sessionFactory.isClosed()) {
        return;
    }

    List<String> hbms = new LinkedList<String>();

    for (Iterator<String> iter = packageNames.iterator(); iter.hasNext();) {
        String pn = iter.next();
        hbms.addAll(FinderFactory.getFinder(pn).find("hbm.xml"));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found: " + hbms);
        }
    }

    try {
        Configuration config = new Configuration();
        /*
         * Let's ask the RHN Config for all properties that begin with
         * hibernate.*
         */
        LOG.info("Adding hibernate properties to hibernate Configuration");
        Properties hibProperties = Config.get().getNamespaceProperties("hibernate");
        hibProperties.put("hibernate.connection.username", Config.get().getString(ConfigDefaults.DB_USER));
        hibProperties.put("hibernate.connection.password", Config.get().getString(ConfigDefaults.DB_PASSWORD));

        hibProperties.put("hibernate.connection.url", ConfigDefaults.get().getJdbcConnectionString());

        config.addProperties(hibProperties);
        // Force the use of our txn factory
        if (config.getProperty(Environment.TRANSACTION_STRATEGY) != null) {
            throw new IllegalArgumentException("The property " + Environment.TRANSACTION_STRATEGY
                    + " can not be set in a configuration file;" + " it is set to a fixed value by the code");
        }

        for (Iterator<String> i = hbms.iterator(); i.hasNext();) {
            String hbmFile = i.next();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding resource " + hbmFile);
            }
            config.addResource(hbmFile);
        }
        if (configurators != null) {
            for (Iterator<Configurator> i = configurators.iterator(); i.hasNext();) {
                Configurator c = i.next();
                c.addConfig(config);
            }
        }

        // add empty varchar warning interceptor
        EmptyVarcharInterceptor interceptor = new EmptyVarcharInterceptor();
        interceptor.setAutoConvert(true);
        config.setInterceptor(interceptor);

        sessionFactory = config.buildSessionFactory();
    } catch (HibernateException e) {
        LOG.error("FATAL ERROR creating HibernateFactory", e);
    }
}

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

License:Open Source License

public void run() {
    try {/*from  www . j a  v  a 2s.  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 ww.  j av  a2s.  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);

    }

}