Example usage for org.springframework.web.context.request NativeWebRequest getNativeRequest

List of usage examples for org.springframework.web.context.request NativeWebRequest getNativeRequest

Introduction

In this page you can find the example usage for org.springframework.web.context.request NativeWebRequest getNativeRequest.

Prototype

@Nullable
<T> T getNativeRequest(@Nullable Class<T> requiredType);

Source Link

Document

Return the underlying native request object, if available.

Usage

From source file:com.expedia.seiso.web.resolver.PEResourceResolver.java

@Override
public Object resolveArgument(MethodParameter param, ModelAndViewContainer mavContainer,
        NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {

    val nativeRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
    val path = nativeRequest.getRequestURI();

    Class<?> itemClass = null;
    val matcher = new AntPathMatcher();
    if (matcher.match(ITEM_FORMAT, path)) {
        val variables = matcher.extractUriTemplateVariables(ITEM_FORMAT, path);
        itemClass = itemMetaLookup.getItemClass(variables.get("repoKey"));
    } else if (matcher.match(PROPERTY_FORMAT, path)) {
        val variables = matcher.extractUriTemplateVariables(PROPERTY_FORMAT, path);
        val repoKey = variables.get("repoKey");
        val propKey = variables.get("propKey");
        itemClass = findPropertyClass(repoKey, propKey);
    } else if (matcher.match(COLLECTION_ELEMENT_FORMAT, path)) {
        val variables = matcher.extractUriTemplateVariables(COLLECTION_ELEMENT_FORMAT, path);
        val repoKey = variables.get("repoKey");
        val propKey = variables.get("propKey");
        itemClass = findPropertyClass(repoKey, propKey);
    } else {//from   w w  w  .  ja  v a2  s.co  m
        throw new RuntimeException("No resolver for requestUri=" + path);
    }

    val pEntity = repositories.getPersistentEntity(itemClass);
    val item = toItem(itemClass, nativeRequest);
    return new PEResource(pEntity, item);

}

From source file:cherry.example.web.basic.ex90.BasicEx90ControllerImpl.java

@Override
public ModelAndView execute(BasicEx90Form form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//www  .  j  a  v  a 2s .c o  m

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    BasicEx90ResultDto result = service.load(form);

    return withoutView().addObject(result).build();
}

From source file:com.eryansky.modules.sys.web.ProxyController.java

/**
 * ?/*from w w w.  j av a 2s  .c  o  m*/
 * @param nativeWebRequest
 * @throws IOException
 */
@RequestMapping(value = { "**" })
public ModelAndView proxy(NativeWebRequest nativeWebRequest) throws Exception {
    CustomHttpServletRequestWrapper request = nativeWebRequest
            .getNativeRequest(CustomHttpServletRequestWrapper.class);
    String requestUrl = request.getRequestURI();

    String contentUrl = StringUtils.substringAfterLast(requestUrl, AppConstants.getAdminPath() + "/proxy/");
    String param = AppUtils.joinParasWithEncodedValue(WebUtils.getParametersStartingWith(request, null));//?
    String url = contentUrl + "?" + param;
    logger.debug("proxy url{}", url);
    HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
    HttpCompoents httpCompoents = HttpCompoents.getInstance();//?? ?Cookie?
    Response remoteResponse = httpCompoents.getResponse(url);
    try {
        // 
        if (remoteResponse == null) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return null;
        }
        HttpResponse httpResponse = remoteResponse.returnResponse();
        HttpEntity entity = httpResponse.getEntity();
        // 
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            logger.error(httpResponse.getStatusLine().getStatusCode() + "");
            logger.error(EntityUtils.toString(entity, "utf-8"));
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return null;
        }

        // Header
        response.setContentType(entity.getContentType().getValue());
        if (entity.getContentLength() > 0) {
            response.setContentLength((int) entity.getContentLength());
        }
        // 
        InputStream input = entity.getContent();
        OutputStream output = response.getOutputStream();
        // byte?InputStreamOutputStream, ?4k.
        IOUtils.copy(input, output);
        output.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
    }
    return null;
}

From source file:com.eryansky.modules.sys.web.ProxyController.java

/**
 * ?//from w ww  . j  a  v a 2  s  .  co  m
 * @param nativeWebRequest
 * @param contentUrl URL
 * @throws IOException
 */
@RequestMapping(value = { "" })
public void getProxy(NativeWebRequest nativeWebRequest, String contentUrl) throws Exception {

    CustomHttpServletRequestWrapper request = nativeWebRequest
            .getNativeRequest(CustomHttpServletRequestWrapper.class);
    HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
    HttpCompoents httpCompoents = HttpCompoents.getInstance();//?? ?Cookie?
    String param = AppUtils.joinParasWithEncodedValue(WebUtils.getParametersStartingWith(request, null));//?
    String url = contentUrl + "?" + param;
    logger.debug("proxy url{}", url);
    Response remoteResponse = httpCompoents.getResponse(url);
    try {
        // 
        if (remoteResponse == null) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return;
        }
        HttpResponse httpResponse = remoteResponse.returnResponse();
        HttpEntity entity = httpResponse.getEntity();
        // 
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            logger.error(httpResponse.getStatusLine().getStatusCode() + "");
            logger.error(EntityUtils.toString(entity, "utf-8"));
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return;
        }

        // Header
        response.setContentType(entity.getContentType().getValue());
        if (entity.getContentLength() > 0) {
            response.setContentLength((int) entity.getContentLength());
        }
        // 
        InputStream input = entity.getContent();
        OutputStream output = response.getOutputStream();
        // byte?InputStreamOutputStream, ?4k.
        IOUtils.copy(input, output);
        output.flush();
    } finally {
    }
}

From source file:com.sishuok.bigpipe.handler.BigpipeTaskReturnValueHandler.java

@Override
public void handleReturnValue(final Object returnValue, final MethodParameter returnType,
        final ModelAndViewContainer mavContainer, final NativeWebRequest webRequest) throws Exception {

    final BigPipeTask bigPipeTask = (BigPipeTask) returnValue;

    final HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    final HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

    final DeferredResult<Void> deferredResult = new DeferredResult<Void>();

    mavContainer.setRequestHandled(true);

    WebAsyncUtils.getAsyncManager(request).startDeferredResultProcessing(deferredResult, mavContainer);

    final BigPipeContext context = new BigPipeContext(request.getContextPath(), bigPipeTask.getModel());

    //?pagelet? ?
    final String framePageletName = bigPipeTask.getFramePageletName();
    final Pagelet framePagelet = pageletFinder.find(framePageletName);
    Assert.notNull(framePagelet, framePageletName + " pagelet not exists");

    final BigPipeContext frameContext = context.copy();
    final PageletResult framePageletResult = framePagelet.run(frameContext, response);
    final PageletView framePageletView = pageletViewResolver.resolve(framePageletResult);
    framePageletView.render(frameContext, response);

    final AtomicInteger counter = new AtomicInteger(bigPipeTask.getPageletNames().size());
    //?Npagelet?/* ww w. j a va2  s .co m*/
    for (String otherPageletName : bigPipeTask.getPageletNames()) {
        final Pagelet pagelet = pageletFinder.find(otherPageletName);
        Assert.notNull(pagelet, otherPageletName + " pagelet not exists");

        //???
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final BigPipeContext pageletContext = context.copy();
                    final PageletResult pageletResult = pagelet.run(pageletContext, response);
                    final PageletView pageletView = pageletViewResolver.resolve(pageletResult);
                    pageletView.render(pageletContext, response);
                } catch (Exception e) {
                    e.printStackTrace();
                    //
                }
                if (counter.decrementAndGet() <= 0) {
                    deferredResult.setResult(null);
                }
            }
        });
    }
}

From source file:cherry.example.web.basic.ex10.BasicEx10ControllerImpl.java

@Override
public ModelAndView execute(BasicEx10Form form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//w w  w .j av  a2 s.co m

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    Long id = service.create(form);
    checkState(id != null, "failed to create: form=%s", form);

    return redirect(redirectOnExecute(id.longValue())).build();
}

From source file:cherry.sqlman.tool.password.PasswordChangeControllerImpl.java

@Override
public ModelAndView update(PasswordChangeForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request, RedirectAttributes redirAttr) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//w w w.j  a  v a2  s .  c  om

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    if (!passwordChangeService.updatePassword(auth.getName(), form.getPassword(), form.getLockVersion())) {
        LogicalErrorUtil.rejectOnOptimisticLockError(binding);
        return withViewname(viewnameOfStart).build();
    }

    redirAttr.addFlashAttribute(FLASH_UPDATED, Boolean.TRUE);

    return redirect(redirectOnUpdate()).build();
}

From source file:cherry.example.web.basic.ex10.BasicEx11ControllerImpl.java

@Override
public ModelAndView execute(long id, BasicEx10Form form, BindingResult binding, Authentication auth,
        Locale locale, SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(id, form, binding)) {
        return withViewname(viewnameOfStart).build();
    }/* w w w.  ja va  2s .c om*/

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    long count = service.update(id, form);
    checkState(count == 1L, "failed to update: id=%s, form=%s", id, form);

    return redirect(redirectOnExecute(id)).build();
}

From source file:cherry.example.web.basic.ex30.BasicEx31ControllerImpl.java

@Override
public ModelAndView execute(long id, BasicEx31Form form, BindingResult binding, Authentication auth,
        Locale locale, SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(id, form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//from ww w .j  a  va2s  .  c om

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    long count = service.update(id, form);
    checkState(count == 1L, "failed to update: id=%s, form=%s", id, form);

    return redirect(redirectOnExecute(id)).build();
}

From source file:cherry.example.web.applied.ex10.AppliedEx10ControllerImpl.java

@Override
public ModelAndView execute(AppliedEx10Form form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, NativeWebRequest request) {

    if (hasErrors(form, binding)) {
        return withViewname(viewnameOfStart).build();
    }//from  www.  j  av a2  s  .c  o  m

    if (!oneTimeTokenValidator.isValid(request.getNativeRequest(HttpServletRequest.class))) {
        LogicalErrorUtil.rejectOnOneTimeTokenError(binding);
        return withViewname(viewnameOfStart).build();
    }

    Long id = service.create(form);
    checkState(id != null, "failed to create: form=%s", form);

    return redirect(redirectOnExecute(id.longValue())).build();
}