List of usage examples for org.hibernate Session getSessionFactory
SessionFactory getSessionFactory();
From source file:org.castafiore.ecm.ui.fileexplorer.events.SearchFilesEvent.java
License:Open Source License
public boolean ServerAction(Container container, Map<String, String> request) throws UIException { EXInput input = container.getParent().getDescendentOfType(EXInput.class); String searchString = input.getValue().toString(); if (StringUtil.isNotEmpty(searchString)) { Session session = SpringUtil.getBeanOfType(Dao.class).getReadOnlySession(); Map map = session.getSessionFactory().getAllClassMetadata(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { String cls = iter.next().toString(); // Class clz = Thread.currentThread().getContextClassLoader().loadClass(cls); // if(clz.isAssignableFrom(FileImpl.class)){ // ClassMetadata m = (ClassMetadata)map.get(cls); // String[] properties = m.getPropertyNames(); // for(String property : properties){ // //m.getPropertyType(property).is // } // } }//from ww w . j ava 2 s . com List<File> files = SpringUtil.getRepositoryService() .executeQuery(new QueryParameters().setFullTextSearch(searchString), Util.getRemoteUser()); container.getAncestorOfType(Explorer.class).getView().showFiles(files); } return true; }
From source file:org.cgiar.ccafs.marlo.data.dao.impl.AuditLogDao.java
License:Open Source License
public void loadRelationsForIAuditLog(IAuditLog iAuditLog, String transactionID) { try {/*w ww .jav a 2 s. c o m*/ Session session = dao.openSession(); ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(iAuditLog.getClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String name : propertyNames) { Type propertyType = classMetadata.getPropertyType(name); if (propertyType instanceof OrderedSetType || propertyType instanceof SetType) { String classNameRelation = propertyType.getName(); String sql = "from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and main=3 and relation_name='" + classNameRelation + ":" + iAuditLog.getId() + "'order by ABS(ENTITY_ID) asc"; List<Auditlog> auditLogsRelations = dao.findAll(sql); Set<IAuditLog> relation = new HashSet<IAuditLog>(); for (Auditlog auditlog : auditLogsRelations) { IAuditLog relationObject = this.loadFromAuditLog(auditlog); this.loadRelationsForIAuditLog(relationObject, transactionID); relation.add(relationObject); } classMetadata.setPropertyValue(iAuditLog, name, relation, EntityMode.POJO); } } session.close(); } catch (JsonSyntaxException e) { e.printStackTrace(); } }
From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AuditLogMySQLDao.java
License:Open Source License
public void loadRelationsForIAuditLog(IAuditLog iAuditLog, String transactionID) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { try {//from w w w . ja v a2s. com Session session = super.getSessionFactory().getCurrentSession(); ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(iAuditLog.getClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String name : propertyNames) { try { Type propertyType = classMetadata.getPropertyType(name); Field privateField = iAuditLog.getClass().getDeclaredField(name); privateField.setAccessible(true); if (propertyType instanceof OneToOneType) { Object obj = privateField.get(iAuditLog); if (obj != null && obj instanceof IAuditLog) { this.loadRelationsForIAuditLog((IAuditLog) obj, transactionID); } } if (propertyType instanceof OrderedSetType || propertyType instanceof SetType) { String classNameRelation = propertyType.getName(); String sql = "from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and main=3 and relation_name='" + classNameRelation + ":" + iAuditLog.getId() + "'order by ABS(ENTITY_ID) asc"; List<Auditlog> auditLogsRelations = super.findAll(sql); Set<IAuditLog> relation = new HashSet<IAuditLog>(); for (Auditlog auditlog : auditLogsRelations) { IAuditLog relationObject = this.loadFromAuditLog(auditlog); this.loadRelationsForIAuditLog(relationObject, transactionID); relation.add(relationObject); } classMetadata.setPropertyValue(iAuditLog, name, relation); } } catch (Exception e) { } } } catch (JsonSyntaxException e) { e.printStackTrace(); } }
From source file:org.cgiar.ccafs.marlo.data.HibernateAuditLogListener.java
License:Open Source License
/** * This code should be simplified!!!//from w w w.j a v a 2s . c o m * * @param entity * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ public Set<HashMap<String, Object>> loadListOfRelations(IAuditLog entity, Session session) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Set<HashMap<String, Object>> setRelations = new HashSet<>(); entity = (IAuditLog) session.get(entity.getClass(), entity.getId()); ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entity.getClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String name : propertyNames) { Object propertyValue = classMetadata.getPropertyValue(entity, name); Type propertyType = classMetadata.getPropertyType(name); if (propertyValue != null && (propertyType instanceof OrderedSetType || propertyType instanceof SetType)) { /** Add instanceof check to ensure no classCast exceptions. **/ Set<?> checkElementCollectionTypes = (Set<?>) propertyValue; /** Java type erasure means we have to do it this way **/ if (checkElementCollectionTypes.size() == 0 || !(checkElementCollectionTypes.iterator().next() instanceof IAuditLog)) { /** We don't want to record entities that are not instances of IAuditLog such as SectionStatus **/ continue; } HashMap<String, Object> objects = new HashMap<>(); Set<IAuditLog> listRelation = new HashSet<>(); /** Our instanceof check in the if statement above ensures that we will only be dealing with IAuditLog **/ @SuppressWarnings(value = { "unchecked" }) Set<IAuditLog> entityRelation = (Set<IAuditLog>) propertyValue; String fieldSet = propertyType.getName() .replaceAll("java.util.Set\\(" + entity.getClass().getName() + ".", "") .replaceAll("\\)", ""); Field privateField = entity.getClass().getDeclaredField(fieldSet); privateField.setAccessible(true); Set<IAuditLog> set = (Set<IAuditLog>) privateField.get(entity); for (IAuditLog iAuditLog : set) { if (iAuditLog.isActive()) { listRelation.add(iAuditLog); } } objects.put(IAuditLog.ENTITY, listRelation); objects.put(IAuditLog.PRINCIPAL, "3"); objects.put(IAuditLog.RELATION_NAME, propertyType.getName() + ":" + entity.getId()); setRelations.add(objects); } } return setRelations; }
From source file:org.cgiar.ccafs.marlo.data.HibernateAuditLogListener.java
License:Open Source License
public Set<HashMap<String, Object>> relations(Object[] state, Type[] types, Object id, boolean firstRelations, Session session, Object object) { Set<HashMap<String, Object>> relations = new HashSet<>(); int i = 0;//ww w . j ava 2 s . co m String parentId = ""; try { parentId = id.toString(); } catch (Exception e1) { e1.printStackTrace(); parentId = ""; } /** * We load and refresh the object to get the relations updated. * Christian Garcia */ for (Type type : types) { HashMap<String, Object> objects = new HashMap<>(); if (type instanceof OneToOneType) { IAuditLog audit = (IAuditLog) state[i]; if (audit != null) { String name = audit.getClass().getName(); Class<?> className; try { className = Class.forName(name); Object obj = session.get(className, audit.getId()); Set<IAuditLog> listRelation = new HashSet<>(); listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this.loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap.get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (type instanceof OrderedSetType || type instanceof SetType) { if (AuditLogContextProvider.getAuditLogContext().getRelationsNames().contains(type.getName())) { Set<IAuditLog> listRelation = new HashSet<>(); try { String fieldSet = type.getName() .replaceAll("java.util.Set\\(" + object.getClass().getName() + ".", "") .replaceAll("\\)", ""); Field privateField = object.getClass().getDeclaredField(fieldSet); privateField.setAccessible(true); Set<Object> set = (Set<Object>) privateField.get(object); // Hibernate.initialize(set); if (set != null && !set.isEmpty()) { Object reObject = session.get( AuditLogContextProvider.getAuditLogContext().getEntityCanonicalName(), (Serializable) id); // session.refresh(reObject); ClassMetadata metadata = session.getSessionFactory() .getClassMetadata(reObject.getClass()); Object[] values = metadata.getPropertyValues(reObject); set = (Set<Object>) values[i]; for (Object iAuditLog : set) { if (iAuditLog instanceof IAuditLog) { IAuditLog audit = (IAuditLog) iAuditLog; if (audit.isActive()) { try { String name = audit.getClass().getName(); Class<?> className = Class.forName(name); /** * Ensure that lazy loaded collections are at least proxy instances (if not fetched). * If you are not getting all collections auditLogged it is because the Action classes are * persisting the detached entity and not copying across the managed collections (e.g. the ones * in our entities that are generally using Set). To overcome refactor the Action classes to copy * the List collections, which are full of detached entities, see OutcomeAction save method for an * example. * When issue #1124 is solved, this won't be a problem. */ /** * We load the object to get the id assigned * Christian Garcia */ Object obj = session.get(className, audit.getId()); if (obj == null) { /** * This is likely to be that the entity has just been hard deleted (MARLO has a mixture of * entities * where some are soft deleted and others are hard deleted). */ LOG.info("IAuditLog obj with className: " + className + ", and id: " + audit.getId() + " can not be found"); // Add the audit from the state object array listRelation.add(audit); continue; } else { ClassMetadata classMetadataObj = session.getSessionFactory() .getClassMetadata(obj.getClass()); String[] propertyNamesRelation = classMetadataObj .getPropertyNames(); Phase phaseObject = null; boolean hasPhase = false; for (String nameAtrribute : propertyNamesRelation) { if (nameAtrribute.equals("phase")) { phaseObject = (Phase) classMetadataObj.getPropertyValue(obj, nameAtrribute); if (phaseObject != null) { phaseObject = (Phase) session.get(Phase.class, phaseObject.getId()); if (phaseObject != null) { hasPhase = true; } } } } /* * if have phase and the phase is the current we are checking , we load the info */ if (hasPhase) { if (AuditLogContextProvider.getAuditLogContext().getPhase() .equals(phaseObject)) { listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this .loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap .get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } } else { /* * If doesn't have phase we alway load the info */ listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this .loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap .get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } } } catch (ClassNotFoundException e) { LOG.error(e.getLocalizedMessage()); } } } } if (!listRelation.isEmpty()) { objects.put(IAuditLog.ENTITY, listRelation); objects.put(IAuditLog.PRINCIPAL, "3"); objects.put(IAuditLog.RELATION_NAME, type.getName() + ":" + parentId); relations.add(objects); } } } catch (HibernateException e) { e.printStackTrace(); LOG.info("Can not load lazy relation " + e.getLocalizedMessage()); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchFieldException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } i++; } return relations; }
From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsSessionContext.java
License:Apache License
protected TransactionManager getJtaTransactionManager(Session session) { SessionFactoryImplementor sessionFactoryImpl = null; if (sessionFactory instanceof SessionFactoryImplementor) { sessionFactoryImpl = ((SessionFactoryImplementor) sessionFactory); } else if (session != null) { SessionFactory internalFactory = session.getSessionFactory(); if (internalFactory instanceof SessionFactoryImplementor) { sessionFactoryImpl = (SessionFactoryImplementor) internalFactory; }//from ww w. j av a2 s. c o m } if (sessionFactoryImpl == null) { return null; } ServiceBinding<JtaPlatform> sb = sessionFactory.getServiceRegistry() .locateServiceBinding(JtaPlatform.class); if (sb == null) { return null; } return sb.getService().retrieveTransactionManager(); }
From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractStaticPersistentMethod.java
License:Apache License
protected Criteria getCriteria(GrailsApplication appliation, Session session, Closure additionalCriteria, Class<?> clazz) {//from w w w. j a va 2 s .co m if (additionalCriteria != null) { HibernateCriteriaBuilder builder = new HibernateCriteriaBuilder(clazz, session.getSessionFactory()); builder.setGrailsApplication(appliation); return builder.buildCriteria(additionalCriteria); } return session.createCriteria(clazz); }
From source file:org.compass.gps.device.hibernate.indexer.ScrollableHibernateIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity entity : entities) { EntityInformation entityInformation = (EntityInformation) entity; if (device.isFilteredForIndex(entityInformation.getName())) { continue; }//from w ww . j a va 2 s. c om if (!device.isRunning()) { return; } ScrollableResults cursor = null; Session hibernateSession = device.getSessionFactory().openSession(); hibernateSession.setCacheMode(CacheMode.IGNORE); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entities [" + entityInformation.getName() + "] using query [" + entityInformation.getQueryProvider() + "]")); } Criteria criteria = entityInformation.getQueryProvider().createCriteria(hibernateSession, entityInformation); if (criteria != null) { if (performOrderById) { Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName()); if (performOrder == null || performOrder) { ClassMetadata metadata = hibernateSession.getSessionFactory() .getClassMetadata(entityInformation.getName()); String idPropName = metadata.getIdentifierPropertyName(); if (idPropName != null) { criteria.addOrder(Order.asc(idPropName)); } } } criteria.setFetchSize(device.getFetchCount()); cursor = criteria.scroll(ScrollMode.FORWARD_ONLY); } else { Query query = entityInformation.getQueryProvider().createQuery(hibernateSession, entityInformation); cursor = query.scroll(ScrollMode.FORWARD_ONLY); } // store things in row buffer to allow using batch fetching in Hibernate RowBuffer buffer = new RowBuffer(session, hibernateSession, device.getFetchCount()); Object prev = null; while (true) { try { if (!cursor.next()) { break; } } catch (ObjectNotFoundException e) { continue; } Object item = cursor.get(0); if (prev != null && item != prev) { buffer.put(prev); } prev = item; if (buffer.shouldFlush()) { // put also the item/prev since we are clearing the session // in the flush process buffer.put(prev); buffer.flush(); prev = null; } } if (prev != null) { buffer.put(prev); } buffer.close(); cursor.close(); hibernateTransaction.commit(); } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (cursor != null) { try { cursor.close(); } catch (Exception e1) { log.warn(device.buildMessage("Failed to close cursor on error, ignoring"), e1); } } if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); session.close(); } } }
From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreAccessor.java
License:Open Source License
private boolean isEReferenceMapped(Session session, String entityName, EReference eref) { // mapped/*w w w . ja v a 2 s .c o m*/ if (null != eref.getEAnnotation(TENEO_MAPPED_SOURCE)) { return true; } else // not mapped if (null != eref.getEAnnotation(TENEO_UNMAPPED_SOURCE)) { return false; } // not computed yet for (String propName : session.getSessionFactory().getClassMetadata(entityName).getPropertyNames()) { if (propName.equals(eref.getName())) { final EAnnotation eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation(); eAnnotation.setSource(TENEO_MAPPED_SOURCE); eref.getEAnnotations().add(eAnnotation); return true; } } // not mapped final EAnnotation eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation(); eAnnotation.setSource(TENEO_UNMAPPED_SOURCE); eref.getEAnnotations().add(eAnnotation); return false; }
From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreChunkReader.java
License:Open Source License
public List<Chunk> executeRead() { // get a transaction, the hibernateStoreAccessor is placed in a threadlocal // so all db access uses the same session. final Session session = getAccessor().getHibernateSession(); // reread the revision as it is probably unreferenced final InternalCDORevision latestRevision = getLatestRevision(session); Object value = latestRevision.getValue(getFeature()); if (value instanceof WrappedHibernateList) { value = ((WrappedHibernateList) value).getDelegate(); }// ww w . j a va 2s .c o m // hibernate details... boolean useExtraLazyMode = false; boolean standardCDOList = false; QueryableCollection persister = null; CollectionEntry entry = null; if (value instanceof PersistentCollection) { final PersistentCollection persistentCollection = (PersistentCollection) value; persister = (QueryableCollection) ((SessionFactoryImplementor) session.getSessionFactory()) .getCollectionPersister(persistentCollection.getRole()); entry = ((SessionImplementor) session).getPersistenceContext().getCollectionEntry(persistentCollection); useExtraLazyMode = !persister.getElementType().isEntityType(); if (useExtraLazyMode && ((PersistentCollection) value).hasQueuedOperations()) { session.flush(); } } else { standardCDOList = true; } final List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { final int startIndex = chunk.getStartIndex(); final int maxElements = chunk.size(); if (standardCDOList) { // for eattributes just read them all, no chunking there... final CDOList list = (CDOList) value; if (startIndex >= list.size()) { return chunks; } for (int i = startIndex; i < startIndex + maxElements; i++) { if (i >= list.size()) { break; } addToChunk(chunk, i - startIndex, list.get(i)); } } else if (useExtraLazyMode) { if (getFeature() instanceof EReference) { for (int i = startIndex; i < startIndex + maxElements; i++) { final Object object = persister.getElementByIndex(entry.getLoadedKey(), i, (SessionImplementor) session, latestRevision); // could happen if the index > size) if (object == null) { continue; } addToChunk(chunk, i - startIndex, object); } } else { // for eattributes just read them all, no chunking there... final List<?> list = (List<?>) value; if (startIndex >= list.size()) { return chunks; } for (int i = startIndex; i < startIndex + maxElements; i++) { if (i >= list.size()) { break; } addToChunk(chunk, i - startIndex, list.get(i)); } } } else { final Query filterQuery = session.createFilter(value, ""); filterQuery.setMaxResults(maxElements); filterQuery.setFirstResult(startIndex); int i = 0; for (Object object : filterQuery.list()) { addToChunk(chunk, i++, object); } } } return chunks; }