Example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

List of usage examples for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder.

Prototype

public StandardServiceRegistryBuilder() 

Source Link

Document

Create a default builder.

Usage

From source file:org.n52.sos.ds.hibernate.UnspecifiedSessionFactoryProvider.java

License:Open Source License

@Override
public void initialize(Properties properties) throws ConfigurationException {
    final DatasourceCallback datasourceCallback = getDatasourceCallback(properties);
    datasourceCallback.onInit(properties);
    try {//from  w  ww.j  a  v  a  2s .co m
        LOGGER.debug("Instantiating configuration and session factory");
        configuration = getConfiguration(properties);
        configuration.mergeProperties(properties);

        // set timestamp mapping to a special type to ensure time is always
        // queried in UTC
        configuration.registerTypeOverride(new UtcTimestampType());
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        this.sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session s = this.sessionFactory.openSession();
        try {
            HibernateMetadataCache.init(s);
            s.doWork(new Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    datasourceCallback.onFirstConnection(connection);
                }
            });
        } finally {
            returnConnection(s);
        }
    } catch (HibernateException he) {
        String exceptionText = "An error occurs during instantiation of the database connection pool!";
        LOGGER.error(exceptionText, he);
        cleanup();
        throw new ConfigurationException(exceptionText, he);
    }
}

From source file:org.n52.sos.inspire.aqd.persistence.ReportingHeaderSQLiteSessionFactory.java

License:Open Source License

private SessionFactory createSessionFactory(Properties properties) {
    Configuration cfg = new Configuration().addAnnotatedClass(JSONFragment.class);
    if (properties != null) {
        cfg.mergeProperties(properties);
    }//from w ww. j  av  a2 s.c o  m
    cfg.mergeProperties(defaultProperties);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
            .build();
    return cfg.buildSessionFactory(serviceRegistry);
}

From source file:org.openo.commonservice.extsys.db.util.HibernateSession.java

License:Apache License

/**
 * Get a hibernate sessionFactory.//from w  w  w .  jav a2s  .c  om
 */
public static SessionFactory init() {
    initConfigure();
    configuration = new Configuration().configure(cfgfile);
    configuration.setProperty("hibernate.connection.url",
            "jdbc:h2:tcp://localhost:18207/" + resourcePath + "db/extsys");
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:org.openo.commontosca.catalog.db.util.HibernateSession.java

License:Apache License

/**
 * Get a hibernate sessionFactory.//from  w  w w.jav  a  2s  . c  o m
 */
public static SessionFactory init() {
    initConfigure();
    configuration = new Configuration().configure(cfgfile);
    configuration.setProperty("hibernate.connection.url",
            "jdbc:h2:tcp://localhost:8205/" + resourcePath + "db/catalog");
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:org.openo.nfvo.monitor.umc.db.UmcDbSession.java

License:Apache License

private static SessionFactory createSession() {
    configuration = new Configuration().configure(cfgfile);
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:org.openo.nfvo.monitor.umc.pm.osf.db.util.HibernateSession.java

License:Apache License

/**
 * Get a hibernate sessionFactory./*  w  w w  .  j  a  v a2  s  .co m*/
 */
public static SessionFactory init() {
    createCfgFile();

    configuration = new Configuration().configure(cfgfile);
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:org.openremote.model.persistence.jpa.H2.java

License:Open Source License

/**
 * Creates an H2 configuration for Hibernate session factory.
 *
 * @param persistenceMode/*  w w  w.  j a  v  a  2s .  c  om*/
 *          see {@link PersistenceMode}
 *
 * @param dbName
 *          file path for the database storage -- only relevant when the persistence mode
 *          is {@link PersistenceMode#ON_DISK}
 *
 * @param config
 *          Hibernate configuration to use as the base
 *
 * @return
 *          Hibernate session factory
 */
private static SessionFactory createSessionFactory(PersistenceMode persistenceMode, String dbName,
        Configuration config) {
    config.setProperty("hibernate.connection.url", "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE");

    if (persistenceMode == PersistenceMode.ON_DISK) {
        config.setProperty("hibernate.connection.url", "jdbc:h2:" + dbName);
    }

    config.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    config.setProperty("hibernate.connection.username", "sa");
    config.setProperty("hibernate.connection.pool_size", "3");
    config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
    config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    config.setProperty("hibernate.hbm2ddl.auto", "create");

    config.setProperty("hibernate.current_session_context_class", "managed");

    ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();

    return config.buildSessionFactory(registry);
}

From source file:org.optaplanner.examples.app.OptaPlannerExamplesApp.java

License:Apache License

public static void generateXMLFile() {
    KING = new xmlKing();

    //Test DB connectivity
    String hibernatePropsFilePath = "D:\\Student Data\\Desktop\\optaplanner-distribution-6.1.0.Final\\examples\\sources\\src\\main\\resources\\hibernate.cfg.xml";
    //String hibernatePropsFilePath = "org.lsdt.optaplannerLittleSprouts.database.hibernate.cfg.xml";
    File hibernatePropsFile = new File(hibernatePropsFilePath);

    Configuration configuration = new Configuration();
    configuration.configure(hibernatePropsFile);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();

    try {/*ww  w . ja v  a2  s .  c  o m*/
        factory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    //Print all users
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        ArrayList<User> users = (ArrayList<User>) session.createQuery("FROM User WHERE type = 'T'").list();
        ArrayList<Child> children = (ArrayList<Child>) session.createQuery("FROM Child").list();
        ArrayList<Availability> childAvailabilities = (ArrayList<Availability>) session
                .createQuery("FROM Availability WHERE is_child = 1").list();
        ArrayList<Availability> teacherAvailabilities = (ArrayList<Availability>) session
                .createQuery("FROM Availability WHERE is_child = 0").list();

        KING.retrieveUserData(users);
        KING.retrieveChildAvailabilityData(childAvailabilities);
        KING.retrieveTeacherAvailabilityData(teacherAvailabilities);
        KING.retrieveChildData(children);
        KING.setWeekStart(box.getSelectedItem().toString());
        KING.doItAll(box.getSelectedItem().toString());

        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

From source file:org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame.java

License:Apache License

public void processOutput() {
    try {// w w w . j a  va2 s.  c o m

        System.out.println("Doing the stuff");
        String fileString = "C://" + weekStart + "solution.xml";
        File fXmlFile = new File(fileString);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        org.w3c.dom.Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("Employee");

        System.out.println("----------------------------");

        //maps employee ids to employee ids in the DB
        HashMap employeeMap = new HashMap();

        //maps shift reference ids to a genuine shift id
        HashMap shiftMap = new HashMap();

        //
        HashMap id2typeMap = new HashMap();

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                employeeMap.put(eElement.getAttribute("id").toString(),
                        eElement.getElementsByTagName("code").item(0).getTextContent());

            }
        }

        NodeList shiftTypeList = doc.getElementsByTagName("shiftType");
        for (int temp = 0; temp < shiftTypeList.getLength(); temp++) {
            Node nNode = shiftTypeList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element shiftType = (Element) nNode;

                //make sure it is a shift type declaration
                NodeList list = shiftType.getElementsByTagName("code");
                if (list.getLength() == 0)
                    continue;

                shiftMap.put(shiftType.getAttribute("id"), list.item(0).getTextContent());

                Integer wut = Integer.parseInt(shiftType.getAttribute("id")) - 1;
                shiftMap.put(wut, list.item(0).getTextContent());
            }
        }

        NodeList shiftList = doc.getElementsByTagName("Shift");
        for (int temp = 0; temp < shiftList.getLength(); temp++) {
            Node nNode = shiftList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element shift = (Element) nNode;

                //make sure it has a shift type declaration
                NodeList list = shift.getElementsByTagName("shiftType");
                if (list.getLength() == 0)
                    continue;

                if (list.item(0).getNodeType() != Node.ELEMENT_NODE)
                    continue;

                Element shiftType = (Element) list.item(0);

                if (shiftType.hasAttribute("reference")) {
                    id2typeMap.put(shift.getAttribute("id"), shiftType.getAttribute("reference"));
                } else {
                    NodeList codeList = shiftType.getElementsByTagName("code");

                    if (codeList.getLength() == 0)
                        continue;
                    if (codeList.item(0).getNodeType() == Node.ELEMENT_NODE) {
                        Element codeElement = (Element) codeList.item(0);

                        id2typeMap.put(shift.getAttribute("id"), codeElement.getTextContent());
                    }
                }
            }
        }

        NodeList assignmentList = doc.getElementsByTagName("ShiftAssignment");
        for (int temp = 0; temp < assignmentList.getLength(); temp++) {
            Node nNode = assignmentList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element assignment = (Element) nNode;

                NodeList list1 = assignment.getElementsByTagName("shift");
                NodeList list2 = assignment.getElementsByTagName("employee");
                if (list1.getLength() == 0 || list2.getLength() == 0)
                    continue;

                if (list1.item(0).getNodeType() != Node.ELEMENT_NODE
                        || list2.item(0).getNodeType() != Node.ELEMENT_NODE)
                    continue;

                Element shift = (Element) list1.item(0);
                Element employee = (Element) list2.item(0);

                String shiftReference = shift.getAttribute("reference");
                String shiftType = id2typeMap.get(shiftReference).toString();

                if (shiftMap.get(shiftType) == null)
                    continue;

                int shiftTypeInt = Integer.parseInt(shiftType);

                if (shiftMap.get(shiftType) != null) {
                    assignmentMap.put(shiftMap.get(shiftType),
                            employeeMap.get(employee.getAttribute("reference")));
                }
            }
        }

        Iterator it = assignmentMap.keySet().iterator();

        while (it.hasNext()) {
            String shift = (String) it.next();

            String employee = assignmentMap.get(shift).toString();

            //Test DB connectivity
            String hibernatePropsFilePath = "D:\\Student Data\\Desktop\\optaplanner-distribution-6.1.0.Final\\examples\\sources\\src\\main\\resources\\hibernate.cfg.xml";
            File hibernatePropsFile = new File(hibernatePropsFilePath);

            Configuration configuration = new Configuration();
            configuration.configure(hibernatePropsFile);

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            try {
                factory = configuration.buildSessionFactory(serviceRegistry);
            } catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object." + ex);
                throw new ExceptionInInitializerError(ex);
            }
            //Print all users
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                session.beginTransaction();

                Schedule s = new Schedule();
                s.setId(Integer.parseInt(employee));

                String description = shiftDescriptionMap.get(Integer.parseInt(shift)).toString();

                if (description.compareTo("Baby") == 0)
                    s.setRoom(1);
                else if (description.compareTo("Mini") == 0)
                    s.setRoom(2);
                else if (description.compareTo("Peewee") == 0)
                    s.setRoom(3);
                else if (description.compareTo("Mighty") == 0)
                    s.setRoom(4);
                else if (description.compareTo("Halfpint") == 0)
                    s.setRoom(5);
                else if (description.compareTo("Junior") == 0)
                    s.setRoom(6);
                else if (description.compareTo("Senior") == 0)
                    s.setRoom(7);
                else
                    s.setRoom(11);

                //get the time start and end
                Integer shiftId = Integer.parseInt(shift);
                if (shiftId < 200) {
                    //get monday shift
                    int shiftKey = shiftId - 100;
                    String mondayShift = mondayShifts.get(shiftKey);

                    int delimIndex = mondayShift.indexOf("-");
                    int startIndex = Integer.parseInt(mondayShift.substring(0, delimIndex));
                    int endIndex = Integer.parseInt(mondayShift.substring(delimIndex + 1));

                    Integer startHour = 600 + (Math.floorDiv(startIndex, 4) * 100);
                    Integer startMinute = (startIndex % 4) * 15;
                    Integer startTimeInteger = startHour + startMinute;
                    String startTime = startTimeInteger.toString();

                    Integer endHour = 600 + (Math.floorDiv(endIndex, 4) * 100);
                    Integer endMinutes = (endIndex % 4) * 15;
                    Integer endTimeInteger = endHour + endMinutes;
                    String endTime = endTimeInteger.toString();

                    if (startTime.length() < 4)
                        startTime = "0" + startTime;

                    s.setTime_start(startTime);
                    s.setTime_end(endTime);

                    //set the proper date
                    delimIndex = weekStart.indexOf("-");
                    String dateYear = weekStart.substring(0, delimIndex);
                    String newWeekStart = weekStart.substring(delimIndex + 1);
                    delimIndex = newWeekStart.indexOf("-");
                    String dateMonth = newWeekStart.substring(0, delimIndex);
                    String dateDay = newWeekStart.substring(newWeekStart.indexOf("-") + 1);
                    System.out.println("Date Month is " + dateMonth);
                    Calendar date = new GregorianCalendar(Integer.parseInt(dateYear),
                            Integer.parseInt(dateMonth) - 1, Integer.parseInt(dateDay));
                    System.out.println(date.getTime());
                    s.setDate(date.getTime());
                } else if (shiftId < 300) {
                    //get tuesday shift
                    int shiftKey = shiftId - 200;
                    String tuesdayShift = tuesdayShifts.get(shiftKey);

                    int delimIndex = tuesdayShift.indexOf("-");
                    int startIndex = Integer.parseInt(tuesdayShift.substring(0, delimIndex));
                    int endIndex = Integer.parseInt(tuesdayShift.substring(delimIndex + 1));

                    //convert to proper time format

                    Integer startHour = 600 + (Math.floorDiv(startIndex, 4) * 100);
                    Integer startMinute = (startIndex % 4) * 15;
                    Integer startTimeInteger = startHour + startMinute;
                    String startTime = startTimeInteger.toString();

                    Integer endHour = 600 + (Math.floorDiv(endIndex, 4) * 100);
                    Integer endMinutes = (endIndex % 4) * 15;
                    Integer endTimeInteger = endHour + endMinutes;
                    String endTime = endTimeInteger.toString();

                    if (startTime.length() < 4)
                        startTime = "0" + startTime;

                    s.setTime_start(startTime);
                    s.setTime_end(endTime);

                    //set the proper date
                    delimIndex = weekStart.indexOf("-");
                    String dateYear = weekStart.substring(0, delimIndex);
                    String newWeekStart = weekStart.substring(delimIndex + 1);
                    delimIndex = newWeekStart.indexOf("-");
                    String dateMonth = newWeekStart.substring(0, delimIndex);
                    String dateDay = newWeekStart.substring(newWeekStart.indexOf("-") + 1);

                    Calendar date = new GregorianCalendar(Integer.parseInt(dateYear),
                            Integer.parseInt(dateMonth) - 1, Integer.parseInt(dateDay));
                    date.add(Calendar.DAY_OF_MONTH, +1);
                    s.setDate(date.getTime());
                } else if (shiftId < 400) {
                    //get wednesday shift
                    int shiftKey = shiftId - 300;
                    String wednesdayShift = wednesdayShifts.get(shiftKey);

                    int delimIndex = wednesdayShift.indexOf("-");
                    int startIndex = Integer.parseInt(wednesdayShift.substring(0, delimIndex));
                    int endIndex = Integer.parseInt(wednesdayShift.substring(delimIndex + 1));

                    Integer startHour = 600 + (Math.floorDiv(startIndex, 4) * 100);
                    Integer startMinute = (startIndex % 4) * 15;
                    Integer startTimeInteger = startHour + startMinute;
                    String startTime = startTimeInteger.toString();

                    Integer endHour = 600 + (Math.floorDiv(endIndex, 4) * 100);
                    Integer endMinutes = (endIndex % 4) * 15;
                    Integer endTimeInteger = endHour + endMinutes;
                    String endTime = endTimeInteger.toString();

                    if (startTime.length() < 4)
                        startTime = "0" + startTime;

                    s.setTime_start(startTime);
                    s.setTime_end(endTime);

                    //set the proper date
                    delimIndex = weekStart.indexOf("-");
                    String dateYear = weekStart.substring(0, delimIndex);
                    String newWeekStart = weekStart.substring(delimIndex + 1);
                    delimIndex = newWeekStart.indexOf("-");
                    String dateMonth = newWeekStart.substring(0, delimIndex);
                    String dateDay = newWeekStart.substring(newWeekStart.indexOf("-") + 1);

                    Calendar date = new GregorianCalendar(Integer.parseInt(dateYear),
                            Integer.parseInt(dateMonth) - 1, Integer.parseInt(dateDay));
                    date.add(Calendar.DAY_OF_MONTH, +2);
                    s.setDate(date.getTime());
                } else if (shiftId < 500) {
                    //get thursday shift
                    int shiftKey = shiftId - 400;
                    String thursdayShift = thursdayShifts.get(shiftKey);

                    int delimIndex = thursdayShift.indexOf("-");
                    int startIndex = Integer.parseInt(thursdayShift.substring(0, delimIndex));
                    int endIndex = Integer.parseInt(thursdayShift.substring(delimIndex + 1));

                    Integer startHour = 600 + (Math.floorDiv(startIndex, 4) * 100);
                    Integer startMinute = (startIndex % 4) * 15;
                    Integer startTimeInteger = startHour + startMinute;
                    String startTime = startTimeInteger.toString();

                    Integer endHour = 600 + (Math.floorDiv(endIndex, 4) * 100);
                    Integer endMinutes = (endIndex % 4) * 15;
                    Integer endTimeInteger = endHour + endMinutes;
                    String endTime = endTimeInteger.toString();

                    if (startTime.length() < 4)
                        startTime = "0" + startTime;

                    s.setTime_start(startTime);
                    s.setTime_end(endTime);

                    //set the proper date
                    delimIndex = weekStart.indexOf("-");
                    String dateYear = weekStart.substring(0, delimIndex);
                    String newWeekStart = weekStart.substring(delimIndex + 1);
                    delimIndex = newWeekStart.indexOf("-");
                    String dateMonth = newWeekStart.substring(0, delimIndex);
                    String dateDay = newWeekStart.substring(newWeekStart.indexOf("-") + 1);

                    Calendar date = new GregorianCalendar(Integer.parseInt(dateYear),
                            Integer.parseInt(dateMonth) - 1, Integer.parseInt(dateDay));
                    date.add(Calendar.DAY_OF_MONTH, +3);
                    s.setDate(date.getTime());
                } else {
                    //get friday shift
                    int shiftKey = shiftId - 500;
                    String fridayShift = fridayShifts.get(shiftKey);

                    int delimIndex = fridayShift.indexOf("-");
                    int startIndex = Integer.parseInt(fridayShift.substring(0, delimIndex));
                    int endIndex = Integer.parseInt(fridayShift.substring(delimIndex + 1));

                    Integer startHour = 600 + (Math.floorDiv(startIndex, 4) * 100);
                    Integer startMinute = (startIndex % 4) * 15;
                    Integer startTimeInteger = startHour + startMinute;
                    String startTime = startTimeInteger.toString();

                    Integer endHour = 600 + (Math.floorDiv(endIndex, 4) * 100);
                    Integer endMinutes = (endIndex % 4) * 15;
                    Integer endTimeInteger = endHour + endMinutes;
                    String endTime = endTimeInteger.toString();

                    if (startTime.length() < 4)
                        startTime = "0" + startTime;

                    s.setTime_start(startTime);
                    s.setTime_end(endTime);

                    //set the proper date
                    delimIndex = weekStart.indexOf("-");
                    String dateYear = weekStart.substring(0, delimIndex);
                    String newWeekStart = weekStart.substring(delimIndex + 1);
                    delimIndex = newWeekStart.indexOf("-");
                    String dateMonth = newWeekStart.substring(0, delimIndex);
                    String dateDay = newWeekStart.substring(newWeekStart.indexOf("-") + 1);

                    Calendar date = new GregorianCalendar(Integer.parseInt(dateYear),
                            Integer.parseInt(dateMonth) - 1, Integer.parseInt(dateDay));
                    date.add(Calendar.DAY_OF_MONTH, +4);
                    s.setDate(date.getTime());
                }

                session.save(s);
                session.getTransaction().commit();

            } catch (HibernateException e) {
                if (tx != null)
                    tx.rollback();
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.primefaces.omega.Util.NewHibernateUtil.java

private NewHibernateUtil() {

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
            .build();//  ww  w. j a v a2s. c  o m
    factory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
    ;
}