Search in sources :

Example 11 with RouterRequest

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

the class TestSimpleRoutes method testBasicRoute.

@Test
public void testBasicRoute() {
    RouterRequest req = createHttpRequest(HttpMethod.GET, "/something");
    MockResponseStream mockResponseStream = new MockResponseStream();
    Current.setContext(new RequestContext(new ValidationImpl(null), new FlashImpl(null), new SessionImpl(null), req));
    server.incomingCompleteRequest(req, mockResponseStream);
    List<RedirectResponse> responses = mockResponseStream.getSendRedirectCalledList();
    Assert.assertEquals(1, responses.size());
    RedirectResponse response = responses.get(0);
    Assert.assertEquals(req.domain, response.domain);
    Assert.assertFalse(response.isHttps);
    Assert.assertEquals("/something", response.redirectToPath);
}
Also used : RedirectResponse(org.webpieces.router.api.dto.RedirectResponse) RequestContext(org.webpieces.ctx.api.RequestContext) FlashImpl(org.webpieces.router.impl.ctx.FlashImpl) SessionImpl(org.webpieces.router.impl.ctx.SessionImpl) RouterRequest(org.webpieces.ctx.api.RouterRequest) MockResponseStream(org.webpieces.router.api.mocks.MockResponseStream) ValidationImpl(org.webpieces.router.impl.ctx.ValidationImpl) Test(org.junit.Test)

Example 12 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest 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 13 with RouterRequest

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

the class ParamToObjectTranslatorImpl method createArgsImpl.

protected 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> result = new ArrayList<>();
    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);
        if (binder != null && isManagedBy(binder, fieldMeta)) {
            Object bean = binder.unmarshal(fieldMeta.getFieldClass(), req.body.createByteArray());
            result.add(bean);
        } else {
            Object arg = translate(req, method, paramNode, fieldMeta, ctx.getValidation());
            result.add(arg);
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) Parameter(java.lang.reflect.Parameter) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 14 with RouterRequest

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

the class ErrorTest method testNoMethod.

@Test
public void testNoMethod() {
    log.info("starting");
    String moduleFileContents = NoMethodRouterModules.class.getName();
    RouterService server = ErrorCommonTest.createServer(false, moduleFileContents);
    //this should definitely not throw since we lazy load everything in dev...
    server.start();
    RouterRequest req = RequestCreation.createHttpRequest(HttpMethod.GET, "/something");
    MockResponseStream mockResponseStream = new MockResponseStream();
    server.incomingCompleteRequest(req, mockResponseStream);
    List<RenderResponse> renders = mockResponseStream.getSendRenderHtmlList();
    Assert.assertEquals(1, renders.size());
    RenderResponse renderResponse = renders.get(0);
    Assert.assertEquals(RouteType.INTERNAL_SERVER_ERROR, renderResponse.routeType);
}
Also used : RouterService(org.webpieces.router.api.RouterService) RenderResponse(org.webpieces.router.api.dto.RenderResponse) RouterRequest(org.webpieces.ctx.api.RouterRequest) MockResponseStream(org.webpieces.router.api.mocks.MockResponseStream) Test(org.junit.Test) ErrorCommonTest(org.webpieces.router.api.error.ErrorCommonTest)

Example 15 with RouterRequest

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

the class TestProdRouter method testAsyncRouteAndMocking.

/**
	 * This test won't work in DevRoute right now as we need to do the following
	 * 1. create CompileOnDemand very early on 
	 * 2. do a Thread.current().setContextClassLoader(compileOnDemand.getLatestClassloader())
	 * 
	 * and this all needs to be done BEFORE TestModule is created and more importantly before
	 * the bind(SomeService.class) as SomeService will be loaded from one classloader and then
	 * when DEVrouter creates the controller, the compileOnDemand classloader is used resulting
	 * in a mismatch.
	 */
@Test
public void testAsyncRouteAndMocking() {
    RouterRequest req = createHttpRequest(HttpMethod.GET, "/async");
    //setup returning a response
    CompletableFuture<Integer> future = new CompletableFuture<Integer>();
    overrides.mockService.addToReturn(future);
    MockResponseStream mockResponseStream = new MockResponseStream();
    server.incomingCompleteRequest(req, mockResponseStream);
    //no response yet...
    List<RedirectResponse> responses = mockResponseStream.getSendRedirectCalledList();
    Assert.assertEquals(0, responses.size());
    int id = 78888;
    future.complete(id);
    responses = mockResponseStream.getSendRedirectCalledList();
    Assert.assertEquals(1, responses.size());
    RedirectResponse response = responses.get(0);
    Assert.assertEquals(req.domain, response.domain);
    Assert.assertFalse(response.isHttps);
    Assert.assertEquals("/meeting/" + id, response.redirectToPath);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) RedirectResponse(org.webpieces.router.api.dto.RedirectResponse) RouterRequest(org.webpieces.ctx.api.RouterRequest) MockResponseStream(org.webpieces.router.api.mocks.MockResponseStream) Test(org.junit.Test)

Aggregations

RouterRequest (org.webpieces.ctx.api.RouterRequest)23 Test (org.junit.Test)8 RequestContext (org.webpieces.ctx.api.RequestContext)8 MockResponseStream (org.webpieces.router.api.mocks.MockResponseStream)8 RouterService (org.webpieces.router.api.RouterService)5 RedirectResponse (org.webpieces.router.api.dto.RedirectResponse)5 FlashImpl (org.webpieces.router.impl.ctx.FlashImpl)5 SessionImpl (org.webpieces.router.impl.ctx.SessionImpl)5 ValidationImpl (org.webpieces.router.impl.ctx.ValidationImpl)5 HttpMethod (org.webpieces.ctx.api.HttpMethod)4 Method (java.lang.reflect.Method)3 Annotation (java.lang.annotation.Annotation)2 Parameter (java.lang.reflect.Parameter)2 ArrayList (java.util.ArrayList)2 RenderResponse (org.webpieces.router.api.dto.RenderResponse)2 ErrorCommonTest (org.webpieces.router.api.error.ErrorCommonTest)2 IllegalReturnValueException (org.webpieces.router.api.exceptions.IllegalReturnValueException)2 Http2Header (com.webpieces.http2parser.api.dto.lib.Http2Header)1 Field (java.lang.reflect.Field)1 ParameterizedType (java.lang.reflect.ParameterizedType)1