Search in sources :

Example 1 with ObjectStringConverter

use of org.webpieces.router.api.extensions.ObjectStringConverter in project webpieces by deanhiller.

the class HibernateLookup method findEntityImpl.

private <T> T findEntityImpl(ParamMeta paramMeta, ParamTreeNode tree, Function<Class<T>, T> beanCreate, EntityManager entityManager) {
    ParamMeta m = paramMeta;
    Class<T> paramTypeToCreate = (Class<T>) m.getFieldClass();
    Metamodel metamodel = entityManager.getMetamodel();
    ManagedType<T> managedType = metamodel.managedType(paramTypeToCreate);
    IdentifiableType<T> entityType = (IdentifiableType<T>) managedType;
    Class<?> idClazz = entityType.getIdType().getJavaType();
    SingularAttribute<? super T, ?> idAttribute = entityType.getId(idClazz);
    String name = idAttribute.getName();
    ParamNode paramNode = tree.get(name);
    String value = null;
    if (paramNode != null) {
        if (!(paramNode instanceof ValueNode))
            throw new IllegalStateException("The id field in the hibernate entity should have matched to a " + "ValueNode on incoming data and did not. node=" + paramNode + ".  bad multipart form?  (Please " + "let us know so we can pair with you on this and I can add better error messaging)");
        ValueNode node = (ValueNode) paramNode;
        value = node.getValue();
    }
    if (value == null)
        return beanCreate.apply(paramTypeToCreate);
    @SuppressWarnings("rawtypes") ObjectStringConverter unmarshaller = translator.getConverter(idClazz);
    Object id = unmarshaller.stringToObject(value);
    UseQuery namedQuery = fetchUseQuery(m.getAnnotations());
    if (namedQuery == null)
        return entityManager.find(paramTypeToCreate, id);
    Query query = entityManager.createNamedQuery(namedQuery.value());
    query.setParameter(namedQuery.id(), id);
    return (T) query.getSingleResult();
}
Also used : IdentifiableType(javax.persistence.metamodel.IdentifiableType) Query(javax.persistence.Query) ParamNode(org.webpieces.router.impl.params.ParamNode) ParamMeta(org.webpieces.router.api.extensions.ParamMeta) ValueNode(org.webpieces.router.impl.params.ValueNode) Metamodel(javax.persistence.metamodel.Metamodel) ObjectStringConverter(org.webpieces.router.api.extensions.ObjectStringConverter)

Example 2 with ObjectStringConverter

use of org.webpieces.router.api.extensions.ObjectStringConverter in project webpieces by deanhiller.

the class ParamToObjectTranslatorImpl method translate.

private XFuture<Object> translate(RouterRequest req, Method method, ParamNode valuesToUse, Meta fieldMeta, Validation validator) {
    Class<?> fieldClass = fieldMeta.getFieldClass();
    ObjectStringConverter<?> converter = objectTranslator.getConverter(fieldClass);
    if (converter != null) {
        Object convert = convert(req, method, valuesToUse, fieldMeta, converter, validator);
        return XFuture.completedFuture(convert);
    } 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 " + fieldClass + " meta class=" + fieldMeta.getFieldClass() + ". This\n" + "can be done like so in one of your guice modules....\n" + "\t\tMultibinder<ObjectStringConverter> conversionBinder = Multibinder.newSetBinder(binder, ObjectStringConverter.class);\n" + "\t\tconversionBinder.addBinding().to({YOUR_ENUM}.WebConverter.class);");
    } else if (List.class.isAssignableFrom(fieldClass)) {
        if (valuesToUse == null)
            return XFuture.completedFuture(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 XFuture.completedFuture(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);
    XFuture<Object> future = null;
    if (pluginLookup != null) {
        future = pluginLookup.find(fieldMeta, tree, c -> createBean(c));
        if (future == null)
            throw new IllegalStateException("plugin=" + pluginLookup.getClass() + " failed to create bean.  This is a plugin bug");
    } else {
        Object newBean = createBean(fieldClass);
        future = XFuture.completedFuture(newBean);
    }
    return future.thenCompose(bean -> {
        return fillBeanIn(bean, tree, req, method, validator);
    });
}
Also used : SneakyThrow(org.webpieces.util.exceptions.SneakyThrow) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) NotFoundException(org.webpieces.http.exception.NotFoundException) RouterRequest(org.webpieces.ctx.api.RouterRequest) EntityLookup(org.webpieces.router.api.extensions.EntityLookup) RequestContext(org.webpieces.ctx.api.RequestContext) Meta(org.webpieces.router.api.extensions.Meta) Parameter(java.lang.reflect.Parameter) IllegalArgException(org.webpieces.router.api.exceptions.IllegalArgException) Map(java.util.Map) DataMismatchException(org.webpieces.router.api.exceptions.DataMismatchException) Method(java.lang.reflect.Method) BadRequestException(org.webpieces.http.exception.BadRequestException) Validation(org.webpieces.ctx.api.Validation) ParamMeta(org.webpieces.router.api.extensions.ParamMeta) Set(java.util.Set) Field(java.lang.reflect.Field) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) HttpMethod(org.webpieces.ctx.api.HttpMethod) ParameterizedType(java.lang.reflect.ParameterizedType) XFuture(org.webpieces.util.futures.XFuture) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) ObjectStringConverter(org.webpieces.router.api.extensions.ObjectStringConverter) BodyContentBinder(org.webpieces.router.api.extensions.BodyContentBinder) EntityLookup(org.webpieces.router.api.extensions.EntityLookup) ArrayList(java.util.ArrayList) List(java.util.List)

Example 3 with ObjectStringConverter

use of org.webpieces.router.api.extensions.ObjectStringConverter in project webpieces by deanhiller.

the class ObjectToParamTranslator method formMap.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map<String, String> formMap(Method method, List<String> pathParamNames, Map<String, Object> redirectArgs) {
    if (pathParamNames.size() != redirectArgs.size())
        throw new IllegalReturnValueException("The Redirect object returned from method='" + method + "' has the wrong number of arguments. args.size=" + redirectArgs.size() + " should be size=" + pathParamNames.size());
    Map<String, String> nameToValue = new HashMap<>();
    for (int i = 0; i < pathParamNames.size(); i++) {
        String key = pathParamNames.get(i);
        Object value = redirectArgs.get(key);
        // value can't be null on redirect
        if (value == null)
            throw new IllegalArgumentException("Controller did not set key='" + key + "' or passed in null" + " for '" + key + "' and this is not allowed as you end up with the word 'null' in your url");
        ObjectStringConverter function = translator.getConverterFor(value);
        nameToValue.put(key, function.objectToString(value));
    }
    return nameToValue;
}
Also used : IllegalReturnValueException(org.webpieces.router.api.exceptions.IllegalReturnValueException) HashMap(java.util.HashMap) ObjectStringConverter(org.webpieces.router.api.extensions.ObjectStringConverter)

Example 4 with ObjectStringConverter

use of org.webpieces.router.api.extensions.ObjectStringConverter in project webpieces by deanhiller.

the class GuiceModule method configure.

// This is where you would put the guice bindings you need though generally if done
// right, you won't have much in this file.
// If you need more Guice Modules as you want to scale, just modify ServerMeta which returns
// the list of all the Guice Modules in your application
@SuppressWarnings("rawtypes")
@Override
public void configure(Binder binder) {
    log.info("running module");
    // all modules have access to adding their own Startable objects to be run on server startup
    Multibinder<Startable> uriBinder = Multibinder.newSetBinder(binder, Startable.class);
    uriBinder.addBinding().to(PopulateDatabase.class);
    Multibinder<ObjectStringConverter> conversionBinder = Multibinder.newSetBinder(binder, ObjectStringConverter.class);
    conversionBinder.addBinding().to(EducationEnum.WebConverter.class);
    conversionBinder.addBinding().to(RoleEnum.WebConverter.class);
    Multibinder<HtmlTagCreator> htmlTagCreators = Multibinder.newSetBinder(binder, HtmlTagCreator.class);
    htmlTagCreators.addBinding().to(MyHtmlTagCreator.class);
    binder.bind(SomeLibrary.class).to(SomeLibraryImpl.class);
    // Must bind a SimpleStorage for plugins to read/save data and render their html pages
    binder.bind(SimpleStorage.class).to(SimpleStorageImpl.class).asEagerSingleton();
    // Must bind a BackendLogin for the backend plugin(or remove the backend plugin)
    binder.bind(BackendLogin.class).to(BackendLoginImpl.class).asEagerSingleton();
    // since GlobalAppContext is a singleton, ApplicationContext will be to and will be the same
    binder.bind(ApplicationContext.class).to(GlobalAppContext.class).asEagerSingleton();
    binder.bind(HttpsConfig.class).toInstance(new HttpsConfig(true));
    binder.bind(ClientAssertions.class).to(ClientAssertionsImpl.class).asEagerSingleton();
}
Also used : SimpleStorageImpl(webpiecesxxxxxpackage.service.SimpleStorageImpl) BackendLoginImpl(webpiecesxxxxxpackage.web.login.BackendLoginImpl) Startable(org.webpieces.router.api.extensions.Startable) EducationEnum(webpiecesxxxxxpackage.db.EducationEnum) RoleEnum(webpiecesxxxxxpackage.db.RoleEnum) HtmlTagCreator(org.webpieces.ctx.api.extension.HtmlTagCreator) MyHtmlTagCreator(webpiecesxxxxxpackage.web.tags.MyHtmlTagCreator) HttpsConfig(org.webpieces.microsvc.client.api.HttpsConfig) ObjectStringConverter(org.webpieces.router.api.extensions.ObjectStringConverter) SomeLibrary(webpiecesxxxxxpackage.service.SomeLibrary)

Example 5 with ObjectStringConverter

use of org.webpieces.router.api.extensions.ObjectStringConverter in project webpieces by deanhiller.

the class DtoLookup method find.

@SuppressWarnings("unchecked")
@Override
public <T> XFuture<T> find(Meta paramMeta, ParamTreeNode tree, Function<Class<T>, T> beanCreate) {
    if (!(paramMeta instanceof ParamMeta))
        throw new UnsupportedOperationException("this plugin does not support type=" + paramMeta.getClass());
    ParamMeta m = (ParamMeta) paramMeta;
    Class<T> paramTypeToCreate = (Class<T>) m.getFieldClass();
    Dto annotation = paramTypeToCreate.getAnnotation(Dto.class);
    // EntityManager entityManager = Em.get();
    // Metamodel metamodel = entityManager.getMetamodel();
    // ManagedType<T> managedType = metamodel.managedType(paramTypeToCreate);
    // IdentifiableType<T> entityType = (IdentifiableType<T>) managedType;
    Method method;
    try {
        method = paramTypeToCreate.getMethod("getId");
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Class=" + paramTypeToCreate.getName() + " has an annotation @Dto and this requires that dto to have a method getId, but we could not find that method", e);
    }
    Class<?> idClazz = method.getReturnType();
    // SingularAttribute<? super T, ?> idAttribute = entityType.getId(idClazz);
    // String name = idAttribute.getName();
    String name = "id";
    ParamNode paramNode = tree.get(name);
    String value = null;
    if (paramNode != null) {
        if (!(paramNode instanceof ValueNode))
            throw new IllegalStateException("The id field in the DTO should have matched to a " + "ValueNode on incoming data and did not. node=" + paramNode + ".  bad multipart form?  (Please " + "let us know so we can pair with you on this and I can add better error messaging)");
        ValueNode node = (ValueNode) paramNode;
        value = node.getValue();
    }
    if (value == null) {
        T theBean = beanCreate.apply(paramTypeToCreate);
        return XFuture.completedFuture(theBean);
    }
    @SuppressWarnings("rawtypes") ObjectStringConverter unmarshaller = translator.getConverter(idClazz);
    Object id = unmarshaller.stringToObject(value);
    Class lookupClass = annotation.lookupClass();
    String function = annotation.function();
    Object instance = webInjector.getCurrentInjector().getInstance(lookupClass);
    Method lookupMethod;
    try {
        lookupMethod = lookupClass.getMethod(function, idClazz);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalArgumentException("Your function in @Dto='XFuture<" + paramTypeToCreate + "> " + function + "(" + idClazz.getName() + ")' on class=" + lookupClass.getName() + " cannot be found.  We also did not find method='" + paramTypeToCreate + " " + function + "(" + idClazz.getName() + ")'");
    }
    Object result;
    try {
        result = lookupMethod.invoke(instance, id);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Exception invoking lookup method", e);
    }
    if (result instanceof XFuture) {
        return (XFuture<T>) result;
    }
    return (XFuture<T>) XFuture.completedFuture(result);
}
Also used : XFuture(org.webpieces.util.futures.XFuture) ParamNode(org.webpieces.router.impl.params.ParamNode) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParamMeta(org.webpieces.router.api.extensions.ParamMeta) ValueNode(org.webpieces.router.impl.params.ValueNode) ObjectStringConverter(org.webpieces.router.api.extensions.ObjectStringConverter)

Aggregations

ObjectStringConverter (org.webpieces.router.api.extensions.ObjectStringConverter)7 ParamMeta (org.webpieces.router.api.extensions.ParamMeta)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 HashMap (java.util.HashMap)2 Set (java.util.Set)2 HtmlTagCreator (org.webpieces.ctx.api.extension.HtmlTagCreator)2 BodyContentBinder (org.webpieces.router.api.extensions.BodyContentBinder)2 EntityLookup (org.webpieces.router.api.extensions.EntityLookup)2 ParamNode (org.webpieces.router.impl.params.ParamNode)2 ValueNode (org.webpieces.router.impl.params.ValueNode)2 XFuture (org.webpieces.util.futures.XFuture)2 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 Parameter (java.lang.reflect.Parameter)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1