@Test @SpecAssertions({ @SpecAssertion(section = "6.11", id = "a"), @SpecAssertion(section = "6.11", id = "b"), @SpecAssertion(section = "6.11", id = "d") }) public void testAnnotationAndMapParametersReflectParameterOverriding() { ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName"); Set<ConstraintDescriptor<?>> composingDescriptors = descriptor.getComposingConstraints(); assertEquals(composingDescriptors.size(), 2, "Wrong number of composing constraints"); boolean hasSize = false; for (ConstraintDescriptor<?> desc : composingDescriptors) { if (desc.getAnnotation().annotationType().equals(Size.class)) { hasSize = true; Size sizeAnn = (Size) desc.getAnnotation(); assertEquals(sizeAnn.min(), 5, "The min parameter should reflect the overridden parameter"); assertEquals( desc.getAttributes().get("min"), 5, "The min parameter should reflect the overridden parameter"); } else if (desc.getAnnotation().annotationType().equals(NotNull.class)) { } else { fail("Unexpected annotation."); } } assertTrue(hasSize, "Size composed annotation not found"); }
@SuppressWarnings({"rawtypes", "unchecked"}) public static <X> X buildMockObject(Class<X> clazz) { X x = null; try { x = clazz.newInstance(); for (Method method : clazz.getDeclaredMethods()) { String mn = method.getName(); if (mn.startsWith("set")) { Class[] parameters = method.getParameterTypes(); if (parameters.length == 1) { Method getMethod = MethodUtils.getAccessibleMethod(clazz, "get" + mn.substring(3), null); if (getMethod != null) { if (getMethod.getName().equals("getId")) { continue; } Object value = null; Class parameter = parameters[0]; if (parameter.isAssignableFrom(String.class)) { Column column = getMethod.getAnnotation(Column.class); int columnLength = 32; if (column != null && column.length() < columnLength) { columnLength = column.length(); } Size size = getMethod.getAnnotation(Size.class); if (size != null && size.min() < columnLength) { columnLength = size.min(); } value = RandomStringUtils.randomAlphabetic(columnLength); } else if (parameter.isAssignableFrom(Date.class)) { value = new Date(); } else if (parameter.isAssignableFrom(BigDecimal.class)) { value = new BigDecimal(new Random().nextDouble()); } else if (parameter.isAssignableFrom(Integer.class)) { value = new Random().nextInt(); } else if (parameter.isAssignableFrom(Boolean.class)) { value = new Random().nextBoolean(); } else if (parameter.isEnum()) { Method m = parameter.getDeclaredMethod("values", null); Object[] result = (Object[]) m.invoke(parameter.getEnumConstants()[0], null); value = result[new Random().nextInt(result.length)]; } if (value != null) { MethodUtils.invokeMethod(x, mn, value); logger.debug("{}={}", method.getName(), value); } } } } } } catch (Exception e) { e.printStackTrace(); } return x; }
public void initialize(Size parameters) { min = parameters.min(); max = parameters.max(); validateParameters(); }
private void readField(DeployBeanProperty prop) { // all Enums will have a ScalarType assigned... boolean isEnum = prop.getPropertyType().isEnum(); Enumerated enumerated = get(prop, Enumerated.class); if (isEnum || enumerated != null) { util.setEnumScalarType(enumerated, prop); } // its persistent and assumed to be on the base table // rather than on a secondary table prop.setDbRead(true); prop.setDbInsertable(true); prop.setDbUpdateable(true); Column column = get(prop, Column.class); if (column != null) { readColumn(column, prop); } Expose expose = get(prop, Expose.class); if (expose != null) { prop.setExposeSerialize(expose.serialize()); prop.setExposeDeserialize(expose.deserialize()); } if (prop.getDbColumn() == null) { // No @Column annotation or @Column.name() not set // Use the NamingConvention to set the DB column name String dbColumn = namingConvention.getColumnFromProperty(beanType, prop.getName()); prop.setDbColumn(dbColumn); } GeneratedValue gen = get(prop, GeneratedValue.class); if (gen != null) { readGenValue(gen, prop); } Id id = (Id) get(prop, Id.class); if (id != null) { readId(id, prop); } // determine the JDBC type using Lob/Temporal // otherwise based on the property Class Lob lob = get(prop, Lob.class); Temporal temporal = get(prop, Temporal.class); if (temporal != null) { readTemporal(temporal, prop); } else if (lob != null) { util.setLobType(prop); } Formula formula = get(prop, Formula.class); if (formula != null) { prop.setSqlFormula(formula.select(), formula.join()); } Version version = get(prop, Version.class); if (version != null) { // explicitly specify a version column prop.setVersionColumn(true); generatedPropFactory.setVersion(prop); } Basic basic = get(prop, Basic.class); if (basic != null) { prop.setFetchType(basic.fetch()); if (!basic.optional()) { prop.setNullable(false); } } else if (prop.isLob()) { // use the default Lob fetchType prop.setFetchType(defaultLobFetchType); } CreatedTimestamp ct = get(prop, CreatedTimestamp.class); if (ct != null) { generatedPropFactory.setInsertTimestamp(prop); } UpdatedTimestamp ut = get(prop, UpdatedTimestamp.class); if (ut != null) { generatedPropFactory.setUpdateTimestamp(prop); } if (validationAnnotations) { NotNull notNull = get(prop, NotNull.class); if (notNull != null && isNotNullOnAllValidationGroups(notNull.groups())) { // Not null on all validation groups so enable // DDL generation of Not Null Constraint prop.setNullable(false); } Size size = get(prop, Size.class); if (size != null) { if (size.max() < Integer.MAX_VALUE) { // explicitly specify a version column prop.setDbLength(size.max()); } } } EmbeddedColumns columns = get(prop, EmbeddedColumns.class); if (columns != null) { if (prop instanceof DeployBeanPropertyCompound) { DeployBeanPropertyCompound p = (DeployBeanPropertyCompound) prop; // convert into a Map String propColumns = columns.columns(); Map<String, String> propMap = StringHelper.delimitedToMap(propColumns, ",", "="); p.getDeployEmbedded().putAll(propMap); CtCompoundType<?> compoundType = p.getCompoundType(); if (compoundType == null) { throw new RuntimeException("No registered CtCompoundType for " + p.getPropertyType()); } } else { throw new RuntimeException( "Can't use EmbeddedColumns on ScalarType " + prop.getFullBeanName()); } } // Want to process last so we can use with @Formula Transient t = get(prop, Transient.class); if (t != null) { // it is not a persistent property. prop.setDbRead(false); prop.setDbInsertable(false); prop.setDbUpdateable(false); prop.setTransient(true); } if (!prop.isTransient()) { EncryptDeploy encryptDeploy = util.getEncryptDeploy(info.getDescriptor().getBaseTableFull(), prop.getDbColumn()); if (encryptDeploy == null || encryptDeploy.getMode().equals(Mode.MODE_ANNOTATION)) { Encrypted encrypted = get(prop, Encrypted.class); if (encrypted != null) { setEncryption(prop, encrypted.dbEncryption(), encrypted.dbLength()); } } else if (Mode.MODE_ENCRYPT.equals(encryptDeploy.getMode())) { setEncryption(prop, encryptDeploy.isDbEncrypt(), encryptDeploy.getDbLength()); } } Index index = get(prop, Index.class); if (index != null) { if (hasRelationshipItem(prop)) { throw new RuntimeException("Can't use Index on foreign key relationships."); } prop.setIndexed(true); prop.setIndexName(index.value()); } }
public static void buildValidatorAttribute( String validatorAttrValue, AbstractUITag tag, ValueStack stack, HttpServletRequest req, UIBean uiBean) { Map<String, Object> dynamicAttributes = new HashMap<String, Object>(); if (validatorAttrValue == null) { Map<String, Object> validator = new HashMap<String, Object>(); Map<String, String> messages = new HashMap<String, String>(); CompoundRoot rootList = stack.getRoot(); Object entity = null; Object controller = null; for (Object obj : rootList) { if (obj instanceof Persistable) { entity = obj; } else if (obj instanceof ActionSupport) { controller = obj; } } if (entity != null) { try { String tagName = tag.name; Method method = OgnlRuntime.getGetMethod( (OgnlContext) stack.getContext(), entity.getClass(), tagName); if (method == null) { String[] tagNameSplits = StringUtils.split(tagName, "."); if (tagNameSplits.length >= 2) { Class<?> retClass = entity.getClass(); for (String tagNameSplit : tagNameSplits) { method = OgnlRuntime.getGetMethod( (OgnlContext) stack.getContext(), retClass, tagNameSplit); if (method != null) { retClass = method.getReturnType(); } } if (method == null) { retClass = controller.getClass(); for (String tagNameSplit : tagNameSplits) { method = OgnlRuntime.getGetMethod( (OgnlContext) stack.getContext(), retClass, tagNameSplit); if (method != null) { retClass = method.getReturnType(); } } } } } if (method != null) { Column column = method.getAnnotation(Column.class); if (column != null) { if (column.nullable() == false) { if (tag.requiredLabel == null) { uiBean.setRequiredLabel("true"); } } if (column.unique() == true) { validator.put("unique", "true"); } } Class<?> retType = method.getReturnType(); if (retType == LocalDate.class) { validator.put("date", true); validator.put("dateISO", true); } else if (retType == LocalDateTime.class) { validator.put("timestamp", true); } else if (retType == DateTime.class || retType == Date.class) { JsonSerialize jsonSerialize = method.getAnnotation(JsonSerialize.class); if (jsonSerialize != null) { if (JodaDateJsonSerializer.class == jsonSerialize.using() || DateJsonSerializer.class == jsonSerialize.using()) { validator.put("date", true); validator.put("dateISO", true); } else if (JodaDateTimeJsonSerializer.class == jsonSerialize.using() || DateTimeJsonSerializer.class == jsonSerialize.using()) { validator.put("timestamp", true); } } } else if (retType == BigDecimal.class) { validator.put("number", true); } else if (retType == Integer.class) { validator.put("number", true); validator.put("digits", true); } else if (retType == Long.class) { validator.put("number", true); validator.put("digits", true); } Size size = method.getAnnotation(Size.class); if (size != null) { if (size.min() > 0) { validator.put("minlength", size.min()); } if (size.max() < Integer.MAX_VALUE) { validator.put("maxlength", size.max()); } } Email email = method.getAnnotation(Email.class); if (email != null) { validator.put("email", true); } Pattern pattern = method.getAnnotation(Pattern.class); if (pattern != null) { validator.put("regex", pattern.regexp()); String message = pattern.message(); if (!"{javax.validation.constraints.Pattern.message}".equals(message)) { messages.put("regex", message); } } } } catch (IntrospectionException e) { e.printStackTrace(); } catch (OgnlException e) { e.printStackTrace(); } } if (validator.size() > 0) { try { if (messages.size() > 0) { validator.put("messages", messages); } String json = mapper.writeValueAsString(validator); json = json.replaceAll("\\\"", "'"); dynamicAttributes.put("validator", json); uiBean.setDynamicAttributes(dynamicAttributes); } catch (JsonProcessingException e) { e.printStackTrace(); } } } else { dynamicAttributes.put("validator", validatorAttrValue); uiBean.setDynamicAttributes(dynamicAttributes); } }