/** * Update the calculated person data. This method and updateCalculatedPersonOnDeleteOfSor need to * be generalized to handle recalculations. * * @param toPerson * @param fromPerson * @param sorPerson Adjust calculated roles... Point prc_role to prc_person receiving role Add the * role to the set of roles in receiving prc_person Remove role from prc person losing role */ protected void updateCalculatedPersonsOnMoveOfSor( final Person toPerson, final Person fromPerson, final SorPerson sorPerson) { Assert.notNull(toPerson, "toPerson cannot be null"); Assert.notNull(fromPerson, "fromPerson cannot be null"); logger.info("UpdateCalculated: recalculating person data for move."); final List<Role> rolesToDelete = new ArrayList<Role>(); final List<SorRole> sorRoles = new ArrayList<SorRole>(sorPerson.getRoles()); for (final SorRole sorRole : sorRoles) { for (final Role role : fromPerson.getRoles()) { if (sorRole.getId().equals(role.getSorRoleId())) { sorRoleElector.addSorRole(sorRole, toPerson); rolesToDelete.add(role); } } } for (final Role role : rolesToDelete) { sorRoleElector.removeCalculatedRole( fromPerson, role, this.personRepository.getSoRRecordsForPerson(fromPerson)); fromPerson.getRoles().remove(role); } // TODO recalculate names for person receiving role? Anything else? // TODO recalculate names for person losing role? Anything else? // this.personRepository.savePerson(fromPerson); // this.personRepository.savePerson(toPerson); }
/** Return the indexes available for this field (for repeated fields ad List) */ public List<Integer> indexes() { List<Integer> result = new ArrayList<Integer>(); if (form.value().isDefined()) { BeanWrapper beanWrapper = new BeanWrapperImpl(form.value().get()); beanWrapper.setAutoGrowNestedPaths(true); String objectKey = name; if (form.name() != null && name.startsWith(form.name() + ".")) { objectKey = name.substring(form.name().length() + 1); } if (beanWrapper.isReadableProperty(objectKey)) { Object value = beanWrapper.getPropertyValue(objectKey); if (value instanceof Collection) { for (int i = 0; i < ((Collection) value).size(); i++) { result.add(i); } } } } else { java.util.regex.Pattern pattern = java.util.regex.Pattern.compile( "^" + java.util.regex.Pattern.quote(name) + "\\[(\\d+)\\].*$"); for (String key : form.data().keySet()) { java.util.regex.Matcher matcher = pattern.matcher(key); if (matcher.matches()) { result.add(Integer.parseInt(matcher.group(1))); } } } return result; }
static { products = new ArrayList<Product>(); products.add(new Product("1111111111111", "Paperclips 1", "Paperclips description 1")); products.add(new Product("2222222222222", "Paperclips 2", "Paperclips description ")); products.add(new Product("3333333333333", "Paperclips 3", "Paperclips description 3")); products.add(new Product("4444444444444", "Paperclips 4", "Paperclips description 4")); products.add(new Product("5555555555555", "Paperclips 5", "Paperclips description 5")); }
/** * Retrieves the first global error (an error without any key), if it exists. * * @return An error or <code>null</code>. */ public ValidationError globalError() { List<ValidationError> errors = globalErrors(); if (errors.isEmpty()) { return null; } else { return errors.get(0); } }
/** Retrieve an error by key. */ public ValidationError error(String key) { List<ValidationError> err = errors.get(key); if (err == null || err.isEmpty()) { return null; } else { return err.get(0); } }
protected List<PersonMatch> createMatches(final List<Person> people) { final List<PersonMatch> personMatches = new ArrayList<PersonMatch>(); for (final Person person : people) { final PersonMatch p = new PersonMatchImpl(person, 50, new ArrayList<FieldMatch>()); personMatches.add(p); } return personMatches; }
/** * Convert the error arguments. * * @param arguments The arguments to convert. * @return The converted arguments. */ private List<Object> convertErrorArguments(Object[] arguments) { List<Object> converted = new ArrayList<>(arguments.length); for (Object arg : arguments) { if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) { converted.add(arg); } } return Collections.unmodifiableList(converted); }
public static List<Product> findByName(String term) { final List<Product> results = new ArrayList<Product>(); for (Product candidate : products) { if (candidate.name.toLowerCase().contains(term.toLowerCase())) { results.add(candidate); } } return results; }
/** Returns the form errors serialized as Json using the given Lang. */ public org.codehaus.jackson.JsonNode errorsAsJson(play.i18n.Lang lang) { Map<String, List<String>> allMessages = new HashMap<String, List<String>>(); for (String key : errors.keySet()) { List<ValidationError> errs = errors.get(key); if (errs != null && !errs.isEmpty()) { List<String> messages = new ArrayList<String>(); for (ValidationError error : errs) { messages.add(play.i18n.Messages.get(lang, error.message(), error.arguments())); } allMessages.put(key, messages); } } return play.libs.Json.toJson(allMessages); }
public List<RollupTask> parseRollupTasks(String json) throws BeanValidationException, QueryException { List<RollupTask> tasks = new ArrayList<RollupTask>(); JsonParser parser = new JsonParser(); JsonArray rollupTasks = parser.parse(json).getAsJsonArray(); for (int i = 0; i < rollupTasks.size(); i++) { JsonObject taskObject = rollupTasks.get(i).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, "tasks[" + i + "]"); task.addJson(taskObject.toString().replaceAll("\\n", "")); tasks.add(task); } return tasks; }
// Consider return map in future. private static List<String> fetchPartialKey(Map<String, String> map, String key) { List<String> keywords = Arrays.asList(key.split("\\{INDEX\\}")); List<String> listStr = new ArrayList<>(); for (Map.Entry<String, String> e : map.entrySet()) { String numStr = e.getKey().toUpperCase(); for (String keyword : keywords) { numStr = StringUtils.remove(numStr, keyword); } if (NumberUtils.isDigits(numStr)) { listStr.add(e.getValue()); } } return listStr; }
protected Object[] getArgumentsForConstraint( String objectName, String field, ConstraintDescriptor<?> descriptor) { List<Object> arguments = new LinkedList<>(); String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field}; arguments.add(new DefaultMessageSourceResolvable(codes, field)); // Using a TreeMap for alphabetical ordering of attribute names Map<String, Object> attributesToExpose = new TreeMap<>(); for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) { String attributeName = entry.getKey(); Object attributeValue = entry.getValue(); if (!internalAnnotationAttributes.contains(attributeName)) { attributesToExpose.put(attributeName, attributeValue); } } arguments.addAll(attributesToExpose.values()); return arguments.toArray(new Object[arguments.size()]); }
public static Map<String, String> toRequestMap(List paypalClassicModelList, String format) { Map<String, String> returnMap = new HashMap<>(); if (paypalClassicModelList != null) { for (int i = 0; i < paypalClassicModelList.size(); i++) { if (paypalClassicModelList.get(i) instanceof PaypalClassicModel) { if (StringUtils.isNoneEmpty(format)) { returnMap.putAll( toRequestMap( (PaypalClassicModel) paypalClassicModelList.get(i), format + String.valueOf(i))); } else { returnMap.putAll( toRequestMap( (PaypalClassicModel) paypalClassicModelList.get(i), String.valueOf(i))); } } if (paypalClassicModelList.get(i) instanceof List) { if (StringUtils.isNoneEmpty(format)) { returnMap.putAll( toRequestMap((List) paypalClassicModelList.get(i), format + String.valueOf(i))); } else { returnMap.putAll(toRequestMap((List) paypalClassicModelList.get(i), String.valueOf(i))); } } } } return returnMap; }
public RollupTask parseRollupTask(JsonObject rollupTask, String context) throws BeanValidationException, QueryException { RollupTask task = m_gson.fromJson(rollupTask.getAsJsonObject(), RollupTask.class); validateObject(task); JsonArray rollups = rollupTask.getAsJsonObject().getAsJsonArray("rollups"); if (rollups != null) { for (int j = 0; j < rollups.size(); j++) { JsonObject rollupObject = rollups.get(j).getAsJsonObject(); Rollup rollup = m_gson.fromJson(rollupObject, Rollup.class); context = context + "rollup[" + j + "]"; validateObject(rollup, context); JsonObject queryObject = rollupObject.getAsJsonObject("query"); List<QueryMetric> queries = parseQueryMetric(queryObject, context); for (int k = 0; k < queries.size(); k++) { QueryMetric query = queries.get(k); context += ".query[" + k + "]"; validateHasRangeAggregator(query, context); // Add aggregators needed for rollups SaveAsAggregator saveAsAggregator = (SaveAsAggregator) m_aggregatorFactory.createAggregator("save_as"); saveAsAggregator.setMetricName(rollup.getSaveAs()); TrimAggregator trimAggregator = (TrimAggregator) m_aggregatorFactory.createAggregator("trim"); trimAggregator.setTrim(TrimAggregator.Trim.LAST); query.addAggregator(saveAsAggregator); query.addAggregator(trimAggregator); } rollup.addQueries(queries); task.addRollup(rollup); } } return task; }
/** Returns the form errors serialized as Json using the given Lang. */ public com.fasterxml.jackson.databind.JsonNode errorsAsJson(play.i18n.Lang lang) { Map<String, List<String>> allMessages = new HashMap<>(); for (String key : errors.keySet()) { List<ValidationError> errs = errors.get(key); if (errs != null && !errs.isEmpty()) { List<String> messages = new ArrayList<String>(); for (ValidationError error : errs) { if (messagesApi != null && lang != null) { messages.add( messagesApi.get( lang, error.messages(), translateMsgArg(error.arguments(), messagesApi, lang))); } else { messages.add(error.message()); } } allMessages.put(key, messages); } } return play.libs.Json.toJson(allMessages); }
private static List mapToClazzList(Map<String, String> mapdata, Class subClazz, String formatStr) throws IllegalAccessException, InstantiationException, InvocationTargetException { Map<String, String> lookupMap = getCaseInsensitveMap(mapdata); List returnList = new ArrayList(); int itemListLength = 0; // find the length of the list for (Field field : FieldUtils.getAllFields(subClazz)) { int i = 0; while (lookupMap.get(getFormatedKeyName(formatStr, field.getName(), i)) != null) { i++; } if (i > itemListLength) { itemListLength = i; } } // inital each item for (int i = 0; i < itemListLength; i++) { returnList.add(mapToClazz(lookupMap, subClazz, getFormatedKeyName(formatStr, null, i))); } return returnList; }
private Object translateMsgArg( List<Object> arguments, MessagesApi messagesApi, play.i18n.Lang lang) { if (arguments != null) { return arguments .stream() .map( arg -> { if (arg instanceof String) { return messagesApi.get(lang, (String) arg); } if (arg instanceof List) { return ((List<?>) arg) .stream() .map(key -> messagesApi.get(lang, (String) key)) .collect(Collectors.toList()); } return arg; }) .collect(Collectors.toList()); } else { return null; } }
public static boolean remove(Product product) { return products.remove(product); }
protected Person recalculatePersonBiodemInfo( final Person person, final SorPerson sorPerson, final RecalculationType recalculationType, boolean mistake) { final List<SorPerson> sorPersons = this.personRepository.getSoRRecordsForPerson(person); logger.info("recalculatePersonBiodemInfo: start"); if (recalculationType == RecalculationType.ADD || (recalculationType == RecalculationType.DELETE && !mistake)) { sorPersons.add(sorPerson); } copySorNamesToPerson(person, sorPersons); final Date birthDate = this.birthDateFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final String gender = this.genderFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final SorName preferredName = this.preferredNameFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final SorName officialName = this.officialNameFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final EmailAddress emailAddress = this.preferredContactEmailAddressFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final Phone phone = this.preferredContactPhoneNumberFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final Map<String, String> attributes = this.attributesElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final SorDisclosureSettings disclosure = this.disclosureFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); final String ssn = this.ssnFieldElector.elect( sorPerson, sorPersons, recalculationType == RecalculationType.DELETE); Identifier primarySSN = person.getPrimaryIdentifiersByType().get("SSN"); // check if the elector elcted some ssn and person does have previous ssn assigned to it if (!org.apache.commons.lang.StringUtils.isEmpty(ssn) && primarySSN != null) { try { this.identifierChangeService.change(person.getPrimaryIdentifiersByType().get("SSN"), ssn); } catch (IllegalArgumentException e) { logger.debug(e.getStackTrace().toString()); } // all other exception should be propogated } person.setDateOfBirth(birthDate); person.setGender(gender); person.getPreferredContactEmailAddress().update(emailAddress); person.getPreferredContactPhoneNumber().update(phone); person.calculateDisclosureSettings(disclosure); person.setAttributes(attributes); String affiliation = ""; Type affiliationType = null; if (disclosure != null) { logger.info( "after person.calculateDisclosureSettings, disclosure code : " + disclosure.getDisclosureCode()); } else { logger.info("Disclosure is null"); } List<SorRole> sorroles = sorPerson.getRoles(); for (SorRole role : sorroles) { if (role != null) { logger.info("Role = " + role.getTitle()); if (role.getAffiliationType() != null) { logger.info("Role desc= " + role.getAffiliationType().getDescription()); affiliation = role.getAffiliationType().getDescription(); if (person.getDisclosureSettings() != null) { logger.info("recalculating disclosure setting 1..."); // person.getDisclosureSettings().recalculate(this.strategyRepository.getDisclosureRecalculationStrategy()); person .getDisclosureSettings() .recalculate( this.strategyRepository.getDisclosureRecalculationStrategy(), affiliation, referenceRepository); } } } } // SSN election is happening in the ssn identifier assigner. boolean preferred = false; boolean official = false; for (final Name name : person.getNames()) { if (!preferred && name.sameAs(preferredName)) { name.setPreferredName(true); preferred = true; } if (!official && name.sameAs(officialName)) { name.setOfficialName(true); official = true; } if (official && preferred) { break; } } logger.info("recalculatePersonBiodemInfo: end"); // return this.personRepository.savePerson(person); return person; }
/** * Binds data to this form - that is, handles form submission. * * @param data data to submit * @return a copy of this form filled with the new data */ public Form<T> bind(Map<String, String> data, String... allowedFields) { DataBinder dataBinder = null; Map<String, String> objectData = data; if (rootName == null) { dataBinder = new DataBinder(blankInstance()); } else { dataBinder = new DataBinder(blankInstance(), rootName); objectData = new HashMap<String, String>(); for (String key : data.keySet()) { if (key.startsWith(rootName + ".")) { objectData.put(key.substring(rootName.length() + 1), data.get(key)); } } } if (allowedFields.length > 0) { dataBinder.setAllowedFields(allowedFields); } SpringValidatorAdapter validator = new SpringValidatorAdapter(play.data.validation.Validation.getValidator()); dataBinder.setValidator(validator); dataBinder.setConversionService(play.data.format.Formatters.conversion); dataBinder.setAutoGrowNestedPaths(true); dataBinder.bind(new MutablePropertyValues(objectData)); Set<ConstraintViolation<Object>> validationErrors; if (groups != null) { validationErrors = validator.validate(dataBinder.getTarget(), groups); } else { validationErrors = validator.validate(dataBinder.getTarget()); } BindingResult result = dataBinder.getBindingResult(); for (ConstraintViolation<Object> violation : validationErrors) { String field = violation.getPropertyPath().toString(); FieldError fieldError = result.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { result.rejectValue( field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint( result.getObjectName(), field, violation.getConstraintDescriptor()), violation.getMessage()); } catch (NotReadablePropertyException ex) { throw new IllegalStateException( "JSR-303 validated property '" + field + "' does not have a corresponding accessor for data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } if (result.hasErrors()) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); for (FieldError error : result.getFieldErrors()) { String key = error.getObjectName() + "." + error.getField(); if (key.startsWith("target.") && rootName == null) { key = key.substring(7); } List<Object> arguments = new ArrayList<Object>(); for (Object arg : error.getArguments()) { if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) { arguments.add(arg); } } if (!errors.containsKey(key)) { errors.put(key, new ArrayList<ValidationError>()); } errors .get(key) .add( new ValidationError( key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments)); } return new Form(rootName, backedType, data, errors, None(), groups); } else { Object globalError = null; if (result.getTarget() != null) { try { java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate"); globalError = v.invoke(result.getTarget()); } catch (NoSuchMethodException e) { } catch (Throwable e) { throw new RuntimeException(e); } } if (globalError != null) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); if (globalError instanceof String) { errors.put("", new ArrayList<ValidationError>()); errors.get("").add(new ValidationError("", (String) globalError, new ArrayList())); } else if (globalError instanceof List) { errors.put("", (List<ValidationError>) globalError); } else if (globalError instanceof Map) { errors = (Map<String, List<ValidationError>>) globalError; } return new Form(rootName, backedType, data, errors, None(), groups); } return new Form( rootName, backedType, new HashMap<String, String>(data), new HashMap<String, List<ValidationError>>(errors), Some((T) result.getTarget()), groups); } }
/** * Binds data to this form - that is, handles form submission. * * @param data data to submit * @return a copy of this form filled with the new data */ @SuppressWarnings("unchecked") public Form<T> bind(Map<String, String> data, String... allowedFields) { DataBinder dataBinder; Map<String, String> objectData = data; if (rootName == null) { dataBinder = new DataBinder(blankInstance()); } else { dataBinder = new DataBinder(blankInstance(), rootName); objectData = new HashMap<>(); for (String key : data.keySet()) { if (key.startsWith(rootName + ".")) { objectData.put(key.substring(rootName.length() + 1), data.get(key)); } } } if (allowedFields.length > 0) { dataBinder.setAllowedFields(allowedFields); } SpringValidatorAdapter validator = new SpringValidatorAdapter(play.data.validation.Validation.getValidator()); dataBinder.setValidator(validator); dataBinder.setConversionService(formatters.conversion); dataBinder.setAutoGrowNestedPaths(true); final Map<String, String> objectDataFinal = objectData; withRequestLocale( () -> { dataBinder.bind(new MutablePropertyValues(objectDataFinal)); return null; }); Set<ConstraintViolation<Object>> validationErrors; if (groups != null) { validationErrors = validator.validate(dataBinder.getTarget(), groups); } else { validationErrors = validator.validate(dataBinder.getTarget()); } BindingResult result = dataBinder.getBindingResult(); for (ConstraintViolation<Object> violation : validationErrors) { String field = violation.getPropertyPath().toString(); FieldError fieldError = result.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { result.rejectValue( field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint( result.getObjectName(), field, violation.getConstraintDescriptor()), getMessageForConstraintViolation(violation)); } catch (NotReadablePropertyException ex) { throw new IllegalStateException( "JSR-303 validated property '" + field + "' does not have a corresponding accessor for data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } if (result.hasErrors() || result.getGlobalErrorCount() > 0) { Map<String, List<ValidationError>> errors = new HashMap<>(); for (FieldError error : result.getFieldErrors()) { String key = error.getObjectName() + "." + error.getField(); if (key.startsWith("target.") && rootName == null) { key = key.substring(7); } if (!errors.containsKey(key)) { errors.put(key, new ArrayList<>()); } ValidationError validationError; if (error.isBindingFailure()) { ImmutableList.Builder<String> builder = ImmutableList.builder(); Optional<Messages> msgs = Optional.of(Http.Context.current.get()).map(c -> messagesApi.preferred(c.request())); for (String code : error.getCodes()) { code = code.replace("typeMismatch", "error.invalid"); if (!msgs.isPresent() || msgs.get().isDefinedAt(code)) { builder.add(code); } } validationError = new ValidationError( key, builder.build().reverse(), convertErrorArguments(error.getArguments())); } else { validationError = new ValidationError( key, error.getDefaultMessage(), convertErrorArguments(error.getArguments())); } errors.get(key).add(validationError); } List<ValidationError> globalErrors = new ArrayList<>(); for (ObjectError error : result.getGlobalErrors()) { globalErrors.add( new ValidationError( "", error.getDefaultMessage(), convertErrorArguments(error.getArguments()))); } if (!globalErrors.isEmpty()) { errors.put("", globalErrors); } return new Form( rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters); } else { Object globalError = null; if (result.getTarget() != null) { try { java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate"); globalError = v.invoke(result.getTarget()); } catch (NoSuchMethodException e) { // do nothing } catch (Throwable e) { throw new RuntimeException(e); } } if (globalError != null) { Map<String, List<ValidationError>> errors = new HashMap<>(); if (globalError instanceof String) { errors.put("", new ArrayList<>()); errors.get("").add(new ValidationError("", (String) globalError, new ArrayList())); } else if (globalError instanceof List) { for (ValidationError error : (List<ValidationError>) globalError) { List<ValidationError> errorsForKey = errors.get(error.key()); if (errorsForKey == null) { errors.put(error.key(), errorsForKey = new ArrayList<>()); } errorsForKey.add(error); } } else if (globalError instanceof Map) { errors = (Map<String, List<ValidationError>>) globalError; } return new Form( rootName, backedType, data, errors, Optional.empty(), groups, messagesApi, formatters); } return new Form( rootName, backedType, new HashMap<>(data), new HashMap<>(errors), Optional.ofNullable((T) result.getTarget()), groups, messagesApi, formatters); } }
public static Map<String, String> toRequestMap( PaypalClassicModel paypalClassicModel, String format) { Map<String, String> returnMap = new HashMap<>(); if (paypalClassicModel == null) { return returnMap; } ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); // ValidatorFactory factory = Validation.byDefaultProvider() // .configure() // .messageInterpolator( new MyMessageInterpolator() ) // .buildValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<PaypalClassicModel>> violations = validator.validate(paypalClassicModel); if (violations.size() == 0) { try { for (Field field : FieldUtils.getAllFields(paypalClassicModel.getClass())) { if (field.getType().isAssignableFrom(String.class)) { if (BeanUtils.getProperty(paypalClassicModel, field.getName()) != null) { if (StringUtils.isNumeric(format)) { returnMap.put( field.getName().toUpperCase() + format, BeanUtils.getProperty(paypalClassicModel, field.getName())); } else { returnMap.put( getFormatedKeyName(format, field.getName(), null), BeanUtils.getProperty(paypalClassicModel, field.getName())); } } } if (PaypalClassicModel.class.isAssignableFrom(field.getType())) { if (PropertyUtils.getProperty(paypalClassicModel, field.getName()) != null) { returnMap.putAll( toRequestMap( (PaypalClassicModel) PropertyUtils.getProperty(paypalClassicModel, field.getName()), format)); } } if (List.class.isAssignableFrom(field.getType())) { List listItem = (List) PropertyUtils.getProperty(paypalClassicModel, field.getName()); if (listItem != null) { for (int i = 0; i < listItem.size(); i++) { if (listItem.get(i) instanceof PaypalClassicModel) { PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class); if (paypalCollection != null && StringUtils.isNotEmpty(paypalCollection.format())) { String formatStr = field.getAnnotation(PaypalCollection.class).format(); returnMap.putAll( toRequestMap( (PaypalClassicModel) listItem.get(i), getFormatedKeyName(formatStr, null, i))); } else { if (StringUtils.isNoneEmpty(format)) { returnMap.putAll( toRequestMap( (PaypalClassicModel) listItem.get(i), format + String.valueOf(i))); } else { returnMap.putAll( toRequestMap((PaypalClassicModel) listItem.get(i), String.valueOf(i))); } } } if (listItem.get(i) instanceof List) { PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class); if (paypalCollection != null && StringUtils.isNotEmpty(paypalCollection.format())) { String formatStr = field.getAnnotation(PaypalCollection.class).format(); returnMap.putAll( toRequestMap( (List) listItem.get(i), getFormatedKeyName(formatStr, null, i))); } else { if (StringUtils.isNoneEmpty(format)) { returnMap.putAll( toRequestMap((List) listItem.get(i), format + String.valueOf(i))); } else { returnMap.putAll(toRequestMap((List) listItem.get(i), String.valueOf(i))); } } } if (listItem.get(i) instanceof String) { PaypalCollection paypalCollection = field.getAnnotation(PaypalCollection.class); if (paypalCollection != null && StringUtils.isNotEmpty(paypalCollection.format())) { String formatStr = paypalCollection.format(); formatStr = getFormatedKeyName(formatStr, field.getName(), i); returnMap.put( getFormatedKeyName(format, formatStr, null), listItem.get(i).toString()); } else { returnMap.put( getFormatedKeyName(format, field.getName(), null) + i, listItem.get(i).toString()); } } } } } } } catch (IllegalAccessException e) { throw new ValidationException(e.getMessage()); } catch (InvocationTargetException e) { throw new ValidationException(e.getMessage()); } catch (NoSuchMethodException e) { throw new ValidationException(e.getMessage()); } } else { StringBuffer buf = new StringBuffer(); for (ConstraintViolation<PaypalClassicModel> violation : violations) { buf.append(violation.getMessage() + "\n"); } throw new ValidationException(buf.toString()); } return returnMap; }
private List<QueryMetric> parseQueryMetric(JsonObject obj, String contextPrefix) throws QueryException, BeanValidationException { List<QueryMetric> ret = new ArrayList<QueryMetric>(); Query query; try { query = m_gson.fromJson(obj, Query.class); validateObject(query); } catch (ContextualJsonSyntaxException e) { throw new BeanValidationException( new SimpleConstraintViolation(e.getContext(), e.getMessage()), "query"); } JsonArray metricsArray = obj.getAsJsonArray("metrics"); if (metricsArray == null) { throw new BeanValidationException( new SimpleConstraintViolation("metric[]", "must have a size of at least 1"), contextPrefix + "query"); } for (int I = 0; I < metricsArray.size(); I++) { String context = (!contextPrefix.isEmpty() ? contextPrefix + "." : contextPrefix) + "query.metric[" + I + "]"; try { Metric metric = m_gson.fromJson(metricsArray.get(I), Metric.class); validateObject(metric, context); long startTime = getStartTime(query, context); QueryMetric queryMetric = new QueryMetric(startTime, query.getCacheTime(), metric.getName()); queryMetric.setExcludeTags(metric.isExcludeTags()); queryMetric.setLimit(metric.getLimit()); long endTime = getEndTime(query); if (endTime > -1) queryMetric.setEndTime(endTime); if (queryMetric.getEndTime() < startTime) throw new BeanValidationException( new SimpleConstraintViolation("end_time", "must be greater than the start time"), context); queryMetric.setCacheString(query.getCacheString() + metric.getCacheString()); JsonObject jsMetric = metricsArray.get(I).getAsJsonObject(); JsonElement group_by = jsMetric.get("group_by"); if (group_by != null) { JsonArray groupBys = group_by.getAsJsonArray(); parseGroupBy(context, queryMetric, groupBys); } JsonElement aggregators = jsMetric.get("aggregators"); if (aggregators != null) { JsonArray asJsonArray = aggregators.getAsJsonArray(); if (asJsonArray.size() > 0) parseAggregators(context, queryMetric, asJsonArray, query.getTimeZone()); } JsonElement plugins = jsMetric.get("plugins"); if (plugins != null) { JsonArray pluginArray = plugins.getAsJsonArray(); if (pluginArray.size() > 0) parsePlugins(context, queryMetric, pluginArray); } JsonElement order = jsMetric.get("order"); if (order != null) queryMetric.setOrder(Order.fromString(order.getAsString(), context)); queryMetric.setTags(metric.getTags()); ret.add(queryMetric); } catch (ContextualJsonSyntaxException e) { throw new BeanValidationException( new SimpleConstraintViolation(e.getContext(), e.getMessage()), context); } } return (ret); }
/** * Retrieve a field. * * @param key field name * @return the field (even if the field does not exist you get a field) */ public Field field(String key) { // Value String fieldValue = null; if (data.containsKey(key)) { fieldValue = data.get(key); } else { if (value.isPresent()) { BeanWrapper beanWrapper = new BeanWrapperImpl(value.get()); beanWrapper.setAutoGrowNestedPaths(true); String objectKey = key; if (rootName != null && key.startsWith(rootName + ".")) { objectKey = key.substring(rootName.length() + 1); } if (beanWrapper.isReadableProperty(objectKey)) { Object oValue = beanWrapper.getPropertyValue(objectKey); if (oValue != null) { final String objectKeyFinal = objectKey; fieldValue = withRequestLocale( () -> formatters.print( beanWrapper.getPropertyTypeDescriptor(objectKeyFinal), oValue)); } } } } // Error List<ValidationError> fieldErrors = errors.get(key); if (fieldErrors == null) { fieldErrors = new ArrayList<>(); } // Format Tuple<String, List<Object>> format = null; BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance()); beanWrapper.setAutoGrowNestedPaths(true); try { for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) { Class<?> annotationType = a.annotationType(); if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) { play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class); if (d.name().startsWith("format.")) { List<Object> attributes = new ArrayList<>(); for (String attr : d.attributes()) { Object attrValue = null; try { attrValue = a.getClass().getDeclaredMethod(attr).invoke(a); } catch (Exception e) { // do nothing } attributes.add(attrValue); } format = Tuple(d.name(), attributes); } } } } catch (NullPointerException e) { // do nothing } // Constraints List<Tuple<String, List<Object>>> constraints = new ArrayList<>(); Class<?> classType = backedType; String leafKey = key; if (rootName != null && leafKey.startsWith(rootName + ".")) { leafKey = leafKey.substring(rootName.length() + 1); } int p = leafKey.lastIndexOf('.'); if (p > 0) { classType = beanWrapper.getPropertyType(leafKey.substring(0, p)); leafKey = leafKey.substring(p + 1); } if (classType != null) { BeanDescriptor beanDescriptor = play.data.validation.Validation.getValidator().getConstraintsForClass(classType); if (beanDescriptor != null) { PropertyDescriptor property = beanDescriptor.getConstraintsForProperty(leafKey); if (property != null) { constraints = Constraints.displayableConstraint(property.getConstraintDescriptors()); } } } return new Field(this, key, constraints, format, fieldErrors, fieldValue); }
public void save() { products.remove(findByEan(this.ean)); products.add(this); }