Example usage for org.springframework.http HttpStatus METHOD_NOT_ALLOWED

List of usage examples for org.springframework.http HttpStatus METHOD_NOT_ALLOWED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus METHOD_NOT_ALLOWED.

Prototype

HttpStatus METHOD_NOT_ALLOWED

To view the source code for org.springframework.http HttpStatus METHOD_NOT_ALLOWED.

Click Source Link

Document

405 Method Not Allowed .

Usage

From source file:edu.isi.misd.scanner.network.registry.web.controller.BaseController.java

@ExceptionHandler({ MethodNotAllowedException.class, UnsupportedOperationException.class })
@ResponseBody/*from  ww w. ja v a 2 s  .  c  om*/
@ResponseStatus(value = HttpStatus.METHOD_NOT_ALLOWED)
public ErrorMessage handleMethodNotAllowedException(Exception e) {
    return new ErrorMessage(HttpStatus.METHOD_NOT_ALLOWED.value(),
            HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase(), e.getLocalizedMessage());
}

From source file:org.cloudfoundry.identity.uaa.web.CorsFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {

    if (isXhrRequest(request)) {
        String method = request.getMethod();
        if (!isCorsXhrAllowedMethod(method)) {
            response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
            return;
        }/* www.  j  a v a  2s.  c  o m*/
        String origin = request.getHeader(HttpHeaders.ORIGIN);
        String requestUri = request.getRequestURI();
        if (!isCorsXhrAllowedRequestUri(requestUri) || !isCorsXhrAllowedOrigin(origin)) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        response.addHeader("Access-Control-Allow-Origin", origin);
        if ("OPTIONS".equals(request.getMethod())) {
            buildCorsXhrPreFlightResponse(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
        return;
    }

    response.addHeader("Access-Control-Allow-Origin", "*");
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Authorization");
        response.addHeader("Access-Control-Max-Age", "1728000");
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:org.cloudfoundry.identity.uaa.web.CorsFilter.java

void buildCorsXhrPreFlightResponse(final HttpServletRequest request, final HttpServletResponse response) {
    String accessControlRequestMethod = request.getHeader("Access-Control-Request-Method");
    if (null == accessControlRequestMethod) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;//  w ww  . j a va  2 s .co m
    }
    if (!"GET".equalsIgnoreCase(accessControlRequestMethod)) {
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Methods", "GET");

    String accessControlRequestHeaders = request.getHeader("Access-Control-Request-Headers");
    if (null == accessControlRequestHeaders) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }
    if (!headersAllowed(accessControlRequestHeaders)) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Headers", "Authorization, X-Requested-With");
    response.addHeader("Access-Control-Max-Age", "1728000");
}

From source file:org.codehaus.groovy.grails.web.mapping.filter.UrlMappingsFilter.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from w w w.  j  a v  a2 s.com*/
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    UrlMappingsHolder holder = WebUtils.lookupUrlMappings(getServletContext());

    String uri = urlHelper.getPathWithinApplication(request);
    if (!"/".equals(uri) && noControllers() && noRegexMappings(holder)) {
        // not index request, no controllers, and no URL mappings for views, so it's not a Grails request
        processFilterChain(request, response, filterChain);
        return;
    }

    if (isUriExcluded(holder, uri)) {
        processFilterChain(request, response, filterChain);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing URL mapping filter...");
        LOG.debug(holder);
    }

    GrailsWebRequest webRequest = (GrailsWebRequest) request
            .getAttribute(GrailsApplicationAttributes.WEB_REQUEST);
    HttpServletRequest currentRequest = webRequest.getCurrentRequest();
    String version = findRequestedVersion(webRequest);

    UrlMappingInfo[] urlInfos = holder.matchAll(uri, currentRequest.getMethod(),
            version != null ? version : UrlMapping.ANY_VERSION);
    WrappedResponseHolder.setWrappedResponse(response);
    boolean dispatched = false;
    try {

        for (UrlMappingInfo info : urlInfos) {
            if (info != null) {
                Object redirectInfo = info.getRedirectInfo();
                if (redirectInfo != null) {
                    final Map redirectArgs;
                    if (redirectInfo instanceof Map) {
                        redirectArgs = (Map) redirectInfo;
                    } else {
                        redirectArgs = CollectionUtils.newMap("uri", redirectInfo);
                    }
                    GrailsParameterMap params = webRequest.getParams();
                    redirectArgs.put("params", params);
                    redirectDynamicMethod.invoke(this, "redirect", new Object[] { redirectArgs });
                    dispatched = true;

                    break;
                }
                // GRAILS-3369: The configure() will modify the
                // parameter map attached to the web request. So,
                // we need to clear it each time and restore the
                // original request parameters.
                webRequest.resetParams();

                final String viewName;
                try {
                    info.configure(webRequest);
                    viewName = info.getViewName();
                    if (viewName == null && info.getURI() == null) {
                        ControllerArtefactHandler.ControllerCacheKey featureId = getFeatureId(info);
                        GrailsClass controller = application
                                .getArtefactForFeature(ControllerArtefactHandler.TYPE, featureId);
                        if (controller == null) {
                            continue;
                        }

                        webRequest.setAttribute(GrailsApplicationAttributes.CONTROLLER_NAME_ATTRIBUTE,
                                controller.getLogicalPropertyName(), WebRequest.SCOPE_REQUEST);
                        webRequest.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, controller,
                                WebRequest.SCOPE_REQUEST);
                        webRequest.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE,
                                Boolean.TRUE, WebRequest.SCOPE_REQUEST);
                    }
                } catch (Exception e) {
                    if (e instanceof MultipartException) {
                        reapplySitemesh(request);
                        throw ((MultipartException) e);
                    }
                    LOG.error("Error when matching URL mapping [" + info + "]:" + e.getMessage(), e);
                    continue;
                }

                dispatched = true;

                if (!WAR_DEPLOYED) {
                    checkDevelopmentReloadingState(request);
                }

                request = checkMultipart(request);

                if (viewName == null || viewName.endsWith(GSP_SUFFIX) || viewName.endsWith(JSP_SUFFIX)) {
                    if (info.isParsingRequest()) {
                        webRequest.informParameterCreationListeners();
                    }
                    String forwardUrl = WebUtils.forwardRequestForUrlMappingInfo(request, response, info);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Matched URI [" + uri + "] to URL mapping [" + info + "], forwarding to ["
                                + forwardUrl + "] with response [" + response.getClass() + "]");
                    }
                } else {
                    if (!renderViewForUrlMappingInfo(request, response, info, viewName)) {
                        dispatched = false;
                    }
                }
                break;
            }
        }
    } finally {
        WrappedResponseHolder.setWrappedResponse(null);
    }

    if (!dispatched) {
        Set<HttpMethod> allowedHttpMethods = allowHeaderForWrongHttpMethod ? allowedMethods(holder, uri)
                : Collections.EMPTY_SET;

        if (allowedHttpMethods.isEmpty()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No match found, processing remaining filter chain.");
            }
            processFilterChain(request, response, filterChain);
        } else {
            response.addHeader(HttpHeaders.ALLOW, DefaultGroovyMethods.join(allowedHttpMethods, ","));
            response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
        }
    }
}

From source file:org.finra.dm.service.helper.DmErrorInformationExceptionHandler.java

/**
 * Handle exceptions that result in a "operation not allowed" status.
 *///from  w  w  w.j  a  v  a  2 s . co  m
@ExceptionHandler(value = MethodNotAllowedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ResponseBody
public ErrorInformation handleOperationNotAllowedException(RuntimeException exception) {
    return getErrorInformation(HttpStatus.METHOD_NOT_ALLOWED, exception);
}

From source file:org.geoserver.rest.security.MasterPasswordController.java

@PutMapping(consumes = { MediaType.APPLICATION_JSON_VALUE, MediaTypeExtensions.TEXT_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE })
public void masterPasswordPut(@RequestBody Map<String, String> putMap) throws IOException {
    if (!getManager().checkAuthenticationForAdminRole()) {
        // yes, for backwards compat, it's really METHOD_NOT_ALLOWED
        throw new RestException("Amdinistrative privelges required", HttpStatus.METHOD_NOT_ALLOWED);
    }//from   w w w . j av a  2 s  .  com

    String providerName;
    try {
        providerName = getManager().loadMasterPasswordConfig().getProviderName();
        if (getManager().loadMasterPassswordProviderConfig(providerName).isReadOnly()) {
            throw new RestException("Master password provider does not allow writes",
                    HttpStatus.METHOD_NOT_ALLOWED);
        }
    } catch (IOException e) {
        throw new RestException("Master password provider does not allow writes",
                HttpStatus.METHOD_NOT_ALLOWED);
    }

    String current = putMap.get(MP_CURRENT_KEY);
    String newpass = putMap.get(MP_NEW_KEY);

    if (!StringUtils.isNotBlank(current))
        throw new RestException("no master password", HttpStatus.BAD_REQUEST);

    if (!StringUtils.isNotBlank(newpass))
        throw new RestException("no master password", HttpStatus.BAD_REQUEST);

    char[] currentArray = current.trim().toCharArray();
    char[] newpassArray = newpass.trim().toCharArray();

    GeoServerSecurityManager m = getManager();
    try {
        m.saveMasterPasswordConfig(m.loadMasterPasswordConfig(), currentArray, newpassArray, newpassArray);
    } catch (Exception e) {
        throw new RestException("Cannot change master password", HttpStatus.UNPROCESSABLE_ENTITY, e);
    } finally {
        m.disposePassword(currentArray);
        m.disposePassword(newpassArray);
    }
}

From source file:org.geoserver.rest.security.UserPasswordController.java

@GetMapping()
public void passwordGet() {
    throw new RestException("You can not request the password!", HttpStatus.METHOD_NOT_ALLOWED);
}

From source file:org.geoserver.rest.security.UserPasswordController.java

@PutMapping(consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE,
        MediaType.TEXT_XML_VALUE, MediaTypeExtensions.TEXT_JSON_VALUE })
public void passwordPut(@RequestBody Map<String, String> putMap) {
    if (!getManager().checkAuthenticationForRole(SecurityContextHolder.getContext().getAuthentication(),
            GeoServerRole.AUTHENTICATED_ROLE))
        // yes, for backwards compat, it's really METHOD_NOT_ALLOWED
        throw new RestException("Amdinistrative privelges required", HttpStatus.METHOD_NOT_ALLOWED);

    try {/*from  w ww  . ja  v a2s  . co  m*/
        // Look for the service that handles the current user
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();

        GeoServerUserGroupService ugService = null;

        for (GeoServerUserGroupService service : getManager().loadUserGroupServices()) {
            if (service.getUserByUsername(userName) != null) {
                ugService = service;
                break;
            }
        }

        if (ugService == null) {
            throw new RestException("Cannot calculate if PUT is allowed (service not found)",
                    HttpStatus.UNPROCESSABLE_ENTITY);
        }

    } catch (IOException e) {
        throw new RestException("Cannot calculate if PUT is allowed (" + e.getMessage() + ")",
                HttpStatus.UNPROCESSABLE_ENTITY, e);
    }
    String newpass = putMap.get(UP_NEW_PW);

    if (StringUtils.isBlank(newpass))
        throw new RestException("Missing '" + UP_NEW_PW + "'", HttpStatus.BAD_REQUEST);

    GeoServerUser user = null;
    GeoServerUserGroupService ugService = null;

    try {
        // Look for the authentication service
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();

        for (GeoServerUserGroupService service : getManager().loadUserGroupServices()) {
            user = service.getUserByUsername(userName);
            if (user != null) {
                ugService = service;
                break;
            }
        }
    } catch (IOException e) {
        throw new RestException("Cannot retrieve user service", HttpStatus.FAILED_DEPENDENCY, e);
    }

    if (ugService == null) {
        throw new RestException("User service not found", HttpStatus.FAILED_DEPENDENCY);
    }

    // Check again if the provider allows updates
    if (!ugService.canCreateStore()) {
        throw new RestException("User service does not support changing pw", HttpStatus.FAILED_DEPENDENCY);
    }

    try {
        UserGroupStoreValidationWrapper ugStore = new UserGroupStoreValidationWrapper(ugService.createStore());

        user.setPassword(newpass);
        ugStore.updateUser(user);

        ugStore.store();
        ugService.load();

        LOGGER.log(Level.INFO, "Changed password for user {0}", user.getUsername());

    } catch (IOException e) {
        throw new RestException("Internal IO error", HttpStatus.INTERNAL_SERVER_ERROR, e);
    } catch (PasswordPolicyException e) {
        throw new RestException("Bad password", HttpStatus.UNPROCESSABLE_ENTITY, e);
    }
}

From source file:org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerSupport.java

/**
 * Provides handling for standard Spring MVC exceptions.
 * @param ex the target exception//from w  ww  .j a va  2s  .  c o m
 * @param request the current request
 */
@ExceptionHandler(value = { NoSuchRequestHandlingMethodException.class,
        HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class,
        HttpMediaTypeNotAcceptableException.class, MissingServletRequestParameterException.class,
        ServletRequestBindingException.class, ConversionNotSupportedException.class,
        TypeMismatchException.class, HttpMessageNotReadableException.class,
        HttpMessageNotWritableException.class, MethodArgumentNotValidException.class,
        MissingServletRequestPartException.class, BindException.class })
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {

    HttpHeaders headers = new HttpHeaders();

    HttpStatus status;
    Object body;

    if (ex instanceof NoSuchRequestHandlingMethodException) {
        status = HttpStatus.NOT_FOUND;
        body = handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, headers, status,
                request);
    } else if (ex instanceof HttpRequestMethodNotSupportedException) {
        status = HttpStatus.METHOD_NOT_ALLOWED;
        body = handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status,
                request);
    } else if (ex instanceof HttpMediaTypeNotSupportedException) {
        status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
        body = handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, headers, status,
                request);
    } else if (ex instanceof HttpMediaTypeNotAcceptableException) {
        status = HttpStatus.NOT_ACCEPTABLE;
        body = handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, headers, status,
                request);
    } else if (ex instanceof MissingServletRequestParameterException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, headers,
                status, request);
    } else if (ex instanceof ServletRequestBindingException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleServletRequestBindingException((ServletRequestBindingException) ex, headers, status,
                request);
    } else if (ex instanceof ConversionNotSupportedException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        body = handleConversionNotSupported((ConversionNotSupportedException) ex, headers, status, request);
    } else if (ex instanceof TypeMismatchException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleTypeMismatch((TypeMismatchException) ex, headers, status, request);
    } else if (ex instanceof HttpMessageNotReadableException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request);
    } else if (ex instanceof HttpMessageNotWritableException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        body = handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, headers, status, request);
    } else if (ex instanceof MethodArgumentNotValidException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleMethodArgumentNotValid((MethodArgumentNotValidException) ex, headers, status, request);
    } else if (ex instanceof MissingServletRequestPartException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleMissingServletRequestPart((MissingServletRequestPartException) ex, headers, status,
                request);
    } else if (ex instanceof BindException) {
        status = HttpStatus.BAD_REQUEST;
        body = handleBindException((BindException) ex, headers, status, request);
    } else {
        logger.warn("Unknown exception type: " + ex.getClass().getName());
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        body = handleExceptionInternal(ex, headers, status, request);
    }

    return new ResponseEntity<Object>(body, headers, status);
}

From source file:org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.java

/**
 * Provides handling for standard Spring MVC exceptions.
 * @param ex the target exception//  w  w w  .  j  av a 2  s  .  c o m
 * @param request the current request
 */
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class,
        HttpMediaTypeNotAcceptableException.class, MissingPathVariableException.class,
        MissingServletRequestParameterException.class, ServletRequestBindingException.class,
        ConversionNotSupportedException.class, TypeMismatchException.class,
        HttpMessageNotReadableException.class, HttpMessageNotWritableException.class,
        MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class,
        NoHandlerFoundException.class, AsyncRequestTimeoutException.class })
@Nullable
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
    HttpHeaders headers = new HttpHeaders();
    if (ex instanceof HttpRequestMethodNotSupportedException) {
        HttpStatus status = HttpStatus.METHOD_NOT_ALLOWED;
        return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status,
                request);
    } else if (ex instanceof HttpMediaTypeNotSupportedException) {
        HttpStatus status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
        return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, headers, status,
                request);
    } else if (ex instanceof HttpMediaTypeNotAcceptableException) {
        HttpStatus status = HttpStatus.NOT_ACCEPTABLE;
        return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, headers, status,
                request);
    } else if (ex instanceof MissingPathVariableException) {
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleMissingPathVariable((MissingPathVariableException) ex, headers, status, request);
    } else if (ex instanceof MissingServletRequestParameterException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, headers,
                status, request);
    } else if (ex instanceof ServletRequestBindingException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleServletRequestBindingException((ServletRequestBindingException) ex, headers, status,
                request);
    } else if (ex instanceof ConversionNotSupportedException) {
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleConversionNotSupported((ConversionNotSupportedException) ex, headers, status, request);
    } else if (ex instanceof TypeMismatchException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleTypeMismatch((TypeMismatchException) ex, headers, status, request);
    } else if (ex instanceof HttpMessageNotReadableException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request);
    } else if (ex instanceof HttpMessageNotWritableException) {
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, headers, status, request);
    } else if (ex instanceof MethodArgumentNotValidException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleMethodArgumentNotValid((MethodArgumentNotValidException) ex, headers, status, request);
    } else if (ex instanceof MissingServletRequestPartException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestPart((MissingServletRequestPartException) ex, headers, status,
                request);
    } else if (ex instanceof BindException) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        return handleBindException((BindException) ex, headers, status, request);
    } else if (ex instanceof NoHandlerFoundException) {
        HttpStatus status = HttpStatus.NOT_FOUND;
        return handleNoHandlerFoundException((NoHandlerFoundException) ex, headers, status, request);
    } else if (ex instanceof AsyncRequestTimeoutException) {
        HttpStatus status = HttpStatus.SERVICE_UNAVAILABLE;
        return handleAsyncRequestTimeoutException((AsyncRequestTimeoutException) ex, headers, status, request);
    } else {
        if (logger.isWarnEnabled()) {
            logger.warn("Unknown exception type: " + ex.getClass().getName());
        }
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleExceptionInternal(ex, null, headers, status, request);
    }
}