Search in sources :

Example 16 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class HibernateAsyncController method entityLoad.

public XFuture<Render> entityLoad(Integer id) {
    EntityManager mgr = Em.get();
    XFuture<Integer> future = new XFuture<Integer>();
    kickOffAsyncResponse(future);
    return future.thenApply(intVal -> runEntityLoad(mgr, id));
}
Also used : EntityManager(javax.persistence.EntityManager) XFuture(org.webpieces.util.futures.XFuture)

Example 17 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class InstallSslCertController method postStartSslInstall.

public XFuture<Redirect> postStartSslInstall(String email) {
    log.info("create key pair");
    KeyPair accountKeyPair = KeyPairUtils.createKeyPair(2048);
    log.info("done creating key pair");
    try (StringWriter writer = new StringWriter()) {
        KeyPairUtils.writeKeyPair(accountKeyPair, writer);
        log.info("done marshalling keypair to string");
        Map<String, String> properties = new HashMap<>();
        properties.put(InstallSslCertPlugin.ACCOUNT_KEYPAIR_KEY, writer.toString());
        properties.put(EMAIL, email);
        return this.storage.save(InstallSslCertPlugin.PLUGIN_PROPERTIES_KEY, properties).thenApply((v) -> {
            log.info("done saving, redirecting to step2");
            return Actions.redirect(InstallSslCertRouteId.STEP2);
        });
    } catch (IOException e) {
        XFuture future = new XFuture();
        future.completeExceptionally(e);
        return future;
    }
}
Also used : KeyPair(java.security.KeyPair) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) XFuture(org.webpieces.util.futures.XFuture) IOException(java.io.IOException)

Example 18 with XFuture

use of org.webpieces.util.futures.XFuture 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 19 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class ParamToObjectTranslatorImpl method createArgsImpl.

protected XFuture<List<Object>> createArgsImpl(Method method, RequestContext ctx, BodyContentBinder binder) {
    RouterRequest req = ctx.getRequest();
    Parameter[] paramMetas = method.getParameters();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    ParamTreeNode paramTree = new ParamTreeNode();
    // For multipart AND for query params such as ?var=xxx&var=yyy&var2=xxx AND for url path params /mypath/{var1}/account/{id}
    // query params first
    Map<String, String> queryParams = translate(req.queryParams);
    treeCreator.createTree(paramTree, queryParams, FromEnum.QUERY_PARAM);
    // next multi-part params
    Map<String, String> multiPartParams = translate(req.multiPartFields);
    treeCreator.createTree(paramTree, multiPartParams, FromEnum.FORM_MULTIPART);
    // lastly path params
    treeCreator.createTree(paramTree, ctx.getPathParams(), FromEnum.URL_PATH);
    List<Object> results = new ArrayList<>();
    XFuture<List<Object>> future = XFuture.completedFuture(results);
    for (int i = 0; i < paramMetas.length; i++) {
        Parameter paramMeta = paramMetas[i];
        Annotation[] annotations = paramAnnotations[i];
        ParamMeta fieldMeta = new ParamMeta(method, paramMeta, annotations);
        String name = fieldMeta.getName();
        ParamNode paramNode = paramTree.get(name);
        XFuture<Object> beanFuture;
        if (binder != null && isManagedBy(binder, fieldMeta)) {
            Object bean = binder.unmarshal(ctx, fieldMeta, req.body.createByteArray());
            beanFuture = XFuture.completedFuture(bean);
        } else {
            beanFuture = translate(req, method, paramNode, fieldMeta, ctx.getValidation());
        }
        future = future.thenCompose(list -> {
            return beanFuture.thenApply(bean -> {
                list.add(bean);
                return list;
            });
        });
    }
    return future;
}
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) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) ParamMeta(org.webpieces.router.api.extensions.ParamMeta) Parameter(java.lang.reflect.Parameter) ArrayList(java.util.ArrayList) List(java.util.List) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 20 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class ParamToObjectTranslatorImpl method createList.

@SuppressWarnings("unchecked")
private XFuture<Object> createList(RouterRequest req, Method method, Meta fieldMeta, Validation validator, List<ParamNode> paramNodes) {
    List<Object> list = new ArrayList<>();
    ParameterizedType type = (ParameterizedType) fieldMeta.getParameterizedType();
    Type[] actualTypeArguments = type.getActualTypeArguments();
    Type type2 = actualTypeArguments[0];
    @SuppressWarnings("rawtypes") GenericMeta genMeta = new GenericMeta((Class) type2);
    XFuture<List<Object>> future = XFuture.completedFuture(list);
    for (ParamNode node : paramNodes) {
        XFuture<Object> fut;
        if (node != null) {
            fut = translate(req, method, node, genMeta, validator);
        } else {
            fut = XFuture.completedFuture(null);
        }
        future = future.thenCompose(myList -> {
            return fut.thenApply(b -> {
                myList.add(b);
                return myList;
            });
        });
    }
    return future.thenApply(l -> (Object) l);
}
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) ArrayList(java.util.ArrayList) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

XFuture (org.webpieces.util.futures.XFuture)71 Test (org.junit.Test)21 StreamWriter (com.webpieces.http2.api.streaming.StreamWriter)20 ByteBuffer (java.nio.ByteBuffer)16 Logger (org.slf4j.Logger)15 LoggerFactory (org.slf4j.LoggerFactory)15 ArrayList (java.util.ArrayList)14 List (java.util.List)13 Map (java.util.Map)12 DataWrapper (org.webpieces.data.api.DataWrapper)12 HttpFullRequest (org.webpieces.httpclient11.api.HttpFullRequest)12 HttpFullResponse (org.webpieces.httpclient11.api.HttpFullResponse)12 NotFoundException (org.webpieces.http.exception.NotFoundException)11 AbstractWebpiecesTest (org.webpieces.webserver.test.AbstractWebpiecesTest)11 ResponseWrapper (org.webpieces.webserver.test.ResponseWrapper)11 Http2Request (com.webpieces.http2.api.dto.highlevel.Http2Request)10 PrivateWebserverForTest (org.webpieces.webserver.PrivateWebserverForTest)10 StreamRef (com.webpieces.http2.api.streaming.StreamRef)9 RequestContext (org.webpieces.ctx.api.RequestContext)9 Http2Response (com.webpieces.http2.api.dto.highlevel.Http2Response)8