Search in sources :

Example 11 with StringType

use of org.hibernate.type.StringType in project openmrs-core by openmrs.

the class HibernateAdministrationDAO method validate.

/**
 * @see org.openmrs.api.db.AdministrationDAO#validate(java.lang.Object, Errors)
 * @should Pass validation if field lengths are correct
 * @should Fail validation if field lengths are not correct
 * @should Fail validation for location class if field lengths are not correct
 * @should Pass validation for location class if field lengths are correct
 */
// @SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
@Override
public void validate(Object object, Errors errors) throws DAOException {
    Class entityClass = object.getClass();
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata != null) {
        String[] propNames = metadata.getPropertyNames();
        Object identifierType = metadata.getIdentifierType();
        String identifierName = metadata.getIdentifierPropertyName();
        if (identifierType instanceof StringType || identifierType instanceof TextType) {
            int maxLength = getMaximumPropertyLength(entityClass, identifierName);
            String identifierValue = (String) metadata.getIdentifier(object, (SessionImplementor) sessionFactory.getCurrentSession());
            if (identifierValue != null) {
                int identifierLength = identifierValue.length();
                if (identifierLength > maxLength) {
                    errors.rejectValue(identifierName, "error.exceededMaxLengthOfField", new Object[] { maxLength }, null);
                }
            }
        }
        for (String propName : propNames) {
            Type propType = metadata.getPropertyType(propName);
            if (propType instanceof StringType || propType instanceof TextType) {
                String propertyValue = (String) metadata.getPropertyValue(object, propName);
                if (propertyValue != null) {
                    int maxLength = getMaximumPropertyLength(entityClass, propName);
                    int propertyValueLength = propertyValue.length();
                    if (propertyValueLength > maxLength) {
                        errors.rejectValue(propName, "error.exceededMaxLengthOfField", new Object[] { maxLength }, null);
                    }
                }
            }
        }
    }
    FlushMode previousFlushMode = sessionFactory.getCurrentSession().getFlushMode();
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
    try {
        for (Validator validator : getValidators(object)) {
            validator.validate(object, errors);
        }
    } finally {
        sessionFactory.getCurrentSession().setFlushMode(previousFlushMode);
    }
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) TextType(org.hibernate.type.TextType) StringType(org.hibernate.type.StringType) Type(org.hibernate.type.Type) StringType(org.hibernate.type.StringType) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PersistentClass(org.hibernate.mapping.PersistentClass) OpenmrsObject(org.openmrs.OpenmrsObject) FlushMode(org.hibernate.FlushMode) Validator(org.springframework.validation.Validator) TextType(org.hibernate.type.TextType)

Example 12 with StringType

use of org.hibernate.type.StringType in project gocd by gocd.

the class MaterialRepository method findModificationsForPipelineIds.

public Map<Long, List<ModificationForPipeline>> findModificationsForPipelineIds(final List<Long> pipelineIds) {
    final int MODIFICATION = 0;
    final int RELEVANT_PIPELINE_ID = 1;
    final int RELEVANT_PIPELINE_NAME = 2;
    final int MATERIAL_TYPE = 3;
    final int MATERIAL_FINGERPRINT = 4;
    // noinspection unchecked
    return (Map<Long, List<ModificationForPipeline>>) getHibernateTemplate().execute((HibernateCallback) session -> {
        if (pipelineIds.isEmpty()) {
            return new HashMap<Long, List<ModificationForPipeline>>();
        }
        Map<PipelineId, Set<Long>> relevantToLookedUpMap = relevantToLookedUpDependencyMap(session, pipelineIds);
        SQLQuery query = session.createSQLQuery("SELECT mods.*, pmr.pipelineId as pmrPipelineId, p.name as pmrPipelineName, m.type as materialType, m.fingerprint as fingerprint" + " FROM modifications mods " + "     INNER JOIN pipelineMaterialRevisions pmr ON (mods.id >= pmr.fromRevisionId AND mods.id <= pmr.toRevisionId) AND mods.materialId = pmr.materialId " + "     INNER JOIN pipelines p ON pmr.pipelineId = p.id" + "     INNER JOIN materials m ON mods.materialId = m.id" + " WHERE pmr.pipelineId IN (:ids)");
        List<Object[]> allModifications = query.addEntity("mods", Modification.class).addScalar("pmrPipelineId", new LongType()).addScalar("pmrPipelineName", new StringType()).addScalar("materialType", new StringType()).addScalar("fingerprint", new StringType()).setParameterList("ids", relevantToLookedUpMap.keySet().stream().map(PipelineId::getPipelineId).collect(Collectors.toList())).list();
        Map<Long, List<ModificationForPipeline>> modificationsForPipeline = new HashMap<>();
        CollectionUtil.CollectionValueMap<Long, ModificationForPipeline> modsForPipeline = CollectionUtil.collectionValMap(modificationsForPipeline, new CollectionUtil.ArrayList<>());
        for (Object[] modAndPmr : allModifications) {
            Modification mod = (Modification) modAndPmr[MODIFICATION];
            Long relevantPipelineId = (Long) modAndPmr[RELEVANT_PIPELINE_ID];
            String relevantPipelineName = (String) modAndPmr[RELEVANT_PIPELINE_NAME];
            String materialType = (String) modAndPmr[MATERIAL_TYPE];
            String materialFingerprint = (String) modAndPmr[MATERIAL_FINGERPRINT];
            PipelineId relevantPipeline = new PipelineId(relevantPipelineName, relevantPipelineId);
            Set<Long> longs = relevantToLookedUpMap.get(relevantPipeline);
            for (Long lookedUpPipeline : longs) {
                modsForPipeline.put(lookedUpPipeline, new ModificationForPipeline(relevantPipeline, mod, materialType, materialFingerprint));
            }
        }
        return modificationsForPipeline;
    });
}
Also used : LongType(org.hibernate.type.LongType) StringType(org.hibernate.type.StringType) ModificationForPipeline(com.thoughtworks.go.server.ui.ModificationForPipeline) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString) CollectionUtil(com.thoughtworks.go.server.util.CollectionUtil) PipelineId(com.thoughtworks.go.server.ui.PipelineId) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback)

Example 13 with StringType

use of org.hibernate.type.StringType in project gocd by gocd.

the class MaterialRepository method relevantToLookedUpDependencyMap.

private Map<PipelineId, Set<Long>> relevantToLookedUpDependencyMap(Session session, List<Long> pipelineIds) {
    final int LOOKED_UP_PIPELINE_ID = 2;
    final int RELEVANT_PIPELINE_ID = 0;
    final int RELEVANT_PIPELINE_NAME = 1;
    String pipelineIdsSql = queryExtensions.queryRelevantToLookedUpDependencyMap(pipelineIds);
    SQLQuery pipelineIdsQuery = session.createSQLQuery(pipelineIdsSql);
    pipelineIdsQuery.addScalar("id", new LongType());
    pipelineIdsQuery.addScalar("name", new StringType());
    pipelineIdsQuery.addScalar("lookedUpId", new LongType());
    final List<Object[]> ids = pipelineIdsQuery.list();
    Map<Long, List<PipelineId>> lookedUpToParentMap = new HashMap<>();
    CollectionUtil.CollectionValueMap<Long, PipelineId> lookedUpToRelevantMap = CollectionUtil.collectionValMap(lookedUpToParentMap, new CollectionUtil.ArrayList<>());
    for (Object[] relevantAndLookedUpId : ids) {
        lookedUpToRelevantMap.put((Long) relevantAndLookedUpId[LOOKED_UP_PIPELINE_ID], new PipelineId((String) relevantAndLookedUpId[RELEVANT_PIPELINE_NAME], (Long) relevantAndLookedUpId[RELEVANT_PIPELINE_ID]));
    }
    return CollectionUtil.reverse(lookedUpToParentMap);
}
Also used : LongType(org.hibernate.type.LongType) StringType(org.hibernate.type.StringType) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString) CollectionUtil(com.thoughtworks.go.server.util.CollectionUtil) PipelineId(com.thoughtworks.go.server.ui.PipelineId)

Example 14 with StringType

use of org.hibernate.type.StringType in project BroadleafCommerce by BroadleafCommerce.

the class SparseTranslationOverrideStrategy method getTemplateTranslations.

protected List<Translation> getTemplateTranslations(TranslatedEntity entityType, String entityId, String property, String localeCode) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Translation> criteria = builder.createQuery(Translation.class);
    Root<TranslationImpl> root = criteria.from(TranslationImpl.class);
    criteria.select(root);
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(root.get("entityType"), entityType.getFriendlyType()));
    restrictions.add(builder.equal(root.get("entityId"), entityId));
    restrictions.add(builder.equal(root.get("fieldName"), property));
    restrictions.add(builder.like(root.get("localeCode").as(String.class), localeCode + "%"));
    try {
        Object testObject = null;
        if (restrictAssociation) {
            try {
                Class<?> type = Class.forName(entityType.getType());
                SessionFactory sessionFactory = ((CriteriaBuilderImpl) em.getCriteriaBuilder()).getEntityManagerFactory().getSessionFactory();
                Class<?>[] entities = helper.getAllPolymorphicEntitiesFromCeiling(type, sessionFactory, true, true);
                // This should already be in level 1 cache and this should not cause a hit to the database.
                Map<String, Object> idMetadata = helper.getIdMetadata(entities[entities.length - 1], (HibernateEntityManager) em);
                Type idType = (Type) idMetadata.get("type");
                if (idType instanceof StringType) {
                    testObject = em.find(entities[entities.length - 1], entityId);
                } else if (idType instanceof LongType) {
                    testObject = em.find(entities[entities.length - 1], Long.parseLong(entityId));
                }
            } catch (ClassNotFoundException e) {
                throw ExceptionHelper.refineException(e);
            }
        }
        if (extensionManager != null) {
            extensionManager.setup(TranslationImpl.class);
            extensionManager.refineParameterRetrieve(TranslationImpl.class, testObject, builder, criteria, root, restrictions);
        }
        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
        TypedQuery<Translation> query = em.createQuery(criteria);
        if (extensionManager != null) {
            extensionManager.refineQuery(TranslationImpl.class, testObject, query);
        }
        query.setHint(QueryHints.HINT_CACHEABLE, true);
        List response = query.getResultList();
        if (extensionManager != null) {
            extensionManager.filterResults(TranslationImpl.class, testObject, response);
        }
        return response;
    } finally {
        extensionManager.breakdown(TranslationImpl.class);
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) SessionFactory(org.hibernate.SessionFactory) Translation(org.broadleafcommerce.common.i18n.domain.Translation) LongType(org.hibernate.type.LongType) TranslationImpl(org.broadleafcommerce.common.i18n.domain.TranslationImpl) StringType(org.hibernate.type.StringType) ArrayList(java.util.ArrayList) Predicate(javax.persistence.criteria.Predicate) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) StringType(org.hibernate.type.StringType) LongType(org.hibernate.type.LongType) ResultType(org.broadleafcommerce.common.extension.ResultType) Type(org.hibernate.type.Type) ArrayList(java.util.ArrayList) List(java.util.List)

Example 15 with StringType

use of org.hibernate.type.StringType in project jbosstools-hibernate by jbosstools.

the class TypeFacadeTest method testIsInstanceOfPrimitiveType.

@Test
public void testIsInstanceOfPrimitiveType() {
    IType typeFacade = null;
    ClassType classType = new ClassType();
    typeFacade = FACADE_FACTORY.createType(classType);
    assertFalse(typeFacade.isInstanceOfPrimitiveType());
    StringType stringType = new StringType();
    typeFacade = FACADE_FACTORY.createType(stringType);
    assertFalse(typeFacade.isInstanceOfPrimitiveType());
    IntegerType integerType = new IntegerType();
    typeFacade = FACADE_FACTORY.createType(integerType);
    assertTrue(typeFacade.isInstanceOfPrimitiveType());
}
Also used : IntegerType(org.hibernate.type.IntegerType) StringType(org.hibernate.type.StringType) ClassType(org.hibernate.type.ClassType) IType(org.jboss.tools.hibernate.runtime.spi.IType) Test(org.junit.jupiter.api.Test)

Aggregations

StringType (org.hibernate.type.StringType)20 ClassType (org.hibernate.type.ClassType)11 IntegerType (org.hibernate.type.IntegerType)11 IType (org.jboss.tools.hibernate.runtime.spi.IType)11 Test (org.junit.jupiter.api.Test)10 Type (org.hibernate.type.Type)5 LongType (org.hibernate.type.LongType)4 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)2 PipelineId (com.thoughtworks.go.server.ui.PipelineId)2 CollectionUtil (com.thoughtworks.go.server.util.CollectionUtil)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ResultType (org.broadleafcommerce.common.extension.ResultType)2 Test (org.junit.Test)2 ModificationForPipeline (com.thoughtworks.go.server.ui.ModificationForPipeline)1 Serializable (java.io.Serializable)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 Predicate (javax.persistence.criteria.Predicate)1