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:org.onebusaway.users.impl.UserDaoImplTest.java

License:Apache License

@Before
public void setup() throws IOException {

    Configuration config = new AnnotationConfiguration();
    config = config.configure("org/onebusaway/users/hibernate-configuration.xml");
    _sessionFactory = config.buildSessionFactory();

    _dao = new UserDaoImpl();
    _dao.setSessionFactory(_sessionFactory);
}

From source file:org.openmobster.core.common.database.HibernateManager.java

License:Open Source License

public void create() {
    try {//from   w w w  .jav a2 s.c  o m
        if (this.config != null && this.config.trim().length() > 0) {
            //Load using the specified configuration location
            Configuration configuration = new Configuration();
            configuration.configure(this.config);
            this.sessionFactory = configuration.buildSessionFactory();
        } else {
            //Load using the default location
            this.sessionFactory = new Configuration().configure().buildSessionFactory();
        }
    } catch (Exception e) {
        log.error(this, e);
        throw new RuntimeException(e);
    }
}

From source file:org.openmobster.core.common.database.HibernateManager.java

License:Open Source License

public void startSessionFactory(Document doc) {
    //Load using the specified configuration location
    Configuration configuration = new Configuration();
    configuration.configure(doc);
    this.sessionFactory = configuration.buildSessionFactory();
}

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 {//from  w  w w .j  av  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 {/*from ww w . j  a va 2  s. c  om*/

        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.ow2.proactive.resourcemanager.db.RMDBManager.java

License:Open Source License

private static RMDBManager createUsingProperties() {
    if (System.getProperty(JAVA_PROPERTYNAME_NODB) != null) {
        return createInMemoryRMDBManager();
    } else {//from   w ww  . j a va 2s.c  o m
        File configFile = new File(PAResourceManagerProperties
                .getAbsolutePath(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getValueAsString()));

        boolean drop = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getValueAsBoolean();
        boolean dropNS = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB_NODESOURCES.getValueAsBoolean();

        if (logger.isInfoEnabled()) {
            logger.info("Starting RM DB Manager " + "with drop DB = " + drop + " and drop nodesources = "
                    + dropNS + " and configuration file = " + configFile.getAbsolutePath());
        }

        Configuration configuration = new Configuration();

        if (configFile.getName().endsWith(".xml")) {
            configuration.configure(configFile);
        } else {
            try {
                Properties properties = new Properties();
                properties.load(Files.newBufferedReader(configFile.toPath(), Charset.defaultCharset()));
                configuration.addProperties(properties);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        return new RMDBManager(configuration, drop, dropNS);
    }
}

From source file:org.pentaho.pac.server.common.HibernateSessionFactory.java

License:Open Source License

public static void addConfiguration(String name, String configFile) {
    Configuration configuration = new AnnotationConfiguration();

    try {//from  ww  w.  ja v  a  2 s.  c  om
        File file = new File(configFile);
        if (file != null && file.exists()) {
            configuration.configure(file);
        } else {
            configuration.configure(configFile);
        }

        // If Hibernate is running in a managed environment
        SessionFactory sessionFactory = null;
        if (!DEFAULT_CONFIG_NAME.equals(name) || !AppConfigProperties.getInstance().isHibernateManaged()) {
            sessionFactory = configuration.buildSessionFactory();
        } else {
            String factoryJndiName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
            if (factoryJndiName != null && factoryJndiName.length() > 0) {
                sessionFactory = configuration.buildSessionFactory(); // Let hibernate Bind it to JNDI...  
            } else {
                throw new HibernateException(Messages.getErrorString(
                        "HibernateSessionFactory.ERROR_0002_MISSING_MANAGED_CONFIGURATION", //$NON-NLS-1$
                        Environment.SESSION_FACTORY_NAME.toString()));
            }
        }
        configs.put(name, new HibConfig(sessionFactory, configuration, configFile));
    } catch (Exception e) {
        throw new HibernateException(
                Messages.getErrorString("HibernateSessionFactory.ERROR_0003_UNABLE_TO_CREATE_SESSION_FACTORY", //$NON-NLS-1$
                        e.getLocalizedMessage()),
                e);
    }
}

From source file:org.pentaho.pat.plugin.PatLifeCycleListener.java

License:Open Source License

public void loaded() throws PluginLifecycleException {
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    IServiceManager serviceManager = (IServiceManager) PentahoSystem.get(IServiceManager.class,
            PentahoSessionHolder.getSession());
    try {/*from  ww  w  .  ja  v  a  2 s . c o  m*/
        sessionBean = (SessionServlet) serviceManager.getServiceBean("gwt", "session.rpc"); //$NON-NLS-1$
        queryBean = (QueryServlet) serviceManager.getServiceBean("gwt", "query.rpc"); //$NON-NLS-1$
        discoveryBean = (DiscoveryServlet) serviceManager.getServiceBean("gwt", "discovery.rpc"); //$NON-NLS-1$
        platformBean = (PlatformServlet) serviceManager.getServiceBean("gwt", "platform.rpc"); //$NON-NLS-1$

        final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class,
                PentahoSessionHolder.getSession());
        final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager
                .getClassLoader(PAT_PLUGIN_NAME);
        final String hibernateConfigurationFile = PentahoSystem
                .getSystemSetting("hibernate/hibernate-settings.xml", "settings/config-file", null); //$NON-NLS-1$
        final String pentahoHibConfigPath = PentahoSystem.getApplicationContext()
                .getSolutionPath(hibernateConfigurationFile);

        if (pluginClassloader == null)
            throw new ServiceException(Messages.getString("LifeCycleListener.NoPluginClassloader")); //$NON-NLS-1$

        Thread.currentThread().setContextClassLoader(pluginClassloader);
        final URL contextUrl = pluginClassloader.getResource(PAT_APP_CONTEXT);
        final URL patHibConfigUrl = pluginClassloader.getResource(PAT_HIBERNATE_CONFIG);
        final URL patPluginPropertiesUrl = pluginClassloader.getResource(PAT_PLUGIN_PROPERTIES);
        if (patHibConfigUrl == null)
            throw new ServiceException("File not found: PAT Hibernate Config : " + PAT_HIBERNATE_CONFIG);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Hibernate Config:" + patHibConfigUrl.toString());

        if (patPluginPropertiesUrl == null)
            throw new ServiceException("File not found: PAT Plugin properties : " + PAT_PLUGIN_PROPERTIES);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Plugin Properties:" + patPluginPropertiesUrl.toString());

        if (contextUrl != null) {
            String appContextUrl = contextUrl.toString();
            final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    new String[] { appContextUrl }, false);
            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setConfigLocation(appContextUrl);
            applicationContext.setAllowBeanDefinitionOverriding(true);

            final Configuration pentahoHibConfig = new Configuration();
            pentahoHibConfig.configure(new File(pentahoHibConfigPath));

            final AnnotationConfiguration patHibConfig = new AnnotationConfiguration();
            patHibConfig.configure(patHibConfigUrl);

            Properties properties = new Properties();
            properties.load(pluginClassloader.getResourceAsStream(PAT_PLUGIN_PROPERTIES));
            String hibernateDialectCfg = (String) properties.get("pat.plugin.datasource.hibernate.dialect");
            String hibernateDialect = null;
            if (StringUtils.isNotBlank(hibernateDialectCfg)) {
                if (hibernateDialectCfg.equals("auto")) {
                    hibernateDialect = pentahoHibConfig.getProperty("dialect");
                } else {
                    hibernateDialect = hibernateDialectCfg;
                }
            }

            if (StringUtils.isNotBlank(hibernateDialect)) {
                patHibConfig.setProperty("hibernate.dialect", hibernateDialect);
                LOG.info(PAT_PLUGIN_NAME + " : using hibernate dialect: " + hibernateDialect);
            }

            String dataSourceType = (String) properties.get("pat.plugin.datasource.type");
            String datasourceResource = null;
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jdbc")) {
                datasourceResource = PAT_DATASOURCE_JDBC;
                LOG.info(PAT_PLUGIN_NAME + " : using JDBC connection");

            }
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jndi")) {
                datasourceResource = PAT_DATASOURCE_JNDI;
                LOG.info(PAT_PLUGIN_NAME + " : using JNDI : " + (String) properties.get("jndi.name"));
            }

            XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(datasourceResource));
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setLocation(new ClassPathResource(PAT_PLUGIN_PROPERTIES));
            cfg.postProcessBeanFactory(factory);

            XmlBeanFactory bfSession = new XmlBeanFactory(new ClassPathResource(PAT_SESSIONFACTORY), factory);

            PropertyPlaceholderConfigurer cfgSession = new PropertyPlaceholderConfigurer();
            cfgSession.setProperties(patHibConfig.getProperties());
            cfgSession.postProcessBeanFactory(bfSession);

            ClassPathXmlApplicationContext tmpCtxt = new ClassPathXmlApplicationContext();
            tmpCtxt.refresh();
            DefaultListableBeanFactory tmpBf = (DefaultListableBeanFactory) tmpCtxt.getBeanFactory();

            tmpBf.setParentBeanFactory(bfSession);

            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setParent(tmpCtxt);
            applicationContext.refresh();

            sessionBean.setStandalone(true);
            SessionServlet.setApplicationContext(applicationContext);
            sessionBean.init();

            queryBean.setStandalone(true);
            QueryServlet.setApplicationContext(applicationContext);
            queryBean.init();

            discoveryBean.setStandalone(true);
            DiscoveryServlet.setApplicationContext(applicationContext);
            discoveryBean.init();

            platformBean.setStandalone(true);
            PlatformServlet.setApplicationContext(applicationContext);
            platformBean.init();

            injectPentahoXmlaUrl();
        } else {
            throw new Exception(Messages.getString("LifeCycleListener.AppContextNotFound"));
        }

    } catch (ServiceException e1) {
        LOG.error(e1.getMessage(), e1);
    } catch (ServletException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        // reset the classloader of the current thread
        if (origContextClassloader != null) {
            Thread.currentThread().setContextClassLoader(origContextClassloader);
        }
    }
}

From source file:org.qbi.seriescalendar.web.utils.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {//from  ww  w .  j  a va2 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");

        return configuration.buildSessionFactory(serviceRegistry);
    } 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:org.seasar.hibernate3.dao.impl.HibernateDaoMetaDataImpl.java

License:Apache License

private void setupHibernateNamedQuerys() {
    Configuration cfg = new Configuration();

    String hibernateConfigPath = s2sessionFactory_.getConfigPath();
    cfg.configure(ResourceUtil.getResource(hibernateConfigPath));
    namedQueries_ = cfg.getNamedQueries();
}