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.buy.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    int cost;//  w  w  w. ja  v a 2 s.  c  om
    HttpSession session = request.getSession(true);
    try {

        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();
        String UEmail = (String) session.getAttribute("email");
        int price = 0;

        price = (Integer) session.getAttribute("price");
        int i = Integer.parseInt(request.getParameter("i"));

        cost = Integer.parseInt(request.getParameter("cost"));
        if (price < cost) {
            out.println("You Dont have Enough Balance to purchase");
        } else {
            Date d = new Date();
            if (i == 1) {
                String comp = request.getParameter("comp");
                String email = request.getParameter("email");
                ShareBuy u = new ShareBuy();

                u.setDate(d);
                u.setRate(cost);
                u.setSellerEmail(email);
                u.setUseremail(UEmail);
                u.setStatus("BUY");
                u.setCompany(comp);
                u.setEnd_rate(0);
                session1.persist(u);
                price = price - cost;
                session.removeAttribute("price");

                session.setAttribute("price", price);
                t.commit();

                Transaction t1 = session1.beginTransaction();
                session1.createSQLQuery(
                        "UPDATE STOCK.STOCKUSER set MONEY=" + price + "   WHERE EMAIL='" + UEmail + "' ")
                        .executeUpdate();
                t1.commit();
                int moneyStock = 0;
                Transaction t3 = session1.beginTransaction();
                List list = session1.createQuery("from com.StockUser Where EMAIL='" + email + "'").list();
                Iterator iterator = list.iterator();

                for (int j = 0; j < list.size(); j++) {
                    StockUser user = (StockUser) iterator.next();
                    moneyStock = user.getMoney();

                }

                t3.commit();
                moneyStock = moneyStock + cost;
                Transaction t2 = session1.beginTransaction();
                session1.createSQLQuery(
                        "UPDATE STOCK.STOCKUSER set MONEY=" + moneyStock + "   WHERE EMAIL='" + email + "' ")
                        .executeUpdate();
                t2.commit();
                out.print("Success");

                Transaction t4 = session1.beginTransaction();
                TransactionT tra = new TransactionT();
                tra.setAmount(cost);
                tra.setSellermail(email);
                tra.setStatus("S-U");
                tra.setD(d);
                tra.setUsermail(UEmail);
                session1.persist(tra);
                t4.commit();

            }

        }

        session1.close();
    }

    catch (Exception e1) {

        e1.printStackTrace();
    }
}

From source file:com.camel.dao.HibernateConnector.java

private HibernateConnector() throws HibernateException {

    // build the config
    cfg = new Configuration().configure();

    sessionFactory = cfg.buildSessionFactory();
}

From source file:com.cgi.poc.dw.dao.HibernateUtil.java

public HibernateUtil() {
    try {// w w w .  ja  v  a2s . c o m
        File newConfiguration = new File(CONFIG_PATH);
        Yaml yaml = new Yaml();
        InputStream is = new FileInputStream(newConfiguration);

        LinkedHashMap yamlParsers = (LinkedHashMap<String, ArrayList>) yaml.load(is);

        LinkedHashMap databaseCfg = (LinkedHashMap<String, ArrayList>) yamlParsers.get("database");
        String driver = (String) databaseCfg.get("driverClass");
        String dbUrl = (String) databaseCfg.get("url");
        String userName = (String) databaseCfg.get("user");
        String userPwd = (String) databaseCfg.get("password");

        Configuration configuration = new Configuration();
        // need to be able to read config file to get the uname/pwd for testing.. can't 
        // use in memory DB b/c we need json, and geometry types which are not supported
        // by h2
        configuration.setProperty("connection.driver_class", driver);
        configuration.setProperty("hibernate.connection.url", dbUrl);
        configuration.setProperty("hibernate.connection.username", userName);
        configuration.setProperty("hibernate.connection.password", userPwd);
        configuration.setProperty("hibernate.current_session_context_class", "thread");

        configuration.addAnnotatedClass(User.class);
        configuration.addAnnotatedClass(FireEvent.class);
        configuration.addAnnotatedClass(EventEarthquake.class);
        configuration.addAnnotatedClass(EventWeather.class);
        configuration.addAnnotatedClass(EventFlood.class);
        configuration.addAnnotatedClass(EventHurricane.class);
        configuration.addAnnotatedClass(EventTsunami.class);
        configuration.addAnnotatedClass(EventVolcano.class);
        configuration.addAnnotatedClass(EventNotification.class);
        configuration.addAnnotatedClass(EventNotificationZipcode.class);
        configuration.addAnnotatedClass(EventNotificationUser.class);

        sessionFactory = configuration.buildSessionFactory();
        openSession = sessionFactory.openSession();
        Connection sqlConnection = ((SessionImpl) openSession).connection();
        sessionFactory.getCurrentSession();

        JdbcConnection conn = new JdbcConnection(sqlConnection);
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn);
        Liquibase liquibase = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), database);
        String ctx = null;
        liquibase.update(ctx);
    } catch (Exception ex) {
        Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(0);

    }

}

From source file:com.cloud.bridge.util.CloudSessionFactory.java

License:Open Source License

private CloudSessionFactory() {
    Configuration cfg = new Configuration();
    File file = ConfigurationHelper.findConfigurationFile("hibernate.cfg.xml");

    File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties");
    Properties dbProp = null;/*  w w w.  j a  va 2  s.c om*/
    String dbName = null;
    String dbHost = null;
    String dbUser = null;
    String dbPassword = null;
    String dbPort = null;

    if (null != propertiesFile) {

        if (EncryptionSecretKeyCheckerUtil.useEncryption()) {
            StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor();
            dbProp = new EncryptableProperties(encryptor);
        } else {
            dbProp = new Properties();
        }

        try {
            dbProp.load(new FileInputStream(propertiesFile));
        } catch (FileNotFoundException e) {
            logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
        } catch (IOException e) {
            logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
        }
    }

    //
    // we are packaging hibernate mapping files along with the class files, 
    // make sure class loader use the same class path when initializing hibernate mapping.
    // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner)
    //
    if (file != null && dbProp != null) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        cfg.configure(file);

        dbHost = dbProp.getProperty("db.cloud.host");
        dbName = dbProp.getProperty("db.awsapi.name");
        dbUser = dbProp.getProperty("db.cloud.username");
        dbPassword = dbProp.getProperty("db.cloud.password");
        dbPort = dbProp.getProperty("db.cloud.port");

        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName);
        cfg.setProperty("hibernate.connection.username", dbUser);
        cfg.setProperty("hibernate.connection.password", dbPassword);

        factory = cfg.buildSessionFactory();
    } else {
        logger.warn("Unable to open load db configuration");
        throw new RuntimeException("nable to open load db configuration");
    }
}

From source file:com.cloud.bridge.util.CloudStackSessionFactory.java

License:Open Source License

private CloudStackSessionFactory() {
    Configuration cfg = new Configuration();
    File file = ConfigurationHelper.findConfigurationFile("CloudStack.cfg.xml");

    File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties");
    Properties dbProp = null;/*from  www.  j ava2s.com*/
    String dbName = null;
    String dbHost = null;
    String dbUser = null;
    String dbPassword = null;
    String dbPort = null;

    if (null != propertiesFile) {

        if (EncryptionSecretKeyCheckerUtil.useEncryption()) {
            StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor();
            dbProp = new EncryptableProperties(encryptor);
        } else {
            dbProp = new Properties();
        }

        try {
            dbProp.load(new FileInputStream(propertiesFile));
        } catch (FileNotFoundException e) {
            logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
        } catch (IOException e) {
            logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
        }
    }

    //
    // we are packaging hibernate mapping files along with the class files, 
    // make sure class loader use the same class path when initializing hibernate mapping.
    // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner)
    //
    if (file != null && dbProp != null) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        cfg.configure(file);

        dbHost = dbProp.getProperty("db.cloud.host");
        dbName = dbProp.getProperty("db.cloud.name");
        dbUser = dbProp.getProperty("db.cloud.username");
        dbPassword = dbProp.getProperty("db.cloud.password");
        dbPort = dbProp.getProperty("db.cloud.port");

        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName);
        cfg.setProperty("hibernate.connection.username", dbUser);
        cfg.setProperty("hibernate.connection.password", dbPassword);

        factory = cfg.buildSessionFactory();
    } else {
        logger.warn("Unable to open load db configuration");
        throw new RuntimeException("nable to open load db configuration");
    }
}

From source file:com.co.codesoftware.persistencia.configuracion.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {/* w w w  .j av a2  s . c  o  m*/
        if (sessionFactory == null) {
            config = "/hibernate.cfg.xml";
            Configuration configuration = new Configuration()
                    .configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        return sessionFactory;
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.collaborativeClouds.workers.LoginLogoutHandler.java

public String verifyLogin(String incoming_info) throws JSONException {

    try {/*from  w w w  . j  a v a  2  s.  c  o  m*/
        SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
        mSession = sessFact.openSession();
        mTransaction = mSession.beginTransaction();
        JSONObject mObject = new JSONObject(incoming_info);
        List<TblAdmin> mAdminList = null;

        String username = mObject.getString("username");
        String password = mObject.getString("password");

        Query checkLogin = mSession
                .createQuery("from TblAdmin where username='" + username + "' and password='" + password + "'");
        mAdminList = (List<TblAdmin>) checkLogin.list();
        if (mAdminList.size() > 0) {
            UUID sess_id = UUID.randomUUID();
            String sessionid = "" + sess_id;
            SessionOperator mOperator = new SessionOperator();
            sessionid = mOperator.setSession(username, sessionid);
            return sessionid;
        } else {
            return "Failed";
        }

    } catch (Exception ex) {
        return "Failed";
    }
}

From source file:com.collaborativeclouds.workers.ParkingData.java

public String getParkingStatus() {
    try {/*from  w  ww.ja  v  a 2  s  . c om*/
        SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
        mSession = sessFact.openSession();
        mTransaction = mSession.beginTransaction();
        List<Parking> mPark = null;
        Query getParkData = mSession.createQuery("select slotno from Parking");
        mPark = (List<Parking>) getParkData.list();
        String json = new Gson().toJson(mPark);
        return json;
    } catch (Exception ex) {
        return "Failed";
    }
}

From source file:com.collaborativeclouds.workers.ParkingData.java

public String getSlotofUser_org(String username) {
    try {/*from   w  w  w  .j  a v a2 s  .  com*/
        SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
        mSession = sessFact.openSession();
        mTransaction = mSession.beginTransaction();
        List<Parking> mPark = null;
        Query getParkData = mSession.createQuery("from Parking where username='" + username + "'");
        mPark = (List<Parking>) getParkData.list();
        String json = new Gson().toJson(mPark);
        return json;
    } catch (Exception ex) {
        return "Failed";
    }
}

From source file:com.collaborativeclouds.workers.ParkingData.java

public String getSlotofUser(String username) {
    try {//from ww  w . j  av a2  s. co  m
        SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
        mSession = sessFact.openSession();
        mTransaction = mSession.beginTransaction();
        List<Parking> mPark = null;
        Criteria mCriteria = mSession.createCriteria(Parking.class);
        mCriteria.add(Restrictions.like("username", username));
        mPark = mCriteria.list();
        String json = new Gson().toJson(mPark);
        return json;
    } catch (Exception ex) {
        return "Failed";
    }
}