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: 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 #2
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 #3
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 #4
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 #5
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 #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: 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 #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: 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 #11
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 #12
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 #13
Source File: ResponseEntityExceptionHandler.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Customize the response for HttpMediaTypeNotSupportedException. * <p>This method sets the "Accept" 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> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<MediaType> mediaTypes = ex.getSupportedMediaTypes(); if (!CollectionUtils.isEmpty(mediaTypes)) { headers.setAccept(mediaTypes); } return handleExceptionInternal(ex, null, headers, status, request); }
Example #14
Source File: CustomRestExceptionHandler.java From tutorials with MIT License | 5 votes |
@ExceptionHandler({ ConstraintViolationException.class }) public ResponseEntity<Object> handleConstraintViolation(final ConstraintViolationException ex, final WebRequest request) { logger.info(ex.getClass().getName()); // final List<String> errors = new ArrayList<String>(); for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(violation.getRootBeanClass().getName() + " " + violation.getPropertyPath() + ": " + violation.getMessage()); } final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); }
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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)); }
Example #23
Source File: RestResponseEntityExceptionHandler.java From edison-microservice with Apache License 2.0 | 5 votes |
@ExceptionHandler({AccessDeniedException.class}) public ResponseEntity<Object> handleAccessDeniedException(final Exception ex, final WebRequest request) { final Map<String, Object> message = new HashMap<>(); message.put("error", HttpStatus.FORBIDDEN.getReasonPhrase().toLowerCase()); message.put("error_description", ex.getMessage()); return new ResponseEntity<>(message, HttpStatus.FORBIDDEN); }
Example #24
Source File: AppResponseEntityExceptionHandler.java From cicada with MIT License | 5 votes |
@ExceptionHandler(value = {InternalServerErrorException.class}) protected ResponseEntity<Object> handleInternalServerException(final Exception ex, final WebRequest request) { log.error("handleInternalServerException {}:{}", ex.getClass(), ex); final HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; final ErrorMessage errorMessage = // new ErrorMessage(AppError.OTHER_SERVER_INERNAL_EXCEPTION.getErrorCode(), ex.getMessage()); return new ResponseEntity<Object>(errorMessage, status); }
Example #25
Source File: StartPageFeedsController.java From podcastpedia-web with MIT License | 5 votes |
/** * Returns list of newest podcasts to be generated as a atom feed. * Request comes from start page. * * @param request * @param model * @return */ @RequestMapping("newest.atom") public String getNewestPodcastsAtomFeed(WebRequest request, Model model) { Locale locale = LocaleContextHolder.getLocale(); model.addAttribute("list_of_podcasts", getNewestPodcastsForLocale(locale)); model.addAttribute("feed_id", "tag:podcastpedia.org,2013-04-30:last_updated"); model.addAttribute("feed_title", messageSource.getMessage("podcasts.newest.feed_title", null, locale)); model.addAttribute("feed_description", messageSource.getMessage("podcasts.newest.feed_description", null, locale)); model.addAttribute("feed_link", configService.getValue("HOST_AND_PORT_URL")); model.addAttribute("HOST_AND_PORT_URL", configService.getValue("HOST_AND_PORT_URL")); return "newestPodcastsAtomFeedView"; }
Example #26
Source File: ExceptionHandlerController.java From egeria with Apache License 2.0 | 5 votes |
@ExceptionHandler(value = {GlossaryViewOmasException.class}) protected ResponseEntity<Object> handleGlossaryViewOmasException(GlossaryViewOmasException ex, WebRequest request) { LOG.error(ex.getMessage(), ex); Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(request, UserInterfaceErrorCodes.INVALID_REQUEST_FOR_GLOSSARY_VIEW); return handleExceptionInternal(ex, errorAttributes, new HttpHeaders(), UserInterfaceErrorCodes.INVALID_REQUEST_FOR_GLOSSARY_VIEW.getHttpErrorCode(), request); }
Example #27
Source File: OpenSessionInViewInterceptor.java From java-technology-stack 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 #28
Source File: AbstractRestExceptionHandler.java From kaif with Apache License 2.0 | 5 votes |
@ExceptionHandler(AccessDeniedException.class) @ResponseBody public ResponseEntity<E> handleAccessDeniedException(final AccessDeniedException ex, final WebRequest request) { final HttpStatus status = HttpStatus.UNAUTHORIZED; final E errorResponse = createErrorResponse(status, i18n(request, "rest-error.RestAccessDeniedException")); if (environment.acceptsProfiles(SpringProfile.DEV)) { //only dev server log detail access denied logException(ex, errorResponse, request); } else { logger.warn("{} {}", guessUri(request), ex.getClass().getSimpleName()); } return new ResponseEntity<>(errorResponse, status); }
Example #29
Source File: FunctionController.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@PostMapping(path = "/**") @ResponseBody public Mono<ResponseEntity<?>> post(WebRequest request, @RequestBody(required = false) String body) { FunctionWrapper wrapper = wrapper(request); return this.processor.post(wrapper, body, false); }
Example #30
Source File: RestResponseEntityExceptionHandler.java From skeleton-ws-spring-boot with Apache License 2.0 | 5 votes |
/** * Handles EmptyResultDataAccessException thrown from web service controller methods. Creates a response with an * ExceptionDetail body and HTTP status code 404, not found. * * @param ex An EmptyResultDataAccessException instance. * @return A ResponseEntity with an ExceptionDetail response body and HTTP status code 404. */ @ExceptionHandler(EmptyResultDataAccessException.class) public ResponseEntity<Object> handleEmptyResultDataAccessException(final EmptyResultDataAccessException ex, final WebRequest request) { logger.info("> handleEmptyResultDataAccessException"); logger.info("- EmptyResultDataAccessException: ", ex); final ExceptionDetail detail = new ExceptionDetailBuilder().exception(ex).httpStatus(HttpStatus.NOT_FOUND) .webRequest(request).build(); logger.info("< handleEmptyResultDataAccessException"); return handleExceptionInternal(ex, detail, new HttpHeaders(), HttpStatus.NOT_FOUND, request); }