org.springframework.web.context.request.WebRequest Java Examples
The following examples show how to use
org.springframework.web.context.request.WebRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebApplicationContextUtils.java From java-technology-stack with MIT License | 6 votes |
/** * Register web-specific scopes ("request", "session", "globalSession", "application") * with the given BeanFactory, as used by the WebApplicationContext. * @param beanFactory the BeanFactory to configure * @param sc the ServletContext that we're running within */ public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, @Nullable ServletContext sc) { beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope()); if (sc != null) { ServletContextScope appScope = new ServletContextScope(sc); beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); // Register as ServletContext attribute, for ContextCleanupListener to detect it. sc.setAttribute(ServletContextScope.class.getName(), appScope); } beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory()); beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); if (jsfPresent) { FacesDependencyRegistrar.registerFacesDependencies(beanFactory); } }
Example #2
Source File: FacultyRegistrationController.java From zhcet-web with Apache License 2.0 | 6 votes |
@PostMapping public String uploadFacultyFile(RedirectAttributes attributes, @RequestParam MultipartFile file, HttpSession session, WebRequest webRequest) throws IOException { try { UploadResult<FacultyUpload> result = facultyUploadService.handleUpload(file); if (!result.getErrors().isEmpty()) { webRequest.removeAttribute(KEY_FACULTY_REGISTRATION, RequestAttributes.SCOPE_SESSION); attributes.addFlashAttribute("faculty_errors", result.getErrors()); } else { attributes.addFlashAttribute("faculty_success", true); Confirmation<FacultyMember> confirmation = facultyUploadService.confirmUpload(result); session.setAttribute(KEY_FACULTY_REGISTRATION, confirmation); } } catch (IOException ioe) { log.error("Error registering faculty", ioe); } return "redirect:/admin/dean"; }
Example #3
Source File: OpenPersistenceManagerInViewInterceptor.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public void preHandle(WebRequest request) throws DataAccessException { if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) { // Do not modify the PersistenceManager: just mark the request accordingly. String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor"); PersistenceManager pm = PersistenceManagerFactoryUtils.getPersistenceManager(getPersistenceManagerFactory(), true); TransactionSynchronizationManager.bindResource( getPersistenceManagerFactory(), new PersistenceManagerHolder(pm)); } }
Example #4
Source File: ResponseEntityExceptionHandler.java From spring-analysis-note with MIT License | 6 votes |
/** * Customize the response for AsyncRequestTimeoutException. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception * @param headers the headers to be written to the response * @param status the selected response status * @param webRequest the current request * @return a {@code ResponseEntity} instance * @since 4.2.8 */ @Nullable protected ResponseEntity<Object> handleAsyncRequestTimeoutException( AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) { if (webRequest instanceof ServletWebRequest) { ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest; HttpServletResponse response = servletWebRequest.getResponse(); if (response != null && response.isCommitted()) { if (logger.isWarnEnabled()) { logger.warn("Async request timed out"); } return null; } } return handleExceptionInternal(ex, null, headers, status, webRequest); }
Example #5
Source File: GrailsOpenSessionInViewInterceptor.java From gorm-hibernate5 with Apache License 2.0 | 6 votes |
@Override public void postHandle(WebRequest request, ModelMap model) throws DataAccessException { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.getResource(getSessionFactory()); Session session = sessionHolder != null ? sessionHolder.getSession() : null; try { super.postHandle(request, model); FlushMode flushMode = session != null ? session.getHibernateFlushMode() : null; boolean isNotManual = flushMode != FlushMode.MANUAL && flushMode != FlushMode.COMMIT; if (session != null && isNotManual) { if(logger.isDebugEnabled()) { logger.debug("Eagerly flushing Hibernate session"); } session.flush(); } } finally { if (session != null) { session.setHibernateFlushMode(FlushMode.MANUAL); } } }
Example #6
Source File: RestExceptionHandler.java From jakduk-api with MIT License | 6 votes |
/** * RequestBody에서 request 값들을 객체화 실패했을때 */ @Override protected ResponseEntity<Object> handleHttpMessageNotReadable( HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ServiceError serviceError = ServiceError.FORM_VALIDATION_FAILED; RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError); try { log.warn(ObjectMapperUtils.writeValueAsString(restErrorResponse), ex); } catch (JsonProcessingException ignore) { log.warn(ex.getLocalizedMessage(), ex); } return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus())); }
Example #7
Source File: AbstractRestExceptionHandler.java From kaif with Apache License 2.0 | 6 votes |
protected final void logException(final Exception ex, final E errorResponse, final WebRequest request) { final StringBuilder sb = new StringBuilder(); sb.append(errorResponse); sb.append("\n"); sb.append(request.getDescription(true)); sb.append("\nparameters -- "); for (final Iterator<String> iter = request.getParameterNames(); iter.hasNext(); ) { final String name = iter.next(); sb.append(name); sb.append(":"); final String[] values = request.getParameterValues(name); if (values == null) { sb.append("null"); } else if (values.length == 0) { sb.append(""); } else if (values.length == 1) { sb.append(values[0]); } else { sb.append(Arrays.toString(values)); } sb.append(" "); } logger.error(sb.toString(), ex); }
Example #8
Source File: RestExceptionHandler.java From java-starthere with MIT License | 6 votes |
@Override protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ErrorDetail errorDetail = new ErrorDetail(); errorDetail.setTimestamp(new Date().getTime()); errorDetail.setStatus(HttpStatus.NOT_FOUND.value()); errorDetail.setTitle(ex.getRequestURL()); errorDetail.setDetail(request.getDescription(true)); errorDetail.setDeveloperMessage("Rest Handler Not Found (check for valid URI)"); return new ResponseEntity<>(errorDetail, headers, HttpStatus.NOT_FOUND); }
Example #9
Source File: RestExceptionHandler.java From java-starthere with MIT License | 6 votes |
@Override protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ErrorDetail errorDetail = new ErrorDetail(); errorDetail.setTimestamp(new Date().getTime()); errorDetail.setStatus(HttpStatus.BAD_REQUEST.value()); errorDetail.setTitle(ex.getVariableName() + " Missing Path Variable"); errorDetail.setDetail(ex.getMessage()); errorDetail.setDeveloperMessage(ex.getClass() .getName()); return new ResponseEntity<>(errorDetail, null, HttpStatus.BAD_REQUEST); }
Example #10
Source File: ApplicationConfigEvernoteBeanTest.java From evernote-rest-webapp with Apache License 2.0 | 6 votes |
@Test public void testWithAccessTokenOnly() { Application application = new Application(); application.evernotePropertiesConfiguration = new Application.EvernotePropertiesConfiguration(); WebRequest request = mock(WebRequest.class); when(request.getHeader("evernote-rest-accesstoken")).thenReturn("ACCESS_TOKEN"); Evernote evernote = application.evernote(request); assertThat(evernote, is(notNullValue())); ClientFactory clientFactory = evernote.clientFactory(); assertThat(clientFactory, is(notNullValue())); EvernoteAuth evernoteAuth = retrieveEvernoteAuth(clientFactory); assertThat(evernoteAuth, is(notNullValue())); assertThat(evernoteAuth.getToken(), is("ACCESS_TOKEN")); assertThat(evernoteAuth.getNoteStoreUrl(), is(nullValue())); assertThat(evernoteAuth.getUserId(), is(0)); // default assertThat(evernoteAuth.getWebApiUrlPrefix(), is(nullValue())); }
Example #11
Source File: ServletRequestMethodArgumentResolver.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public boolean supportsParameter(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); return (WebRequest.class.isAssignableFrom(paramType) || ServletRequest.class.isAssignableFrom(paramType) || MultipartRequest.class.isAssignableFrom(paramType) || HttpSession.class.isAssignableFrom(paramType) || Principal.class.isAssignableFrom(paramType) || InputStream.class.isAssignableFrom(paramType) || Reader.class.isAssignableFrom(paramType) || HttpMethod.class == paramType || Locale.class == paramType || TimeZone.class == paramType || "java.time.ZoneId".equals(paramType.getName())); }
Example #12
Source File: OpenSessionInViewInterceptor.java From java-technology-stack with MIT License | 5 votes |
/** * Open a new Hibernate {@code Session} according and bind it to the thread via the * {@link TransactionSynchronizationManager}. */ @Override public void preHandle(WebRequest request) throws DataAccessException { String key = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) { return; } if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) { // Do not modify the Session: just mark the request accordingly. Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor"); Session session = openSession(); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder); AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder); asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor); asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor); } }
Example #13
Source File: RestExceptionHandler.java From POC with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * * Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is invalid * as well. */ @Override protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { final StringBuilder builder = new StringBuilder(); builder.append(ex.getContentType()); builder.append(" media type is not supported. Supported media types are "); ex.getSupportedMediaTypes().forEach(mediaType -> builder.append(mediaType).append(", ")); return buildResponseEntity( new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex)); }
Example #14
Source File: RestExceptionHandler.java From spring-boot-exception-handling with MIT License | 5 votes |
/** * Handle MethodArgumentNotValidException. Triggered when an object fails @Valid validation. * * @param ex the MethodArgumentNotValidException that is thrown when @Valid validation fails * @param headers HttpHeaders * @param status HttpStatus * @param request WebRequest * @return the ApiError object */ @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ApiError apiError = new ApiError(BAD_REQUEST); apiError.setMessage("Validation error"); apiError.addValidationErrors(ex.getBindingResult().getFieldErrors()); apiError.addValidationError(ex.getBindingResult().getGlobalErrors()); return buildResponseEntity(apiError); }
Example #15
Source File: OpenSessionInViewInterceptor.java From spring-analysis-note with MIT License | 5 votes |
private boolean decrementParticipateCount(WebRequest request) { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); if (count == null) { return false; } // Do not modify the Session: just clear the marker. if (count > 1) { request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST); } else { request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); } return true; }
Example #16
Source File: CustomErrorAttributes.java From egeria with Apache License 2.0 | 5 votes |
/** * * @param webRequest initial request * @param errorCode * @return error attributes to return to client */ public Map<String, Object> getErrorAttributes(WebRequest webRequest, UserInterfaceErrorCodes errorCode) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, false); errorAttributes.put("message", errorCode.getErrorMessage()); errorAttributes.put("status", errorCode.getHttpErrorCode()); errorAttributes.put("userAction", errorCode.getUserAction()); errorAttributes.put("systemAction", errorCode.getSystemAction()); errorAttributes.put("errorId", errorCode.getErrorMessageId()); return errorAttributes; }
Example #17
Source File: ServletIT.java From errors-spring-boot-starter with Apache License 2.0 | 5 votes |
@Test public void controllerAdvice_HttpErrorShouldContainAppropriateDetails() throws Exception { ArgumentCaptor<HttpError> captor = ArgumentCaptor.forClass(HttpError.class); mvc.perform(get("/test//type-mismatch").param("number", "not a number")) .andExpect(status().isBadRequest()); verify(processor).process(captor.capture()); HttpError value = captor.getValue(); assertThat(value.getRequest()).isNotNull(); assertThat(value.getRequest()).isInstanceOf(WebRequest.class); assertThat(value.getOriginalException()).isNotNull(); assertThat(value.getRefinedException()).isNotNull(); }
Example #18
Source File: OpenSessionInViewInterceptor.java From lams with GNU General Public License v2.0 | 5 votes |
private boolean decrementParticipateCount(WebRequest request) { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); if (count == null) { return false; } // Do not modify the Session: just clear the marker. if (count > 1) { request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST); } else { request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); } return true; }
Example #19
Source File: OpenEntityManagerInViewInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException { if (!decrementParticipateCount(request)) { EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor"); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } }
Example #20
Source File: RestExceptionHandler.java From angularjs-springmvc-sample-boot with Apache License 2.0 | 5 votes |
@ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception..."); } return new ResponseEntity<>(new ResponseMessage(ResponseMessage.Type.danger, ex.getMessage()), HttpStatus.BAD_REQUEST); }
Example #21
Source File: ExceptionHandlerController.java From egeria with Apache License 2.0 | 5 votes |
/** * * @param ex - raised exception to be handled * @param request - the initial web request * @return the entity containing the response exception */ @ExceptionHandler(value = {InvalidParameterException.class, PropertyServerException.class}) protected ResponseEntity<Object> handleAssetCatalogException(AssetCatalogException ex, WebRequest request) { LOG.error(ex.getMessage(), ex); Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(request, UserInterfaceErrorCodes.INVALID_REQUEST_FOR_ASSET_CATALOG); return handleExceptionInternal(ex, errorAttributes, new HttpHeaders(), UserInterfaceErrorCodes.INVALID_REQUEST_FOR_ASSET_CATALOG.getHttpErrorCode(), request); }
Example #22
Source File: ResponseEntityExceptionHandler.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Customize the response for HttpRequestMethodNotSupportedException. * <p>This method logs a warning, sets the "Allow" header, and delegates to * {@link #handleExceptionInternal}. * @param ex the exception * @param headers the headers to be written to the response * @param status the selected response status * @param request the current request * @return a {@code ResponseEntity} instance */ protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { pageNotFoundLogger.warn(ex.getMessage()); Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods(); if (!CollectionUtils.isEmpty(supportedMethods)) { headers.setAllow(supportedMethods); } return handleExceptionInternal(ex, null, headers, status, request); }
Example #23
Source File: V1ExceptionHandler.java From kaif with Apache License 2.0 | 5 votes |
@ExceptionHandler(MissingBearerTokenException.class) @ResponseBody public ResponseEntity<V1ErrorResponse> handleMissingBearerTokenException(final MissingBearerTokenException ex, final WebRequest request) { final HttpStatus status = HttpStatus.UNAUTHORIZED; final V1ErrorResponse errorResponse = createErrorResponse(status, "missing Bearer token in Authorization header"); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add(Oauths.HeaderType.WWW_AUTHENTICATE, realm()); return new ResponseEntity<>(errorResponse, responseHeaders, status); }
Example #24
Source File: OpenSessionInViewInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Open a new Hibernate {@code Session} according and bind it to the thread via the * {@link TransactionSynchronizationManager}. */ @Override public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { return; } } if (TransactionSynchronizationManager.hasResource(getSessionFactory())) { // Do not modify the Session: just mark the request accordingly. Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor"); Session session = openSession(); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } }
Example #25
Source File: GlobalExceptionHandler.java From NFVO with Apache License 2.0 | 5 votes |
@ExceptionHandler({AccessDeniedException.class}) protected ResponseEntity<Object> handleAccessDeniedException(Exception e, WebRequest request) { if (log.isDebugEnabled()) log.error("Exception was thrown -> Retrun message: " + e.getMessage(), e); else log.error("Exception was thrown -> Retrun message: " + e.getMessage()); ExceptionResource exceptionResource = new ExceptionResource("Access denied", e.getMessage()); return handleExceptionInternal( e, exceptionResource, new HttpHeaders(), HttpStatus.FORBIDDEN, request); }
Example #26
Source File: DefaultSessionAttributeStore.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void storeAttribute(WebRequest request, String attributeName, Object attributeValue) { Assert.notNull(request, "WebRequest must not be null"); Assert.notNull(attributeName, "Attribute name must not be null"); Assert.notNull(attributeValue, "Attribute value must not be null"); String storeAttributeName = getAttributeNameInSession(request, attributeName); request.setAttribute(storeAttributeName, attributeValue, WebRequest.SCOPE_SESSION); }
Example #27
Source File: AbstractRestExceptionHandler.java From kaif with Apache License 2.0 | 5 votes |
@ExceptionHandler({ QueryTimeoutException.class }) @ResponseBody public ResponseEntity<E> handleQueryTimeoutException(final QueryTimeoutException ex, final WebRequest request) { final HttpStatus status = HttpStatus.REQUEST_TIMEOUT; final E errorResponse = createErrorResponse(status, i18n(request, "rest-error.QueryTimeoutException")); logException(ex, errorResponse, request); return new ResponseEntity<>(errorResponse, status); }
Example #28
Source File: CustomRestExceptionHandler.java From xxproject with Apache License 2.0 | 5 votes |
@ExceptionHandler({ Exception.class }) public ResponseEntity<Object> handleAll(final Exception ex, final WebRequest request) { logger.info(ex.getClass().getName()); logger.error("error", ex); // final ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred"); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); }
Example #29
Source File: RestExceptionHandler.java From spring-boot-exception-handling with MIT License | 5 votes |
/** * Handle DataIntegrityViolationException, inspects the cause for different DB causes. * * @param ex the DataIntegrityViolationException * @return the ApiError object */ @ExceptionHandler(DataIntegrityViolationException.class) protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) { if (ex.getCause() instanceof ConstraintViolationException) { return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex.getCause())); } return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex)); }
Example #30
Source File: RestExceptionHandler.java From POC with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * * Handle HttpMessageNotWritableException. */ @Override protected ResponseEntity<Object> handleHttpMessageNotWritable(HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { final String error = "Error writing JSON output"; return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, error, ex)); }