Example usage for org.hibernate.type Type getName

List of usage examples for org.hibernate.type Type getName

Introduction

In this page you can find the example usage for org.hibernate.type Type getName.

Prototype

String getName();

Source Link

Document

Returns the abbreviated name of the type.

Usage

From source file:com.autobizlogic.abl.mgmt.ClassMetadataService.java

License:Open Source License

public static Map<String, Object> getMetadataForClass(Map<String, String> args) {
    String sessionFactoryId = args.get("sessionFactoryId");
    String name = args.get("className");
    HashMap<String, Object> result = new HashMap<String, Object>();

    SessionFactory factory = HibernateConfiguration.getSessionFactoryById(sessionFactoryId);
    if (factory == null)
        return null;

    ClassMetadata meta = factory.getClassMetadata(name);
    if (meta == null)
        return null;

    result.put("sessionFactoryId", sessionFactoryId);
    result.put("className", meta.getEntityName());
    result.put("identifierPropertyName", meta.getIdentifierPropertyName());

    Class<?> cls = meta.getMappedClass(EntityMode.POJO);
    Class<?> supercls = cls.getSuperclass();
    while (ProxyFactory.isProxyClass(supercls))
        supercls = supercls.getSuperclass();
    result.put("superclassName", supercls.getName());

    Map<String, String> properties = new HashMap<String, String>();
    Map<String, Object> collections = new HashMap<String, Object>();
    Map<String, String> associations = new HashMap<String, String>();

    String[] propNames = meta.getPropertyNames();
    Type[] propTypes = meta.getPropertyTypes();
    int i = 0;//from w  w  w.j a v  a  2 s. c om
    for (String propName : propNames) {
        if (propTypes[i].isCollectionType()) {
            CollectionType collType = (CollectionType) propTypes[i];
            Type elementType = collType.getElementType((SessionFactoryImplementor) factory);
            HashMap<String, String> collEntry = new HashMap<String, String>();
            collEntry.put("collectionType", collType.getReturnedClass().getName());
            collEntry.put("elementType", elementType.getName());
            collections.put(propName, collEntry);
        } else if (propTypes[i].isAssociationType()) {
            AssociationType assType = (AssociationType) propTypes[i];
            String assName = assType.getAssociatedEntityName((SessionFactoryImplementor) factory);
            associations.put(propName, assName);
        } else {
            properties.put(propName, propTypes[i].getName());
        }
        i++;
    }
    result.put("properties", properties);
    result.put("associations", associations);
    result.put("collections", collections);

    MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(factory);
    LogicGroup logicGroup = RuleManager.getInstance(metaModel).getLogicGroupForClassName(name);
    if (logicGroup != null) {

        // Operations are actually actions and constraints
        List<Map<String, Object>> operations = new Vector<Map<String, Object>>();
        result.put("operations", operations);

        Set<ActionRule> actions = logicGroup.getActions();
        if (actions != null && actions.size() > 0) {
            for (ActionRule a : actions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "action");
                operations.add(op);
            }
        }

        Set<EarlyActionRule> eactions = logicGroup.getEarlyActions();
        if (eactions != null && eactions.size() > 0) {
            for (EarlyActionRule a : eactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "early action");
                operations.add(op);
            }
        }

        Set<CommitActionRule> cactions = logicGroup.getCommitActions();
        if (cactions != null && cactions.size() > 0) {
            for (CommitActionRule a : cactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "commit action");
                operations.add(op);
            }
        }

        Set<ConstraintRule> constraints = logicGroup.getConstraints();
        if (constraints != null && constraints.size() > 0) {
            for (ConstraintRule constraint : constraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", constraint.getLogicMethodName());
                op.put("type", "constraint");
                operations.add(op);
            }
        }

        Set<CommitConstraintRule> cconstraints = logicGroup.getCommitConstraints();
        if (cconstraints != null && cconstraints.size() > 0) {
            for (ConstraintRule cconstraint : cconstraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", cconstraint.getLogicMethodName());
                op.put("type", "commit constraint");
                operations.add(op);
            }
        }

        // Derivations are derived attributes
        Map<String, Object> derivations = new HashMap<String, Object>();
        result.put("derivations", derivations);

        Set<AbstractAggregateRule> aggregates = logicGroup.getAggregates();
        if (aggregates != null && aggregates.size() > 0) {
            for (AbstractAggregateRule aggregate : aggregates) {
                Map<String, Object> agg = new HashMap<String, Object>();
                if (aggregate instanceof CountRule)
                    agg.put("type", "count");
                else if (aggregate instanceof SumRule)
                    agg.put("type", "sum");
                else
                    agg.put("type", "unknown");
                agg.put("methodName", aggregate.getLogicMethodName());
                derivations.put(aggregate.getBeanAttributeName(), agg);
            }
        }

        List<FormulaRule> formulas = logicGroup.getFormulas();
        if (formulas != null && formulas.size() > 0) {
            for (FormulaRule formula : formulas) {
                Map<String, Object> form = new HashMap<String, Object>();
                form.put("type", "formula");
                form.put("methodName", formula.getLogicMethodName());
                derivations.put(formula.getBeanAttributeName(), form);
            }
        }

        Set<ParentCopyRule> pcRules = logicGroup.getParentCopies();
        if (pcRules != null && pcRules.size() > 0) {
            for (ParentCopyRule pcRule : pcRules) {
                Map<String, Object> parentCopy = new HashMap<String, Object>();
                parentCopy.put("type", "parent copy");
                parentCopy.put("methodName", pcRule.getLogicMethodName());
                derivations.put(pcRule.getChildAttributeName(), parentCopy);
            }
        }
    }

    HashMap<String, Object> finalResult = new HashMap<String, Object>();
    finalResult.put("data", result);

    return finalResult;
}

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * Translate a relative path expression into a Hibernate relative path
 * // w w  w  .j a  v  a2s  . com
 * @param rpe
 * @param hStep
 */
protected HibernateRelativePath process(RelativePathExpr rpe, HibernateStep context) {
    logger.debug("Processing relative path [{}]", rpe.getXPath());

    HibernateRelativePath hRPath = new HibernateRelativePath();
    hRPath.setContext(context);

    /**
     * Offset to the first step after the context step if the relative path
     * is an absolute. Assumption is that absolute paths are grounds for the
     * start of a Hibernate criteria.
     */
    int contextDepth = 0;
    if (rpe.getFirstExpr().getType() == Expr.Type.Root) {
        logger.debug("Offsetting processing by 2 adding the passed context [{}] as the first Hibernate step",
                context);
        contextDepth = 2;

        hRPath.setAbsolute(true);
        hRPath.getHiberateSteps().add(context);
    }

    /**
     * Process each step. Non absolute relative paths take their context
     * from the passed Hibernate step (likely predicate expressions).
     */
    for (int depth = contextDepth; depth < rpe.getDepth(); depth++) {
        Step step = (Step) rpe.getExpr(depth);

        switch (step.getType()) {
        case Step:
            if (hRPath.getHiberateSteps().size() > 0)
                context = hRPath.getLastHibernateStep();

            CIBean bean = context.getCIBean();
            ClassMetadata cm = session.getSessionFactory().getClassMetadata(bean.getJavaClass());

            String property = step.getQName().getLocalPart();
            org.hibernate.type.Type propertyType = getPropertyType(cm, property);

            if (propertyType == null)
                throw new ApplicationException(
                        String.format("Step [%s] not defined as a property to the Hibernate context [%s]", step,
                                cm.getEntityName()));

            HibernateStep hStep = new HibernateStep();
            hStep.setStep(step);
            hStep.setName(property);
            hStep.setPath(String.format("%s.%s", context.getPath(), property));

            /**
             * Type
             */
            if (propertyType.isEntityType())
                hStep.setType(Type.Entity);

            if (propertyType.isAssociationType())
                hStep.setType(Type.Association);

            /**
             * Store the CIBean corresponding to the property by type not
             * name. Store as well the alias.
             */
            if (hStep.getType() != Type.Property) {
                CIProperty prop = bean.getPropertyByName(step.getQName());

                /**
                 * Does the property have corresponding CI Bean?
                 */
                CIBean other = ciContext.getBean(prop.getType());
                if (other == null)
                    throw new ApplicationException(
                            String.format("Step [%s] has no corresponding CI Bean metadata", step));

                hStep.setCIBean(other);
            }

            if (propertyType.getName().equals(JAXBUserType.class.getName())) {
                hStep.setXml(true);

                if (step.getNext() != null)
                    hRPath.setTruncated(true);
            }

            /**
             * Connect together the Hibernate steps
             */
            if (hRPath.getHiberateSteps().size() > 0) {
                HibernateStep last = hRPath.getLastHibernateStep();
                last.setNext(hStep);
                hStep.setPrevious(last);
            }

            /**
             * Make sure the PathExpression is stored
             */
            hStep.setBaseExpression(context.getBaseExpression());

            /**
             * Add the Hibernate step
             */
            hRPath.getHiberateSteps().add(hStep);
            break;
        case Root:
            throw new ApplicationException(String
                    .format("Only resolute steps valid [Root encountered at depth: %d]", step.getDepth()));
        case Irresolute:
            throw new ApplicationException(
                    String.format("Only resolute steps valid [Irresolute encountered at depth: %d]", depth));
        default:
            throw new ApplicationException(String
                    .format(String.format("Undefined expression type [%s] at depth", step.getType(), depth)));
        }

        if (hRPath.getLastHibernateStep().getType() == Type.Property)
            break;
    }

    logger.debug("Hibernate relative path: {}", hRPath);
    return hRPath;
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

License:Open Source License

public void auditCreate(PostInsertEvent createEvent) {
    if (!isAuditActivated)
        return;// w  ww .  ja v a2  s. co  m

    try {
        Lock lock = entityAuditSetupLock.readLock();
        lock.lock();
        try {
            EntityAuditSetup auditSetup = entityAuditSetup.get(createEvent.getPersister().getEntityName());
            if (auditSetup == null || !auditSetup.isAuditCreate())
                return;
        } finally {
            lock.unlock();
        }

        String[] names = createEvent.getPersister().getPropertyNames();
        String[] stateStr = new String[names.length];
        String[] oldStateStr = new String[names.length];

        for (int i = 0; i < names.length; i++) {
            Type type = createEvent.getPersister().getPropertyType(names[i]);
            if (type.isCollectionType())
                continue;

            if (type.isEntityType()) {
                ClassMetadata metadata = createEvent.getPersister().getFactory()
                        .getClassMetadata(type.getName());
                stateStr[i] = entityPropertyToString(createEvent.getState()[i], metadata);
                oldStateStr[i] = null;
            } else {
                stateStr[i] = createEvent.getState()[i] == null ? null : createEvent.getState()[i].toString();
                oldStateStr[i] = null;
            }
        }

        sendAuditMessage(new EntityAuditEvent(createEvent.getPersister().getEntityName(),
                DatabaseAuditType.CREATE, createEvent.getId().toString(),
                createEvent.getPersister().getIdentifierPropertyName(), names, stateStr, oldStateStr));
    } catch (Exception e) {
        logger.error("audit create failed", e);
    }
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

License:Open Source License

public void auditModify(PostUpdateEvent modifyEvent) {
    if (!isAuditActivated)
        return;//from w  w  w. j a v a  2  s  .c o m

    try {
        List<Integer> auditedList;
        String[] names;
        Lock lock = entityAuditSetupLock.readLock();
        lock.lock();
        try {
            EntityAuditSetup auditSetup = entityAuditSetup.get(modifyEvent.getPersister().getEntityName());
            if (auditSetup == null || !auditSetup.isAuditModify())
                return;

            auditedList = new ArrayList<Integer>();
            names = modifyEvent.getPersister().getPropertyNames();
            if (!auditSetup.isAuditModifyAllProperties()) {
                for (int i = 0; i < names.length; i++)
                    if (auditSetup.isAuditModifyProperty(names[i]))
                        auditedList.add(i);
            } else {
                for (int i = 0; i < names.length; i++)
                    auditedList.add(i);
            }
        } finally {
            lock.unlock();
        }

        if (auditedList.isEmpty())
            return;

        String[] stateStr = new String[auditedList.size()];
        String[] oldStateStr = new String[auditedList.size()];
        String[] auditedNames = new String[auditedList.size()];

        int j = 0;
        for (int i = 0; i < names.length; i++) {
            if (!auditedList.contains(i))
                continue;

            Type type = modifyEvent.getPersister().getPropertyType(names[i]);
            if (type.isCollectionType())
                continue;

            auditedNames[j] = names[i];
            if (type.isEntityType()) {
                ClassMetadata metadata = modifyEvent.getPersister().getFactory()
                        .getClassMetadata(type.getName());
                stateStr[j] = entityPropertyToString(modifyEvent.getState()[i], metadata);
                oldStateStr[j] = entityPropertyToString(modifyEvent.getOldState()[i], metadata);
            } else {
                stateStr[j] = modifyEvent.getState()[i] == null ? null : modifyEvent.getState()[i].toString();
                oldStateStr[j] = modifyEvent.getOldState()[i] == null ? null
                        : modifyEvent.getOldState()[i].toString();
            }

            j++;
        }

        // ?? ? 
        if (j == 0)
            return;

        //?? ?     ?
        if (names.length > j) {
            auditedNames = (String[]) ArrayUtils.subarray(auditedNames, 0, j);
            stateStr = (String[]) ArrayUtils.subarray(stateStr, 0, j);
            oldStateStr = (String[]) ArrayUtils.subarray(oldStateStr, 0, j);
        }

        sendAuditMessage(new EntityAuditEvent(modifyEvent.getPersister().getEntityName(),
                DatabaseAuditType.MODIFY, modifyEvent.getId().toString(),
                modifyEvent.getPersister().getIdentifierPropertyName(), auditedNames, stateStr, oldStateStr));
    } catch (Exception e) {
        logger.error("audit modify failed", e);
    }
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

License:Open Source License

public void auditRemove(PostDeleteEvent removeEvent) {
    if (!isAuditActivated)
        return;//w w  w.  j av  a 2s. c om

    try {
        Lock lock = entityAuditSetupLock.readLock();
        lock.lock();
        try {
            EntityAuditSetup auditSetup = entityAuditSetup.get(removeEvent.getPersister().getEntityName());
            if (auditSetup == null || !auditSetup.isAuditRemove())
                return;
        } finally {
            lock.unlock();
        }

        String[] names = removeEvent.getPersister().getPropertyNames();
        String[] stateStr = new String[names.length];
        String[] oldStateStr = new String[names.length];

        for (int i = 0; i < names.length; i++) {
            Type type = removeEvent.getPersister().getPropertyType(names[i]);
            if (type.isCollectionType())
                continue;

            if (type.isEntityType()) {
                ClassMetadata metadata = removeEvent.getPersister().getFactory()
                        .getClassMetadata(type.getName());
                oldStateStr[i] = entityPropertyToString(removeEvent.getDeletedState()[i], metadata);
                stateStr[i] = null;
            } else {
                oldStateStr[i] = removeEvent.getDeletedState()[i] == null ? null
                        : removeEvent.getDeletedState()[i].toString();
                stateStr[i] = null;
            }
        }

        sendAuditMessage(new EntityAuditEvent(removeEvent.getPersister().getEntityName(),
                DatabaseAuditType.REMOVE, removeEvent.getId().toString(),
                removeEvent.getPersister().getIdentifierPropertyName(), names, stateStr, oldStateStr));
    } catch (Exception e) {
        logger.error("audit create failed", e);
    }
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

License:Open Source License

public static String getHibernatePropTypes(String className, String propName) {

    Session session = HibernateUtil.currentSession();
    SessionFactory sf = session.getSessionFactory();
    org.hibernate.type.Type hibClassProps = sf.getClassMetadata(className).getPropertyType(propName);
    return (hibClassProps.getName());

}

From source file:com.wavemaker.tools.data.DataTypeMapper.java

License:Open Source License

public static String getHibernateType(String type) {
    Type t = JAVA_TYPE_TO_HB_TYPE.get(type);
    if (t == null) {
        return StringUtils.fromLastOccurrence(type, ".");
    }/*from w ww .  j av a  2  s .  c o m*/
    return t.getName();
}

From source file:com.wavemaker.tools.data.DataTypeMapper.java

License:Open Source License

public static String getFQHibernateType(String type) {
    Type t = JAVA_TYPE_TO_HB_TYPE.get(type);
    if (t == null) {
        return type;
    }/*from w ww . j ava 2  s. co m*/
    return t.getName();
}

From source file:gov.nih.nci.calims2.business.report.query.MetadataServiceImpl.java

License:BSD License

/**
 * Process a given property for the descriptor construction. 
 * @param descriptor The descriptor under construction
 * @param prefix The property prefix (in case of component properties)
 * @param name The property name//from w ww .  jav a 2s  .c  om
 * @param type The property type
 * @param excludeRelationship true if relationship must not be extracted
 */
void processProperty(EntityDescriptor descriptor, String prefix, String name, Type type,
        boolean excludeRelationship) {
    if (type.isAssociationType()) {
        if (excludeRelationship) {
            return;
        }
        if (!type.isCollectionType()) {
            RelationshipDescriptor rd = new RelationshipDescriptor();
            rd.setName(name);
            Class<?> relatedClass;
            try {
                relatedClass = Class.forName(type.getName());
            } catch (ClassNotFoundException e) {
                throw new InternalError("Should not happern. Hibernate is initialized correctly at this point");
            }
            rd.setPersistentClass(relatedClass);
            EntityDescriptor relatedClassDescriptor = getEntityDescriptor(relatedClass, true);
            rd.setProperties(relatedClassDescriptor.getProperties());
            Collections.sort(rd.getProperties());
            descriptor.addRelationship(rd);
        }
    } else {
        if (type.isComponentType()) {
            ComponentType componentType = (ComponentType) type;
            String[] propertyNames = componentType.getPropertyNames();
            Type[] types = componentType.getSubtypes();
            String newPrefix = prefix + name + ".";
            for (int i = 0; i < propertyNames.length; i++) {
                processProperty(descriptor, newPrefix, propertyNames[i], types[i], false);
            }
        } else {
            if (!type.isCollectionType()) {
                PropertyDescriptor property = new PropertyDescriptor();
                property.setName(prefix + name);
                property.setType(type.getName());
                property.setReturnedClass(type.getReturnedClass());
                descriptor.addProperty(property);
            }
        }
    }
}

From source file:it.eng.qbe.model.structure.builder.hibernate.HibernateModelStructureBuilder.java

License:Mozilla Public License

private void addKeyFields(IModelEntity dataMartEntity) {

    PersistentClass classMapping;/*from   www .  j a  va 2  s  .c  om*/
    ClassMetadata classMetadata;
    Type identifierType;

    getDataSource().getHibernateConfiguration().buildMappings();//must be called 
    classMapping = getDataSource().getHibernateConfiguration().getClassMapping(dataMartEntity.getType());
    if (classMapping == null) {
        System.out.println("class mapping for entity [" + dataMartEntity.getType() + "] not found");
        Iterator<PersistentClass> it = getDataSource().getHibernateConfiguration().getClassMappings();
        while (it.hasNext()) {
            PersistentClass pc = it.next();
            System.out.println("-> [" + pc.getClass().getName() + "] not found");
        }
    }

    classMetadata = getDataSource().getHibernateSessionFactory().getClassMetadata(dataMartEntity.getType());
    identifierType = classMetadata.getIdentifierType();

    List identifierPropertyNames = new ArrayList();
    String[] propertyClass = null;
    String[] type = null;
    int[] scale = null;
    int[] precision = null;

    String identifierPropertyName = classMetadata.getIdentifierPropertyName();

    if (identifierType.isComponentType()) {

        ComponentType componentIdentifierType = (ComponentType) identifierType;
        String[] subPropertyNames = componentIdentifierType.getPropertyNames();

        Type[] subPropertyTypes = componentIdentifierType.getSubtypes();

        propertyClass = new String[subPropertyNames.length];
        type = new String[subPropertyNames.length];
        scale = new int[subPropertyNames.length];
        precision = new int[subPropertyNames.length];
        Class subPropertyClass = null;

        for (int j = 0; j < subPropertyNames.length; j++) {
            subPropertyClass = subPropertyTypes[j].getClass();

            if (subPropertyTypes[j].isComponentType()) {
                ComponentType cType = (ComponentType) subPropertyTypes[j];
                String[] sPropertyNames = cType.getPropertyNames();
                Type[] sTypes = cType.getSubtypes();
                for (int z = 0; z < sPropertyNames.length; z++) {
                    identifierPropertyNames
                            .add(identifierPropertyName + "." + subPropertyNames[j] + "." + sPropertyNames[z]);
                    propertyClass[j] = subPropertyClass.getName();
                    type[j] = subPropertyTypes[j].getName();
                }
            } else {
                identifierPropertyNames.add(identifierPropertyName + "." + subPropertyNames[j]);
                propertyClass[j] = subPropertyClass.getName();
                type[j] = subPropertyTypes[j].getName();
            }
        }

    } else {
        propertyClass = new String[1];
        type = new String[1];
        scale = new int[1];
        precision = new int[1];

        identifierPropertyNames.add(identifierPropertyName);
        propertyClass[0] = identifierType.getClass().getName();
        type[0] = identifierType.getName();
    }

    Iterator it = classMapping.getIdentifierProperty().getColumnIterator();
    for (int k = 0; k < scale.length; k++) {
        if (!it.hasNext())
            continue;
        Column column = (Column) it.next();
        scale[k] = column.getScale();
        precision[k] = column.getPrecision();
    }

    for (int j = 0; j < identifierPropertyNames.size(); j++) {
        String fieldName = (String) identifierPropertyNames.get(j);
        IModelField dataMartField = dataMartEntity.addKeyField(fieldName);
        dataMartField.setType(type[j]);
        dataMartField.setPrecision(precision[j]);
        dataMartField.setLength(scale[j]);
        propertiesInitializer.addProperties(dataMartField);
    }
}