Example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

List of usage examples for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Prototype

int SC_METHOD_NOT_ALLOWED

To view the source code for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Click Source Link

Document

Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI.

Usage

From source file:org.sakaiproject.kernel.rest.friends.RestFriendsProvider.java

/**
 * {@inheritDoc}// w  w w  . j  a  va 2  s  . co  m
 *
 * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[],
 *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void dispatch(String[] elements, HttpServletRequest request, HttpServletResponse response) {
    try {
        FriendsParams params = new FriendsParams(elements, request, sessionManagerService,
                userEnvironmentResolverService);
        Map<String, Object> map = Maps.newHashMap();
        switch (params.major) {
        case connect:
            if (!"POST".equals(request.getMethod())) {
                throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
            switch (params.minor) {
            case request:
                map = doRequestConnect(params, request, response);
                break;
            case accept:
                map = doAcceptConnect(params, request, response);
                break;
            case cancel:
                map = doCancelConnect(params, request, response);
                break;
            case reject:
                map = doRejectConnect(params, request, response);
                break;
            case ignore:
                map = doIgnoreConnect(params, request, response);
                break;
            case remove:
                map = doRemoveConnect(params, request, response);
                break;
            default:
                doRequestError();
                break;
            }
            break;
        case status:
            if (!"GET".equals(request.getMethod())) {
                throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
            map = doStatus(params, request, response);
            break;
        default:
            doRequestError();
            break;
        }

        if (map != null) {
            String responseBody = beanConverter.convertToString(map);
            response.setContentType(RestProvider.CONTENT_TYPE);
            response.getOutputStream().print(responseBody);
        }
    } catch (SecurityException ex) {
        throw ex;
    } catch (RestServiceFaultException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RestServiceFaultException(ex.getMessage(), ex);
    }
}

From source file:org.eclipse.orion.internal.server.hosting.HostedSiteServlet.java

private void serve(HttpServletRequest req, HttpServletResponse resp, IHostedSite site, URI[] mappedURIs)
        throws ServletException, IOException {
    for (int i = 0; i < mappedURIs.length; i++) {
        URI uri = mappedURIs[i];//www  . j av  a2s .  com
        // Bypass a 404 if any workspace or remote paths remain to be checked.
        boolean failEarlyOn404 = i + 1 < mappedURIs.length;
        if (uri.getScheme() == null) {
            if ("GET".equals(req.getMethod())) { //$NON-NLS-1$
                if (serveOrionFile(req, resp, site, new Path(uri.getPath()), failEarlyOn404))
                    return;
            } else {
                String message = "Only GET method is supported for workspace paths";
                handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                        NLS.bind(message, mappedURIs), null));
                return;
            }
        } else {
            if (proxyRemotePath(req, new LocationHeaderServletResponseWrapper(req, resp, site), uri,
                    failEarlyOn404))
                return;
        }
    }
}

From source file:com.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

/**
 * Dispatches to feed, entry or whatever.
 *///from www.jav a 2  s.co m
private void dispatch(CallContext context, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    CmisService service = null;
    try {
        // get the service
        service = getServiceFactory().getService(context);

        // analyze the path
        String[] pathFragments = HttpUtils.splitPath(request);

        if (pathFragments.length < 2) {
            // root -> service document
            dispatcher.dispatch("", METHOD_GET, context, service, null, request, response);
            return;
        }

        String method = request.getMethod();
        String repositoryId = pathFragments[0];
        String resource = pathFragments[1];

        // dispatch
        boolean callServiceFound = dispatcher.dispatch(resource, method, context, service, repositoryId,
                request, response);

        // if the dispatcher couldn't find a matching service
        // -> return an error message
        if (!callServiceFound) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Unknown operation");
        }
    } finally {
        if (service != null) {
            service.close();
        }
    }
}

From source file:org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.java

/**
 * Handle the case where no request handler method was found for the particular HTTP request method.
 * <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header,
 * and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen,
 * or the HttpRequestMethodNotSupportedException could be rethrown as-is.
 * @param ex the HttpRequestMethodNotSupportedException to be handled
 * @param request current HTTP request//w  ww  . j  av a  2s.c  om
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen
 * at the time of the exception (for example, if multipart resolution failed)
 * @return an empty ModelAndView indicating the exception was handled
 * @throws IOException potentially thrown from response.sendError()
 */
protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
        HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException {

    pageNotFoundLogger.warn(ex.getMessage());
    String[] supportedMethods = ex.getSupportedMethods();
    if (supportedMethods != null) {
        response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
    }
    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
    return new ModelAndView();
}

From source file:org.artifactory.webapp.servlet.RepoFilter.java

private void doWebDavMethod(HttpServletRequest request, HttpServletResponse response, String method,
        ArtifactoryRequest artifactoryRequest, ArtifactoryResponse artifactoryResponse) throws IOException {
    if (!getWebdavService().handleRequest(method, artifactoryRequest, artifactoryResponse)) {
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        response.setHeader("Allow",
                PathUtils.collectionToDelimitedString(getWebdavService().supportedMethods()));
        log.info("Received unsupported request method: {} from:{ }.", method, request.getRemoteAddr());
    }/*  www . j  a  v a 2 s .  c om*/
}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

/**
 * Handle storing and updating file resources.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are creating
 * @throws IOException if the response cannot be sent
 *///from  w w  w.  java 2  s  .c o  m
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // TODO: fix code duplication between doPut() and Webdav.doPut()
    // Strip the username part
    String path;
    try {
        path = getUserPath(req);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }

    if (path.startsWith(PATH_GROUPS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_GROUPS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_OTHERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_OTHERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SEARCH)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SEARCH));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TOKEN)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TOKEN));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_USERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_USERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SHARED)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SHARED));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TAGS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TAGS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TRASH)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TRASH));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_FILES))
        new FilesHandler(getServletContext()).putResource(req, resp);
    else
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
}

From source file:org.jitsi.rest.AbstractJSONHandler.java

/**
 * Handles an HTTP request for a {@link #HEALTH_TARGET}-related resource.
 *
 * @param target the target of the request
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request//from ww w .ja  va  2s . c o m
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
protected void handleHealthJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (GET_HTTP_METHOD.equals(request.getMethod())) {
        // Check/get the health (status) of the associated server/service.
        doGetHealthJSON(baseRequest, request, response);
    } else {
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
}

From source file:org.opendaylight.iotdm.onem2m.protocols.http.Onem2mHttpProvider.java

private int mapCoreResponseToHttpResponse(HttpServletResponse httpResponse, String rscString) {

    httpResponse.setHeader(Onem2m.HttpHeaders.X_M2M_RSC, rscString);
    switch (rscString) {
    case Onem2m.ResponseStatusCode.OK:
        return HttpServletResponse.SC_OK;
    case Onem2m.ResponseStatusCode.CREATED:
        return HttpServletResponse.SC_CREATED;
    case Onem2m.ResponseStatusCode.CHANGED:
        return HttpServletResponse.SC_OK;
    case Onem2m.ResponseStatusCode.DELETED:
        return HttpServletResponse.SC_OK;

    case Onem2m.ResponseStatusCode.NOT_FOUND:
        return HttpServletResponse.SC_NOT_FOUND;
    case Onem2m.ResponseStatusCode.OPERATION_NOT_ALLOWED:
        return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    case Onem2m.ResponseStatusCode.CONTENTS_UNACCEPTABLE:
        return HttpServletResponse.SC_BAD_REQUEST;
    case Onem2m.ResponseStatusCode.CONFLICT:
        return HttpServletResponse.SC_CONFLICT;

    case Onem2m.ResponseStatusCode.INTERNAL_SERVER_ERROR:
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    case Onem2m.ResponseStatusCode.NOT_IMPLEMENTED:
        return HttpServletResponse.SC_NOT_IMPLEMENTED;
    case Onem2m.ResponseStatusCode.TARGET_NOT_REACHABLE:
        return HttpServletResponse.SC_NOT_FOUND;
    case Onem2m.ResponseStatusCode.ALREADY_EXISTS:
        return HttpServletResponse.SC_FORBIDDEN;
    case Onem2m.ResponseStatusCode.TARGET_NOT_SUBSCRIBABLE:
        return HttpServletResponse.SC_FORBIDDEN;
    case Onem2m.ResponseStatusCode.NON_BLOCKING_REQUEST_NOT_SUPPORTED:
        return HttpServletResponse.SC_NOT_IMPLEMENTED;

    case Onem2m.ResponseStatusCode.INVALID_ARGUMENTS:
        return HttpServletResponse.SC_BAD_REQUEST;
    case Onem2m.ResponseStatusCode.INSUFFICIENT_ARGUMENTS:
        return HttpServletResponse.SC_BAD_REQUEST;
    }/*from  w w w. ja  v  a2 s  .c o m*/
    return HttpServletResponse.SC_BAD_REQUEST;
}

From source file:org.jahia.bin.TestServlet.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getMethod().equalsIgnoreCase("get")) {
        handleGet(request, response);/*from   w  ww .  j  a va  2 s  .c om*/
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
    return null;
}

From source file:com.imaginary.home.cloud.api.RestApi.java

@Override
public void doPost(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp) throws IOException {
    String requestId = request(req);

    try {// w  w  w  .j a v a  2 s .  c om
        Map<String, Object> headers = parseHeaders(req);
        String[] path = getPath(req);

        if (path.length < 1) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No POST is allowed against /");
        } else if (path[0].equals("token")) {
            String token = generateToken("POST", req, headers);
            HashMap<String, Object> json = new HashMap<String, Object>();

            json.put("token", token);
            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.getWriter().println((new JSONObject(json)).toString());
            resp.getWriter().flush();
        } else if (path[0].equals("relay")) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get("relay");

            call.post(requestId, null, path, req, resp, headers, parameters);
        } else if (path[0].equals("user")) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
            StringBuilder source = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                source.append(line);
                source.append(" ");
            }
            String email = null, firstName = null, lastName = null, password = null;
            JSONObject object = new JSONObject(source.toString());

            if (object.has("email") && !object.isNull("email")) {
                email = object.getString("email").toLowerCase();
            }
            if (object.has("firstName") && !object.isNull("firstName")) {
                firstName = object.getString("firstName");
            }
            if (object.has("lastName") && !object.isNull("lastName")) {
                lastName = object.getString("lastName");
            }
            if (object.has("password") && !object.isNull("password")) {
                password = object.getString("password");
            }
            if (email == null || firstName == null || lastName == null || password == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                        "Required fields: email, firstName, lastName, password");
            }
            User user = User.create(email, firstName, lastName, password);
            ApiKey key = ApiKey.create(user, "default");

            HashMap<String, Object> json = new HashMap<String, Object>();

            json.put("email", email);
            json.put("firstName", firstName);
            json.put("lastName", lastName);
            json.put("userId", user.getUserId());

            HashMap<String, Object> k = new HashMap<String, Object>();

            k.put("apiKeyId", key.getApiKeyId());
            k.put("apiKeySecret", Configuration.decrypt(user.getUserId(), key.getApiKeySecret()));
            k.put("userId", user.getUserId());

            json.put("apiKeys", k);

            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.getWriter().println((new JSONObject(json)).toString());
            resp.getWriter().flush();
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

            String userId = authenticate("POST", req, headers);

            call.post(requestId, userId, path, req, resp, headers, parameters);
        } else {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE,
                    "No " + path[0] + " resource exists in this API");
        }
    } catch (RestException e) {
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", e.getStatus());
        error.put("message", e.getMessage());
        error.put("description", e.getDescription());
        resp.setStatus(e.getStatus());
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    } catch (Throwable t) {
        t.printStackTrace();
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        error.put("message", RestException.INTERNAL_ERROR);
        error.put("description", t.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    }
}