Search in sources :

Example 21 with RequestContext

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

the class Actions method redirectFlashAll.

public static Redirect redirectFlashAll(RouteId addRoute, RouteId editRoute, FlashAndRedirect redirect) {
    RequestContext ctx = redirect.getContext();
    ctx.getFlash().setMessage(redirect.getGlobalMessage());
    if (redirect.getIdValue() == null) {
        // If id is null, this is an add(not an edit) so redirect back to add route
        return redirectFlashAllSecure(addRoute, ctx, redirect.getPageArgs(), redirect.getSecureFields());
    } else {
        // If id is not null, this is an edit(not an add) so redirect back to edit route
        String[] args = redirect.getPageArgs();
        Object[] allArgs = new Object[args.length + 2];
        allArgs[0] = redirect.getIdField();
        allArgs[1] = redirect.getIdValue();
        System.arraycopy(args, 0, allArgs, 2, args.length);
        return redirectFlashAllSecure(editRoute, ctx, allArgs, redirect.getSecureFields());
    }
}
Also used : RequestContext(org.webpieces.ctx.api.RequestContext)

Example 22 with RequestContext

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

the class PropertiesController method postBean.

public Redirect postBean(String category, String name, boolean thisServerOnly) throws InterruptedException, ExecutionException {
    Map<String, List<String>> multiPartFields = Current.getContext().getRequest().multiPartFields;
    BeanMeta meta = beanMetaData.getBeanMeta(category, name);
    List<PropertyInfo> props = meta.getProperties();
    // first validate the strings are of the right type for each return type and gather error messages up
    // 1. lookup converter.  if not exist, add validation error
    // 2. convert and catch conversion exception if needed and add validation error
    // 3. store all values while doing 1 and 2.  apply in next loop below
    List<ValueInfo> values = new ArrayList<>();
    for (PropertyInfo info : props) {
        if (info.isReadOnly())
            continue;
        List<String> valueList = multiPartFields.get(info.getName());
        String valueAsString = valueList.get(0);
        Class<?> returnType = info.getGetter().getReturnType();
        ObjectStringConverter<?> converter = invoker.fetchConverter(info);
        try {
            Object objectValue = converter.stringToObject(valueAsString);
            values.add(new ValueInfo(info, objectValue, valueAsString));
        } catch (Exception e) {
            Current.validation().addError(info.getName(), "Converter=" + converter.getClass().getName() + " cannot convert String to " + returnType.getName());
        }
    }
    RequestContext ctx = Current.getContext();
    if (Current.validation().hasErrors()) {
        ctx.moveFormParamsToFlash(new HashSet<>());
        ctx.getFlash().keep(true);
        ctx.getValidation().keep(true);
        return Actions.redirect(PropertiesRouteId.BEAN_ROUTE, "category", category, "name", name);
    }
    ctx.getValidation().keep(false);
    // KISS: not doing rollback code so if one prop fails to set, it does not save to database
    // and is partially applied.  (ie. keep your setter code simple!!).
    // ALSO, we are taking an apply all properties type of approach to keep it simple for now.  in the future,
    // we could read all props and only call setXXX on changes (in case they wrote extra not idempotent type code so
    // that code does not run on accident)
    Map<String, String> propertiesToSaveToDatabase = new HashMap<>();
    for (ValueInfo value : values) {
        updateProperty(value.getInfo(), value.getValue());
        String key = KeyUtil.formKey(category, name, value.getInfo().getName());
        propertiesToSaveToDatabase.put(key, value.getValueAsString());
    }
    if (thisServerOnly) {
        Current.flash().setMessage("Modified Bean '" + name + ".class' ONLY on this server in-memory.  (Changes not applied to database for restarts)");
        Current.flash().keep();
    } else {
        XFuture<Void> future = storage.save(KeyUtil.PLUGIN_PROPERTIES_KEY, propertiesToSaveToDatabase);
        // synchronously wait in case it fails so user is told it failed to save to database
        future.get();
        Current.flash().setMessage("Modified Bean '" + name + ".class' and persisted to Database");
        Current.flash().keep();
    }
    return Actions.redirect(PropertiesRouteId.MAIN_PROPERTIES);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BeanMeta(org.webpieces.plugin.secure.properties.beans.BeanMeta) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) ArrayList(java.util.ArrayList) List(java.util.List) RequestContext(org.webpieces.ctx.api.RequestContext) PropertyInfo(org.webpieces.plugin.secure.properties.beans.PropertyInfo)

Example 23 with RequestContext

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

the class RecordingFilter method filter.

@Override
public XFuture<Action> filter(MethodMeta meta, Service<MethodMeta, Action> nextFilter) {
    RequestContext context = Current.getContext();
    List<RouterHeader> routerHeaders = context.getRequest().getHeaders().get(MicroSvcHeader.RECORDING.getHeaderName());
    if (routerHeaders == null)
        return nextFilter.invoke(meta);
    Map<String, Object> fullRequestContext = Context.copyContext();
    // let the recording begin...
    Context.put(TestCaseRecorder.RECORDER_KEY, new TestCaseRecorderImpl(Current.getContext().getRequest().originalRequest, meta, fullRequestContext));
    return nextFilter.invoke(meta).thenApply((resp) -> writeOutTestCase(resp));
}
Also used : TestCaseRecorderImpl(org.webpieces.microsvc.server.impl.TestCaseRecorderImpl) RequestContext(org.webpieces.ctx.api.RequestContext) RouterHeader(org.webpieces.ctx.api.RouterHeader)

Example 24 with RequestContext

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

the class JsonController method myStream.

// Method signature cannot have RequestContext since in microservices, we implement an api as the server
// AND a client implements the same api AND client does not have a RequestContext!!
@Override
public StreamRef myStream(ResponseStreamHandle handle2) {
    RouterStreamHandle handle = (RouterStreamHandle) handle2;
    RequestContext requestCtx = Current.getContext();
    Http2Response response = handle.createBaseResponse(requestCtx.getRequest().originalRequest, "text/plain", 200, "Ok");
    response.setEndOfStream(false);
    XFuture<StreamWriter> responseWriter = handle.process(response);
    return new RequestStreamEchoWriter(requestCtx, handle, responseWriter);
}
Also used : RouterStreamHandle(org.webpieces.router.api.RouterStreamHandle) Http2Response(com.webpieces.http2.api.dto.highlevel.Http2Response) StreamWriter(com.webpieces.http2.api.streaming.StreamWriter) RequestContext(org.webpieces.ctx.api.RequestContext)

Example 25 with RequestContext

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

the class ReverseRoutes method createUrl.

private String createUrl(ReversableRouter routeMeta, String urlPath) {
    RequestContext ctx = Current.getContext();
    RouterRequest request = ctx.getRequest();
    boolean isBoth = routeMeta.getMatchInfo().getExposedPorts() == Port.BOTH;
    // 2. OR if request is https, we can also just use the relative path since it will stay in https
    if (isBoth || request.isHttps)
        return urlPath;
    // else request is HTTP and route to go to is HTTPS so we have to do more work
    // we are rendering an http page with a link to https so need to do special magic
    String domain = request.domain;
    int httpsPort = redirectFormation.calculateHttpsPort(request);
    return "https://" + domain + ":" + httpsPort + urlPath;
}
Also used : RequestContext(org.webpieces.ctx.api.RequestContext) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Aggregations

RequestContext (org.webpieces.ctx.api.RequestContext)25 RouterRequest (org.webpieces.ctx.api.RouterRequest)8 LoadedController (org.webpieces.router.impl.loader.LoadedController)7 XFuture (org.webpieces.util.futures.XFuture)6 StreamWriter (com.webpieces.http2.api.streaming.StreamWriter)5 List (java.util.List)5 ProxyStreamHandle (org.webpieces.router.impl.proxyout.ProxyStreamHandle)5 Method (java.lang.reflect.Method)4 Map (java.util.Map)4 Function (java.util.function.Function)4 NotFoundException (org.webpieces.http.exception.NotFoundException)4 ArrayList (java.util.ArrayList)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 HttpMethod (org.webpieces.ctx.api.HttpMethod)3 RenderResponse (org.webpieces.router.impl.dto.RenderResponse)3 View (org.webpieces.router.impl.dto.View)3 RouterStreamRef (org.webpieces.router.impl.routeinvoker.RouterStreamRef)3 FutureHelper (org.webpieces.util.futures.FutureHelper)3 Http2Response (com.webpieces.http2.api.dto.highlevel.Http2Response)2