List of usage examples for org.hibernate.cfg Configuration getProperties
public Properties getProperties()
From source file:org.optaplanner.examples.common.swingui.SolverAndPersistenceFrame.java
License:Apache License
public void processOutput() { try {/*from w w 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.overlord.rtgov.common.jpa.JpaStore.java
License:Apache License
/** * This method returns a Session.//from ww w. j a va2 s . c o m * * @return The Session */ private Session getSession() { if (_persistenceUnit == null) { if (_sessionFactory == null) { final Configuration cfg = new Configuration().configure(_configXml); final Properties properties = RTGovProperties.getProperties(); if (_jndiProperty != null) { String prop = RTGovProperties.getProperty(_jndiProperty); if (prop != null) { properties.setProperty(AvailableSettings.DATASOURCE, prop); } } final String jtaPlatform = RTGovProperties.getProperty(JTA_PLATFORM_PROPERTY); if (jtaPlatform == null) { LOG.warning("JpaStore.jtaPlatform not set in overlord-rtgov.properties!"); _isJta = false; } else { properties.setProperty(AvailableSettings.JTA_PLATFORM, RTGovProperties.getProperty(JTA_PLATFORM_PROPERTY)); } cfg.getProperties().putAll(properties); _sessionFactory = cfg.buildSessionFactory(); } return _sessionFactory.openSession(); } else { // NOTE: For backward compatibility in EAP, I'm allowing the // continued use of a persistence unit. // Simply use it to create an EntityManager, then unwrap to the // native Hibernate Session. if (_entityManagerFactory == null) { final Properties properties = RTGovProperties.getProperties(); if (_jndiProperty != null) { properties.setProperty(AvailableSettings.DATASOURCE, RTGovProperties.getProperty(_jndiProperty)); } final String jtaPlatform = RTGovProperties.getProperty(JTA_PLATFORM_PROPERTY); if (jtaPlatform == null) { LOG.warning("JpaStore.jtaPlatform not set in overlord-rtgov.properties!"); _isJta = false; } else { properties.setProperty(AvailableSettings.JTA_PLATFORM, RTGovProperties.getProperty(JTA_PLATFORM_PROPERTY)); } _entityManagerFactory = Persistence.createEntityManagerFactory(_persistenceUnit, properties); } return _entityManagerFactory.createEntityManager().unwrap(Session.class); } }
From source file:org.ow2.bonita.search.SearchUtil.java
License:Open Source License
public static void addSearchConfiguration(final Configuration configuration) { boolean disable = disableSearchConfiguration(configuration); if (disable) { if (LOG.isLoggable(Level.INFO)) { LOG.info("Disable Bonita Indexes"); }// w w w .j a v a 2 s .c om } else { if (LOG.isLoggable(Level.INFO)) { LOG.info("Configuring indexes"); } SearchMapping mapping = new SearchMapping(); mapping.entity(InternalProcessDefinition.class).indexed().indexName("process_definition") .property("dbid", ElementType.FIELD).documentId().name(ProcessDefinitionIndex.DBID) .entity(LightProcessDefinitionImpl.class).property("uuid", ElementType.FIELD).field() .name(ProcessDefinitionIndex.UUID).bridge(UUIDFieldBridge.class) .property("categoryNames", ElementType.METHOD).field() .name(ProcessDefinitionIndex.CATEGORY_NAME).bridge(StringSetFieldBridge.class) .entity(NamedElementImpl.class).property("name", ElementType.METHOD).field() .name(ProcessDefinitionIndex.NAME).entity(DescriptionElementImpl.class) // share with All DescriptionElement: processes, groups, ... .property("description", ElementType.METHOD).field().name(ProcessDefinitionIndex.DESCRIPTION) .entity(InternalProcessInstance.class).indexed().indexName("process_instance") .property("dbid", ElementType.FIELD).documentId().name(ProcessInstanceIndex.DBID) .entity(ProcessInstanceImpl.class).property("commentFeed", ElementType.METHOD).indexEmbedded() .property("involvedUsers", ElementType.METHOD).field().name(ProcessInstanceIndex.INVOLVED_USER) .bridge(StringSetFieldBridge.class).property("activities", ElementType.METHOD).indexEmbedded() .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).property("activeUsers", ElementType.METHOD).field() .name(ProcessInstanceIndex.ACTIVE_USER).bridge(StringSetFieldBridge.class) .entity(LightProcessInstanceImpl.class).property("nb", ElementType.FIELD).field() .name(ProcessInstanceIndex.NB).property("startedBy", ElementType.METHOD).field() .name(ProcessInstanceIndex.STARTED_BY).property("endedBy", ElementType.METHOD).field() .name(ProcessInstanceIndex.ENDED_BY).property("startedDate", ElementType.METHOD).field() .name(ProcessInstanceIndex.STARTED_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("endedDate", ElementType.METHOD).field() .name(ProcessInstanceIndex.ENDED_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("lastUpdate", ElementType.METHOD).field() .name(ProcessInstanceIndex.LAST_UPDATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).entity(RuntimeRecordImpl.class) .property("processDefinitionUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_DEFINITION_UUID).bridge(UUIDFieldBridge.class) .property("processInstanceUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_INSTANCE_UUID).bridge(UUIDFieldBridge.class) .property("rootInstanceUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_ROOT_INSTANCE_UUID).bridge(UUIDFieldBridge.class) .entity(CommentImpl.class).indexed().indexName("comment").property("dbid", ElementType.FIELD) .documentId().name(CommentIndex.DBID).entity(Comment.class) .property("message", ElementType.METHOD).field().name(CommentIndex.MESSAGE) .property("userId", ElementType.METHOD).field().name(CommentIndex.AUTHOR) .property("date", ElementType.METHOD).field().name(CommentIndex.DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND) .entity(InternalActivityInstance.class).indexed().indexName("activity_instance") .property("dbid", ElementType.FIELD).documentId().name(ActivityInstanceIndex.DBID) .entity(TaskInstance.class).property("taskCandidates", ElementType.METHOD).field() .name(ActivityInstanceIndex.CANDIDATE).bridge(StringSetFieldBridge.class) .entity(ActivityInstanceImpl.class).property("taskCandidates", ElementType.METHOD).field() .name(ActivityInstanceIndex.CANDIDATE).bridge(StringSetFieldBridge.class) .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).entity(LightActivityInstanceImpl.class) .property("activityName", ElementType.METHOD).field().name(ActivityInstanceIndex.NAME) .property("state", ElementType.METHOD).field().name(ActivityInstanceIndex.STATE) .property("priority", ElementType.METHOD).field().name(ActivityInstanceIndex.PRIORITY) .index(Index.UN_TOKENIZED).property("lastUpdate", ElementType.METHOD).field() .name(ActivityInstanceIndex.LAST_UPDATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("expectedEndDate", ElementType.METHOD).field() .name(ActivityInstanceIndex.EXPECTED_END_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).entity(ActivityInstance.class) .property("activityName", ElementType.METHOD).field().name(ActivityInstanceIndex.NAME) .property("state", ElementType.METHOD).field().name(ActivityInstanceIndex.STATE) .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).entity(LightActivityInstance.class) .property("activityDescription", ElementType.METHOD).field() .name(ActivityInstanceIndex.DESCRIPTION).property("priority", ElementType.METHOD).field() .name(ActivityInstanceIndex.PRIORITY).index(Index.UN_TOKENIZED) .property("lastUpdate", ElementType.METHOD).field().name(ActivityInstanceIndex.LAST_UPDATE) .index(Index.UN_TOKENIZED).dateBridge(Resolution.MILLISECOND) .property("expectedEndDate", ElementType.METHOD).field() .name(ActivityInstanceIndex.EXPECTED_END_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND) .entity(UserImpl.class).indexed().indexName("user").property("dbid", ElementType.FIELD) .documentId().name(UserIndex.DBID).property("username", ElementType.FIELD).field() .name(UserIndex.NAME).property("firstName", ElementType.FIELD).field() .name(UserIndex.FIRST_NAME).property("lastName", ElementType.FIELD).field() .name(UserIndex.LAST_NAME).property("manager", ElementType.FIELD).field() .name(UserIndex.MANAGER).property("delegate", ElementType.FIELD).field() .name(UserIndex.DELEGATE).property("title", ElementType.FIELD).field().name(UserIndex.TITLE) .property("jobTitle", ElementType.FIELD).field().name(UserIndex.JOB_TITLE) .property("professionalContactInfo", ElementType.FIELD).indexEmbedded() .property("personalContactInfo", ElementType.FIELD).indexEmbedded().entity(ContactInfo.class) .property("email", ElementType.METHOD).field().name(ContactInfoIndex.EMAIL) .property("phoneNumber", ElementType.METHOD).field().name(ContactInfoIndex.PHONE_NUMBER) .property("faxNumber", ElementType.METHOD).field().name(ContactInfoIndex.FAX_NUMBER) .property("building", ElementType.METHOD).field().name(ContactInfoIndex.BUILDING) .property("room", ElementType.METHOD).field().name(ContactInfoIndex.ROOM) .property("address", ElementType.METHOD).field().name(ContactInfoIndex.ADDRESS) .property("zipCode", ElementType.METHOD).field().name(ContactInfoIndex.ZIP_CODE) .property("city", ElementType.METHOD).field().name(ContactInfoIndex.CITY) .property("state", ElementType.METHOD).field().name(ContactInfoIndex.STATE) .property("country", ElementType.METHOD).field().name(ContactInfoIndex.COUNTRY) .property("website", ElementType.METHOD).field().name(ContactInfoIndex.WEBSITE) .entity(RoleImpl.class).indexed().indexName("role").property("dbid", ElementType.FIELD) .documentId().name(RoleIndex.DBID).property("name", ElementType.FIELD).field() .name(RoleIndex.NAME).property("label", ElementType.FIELD).field().name(RoleIndex.LABEL) .entity(GroupImpl.class).indexed().indexName("group").property("dbid", ElementType.FIELD) .documentId().name(GroupIndex.DBID).property("name", ElementType.METHOD).field() .name(GroupIndex.NAME).property("label", ElementType.METHOD).field().name(GroupIndex.LABEL) .entity(CaseImpl.class).indexed().indexName("case").property("dbid", ElementType.FIELD) .documentId().name(CaseIndex.DBID).property("labelName", ElementType.FIELD).field() .name(CaseIndex.LABEL_NAME).property("ownerName", ElementType.FIELD).field() .name(CaseIndex.OWNER_NAME).property("uuid", ElementType.FIELD).field() .name(CaseIndex.PROCESS_INSTANCE_UUID).bridge(UUIDFieldBridge.class); configuration.getProperties().put(Environment.MODEL_MAPPING, mapping); configuration.setProperty("hibernate.search.default.directory_provider", FSDirectoryProvider.class.getName()); String path = getDefaultIndexesDirectorPath(configuration); configuration.setProperty("hibernate.search.default.indexBase", path); configuration.setProperty("hibernate.search.autoregister_listeners", "false"); String fullTextIndexListener = FullTextIndexEventListener.class.getName(); configuration.setListener("post-update", fullTextIndexListener); configuration.setListener("post-insert", fullTextIndexListener); configuration.setListener("post-delete", fullTextIndexListener); configuration.setListener("post-collection-recreate", fullTextIndexListener); configuration.setListener("post-collection-remove", fullTextIndexListener); configuration.setListener("post-collection-update", fullTextIndexListener); String[] listeners = new String[] { DefaultFlushEventListener.class.getName(), fullTextIndexListener }; configuration.setListeners("flush", listeners); } }
From source file:org.paxle.data.db.impl.ConnectionUrlTool.java
License:Open Source License
public static void postProcessProperties(Configuration configuration) { // getting db-config-properties Properties configProps = configuration.getProperties(); String connectionURL = configProps.getProperty("connection.url"); if (connectionURL != null) { configuration.setProperty("connection.url", processProperty(connectionURL)); }/* ww w .j a va 2 s .c om*/ connectionURL = configProps.getProperty("hibernate.connection.url"); if (connectionURL != null) { configuration.setProperty("hibernate.connection.url", processProperty(connectionURL)); } }
From source file:org.qbi.seriescalendar.web.utils.HibernateUtil.java
private static SessionFactory buildSessionFactory() { try {/*from 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"); 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.semtix.db.hibernate.HibernateUtil.java
License:Open Source License
private static SessionFactory buildSessionFactory() { Configuration configuration; try {//from w w w. j a va 2s . c o m String path = SettingsExternal.HIBERNATE_CONF_XML; if (path.trim().length() <= 1) { configuration = new Configuration().configure(); } else { // Create the SessionFactory from hibernate.cfg.xml configuration = new Configuration().configure(new File(path)); } } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed configuration = new Configuration().configure(); } StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); return configuration.buildSessionFactory(builder.build()); }
From source file:org.smartsnip.persistence.hibernate.DBSessionFactory.java
/** * initialize the session factory// w w w. j a v a2 s . c o m * * @param configFile * the path to the configuration file * @throws ExceptionInInitializerError */ private static synchronized void initialize(String configFile) throws ExceptionInInitializerError { if (configFile == null || configFile.isEmpty()) { configFile = "/hibernate.cfg.xml"; } if (factory == null) { try { Configuration configuration = new Configuration(); configuration.configure(configFile); // add entity classes configuration.addAnnotatedClass(DBCategory.class); configuration.addAnnotatedClass(DBCode.class); configuration.addAnnotatedClass(DBCodeFile.class); configuration.addAnnotatedClass(DBComment.class); configuration.addAnnotatedClass(DBFavourite.class); configuration.addAnnotatedClass(DBLanguage.class); configuration.addAnnotatedClass(DBLicense.class); configuration.addAnnotatedClass(DBLogin.class); configuration.addAnnotatedClass(DBNotification.class); configuration.addAnnotatedClass(DBRating.class); configuration.addAnnotatedClass(DBSnippet.class); configuration.addAnnotatedClass(DBTag.class); configuration.addAnnotatedClass(DBUser.class); configuration.addAnnotatedClass(DBVote.class); configuration.addAnnotatedClass(DBRelTagSnippet.class); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); factory = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { Logger log = Logger.getLogger(DBSessionFactory.class); log.error("Failed to create sessionFactory object.", ex); throw new ExceptionInInitializerError(ex); } } }
From source file:org.specrunner.hibernate4.PluginSessionFactory.java
License:Open Source License
/** * Create session service registry.//w ww.j a va 2s. co m * * @param cfg * A configuration. * @return A service registry. */ protected ServiceRegistry createServiceRegistry(Configuration cfg) { Properties properties = cfg.getProperties(); Environment.verifyProperties(properties); ConfigurationHelper.resolvePlaceHolders(properties); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build(); return serviceRegistry; }
From source file:org.transitime.db.hibernate.HibernateUtils.java
License:Open Source License
/** * Creates a new session factory. This is to be cached and only access * internally since creating one is expensive. * //from ww w . j a v a2 s . co m * @param dbName * @return */ private static SessionFactory createSessionFactory(String dbName) throws HibernateException { logger.debug("Creating new Hibernate SessionFactory for dbName={}", dbName); // Create a Hibernate configuration based on customized config file Configuration config = new Configuration(); // Want to be able to specify a configuration file for now // since developing in Eclipse and want all config files // to be in same place. But the Config.configure(String) // method can't seem to work with a Windows directory name such // as C:/users/Mike/software/hibernate.cfg.xml . Therefore create // a File object for that file name and pass in the File object // to configure(). String fileName = DbSetupConfig.getHibernateConfigFileName(); logger.info("Configuring Hibernate for dbName={} using config file={}", dbName, fileName); File f = new File(fileName); if (!f.exists()) { logger.info( "The Hibernate file {} doesn't exist as a regular file " + "so seeing if it is in classpath.", fileName); // Couldn't find file directly so look in classpath for it ClassLoader classLoader = HibernateUtils.class.getClassLoader(); URL url = classLoader.getResource(fileName); if (url != null) f = new File(url.getFile()); } if (f.exists()) config.configure(f); else { logger.error("Could not load in hibernate config file {}", fileName); } // Add the annotated classes so that they can be used AnnotatedClassesList.addAnnotatedClasses(config); // Set the db info for the URL, user name, and password. Use values // from CoreConfig if set. If they are not set then the values will be // obtained from the hibernate.cfg.xml // config file. String dbUrl = null; if (DbSetupConfig.getDbHost() != null) { dbUrl = "jdbc:" + DbSetupConfig.getDbType() + "://" + DbSetupConfig.getDbHost() + "/" + dbName; config.setProperty("hibernate.connection.url", dbUrl); } else { dbUrl = config.getProperty("hibernate.connection.url"); } String dbUserName = DbSetupConfig.getDbUserName(); if (dbUserName != null) { config.setProperty("hibernate.connection.username", dbUserName); } else { dbUserName = config.getProperty("hibernate.connection.username"); } if (DbSetupConfig.getDbPassword() != null) config.setProperty("hibernate.connection.password", DbSetupConfig.getDbPassword()); // Log info, but don't log password. This can just be debug logging // even though it is important because the C3P0 connector logs the info. logger.debug( "For Hibernate factory project dbName={} " + "using url={} username={}, and configured password", dbName, dbUrl, dbUserName); // Get the session factory for persistence Properties properties = config.getProperties(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); // Return the factory return sessionFactory; }
From source file:org.trianacode.TrianaCloud.Utils.DAO.java
License:Open Source License
private static SessionFactory buildSessionFactory() { try {/*from w w w .j a v a 2s . co m*/ // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); 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); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }