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:ch.entwine.weblounge.dispatcher.impl.handler.FileRequestHandlerImpl.java

/**
 * Handles the request for a file resource that is believed to be in the
 * content repository. The handler sets the response headers and the writes
 * the file contents to the response./*from   ww  w  . j  a v  a2  s. com*/
 * <p>
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for files. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is a file with the current path.
    ResourceURI fileURI = null;
    Resource<? extends FileContent> fileResource = null;
    try {
        String id = null;
        String filePath = null;

        if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

            // Check whether we are looking at a uuid or a url path
            if (uriSuffix.length() == UUID_LENGTH) {
                id = uriSuffix;
            } else if (uriSuffix.length() >= UUID_LENGTH) {
                int lastSeparator = uriSuffix.indexOf('/');
                if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                    id = uriSuffix.substring(0, lastSeparator);
                    fileName = uriSuffix.substring(lastSeparator + 1);
                } else {
                    filePath = uriSuffix;
                    fileName = FilenameUtils.getName(filePath);
                }
            } else {
                filePath = "/" + uriSuffix;
                fileName = FilenameUtils.getName(filePath);
            }
            fileURI = new GeneralResourceURIImpl(site, filePath, id);
        } else {
            filePath = path;
            fileName = FilenameUtils.getName(filePath);
            fileURI = new FileResourceURIImpl(site, filePath, null);
        }

        // Try to load the resource
        try {
            fileResource = (Resource<? extends FileContent>) contentRepository.get(fileURI);
            if (fileResource == null) {
                logger.debug("No file found at {}", fileURI);
                return false;
            }
        } catch (ClassCastException e) {
            logger.debug("Resource {} does not extend file resource {}", fileURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading file from {}: {}", contentRepository, e);
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding file url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Try to serve the file
    logger.debug("File handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("File request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. fileResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!fileResource.isPublished()) {
    // logger.debug("Access to unpublished file {}", fileURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the page be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to file {} denied for user {}", fileURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (FileContent c : fileResource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("File {} does not exist in any supported language", fileURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, fileResource, language)) {
        logger.debug("File {} was not modified", fileURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Add mime type header
    FileContent content = fileResource.getContent(language);

    // If the content is hosted externally, send a redirect and be done with it
    if (content.getExternalLocation() != null) {
        try {
            response.sendRedirect(content.getExternalLocation().toExternalForm());
        } catch (IOException e) {
            logger.debug("Client ignore redirect to {}", content.getExternalLocation());
        }
        return true;
    }

    String contentType = content.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Add last modified header
    response.setDateHeader("Last-Modified",
            ResourceUtils.getModificationDate(fileResource, language).getTime());

    // Add ETag header
    String eTag = ResourceUtils.getETagValue(fileResource);
    response.setHeader("ETag", eTag);

    // Set the Expires header
    response.setDateHeader("Expires", expirationDate);

    // Add content disposition header
    response.setHeader("Content-Disposition", "inline; filename=" + content.getFilename());

    // Add content size
    response.setHeader("Content-Length", Long.toString(content.getSize()));

    // Write the file back to the response
    InputStream fileContents = null;
    try {
        fileContents = contentRepository.getContent(fileURI, language);
        IOUtils.copy(fileContents, response.getOutputStream());
        response.getOutputStream().flush();
        return true;
    } catch (ContentRepositoryException e) {
        logger.error("Unable to load file {}: {}", new Object[] { fileURI, e.getMessage(), e });
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (EOFException e) {
        logger.debug("Error writing file '{}' back to client: connection closed by client", fileURI);
        return true;
    } catch (IOException e) {
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error sending file {} to the client: {}", fileURI, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } finally {
        IOUtils.closeQuietly(fileContents);
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.ImageRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>/*from w ww . j  av  a 2  s.  c o  m*/
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for images. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI imageURI = null;
    ImageResource imageResource = null;
    try {
        String id = null;
        String imagePath = null;

        if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

            // Check whether we are looking at a uuid or a url path
            if (uriSuffix.length() == UUID_LENGTH) {
                id = uriSuffix;
            } else if (uriSuffix.length() >= UUID_LENGTH) {
                int lastSeparator = uriSuffix.indexOf('/');
                if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                    id = uriSuffix.substring(0, lastSeparator);
                    fileName = uriSuffix.substring(lastSeparator + 1);
                } else {
                    imagePath = uriSuffix;
                    fileName = FilenameUtils.getName(imagePath);
                }
            } else {
                imagePath = "/" + uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = path;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        imageURI = new ImageResourceURIImpl(site, imagePath, id);
        imageResource = contentRepository.get(imageURI);
        if (imageResource == null) {
            logger.debug("No image found at {}", imageURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the image
    logger.debug("Image handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the image be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to image {} denied for user {}", imageURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ImageContent c : imageResource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Image {} does not exist in any supported language", imageURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Extract the image style and scale the image
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        try {
            StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX,
                    imageResource.getURI().getIdentifier()));
            redirect.append("?style=").append(styleId);
            response.sendRedirect(redirect.toString());
        } catch (Throwable t) {
            logger.debug("Error sending redirect to the client: {}", t.getMessage());
        }
        return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, imageResource, language)) {
        logger.debug("Image {} was not modified", imageURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ImageContent imageContents = imageResource.getContent(language);

    // Add mime type header
    String contentType = imageContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Determine the resource's modification date
    long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime();

    // Add last modified header
    response.setDateHeader("Last-Modified", resourceLastModified);

    // Add ETag header
    response.setHeader("ETag", ResourceUtils.getETagValue(imageResource));

    // Load the input stream from the repository
    InputStream imageInputStream = null;
    try {
        imageInputStream = contentRepository.getContent(imageURI, language);
    } catch (Throwable t) {
        logger.error("Error loading {} image '{}' from {}: {}",
                new Object[] { language, imageResource, contentRepository, t.getMessage() });
        logger.error(t.getMessage(), t);
        IOUtils.closeQuietly(imageInputStream);
        return false;
    }

    // Write the image back to the client
    try {
        response.setHeader("Content-Length", Long.toString(imageContents.getSize()));
        response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename());
        IOUtils.copy(imageInputStream, response.getOutputStream());
        response.getOutputStream().flush();
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource);
        return true;
    } catch (IOException e) {
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error writing {} image '{}' back to client: {}",
                new Object[] { language, imageResource, e.getMessage() });
    } finally {
        IOUtils.closeQuietly(imageInputStream);
    }
    return true;

}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * @param httpServletRequest// www. j a  v  a  2 s. co m
 * @param httpServletResponse
 * @throws ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = "
            + httpServletRequest.getPathInfo());
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    if (path != null) {
        String[] params = path.substring(1, path.length()).split("/");

        if (params.length == 1) {
            patronid = params[0];
            service = "patron";
        } else if (params.length == 2) {
            patronid = params[0];
            service = params[1];
        }
    }

    // 1. Schritt: Hole 'Accept' und 'Authorization' aus dem Header;
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = (String) headerNames.nextElement();
        this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = "
                + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Accept")) {
            accept = httpServletRequest.getHeader(headerNameKey);
        }
        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }
    }

    if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null
            && !httpServletRequest.getParameter("access_token").equals("")) {
        authorization = "Bearer " + httpServletRequest.getParameter("access_token");
    }

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization);

    this.logger.error("[" + this.config.getProperty("service.name") + "] "
            + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "GET for '" + service + "' not allowed!");

    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA Core\"");
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null
            && !httpServletRequest.getParameter("suppress_response_codes").equals("")) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
    requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    requestError.setDescription(this.config.getProperty(
            "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
    requestError.setErrorUri(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

    StringWriter json = new StringWriter();
    mapper.writeValue(json, requestError);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

    // send response
    httpServletResponse.getWriter().println(json);
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.java

@SuppressWarnings("rawtypes")
public ModelAndView handleURI(final String originalUri, GrailsWebRequest grailsWebRequest, Map params) {
    Assert.notNull(originalUri, "Controller URI [" + originalUri + "] cannot be null!");

    HttpServletRequest request = grailsWebRequest.getCurrentRequest();
    HttpServletResponse response = grailsWebRequest.getCurrentResponse();

    String uri = originalUri;/*from   ww  w  . j a  va 2s . c o  m*/
    if (uri.endsWith("/")) {
        uri = uri.substring(0, uri.length() - 1);
    }

    // Step 2: lookup the controller in the application.
    GrailsControllerClass controllerClass = null;
    if (!WebUtils.isIncludeRequest(request) && request.getAttribute(FORWARD_IN_PROGRESS) == null) {

        Object attribute = grailsWebRequest.getAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS,
                WebRequest.SCOPE_REQUEST);
        if (attribute instanceof GrailsControllerClass) {
            controllerClass = (GrailsControllerClass) attribute;
            Boolean canUse = (Boolean) grailsWebRequest.getAttribute(
                    GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE, WebRequest.SCOPE_REQUEST);
            if (canUse == null) {
                controllerClass = null;
            } else {
                grailsWebRequest.removeAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE,
                        WebRequest.SCOPE_REQUEST);
            }
        }
    }

    if (controllerClass == null) {
        controllerClass = getControllerClassByURI(uri);
    }

    if (controllerClass == null) {
        throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
    }

    String actionName = controllerClass.getMethodActionName(uri);
    if (controllerClass.isFlowAction(actionName)) {
        // direct access to flow action not allowed
        return null;
    }
    grailsWebRequest.setActionName(actionName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for controller action [" + actionName + "]");
    }
    // Step 3: load controller from application context.
    GroovyObject controller = getControllerInstance(controllerClass);

    if (!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
        try {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return null;
        } catch (IOException e) {
            throw new ControllerExecutionException("I/O error sending 403 error", e);
        }
    }

    request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller);

    // Step 4: Set grails attributes in request scope
    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Step 5: get the view name for this URI.
    String viewName = controllerClass.getViewByURI(uri);

    boolean executeAction = invokeBeforeInterceptor(controller, actionName, controllerClass);
    // if the interceptor returned false don't execute the action
    if (!executeAction) {
        return null;
    }

    ModelAndView mv = executeAction(controller, actionName, viewName, grailsWebRequest, params);

    boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, actionName, mv)
            && !response.isCommitted();
    return returnModelAndView ? mv : null;
}

From source file:org.apache.hadoop.hbase.rest.Status.java

public void setMethodNotImplemented() {
    this.statusCode = HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    this.message = new StatusMessage(statusCode, true, "method not implemented");
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.PreviewRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>/*from w  ww. ja  v  a 2 s.  c om*/
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // This request handler can only be used with the prefix
    if (!path.startsWith(URI_PREFIX))
        return false;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for previews. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI resourceURI = null;
    Resource<?> resource = null;
    try {
        String id = null;
        String imagePath = null;

        String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
        uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

        // Check whether we are looking at a uuid or a url path
        if (uriSuffix.length() == UUID_LENGTH) {
            id = uriSuffix;
        } else if (uriSuffix.length() >= UUID_LENGTH) {
            int lastSeparator = uriSuffix.indexOf('/');
            if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                id = uriSuffix.substring(0, lastSeparator);
                fileName = uriSuffix.substring(lastSeparator + 1);
            } else {
                imagePath = uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = "/" + uriSuffix;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        resourceURI = new ResourceURIImpl(null, site, imagePath, id);
        resource = contentRepository.get(resourceURI);
        if (resource == null) {
            logger.debug("No resource found at {}", resourceURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading resource from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding resource url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the preview
    logger.debug("Preview handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the resource be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to resource {} denied for user {}", resourceURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ResourceContent c : resource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Resource {} does not exist in any supported language", resourceURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Find a resource preview generator
    PreviewGenerator previewGenerator = null;
    synchronized (previewGenerators) {
        for (PreviewGenerator generator : previewGenerators) {
            if (generator.supports(resource)) {
                previewGenerator = generator;
                break;
            }
        }
    }

    // If we did not find a preview generator, we need to let go
    if (previewGenerator == null) {
        logger.debug("Unable to generate preview for {} since no suitable preview generator is available",
                resource);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Extract the image style
    ImageStyle style = null;
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        style = ImageStyleUtils.findStyle(styleId, site);
        if (style == null) {
            DispatchUtils.sendBadRequest("Image style '" + styleId + "' not found", request, response);
            return true;
        }
    }

    // Get the path to the preview image
    File previewFile = ImageStyleUtils.getScaledFile(resource, language, style);

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, previewFile)) {
        logger.debug("Scaled preview {} was not modified", resourceURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ResourceContent resourceContents = resource.getContent(language);

    // Add mime type header
    String contentType = resourceContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Write the image back to the client
    InputStream previewInputStream = null;
    try {
        if (previewFile.isFile()
                && previewFile.lastModified() >= resourceContents.getCreationDate().getTime()) {
            previewInputStream = new FileInputStream(previewFile);
        } else {
            previewInputStream = createPreview(request, response, resource, language, style, previewGenerator,
                    previewFile, contentRepository);
        }

        if (previewInputStream == null) {
            // Assuming that createPreview() is setting the response header in the
            // case of failure
            return true;
        }

        // Add last modified header
        response.setDateHeader("Last-Modified", previewFile.lastModified());
        response.setHeader("ETag", ResourceUtils.getETagValue(previewFile.lastModified()));
        response.setHeader("Content-Disposition", "inline; filename=" + previewFile.getName());
        response.setHeader("Content-Length", Long.toString(previewFile.length()));
        previewInputStream = new FileInputStream(previewFile);
        IOUtils.copy(previewInputStream, response.getOutputStream());
        response.getOutputStream().flush();
        return true;
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", resource);
        return true;
    } catch (IOException e) {
        DispatchUtils.sendInternalError(request, response);
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error sending image '{}' to the client: {}", resourceURI, e.getMessage());
        return true;
    } catch (Throwable t) {
        logger.error("Error creating scaled image '{}': {}", resourceURI, t.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } finally {
        IOUtils.closeQuietly(previewInputStream);
    }
}

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

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

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

        if (path.length < 1) {
            // TODO: documentation
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No GET is allowed against /");
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

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

            call.get(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();
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.FeedRequestHandlerImpl.java

/**
 * Handles the request for a feed of a certain type.
 * <p>/* ww  w  .ja v a  2s . co  m*/
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    Site site = request.getSite();
    WebUrl url = request.getUrl();
    String path = request.getRequestURI();
    String feedType = null;
    String feedVersion = null;

    // Currently, we only support feeds mapped to our well-known uri
    if (!path.startsWith(URI_PREFIX) || !(path.length() > URI_PREFIX.length()))
        return false;

    // Check for feed type and version
    String feedURI = path.substring(URI_PREFIX.length());
    String[] feedURIParts = feedURI.split("/");
    if (feedURIParts.length == 0) {
        logger.debug("Feed request {} does not include feed type", path);
        return false;
    } else if (feedURIParts.length == 1) {
        logger.debug("Feed request {} does not include feed version", path);
        return false;
    }

    // Check the request method. This handler only supports GET
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Feed request handler does not support {} requests", url, requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    feedType = feedURIParts[0];
    feedVersion = feedURIParts[1];

    // Check for explicit no cache instructions
    boolean noCache = request.getParameter(ResponseCache.NOCACHE_PARAM) != null;

    // Check if the page is already part of the cache. If so, our task is
    // already done!
    if (!noCache) {
        long expirationTime = Renderer.DEFAULT_VALID_TIME;
        long revalidationTime = Renderer.DEFAULT_RECHECK_TIME;

        // Create the set of tags that identify the request output
        CacheTagSet cacheTags = createPrimaryCacheTags(request);

        // Check if the page is already part of the cache
        if (response.startResponse(cacheTags.getTags(), expirationTime, revalidationTime)) {
            logger.debug("Feed handler answered request for {} from cache", request.getUrl());
            return true;
        }
    }

    try {

        // Compile the feed
        SyndFeed feed = createFeed(feedType, feedVersion, site, request, response);
        if (feed == null)
            return true;

        // Set the response type
        String characterEncoding = "utf-8";
        if (feedType.startsWith("atom"))
            response.setContentType("application/atom+xml; charset=" + characterEncoding);
        else if (feedType.startsWith("rss"))
            response.setContentType("application/rss+xml; charset=" + characterEncoding);

        // Set the character encoding
        feed.setEncoding(response.getCharacterEncoding());

        // Set the modification date
        response.setModificationDate(feed.getPublishedDate());

        // Write the feed back to the response

        SyndFeedOutput output = new SyndFeedOutput();
        Writer responseWriter = new OutputStreamWriter(response.getOutputStream(), characterEncoding);
        output.output(feed, responseWriter);
        response.getOutputStream().flush();
        return true;

    } catch (ContentRepositoryException e) {
        logger.error("Error loading articles for feeds from {}: {}", site.getIdentifier(), e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (FeedException e) {
        logger.error("Error creating {} feed: {}", feedType, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (EOFException e) {
        logger.debug("Error writing feed '{}' back to client: connection closed by client", feedType);
        return true;
    } catch (IOException e) {
        logger.error("Error sending {} feed to the client: {}", feedType, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to create feed of type '{}': {}", feedType, e.getMessage());
        DispatchUtils.sendNotFound(e.getMessage(), request, response);
        return true;
    } catch (Throwable t) {
        logger.error("Error creating feed of type '{}': {}", feedType, t.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } finally {
        response.endResponse();
    }
}

From source file:org.codice.proxy.http.HttpProxyCamelHttpTransportServlet.java

@Override
protected void service(HttpServletRequest oldRequest, HttpServletResponse response)
        throws ServletException, IOException {

    //Wrap request and clean the query String
    HttpProxyWrappedCleanRequest request = new HttpProxyWrappedCleanRequest(oldRequest);

    log.trace("Service: {}", request);

    // Is there a consumer registered for the request.
    HttpConsumer consumer = resolve(request);

    if (consumer == null) {
        String path = request.getPathInfo();
        log.trace("Service Request Path = {}", path);
        String endpointName = getEndpointNameFromPath(path);
        log.trace("Endpoint Name = {}", endpointName);

        Route route = camelContext.getRoute(endpointName);
        try {//w  ww. java2  s .c  o m
            if (route != null) {
                connect((HttpConsumer) route.getConsumer());
            }
        } catch (Exception e) {
            log.debug("Exception while creating consumer", e);
        }
        consumer = resolve(request);
    }

    if (consumer == null) {
        log.debug("No consumer to service request {}", request);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // are we suspended?
    if (consumer.getEndpoint().isSuspended()) {
        log.debug("Consumer suspended, cannot service request {}", request);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    if (consumer.getEndpoint().getHttpMethodRestrict() != null
            && !consumer.getEndpoint().getHttpMethodRestrict().equals(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if ("TRACE".equals(request.getMethod()) && !consumer.getEndpoint().isTraceEnabled()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    // create exchange and set data on it
    Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);

    if (consumer.getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
    }
    if (consumer.getEndpoint().isDisableStreamCache()) {
        exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
    }

    // we override the classloader before building the HttpMessage just in case the binding
    // does some class resolution
    ClassLoader oldTccl = overrideTccl(exchange);
    HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
    exchange.setIn(new HttpMessage(exchange, request, response));
    // set context path as header
    String contextPath = consumer.getEndpoint().getPath();
    exchange.getIn().setHeader("CamelServletContextPath", contextPath);

    String httpPath = (String) exchange.getIn().getHeader(Exchange.HTTP_PATH);
    // here we just remove the CamelServletContextPath part from the HTTP_PATH
    if (contextPath != null && httpPath.startsWith(contextPath)) {
        exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length()));
    }

    // we want to handle the UoW
    try {
        consumer.createUoW(exchange);
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    }

    try {
        if (log.isTraceEnabled()) {
            log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
        }
        // process the exchange
        consumer.getProcessor().process(exchange);
    } catch (Exception e) {
        exchange.setException(e);
    }

    try {
        // now lets output to the response
        if (log.isTraceEnabled()) {
            log.trace("Writing response for exchangeId: {}", exchange.getExchangeId());
        }
        Integer bs = consumer.getEndpoint().getResponseBufferSize();
        if (bs != null) {
            log.trace("Using response buffer size: {}", bs);
            response.setBufferSize(bs);
        }
        consumer.getBinding().writeResponse(exchange, response);
    } catch (IOException e) {
        log.error("Error processing request", e);
        throw e;
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    } finally {
        consumer.doneUoW(exchange);
        restoreTccl(exchange, oldTccl);
    }
}