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.sprintapi.api.http.HttpServlet.java

protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ErrorException, IOException {

    final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest));
    request.setContext(httpRequest.getContextPath());

    // Resolve incoming URL and get resource descriptor
    final ResourceDescriptor resourceDsc = resolve(request.getUri());

    // Does the requested resource exist?
    if (resourceDsc == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND);
    }//from  w  w  w .j  a v  a 2 s .c o m

    // Is requested method supported?
    if (httpRequest.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US)));

    } catch (IllegalArgumentException ex) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    if (request.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get supported methods for requested resource
    Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods();

    // Get requested method descriptors for the resource
    MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null;

    // Is requested method supported?
    if ((methodDsc == null)) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    ContentAdapter<InputStream, ?> inputContentAdapter = null;

    // Is request body expected?
    if (request.getMethod().isRequestBody()) {
        String requestContentType = httpRequest.getContentType();

        inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType)
                : null;
        if (inputContentAdapter == null) {
            throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

    } else if (httpRequest.getContentLength() > 0) {
        // Unexpected request body
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    ContentAdapter<?, InputStream> outputContentAdapter = null;

    String responseContentType = null;

    // Is response body expected?
    if (request.getMethod().isResponseBody()) {
        // Check Accept header
        HttpAcceptHeader acceptHeader = HttpAcceptHeader
                .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT));
        if (acceptHeader != null) {

            Map<String, ?> produces = methodDsc.produces();

            // Response content negotiation 
            if (produces != null) {
                int weight = 0;

                for (String ct : produces.keySet()) {
                    int tw = acceptHeader.accept(ct);
                    if (tw > weight) {
                        weight = tw;
                        responseContentType = ct;
                        outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct);
                    }
                }
            }
            if (outputContentAdapter == null) {
                throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        }
    }

    if (inputContentAdapter != null) {
        ContentHolder<Object> lc = new ContentHolder<Object>();
        lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream()));
        request.setContent(lc);
    }

    // Invoke resource method
    Response response = methodDsc.invoke((Request) request);

    if (response == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // Write response status
    int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK;
    httpResponse.setStatus(responseStatus);

    if (response.getContent() == null) {
        return;
    }

    // Write response headers
    if (response.getContent().getMetaNames() != null) {
        for (String metaName : response.getContent().getMetaNames()) {
            Object metaValue = response.getContent().getMeta(metaName);
            if (metaValue != null) {
                if (metaValue instanceof Date) {
                    httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue)));
                } else {
                    httpResponse.setHeader(metaName, metaValue.toString());
                }
            }
        }
    }

    if ((HttpServletResponse.SC_CREATED == responseStatus)) {
        httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri());
    }

    if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) {
        return;
    }

    // Write response body
    if (outputContentAdapter != null) {
        httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType);
        InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter)
                .transform(request.getUri(), response.getContent().getBody());
        if (is != null) {
            CopyUtils.copy(is, httpResponse.getOutputStream());
        }
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    resp.setContentLength(0);//from  ww w.j a  va 2 s  .co m
}

From source file:org.apache.hadoop.gateway.dispatch.AbstractGatewayDispatch.java

public void doPut(URI url, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore.DumpRestoreController.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    if (!PolicyHelper.isAuthorizedForActions(req, REQUIRED_ACTION)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
    }//from  w w  w.  j  a v  a 2s  . com

    try {
        if (ACTION_RESTORE.equals(req.getPathInfo())) {
            long tripleCount = new RestoreModelsAction(req, resp).restoreModels();
            req.setAttribute(ATTRIBUTE_TRIPLE_COUNT, tripleCount);
            super.doGet(req, resp);
        } else {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (BadRequestException | RDFServiceException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jaspersoft.jasperserver.rest.RESTAbstractService.java

/**
 * Check for the request method, and dispatch the code to the right class method
 * PUT and DELETE methods can be overridden by using the X-Method-Override header or
 * the special parameter X-Method-Override when using a POST.
 *
 * @param req/*w w w. j  a v  a  2s  .  c om*/
 * @param resp
 * @throws ServiceException
 */
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    String method = req.getMethod().toLowerCase();

    // Tunnels a PUT or DELETE request over the HTTP POST request.
    String methodOverride = req.getHeader("X-Method-Override");
    if (methodOverride == null) {
        methodOverride = req.getParameter("X-Method-Override");
    }
    if (methodOverride != null && HTTP_POST.equals(method)) {
        methodOverride = methodOverride.toLowerCase();
        if (HTTP_DELETE.equals(methodOverride) || HTTP_PUT.equals(methodOverride)) {
            method = methodOverride;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("execute: Resource=" + req.getPathInfo() + " Method=" + method);
    }

    if (HTTP_GET.equals(method)) {
        doGet(req, resp);
    } else if (HTTP_POST.equals(method)) {
        doPost(req, resp);
    } else if (HTTP_PUT.equals(method)) {
        doPut(req, resp);
    } else if (HTTP_DELETE.equals(method)) {
        doDelete(req, resp);
    } else {
        restUtils.setStatusAndBody(HttpServletResponse.SC_METHOD_NOT_ALLOWED, resp,
                "Method not supported for this object type");
    }
    if (log.isDebugEnabled()) {
        log.debug("finished: Resource=" + req.getPathInfo() + " Method=" + method);
    }

}

From source file:org.apache.hadoop.gateway.dispatch.AbstractGatewayDispatch.java

public void doDelete(URI url, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}

From source file:org.osaf.cosmo.webcal.WebcalServlet.java

/**
 * Handles GET requests for calendar collections. Returns a 200
 * <code>text/calendar</code> response containing an iCalendar
 * representation of all of the calendar items within the
 * collection.//w w w .j a  v  a 2s .co m
 *
 * Returns 404 if the request's path info does not specify a
 * collection path or if the identified collection is not found.
 *
 * Returns 405 if the item with the identified uid is not a
 * calendar collection.
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling GET for " + req.getPathInfo());

    // requests will usually come in with the collection's display
    // name appended to the collection path so that clients will
    // save the file with that name
    CollectionPath cp = CollectionPath.parse(req.getPathInfo(), true);
    if (cp == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Item item;

    try {
        item = contentService.findItemByUid(cp.getUid());
    }
    // handle security errors by returing 403
    catch (CosmoSecurityException e) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (item == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (!(item instanceof CollectionItem)) {
        resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a collection");
        return;
    }

    CollectionItem collection = (CollectionItem) item;
    if (StampUtils.getCalendarCollectionStamp(collection) == null) {
        resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a calendar collection");
        return;
    }

    EntityTag etag = new EntityTag(collection.getEntityTag());

    // set ETag
    resp.setHeader("ETag", etag.toString());

    // check for If-None-Match
    EntityTag[] requestEtags = getIfNoneMatch(req);
    if (requestEtags != null && requestEtags.length != 0) {
        if (EntityTag.matchesAny(etag, requestEtags)) {
            resp.setStatus(304);
            return;
        }
    }

    // check for If-Modified-Since
    long since = req.getDateHeader("If-Modified-Since");

    // If present and if collection's modified date not more recent,
    // return 304 not modified
    if (since != -1) {
        long lastModified = collection.getModifiedDate().getTime() / 1000 * 1000;

        if (lastModified <= since) {
            resp.setStatus(304);
            return;
        }
    }

    // set Last-Modified
    resp.setDateHeader("Last-Modified", collection.getModifiedDate().getTime());

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType(ICALENDAR_MEDIA_TYPE);
    resp.setCharacterEncoding("UTF-8");

    // send Content-Disposition to provide another hint to clients
    // on how to save and name the downloaded file
    String filename = collection.getDisplayName() + "." + ICALENDAR_FILE_EXTENSION;
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    // get icalendar
    Calendar calendar = entityConverter.convertCollection(collection);

    // Filter if necessary so we play nicely with clients
    // that don't adhere to spec
    if (clientFilterManager != null)
        clientFilterManager.filterCalendar(calendar);

    // spool
    ICalendarOutputter.output(calendar, resp.getOutputStream());
}

From source file:com.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;/*from ww w .  jav  a  2 s . co m*/
    }

    String pathInfo = request.getPathInfo();

    // Only serve the content if the request matches the base path.
    if (pathInfo == null || !pathInfo.startsWith(basePath)) {
        return;
    }

    pathInfo = pathInfo.substring(basePath.length());

    if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) {
        // basepath is /foo and request went to /foobar --> pathInfo starts with bar
        // basepath is /foo and request went to /foo --> pathInfo should be /index.html
        return;
    }

    // Allow index.html as welcome file
    if ("/".equals(pathInfo) || "".equals(pathInfo)) {
        pathInfo = "/index.html";
    }

    boolean skipContent = false;

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    final String method = request.getMethod();
    if (!StringUtils.equals(HttpMethods.GET, method)) {
        if (StringUtils.equals(HttpMethods.HEAD, method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    // Does the request contain an IF_MODIFIED_SINCE header?
    final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    InputStream resourceStream = null;

    try {
        if (pathInfo.startsWith("/")) {
            final String resourcePath = resourceLocation + pathInfo;
            resourceStream = getClass().getResourceAsStream(resourcePath);
        }

        if (resourceStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo());
        if (mime != null) {
            response.setContentType(mime.toString("ISO8859-1"));
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        if (out instanceof AbstractHttpConnection.Output) {
            ((AbstractHttpConnection.Output) out).sendContent(resourceStream);
        } else {
            ByteStreams.copy(resourceStream, out);
        }
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.GatewayDispatchFilter.java

@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String method = request.getMethod().toUpperCase();
    Adapter adapter = METHOD_ADAPTERS.get(method);
    if (adapter != null) {
        try {//from w w  w  . j  a v a  2  s  .  c  o  m
            adapter.doMethod(dispatch, request, response);
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        }
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.AbstractGatewayDispatch.java

public void doOptions(URI url, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}