Search in sources :

Example 1 with Validation

use of org.webpieces.ctx.api.Validation in project webpieces by deanhiller.

the class ParamToObjectTranslatorImpl method translate.

private Object translate(RouterRequest req, Method method, ParamNode valuesToUse, Meta fieldMeta, Validation validator) {
    Class<?> fieldClass = fieldMeta.getFieldClass();
    ObjectStringConverter<?> converter = objectTranslator.getConverter(fieldClass);
    if (converter != null) {
        return convert(req, method, valuesToUse, fieldMeta, converter, validator);
    } else if (fieldClass.isArray()) {
        throw new UnsupportedOperationException("not done yet...let me know and I will do it=" + fieldMeta);
    } else if (fieldClass.isEnum()) {
        throw new UnsupportedOperationException("You need to install a " + ObjectStringConverter.class.getSimpleName() + " for this enum " + fieldMeta);
    } else if (List.class.isAssignableFrom(fieldClass)) {
        if (valuesToUse == null)
            return new ArrayList<>();
        else if (valuesToUse instanceof ArrayNode) {
            List<ParamNode> paramNodes = ((ArrayNode) valuesToUse).getList();
            return createList(req, method, fieldMeta, validator, paramNodes);
        } else if (valuesToUse instanceof ValueNode) {
            List<ParamNode> paramNodes = new ArrayList<>();
            paramNodes.add(valuesToUse);
            return createList(req, method, fieldMeta, validator, paramNodes);
        }
        throw new IllegalArgumentException("Found List on field or param=" + fieldMeta + " but did not find ArrayNode type");
    } else if (valuesToUse instanceof ArrayNode) {
        throw new IllegalArgumentException("Incoming array need a type List but instead found type=" + fieldClass + " on field=" + fieldMeta);
    } else if (valuesToUse instanceof ValueNode) {
        ValueNode v = (ValueNode) valuesToUse;
        String fullName = v.getFullName();
        throw new IllegalArgumentException("Could not convert incoming value=" + v.getValue() + " of key name=" + fullName + " field=" + fieldMeta);
    } else if (valuesToUse == null) {
        //validate if null is ok or not
        fieldMeta.validateNullValue();
        return null;
    } else if (!(valuesToUse instanceof ParamTreeNode)) {
        throw new IllegalStateException("Bug, must be missing a case. v=" + valuesToUse + " type to field=" + fieldMeta);
    }
    ParamTreeNode tree = (ParamTreeNode) valuesToUse;
    EntityLookup pluginLookup = fetchPluginLoader(fieldClass);
    Object bean = null;
    if (pluginLookup != null) {
        bean = pluginLookup.find(fieldMeta, tree, c -> createBean(c));
        if (bean == null)
            throw new IllegalStateException("plugin=" + pluginLookup.getClass() + " failed to create bean.  This is a plugin bug");
    } else
        bean = createBean(fieldClass);
    for (Map.Entry<String, ParamNode> entry : tree.entrySet()) {
        String key = entry.getKey();
        ParamNode value = entry.getValue();
        Field field = findBeanFieldType(bean.getClass(), key, new ArrayList<>());
        FieldMeta nextFieldMeta = new FieldMeta(field);
        Object translatedValue = translate(req, method, value, nextFieldMeta, validator);
        nextFieldMeta.setValueOnBean(bean, translatedValue);
    }
    return bean;
}
Also used : ObjectStringConverter(org.webpieces.router.api.ObjectStringConverter) Validation(org.webpieces.ctx.api.Validation) Set(java.util.Set) HashMap(java.util.HashMap) Field(java.lang.reflect.Field) Singleton(javax.inject.Singleton) BodyContentBinder(org.webpieces.router.api.BodyContentBinder) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) List(java.util.List) RouterRequest(org.webpieces.ctx.api.RouterRequest) HttpMethod(org.webpieces.ctx.api.HttpMethod) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) RequestContext(org.webpieces.ctx.api.RequestContext) EntityLookup(org.webpieces.router.api.EntityLookup) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) NotFoundException(org.webpieces.router.api.exceptions.NotFoundException) Annotation(java.lang.annotation.Annotation) DataMismatchException(org.webpieces.router.api.exceptions.DataMismatchException) Method(java.lang.reflect.Method) ClientDataError(org.webpieces.router.api.exceptions.ClientDataError) EntityLookup(org.webpieces.router.api.EntityLookup) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with Validation

use of org.webpieces.ctx.api.Validation in project webpieces by deanhiller.

the class AbstractRouterService method incomingCompleteRequest.

@Override
public final CompletableFuture<Void> incomingCompleteRequest(RouterRequest routerRequest, ResponseStreamer responseCb) {
    try {
        if (!started)
            throw new IllegalStateException("Either start was not called by client or start threw an exception that client ignored and must be fixed");
        ;
        Session session = (Session) cookieTranslator.translateCookieToScope(routerRequest, new SessionImpl(translator));
        FlashSub flash = (FlashSub) cookieTranslator.translateCookieToScope(routerRequest, new FlashImpl(translator));
        Validation validation = (Validation) cookieTranslator.translateCookieToScope(routerRequest, new ValidationImpl(translator));
        RequestContext requestCtx = new RequestContext(validation, flash, session, routerRequest);
        return processRequest(requestCtx, responseCb);
    } catch (BadCookieException e) {
        throw e;
    } catch (Throwable e) {
        log.warn("uncaught exception", e);
        return responseCb.failureRenderingInternalServerErrorPage(e);
    }
}
Also used : Validation(org.webpieces.ctx.api.Validation) BadCookieException(org.webpieces.router.api.exceptions.BadCookieException) SessionImpl(org.webpieces.router.impl.ctx.SessionImpl) FlashImpl(org.webpieces.router.impl.ctx.FlashImpl) RequestContext(org.webpieces.ctx.api.RequestContext) FlashSub(org.webpieces.ctx.api.FlashSub) Session(org.webpieces.ctx.api.Session) ValidationImpl(org.webpieces.router.impl.ctx.ValidationImpl)

Example 3 with Validation

use of org.webpieces.ctx.api.Validation in project webpieces by deanhiller.

the class FieldTag method createFieldData.

/**
	 *
	 */
@SuppressWarnings("rawtypes")
private Map<String, Object> createFieldData(String fieldName2, Map<String, Object> pageArgs) {
    Result result = reworkNameForArrayOnly(fieldName2, pageArgs);
    String fieldName = result.fieldName;
    Flash flash = Current.flash();
    Validation validation = Current.validation();
    Map<String, Object> field = new HashMap<String, Object>();
    field.put("name", fieldName);
    String id = makeValidHtml4Id(fieldName);
    field.put("id", id);
    String flashValue = flash.get(fieldName);
    //different from fieldName only for Arrays
    field.put("i18nKey", result.i18nName);
    field.put("flash", flashValue);
    field.put("error", validation.getError(fieldName));
    field.put("errorClass", field.get("error") != null ? getErrorClass() : "");
    String[] pieces = fieldName.split("\\.");
    Object pageArgValue = null;
    Object obj = pageArgs.get(pieces[0]);
    if (pieces.length > 1) {
        try {
            String path = fieldName.substring(fieldName.indexOf(".") + 1);
            pageArgValue = PropertyUtils.getProperty(obj, path);
        } catch (Exception e) {
            // if there is a problem reading the field we dont set any
            // value
            log.trace(() -> "exception", e);
        }
    } else {
        //for method parameters not fields in the bean like above
        pageArgValue = obj;
    }
    field.put("value", pageArgValue);
    String valAsStr = null;
    if (pageArgValue instanceof Collection) {
        //For multiple select html OptionTag to work, this was needed
        valAsStr = convert((Collection) pageArgValue);
    } else {
        valAsStr = converter.convert(pageArgValue);
    }
    field.put("flashOrValue", preferFirst(flashValue, valAsStr));
    field.put("valueOrFlash", preferFirst(valAsStr, flashValue));
    return field;
}
Also used : Validation(org.webpieces.ctx.api.Validation) HashMap(java.util.HashMap) Collection(java.util.Collection) Flash(org.webpieces.ctx.api.Flash)

Aggregations

Validation (org.webpieces.ctx.api.Validation)3 HashMap (java.util.HashMap)2 RequestContext (org.webpieces.ctx.api.RequestContext)2 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 Parameter (java.lang.reflect.Parameter)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 Inject (javax.inject.Inject)1 Singleton (javax.inject.Singleton)1 Flash (org.webpieces.ctx.api.Flash)1 FlashSub (org.webpieces.ctx.api.FlashSub)1 HttpMethod (org.webpieces.ctx.api.HttpMethod)1 RouterRequest (org.webpieces.ctx.api.RouterRequest)1