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:com.aol.webservice_base.util.http.HttpHelper.java

/**
 * Gets the http request./*  www.  j  ava2s.  c  om*/
 *
 * @param requestMethod the request method
 * @param url the url
 * @param content the content
 * @return the http request
 * @throws HttpException the http exception
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
private HttpRequestBase getHttpRequest(String requestMethod, String url, Object content)
        throws HttpException, UnsupportedEncodingException {
    HttpRequestBase httpRequest = null;

    if (requestMethod.equalsIgnoreCase("GET")) {
        httpRequest = new HttpGet(url);
    } else if (requestMethod.equalsIgnoreCase("POST")) {
        HttpPost postMethod = new HttpPost(url);
        if (content != null) {
            if (content instanceof byte[]) {
                postMethod.setEntity(new ByteArrayEntity((byte[]) content));
            } else if (content instanceof String) {
                postMethod.setEntity(new StringEntity((String) content, REQUEST_CONTENT_TYPE, REQUEST_CHARSET));
            } else {
                throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "content must be String or byte[]");
            }
            httpRequest = postMethod;
        }
    } else if (requestMethod.equalsIgnoreCase("DELETE")) {
        httpRequest = new HttpDelete(url);
    } else if (requestMethod.equalsIgnoreCase("PUT")) {
        HttpPut putMethod = new HttpPut(url);
        if (content != null) {
            if (content instanceof byte[]) {
                putMethod.setEntity(new ByteArrayEntity((byte[]) content));
            } else if (content instanceof String) {
                putMethod.setEntity(new StringEntity((String) content, REQUEST_CONTENT_TYPE, REQUEST_CHARSET));
            } else {
                throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "content must be String or byte[]");

            }
            httpRequest = putMethod;
        }
    } else {
        throw new HttpException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "Unsupported request method [" + requestMethod + "]");
    }
    return httpRequest;

}

From source file:net.ymate.platform.webmvc.WebMVC.java

public void processRequest(IRequestContext context, ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    StopWatch _consumeTime = null;//from   ww w. j a  v  a 2  s  .  c o  m
    long _threadId = Thread.currentThread().getId();
    try {
        if (__owner.getConfig().isDevelopMode()) {
            _consumeTime = new StopWatch();
            _consumeTime.start();
        }
        _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":"
                + context.getRequestMapping());
        //
        RequestMeta _meta = __mappingParser.doParse(context);
        if (_meta != null) {
            //
            _LOG.debug("--- [" + _threadId + "] Request mode: controller");
            // ????
            if (_meta.allowHttpMethod(context.getHttpMethod())) {
                // ?
                Map<String, String> _allowMap = _meta.getAllowHeaders();
                for (Map.Entry<String, String> _entry : _allowMap.entrySet()) {
                    String _value = WebContext.getRequest().getHeader(_entry.getKey());
                    if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) {
                        if (StringUtils.isBlank(_value)) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                            //
                            _LOG.debug("--- [" + _threadId + "] Check request allowed: NO");
                            return;
                        }
                    } else {
                        if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                            //
                            _LOG.debug("--- [" + _threadId + "] Check request allowed: NO");
                            return;
                        }
                    }
                }
                // ??
                _allowMap = _meta.getAllowParams();
                for (Map.Entry<String, String> _entry : _allowMap.entrySet()) {
                    if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) {
                        if (!WebContext.getRequest().getParameterMap().containsKey(_entry.getKey())) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                            //
                            _LOG.debug("--- [" + _threadId + "] Check request allowed: NO");
                            return;
                        }
                    } else {
                        String _value = WebContext.getRequest().getParameter(_entry.getKey());
                        if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                            //
                            _LOG.debug("--- [" + _threadId + "] Check request allowed: NO");
                            return;
                        }
                    }
                }
                // ???
                if (context.getHttpMethod().equals(Type.HttpMethod.POST)
                        && _meta.getMethod().isAnnotationPresent(FileUpload.class)) {
                    if (!(request instanceof IMultipartRequestWrapper)) {
                        // ?????
                        request = new MultipartRequestWrapper(this, request);
                    }
                    //
                    _LOG.debug("--- [" + _threadId + "] Include file upload: YES");
                }
                WebContext.getContext().addAttribute(Type.Context.HTTP_REQUEST, request);
                //
                IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_meta.getResponseCache());
                IView _view = null;
                // ??
                if (_cacheProcessor != null) {
                    // ?
                    if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, null)) {
                        // ?, 
                        _view = View.nullView();
                        //
                        _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES");
                    }
                }
                if (_view == null) {
                    _view = RequestExecutor.bind(this, _meta).execute();
                    if (_view != null) {
                        if (_cacheProcessor != null) {
                            try {
                                // ?
                                if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(),
                                        context, _view)) {
                                    _view = View.nullView();
                                    //
                                    _LOG.debug("--- [" + _threadId + "] Results data cached: YES");
                                }
                            } catch (Exception e) {
                                // ????, 
                                _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e));
                            }
                        }
                        _view.render();
                    } else {
                        HttpStatusView.NOT_FOUND.render();
                    }
                } else {
                    _view.render();
                }
            } else {
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        } else if (__moduleCfg.isConventionMode()) {
            boolean _isAllowConvention = true;
            if (!__moduleCfg.getConventionViewNotAllowPaths().isEmpty()) {
                for (String _vPath : __moduleCfg.getConventionViewNotAllowPaths()) {
                    if (context.getRequestMapping().startsWith(_vPath)) {
                        _isAllowConvention = false;
                        break;
                    }
                }
            }
            if (_isAllowConvention && !__moduleCfg.getConventionViewAllowPaths().isEmpty()) {
                _isAllowConvention = false;
                for (String _vPath : __moduleCfg.getConventionViewAllowPaths()) {
                    if (context.getRequestMapping().startsWith(_vPath)) {
                        _isAllowConvention = true;
                        break;
                    }
                }
            }
            if (_isAllowConvention) {
                //
                _LOG.debug("--- [" + _threadId + "] Request mode: convention");
                //
                IView _view = null;
                ResponseCache _responseCache = null;
                if (__interceptorRuleProcessor != null) {
                    // ?Convention
                    PairObject<IView, ResponseCache> _result = __interceptorRuleProcessor.processRequest(this,
                            context);
                    _view = _result.getKey();
                    _responseCache = _result.getValue();
                }
                // ??
                IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_responseCache);
                // ??
                if (_cacheProcessor != null) {
                    // ?
                    if (_cacheProcessor.processResponseCache(this, _responseCache, context, null)) {
                        // ?, 
                        _view = View.nullView();
                        //
                        _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES");
                    }
                }
                if (_view == null) {
                    // ?Convention?URL??
                    String _requestMapping = context.getRequestMapping();
                    String[] _urlParamArr = getModuleCfg().isConventionUrlrewriteMode()
                            ? StringUtils.split(_requestMapping, '_')
                            : new String[] { _requestMapping };
                    if (_urlParamArr != null && _urlParamArr.length > 1) {
                        _requestMapping = _urlParamArr[0];
                        List<String> _urlParams = Arrays.asList(_urlParamArr).subList(1, _urlParamArr.length);
                        WebContext.getRequest().setAttribute("UrlParams", _urlParams);
                        //
                        _LOG.debug("--- [" + _threadId + "] With parameters : " + _urlParams);
                    }
                    //
                    if (__moduleCfg.getErrorProcessor() != null) {
                        _view = __moduleCfg.getErrorProcessor().onConvention(this, context);
                    }
                    if (_view == null) {
                        // ???URL
                        String[] _fileTypes = { ".html", ".jsp", ".ftl", ".vm" };
                        for (String _fileType : _fileTypes) {
                            File _targetFile = new File(__moduleCfg.getAbstractBaseViewPath(),
                                    _requestMapping + _fileType);
                            if (_targetFile.exists()) {
                                if (".html".equals(_fileType)) {
                                    _view = HtmlView.bind(this, _requestMapping.substring(1));
                                    //
                                    _LOG.debug("--- [" + _threadId + "] Rendering template file : "
                                            + _requestMapping + _fileType);
                                    break;
                                } else if (".jsp".equals(_fileType)) {
                                    _view = JspView.bind(this, _requestMapping.substring(1));
                                    //
                                    _LOG.debug("--- [" + _threadId + "] Rendering template file : "
                                            + _requestMapping + _fileType);
                                    break;
                                } else if (".ftl".equals(_fileType)) {
                                    _view = FreemarkerView.bind(this, _requestMapping.substring(1));
                                    //
                                    _LOG.debug("--- [" + _threadId + "] Rendering template file : "
                                            + _requestMapping + _fileType);
                                    break;
                                } else if (".vm".equals(_fileType)) {
                                    _view = VelocityView.bind(this, _requestMapping.substring(1));
                                    //
                                    _LOG.debug("--- [" + _threadId + "] Rendering template file : "
                                            + _requestMapping + _fileType);
                                }
                            }
                        }
                    }
                    //
                    if (_view != null && _cacheProcessor != null) {
                        try {
                            if (_cacheProcessor.processResponseCache(this, _responseCache, context, _view)) {
                                _view = View.nullView();
                                //
                                _LOG.debug("--- [" + _threadId + "] Results data cached: YES");
                            }
                        } catch (Exception e) {
                            // ????, 
                            _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e));
                        }
                    }
                }
                if (_view != null) {
                    _view.render();
                } else {
                    HttpStatusView.NOT_FOUND.render();
                }
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } finally {
        if (_consumeTime != null && __owner.getConfig().isDevelopMode()) {
            _consumeTime.stop();
            _LOG.debug("--- [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms");
        }
        _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":"
                + context.getRequestMapping());
    }
}

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

/**
 * Handles the request for a simple url available somewhere in the system. The
 * handler sets the response type, does the url history and then forwards
 * request to the corresponding JSP page or XSLT stylesheet.
 * <p>//from  w w w.j  a va2  s .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) {

    logger.debug("Page handler agrees to handle {}", request.getUrl());

    Mode processingMode = Mode.Default;
    WebUrl url = request.getUrl();
    String path = url.getPath();
    RequestFlavor contentFlavor = request.getFlavor();

    if (contentFlavor == null || contentFlavor.equals(ANY))
        contentFlavor = RequestFlavor.HTML;

    // Check the request flavor
    // TODO: Criteria would be loading the page from the repository
    // TODO: Think about performance, page lookup is expensive
    if (!HTML.equals(contentFlavor)) {
        logger.debug("Skipping request for {}, flavor {} is not supported", path, request.getFlavor());
        return false;
    }

    // Determine the editing state
    boolean isEditing = RequestUtils.isEditingState(request);

    // Check if the request is controlled by an action.
    Action action = (Action) request.getAttribute(WebloungeRequest.ACTION);

    // Get the renderer id that has been registered with the url. For this,
    // we first have to load the page data, then get the associated renderer
    // bundle.
    try {
        Page page = null;
        ResourceURI pageURI = null;
        Site site = request.getSite();

        // Check if a page was passed as an attribute
        if (request.getAttribute(WebloungeRequest.PAGE) != null) {
            page = (Page) request.getAttribute(WebloungeRequest.PAGE);
            pageURI = page.getURI();
        }

        // Load the page from the content repository
        else {
            ContentRepository contentRepository = site.getContentRepository();
            if (contentRepository == null) {
                logger.debug("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;
            }

            ResourceURI requestURI = null;
            ResourceURI requestedURI = null;

            // Load the page. Note that we are taking care of the special case where
            // a user may have created a page with a url that matches a valid
            // language identifier, in which case it would have been stripped from
            // request.getUrl().
            try {
                if (action != null) {
                    pageURI = getPageURIForAction(action, request);
                    requestURI = pageURI;
                } else if (path.startsWith(URI_PREFIX)) {
                    String uriSuffix = StringUtils.substringBefore(path.substring(URI_PREFIX.length()), "/");
                    uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");
                    ResourceURI uri = new PageURIImpl(site, null, uriSuffix, request.getVersion());
                    requestURI = uri;
                    WebUrl requestedUrl = request.getRequestedUrl();
                    if (requestedUrl.hasLanguagePathSegment()) {
                        String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier());
                        String requestedUriSuffix = StringUtils
                                .substringBefore(requestedPath.substring(URI_PREFIX.length()), "/");
                        requestedUriSuffix = URLDecoder.decode(requestedUriSuffix, "utf-8");
                        requestedURI = new PageURIImpl(site, requestedUriSuffix, null, request.getVersion());
                    }
                } else {
                    long version = isEditing ? Resource.WORK : Resource.LIVE;
                    ResourceURI uri = new PageURIImpl(request);
                    uri.setVersion(version);
                    requestURI = uri;
                    WebUrl requestedUrl = request.getRequestedUrl();
                    if (requestedUrl.hasLanguagePathSegment()) {
                        String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier());
                        requestedPath = URLDecoder.decode(requestedPath, "utf-8");
                        requestedURI = new PageURIImpl(site, requestedPath, null, version);
                    }
                }

                // Is this a request with potential path clashes?
                if (requestedURI != null) {
                    long version = requestedURI.getVersion();
                    if (contentRepository.existsInAnyVersion(requestedURI)) {
                        if (!isEditing && version == Resource.LIVE && contentRepository.exists(requestedURI)) {
                            pageURI = requestedURI;
                            ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
                        } else if (isEditing && version == Resource.WORK
                                && !contentRepository.exists(requestedURI)) {
                            requestedURI.setVersion(Resource.LIVE);
                            pageURI = requestedURI;
                            ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
                        } else if (isEditing && version == Resource.WORK
                                && !contentRepository.exists(requestedURI)) {
                            pageURI = requestedURI;
                            ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage());
                        }
                    }
                }

                // Does the page exist?
                if (pageURI == null && contentRepository.existsInAnyVersion(requestURI)) {
                    long version = requestURI.getVersion();

                    // If the work version is requested, we need to make sure
                    // a) it exists and b) the user is in editing mode
                    if (version == Resource.WORK && isEditing) {
                        if (contentRepository.exists(requestURI)) {
                            pageURI = requestURI;
                        } else {
                            requestURI.setVersion(Resource.LIVE);
                            if (contentRepository.exists(requestURI))
                                pageURI = requestURI;
                        }
                    } else if (contentRepository.exists(requestURI)) {
                        pageURI = requestURI;
                    }
                }

                // Did we find a matching uri?
                if (pageURI == null) {
                    DispatchUtils.sendNotFound(request, response);
                    return true;
                }

                page = (Page) contentRepository.get(pageURI);
                if (page == null) {
                    DispatchUtils.sendNotFound(request, response);
                    return true;
                }
            } catch (ContentRepositoryException e) {
                logger.error("Unable to load page {} from {}: {}",
                        new Object[] { pageURI, contentRepository, e.getMessage(), e });
                DispatchUtils.sendInternalError(request, response);
                return true;
            }
        }

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

        // Is it published?
        if (!page.isPublished() && !(page.getVersion() == Resource.WORK)) {
            logger.debug("Access to unpublished page {}", pageURI);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            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("Accessed to page {} denied for user {}", pageURI, user);
            DispatchUtils.sendAccessDenied(request, response);
            return true;
        }

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

        // Check if the page is already part of the cache. If so, our task is
        // already done!
        if (!ignoreCache && request.getVersion() == Resource.LIVE && !isEditing) {

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

            if (action == null) {
                long expirationTime = Renderer.DEFAULT_VALID_TIME;
                long revalidationTime = Renderer.DEFAULT_RECHECK_TIME;

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

            processingMode = Mode.Cached;
            cacheTags.add(CacheTag.Resource, page.getURI().getIdentifier());
            response.addTags(cacheTags);

        } else if (Http11Constants.METHOD_HEAD.equals(requestMethod)) {
            // handle HEAD requests
            Http11Utils.startHeadResponse(response);
            processingMode = Mode.Head;
        } else if (request.getVersion() == Resource.WORK) {
            response.setCacheExpirationTime(0);
        }

        // Set the default maximum render and valid times for pages
        response.setClientRevalidationTime(Renderer.DEFAULT_RECHECK_TIME);
        response.setCacheExpirationTime(Renderer.DEFAULT_VALID_TIME);

        // Store the page in the request
        request.setAttribute(WebloungeRequest.PAGE, page);

        // Get hold of the page template
        PageTemplate template = null;
        try {
            template = getPageTemplate(page, request);
            template.setEnvironment(request.getEnvironment());
        } catch (IllegalStateException e) {
            logger.debug(e.getMessage());
            DispatchUtils.sendInternalError(request, response);
            return true;
        }

        // Does the template support the requested flavor?
        if (!template.supportsFlavor(contentFlavor)) {
            logger.warn("Template '{}' does not support requested flavor {}", template, contentFlavor);
            DispatchUtils.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, request, response);
            return true;
        }

        // Suggest a last modified data. Note that this may not be the final date
        // as the page may contain content embedded from other pages that feature
        // more recent modification dates
        response.setModificationDate(page.getLastModified());

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

        // Add the template's HTML header elements to the response if it's not
        // only used in editing mode
        for (HTMLHeadElement header : template.getHTMLHeaders()) {
            if (!HTMLInclude.Use.Editor.equals(header.getUse()))
                response.addHTMLHeader(header);
        }

        // Select the actual renderer by method and have it render the
        // request. Since renderers are being pooled by the bundle, we
        // have to return it after the request has finished.
        try {
            logger.debug("Rendering {} using page template '{}'", path, template);
            template.render(request, response);
        } catch (Throwable t) {
            String params = RequestUtils.dumpParameters(request);
            String msg = "Error rendering template '" + template + "' on '" + path + "' " + params;
            Throwable o = t.getCause();
            if (o != null) {
                msg += ": " + o.getMessage();
                logger.error(msg, o);
            } else {
                logger.error(msg, t);
            }
            DispatchUtils.sendInternalError(request, response);
        }

        return true;
    } catch (EOFException e) {
        logger.debug("Error writing page '{}' back to client: connection closed by client", url);
        return true;
    } catch (IOException e) {
        logger.error("I/O exception while sending error status: {}", e.getMessage(), e);
        return true;
    } finally {
        if (action == null) {
            switch (processingMode) {
            case Cached:
                response.endResponse();
                break;
            case Head:
                Http11Utils.endHeadResponse(response);
                break;
            default:
                break;
            }
        }
    }
}

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

/**
 * Handles an HTTP request for a {@link #VERSION_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. j a v  a  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 handleVersionJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (GET_HTTP_METHOD.equals(request.getMethod())) {
        // Get the Version of the associated server/service.
        doGetVersionJSON(baseRequest, request, response);
    } else {
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;//from  www. j  a v  a  2  s.  co m
    String language;
    String redirect_url;

    this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("QueryString = " + httpServletRequest.getQueryString());

    String service = "";
    String authorization = "";

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

    if (params.length == 1) {
        service = params[0];
    }

    format = "html";
    language = "";

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

        String headerNameKey = (String) headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Accept")) {

            this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

            if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
        if (headerNameKey.equals("Accept-Language")) {
            language = httpServletRequest.getHeader(headerNameKey);
            this.logger.debug("Accept-Language: " + language);
        }
        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.debug("Service: " + service);

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

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

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

        this.sendRequestError(httpServletResponse, requestError, format, language, "");
    } else {

        // redirect_url
        redirect_url = "";

        if (httpServletRequest.getParameter("redirect_url") != null
                && !httpServletRequest.getParameter("redirect_url").equals("")) {

            if (httpServletRequest.getParameter("redirect_url").contains("redirect_url=")) {
                String tmp[] = httpServletRequest.getParameter("redirect_url").split("redirect_url=");

                redirect_url = tmp[0] + "redirect_url=" + URLEncoder.encode(tmp[1], "UTF-8");
            } else {
                redirect_url = httpServletRequest.getParameter("redirect_url");
            }
        }

        this.logger.info("redirect_url = " + redirect_url);

        // language
        if (language.startsWith("de")) {
            language = "de";
        } else if (language.startsWith("en")) {
            language = "en";
        } else if (httpServletRequest.getParameter("l") != null) {
            language = httpServletRequest.getParameter("l");
        } else {
            language = "de";
        }

        this.logger.info("language = " + language);

        if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null) {

            authorization = httpServletRequest.getParameter("access_token");
        }

        if (authorization.equals("")) {

            // if exists PaiaService-Cookie: read content
            Cookie[] cookies = httpServletRequest.getCookies();

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("PaiaService")) {

                        String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                        this.logger.info(value);
                        LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                        authorization = loginResponse.getAccess_token();

                        break;
                    }
                }
            }
        }

        this.logger.debug("Access_token: " + authorization);

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        this.logger.info(requestBody);

        httpServletResponse.setHeader("Access-Control-Allow-Origin",
                this.config.getProperty("Access-Control-Allow-Origin"));
        httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));

        // 2. Schritt: Service
        if (service.equals("login") || service.equals("logout") || service.equals("change")
                || service.equals("renew")) {

            this.provideService(httpServletRequest, httpServletResponse, service, authorization, requestBody,
                    format, language, redirect_url);
        } else {

            this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service
                    + "' not allowed!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                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"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }
    }
}

From source file:com.redhat.jenkins.nodesharingbackend.Api.java

/**
 * Return node to orchestrator when no longer needed.
 */// w  w w  .  j a v a2 s .  co m
@RequirePOST
public void doReturnNode(@Nonnull final StaplerRequest req, @Nonnull final StaplerResponse rsp)
        throws IOException {
    Jenkins.getActiveInstance().checkPermission(RestEndpoint.RESERVE);

    String ocr = Pool.getInstance().getConfigRepoUrl(); // Fail early when there is no config
    ReturnNodeRequest request = Entity.fromInputStream(req.getInputStream(), ReturnNodeRequest.class);
    String ecr = request.getConfigRepoUrl();
    if (!Objects.equals(ocr, ecr)) { // TODO we do not require this anywhere else, should we?
        rsp.getWriter().println("Unable to return node - config repo mismatch " + ocr + " != " + ecr);
        rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    Jenkins jenkins = Jenkins.getActiveInstance();
    Computer c = jenkins.getComputer(request.getNodeName());
    if (c == null) {
        LOGGER.info("An attempt to return a node '" + request.getNodeName() + "' that does not exist by "
                + request.getExecutorUrl());
        rsp.getWriter().println("No shareable node named '" + request.getNodeName() + "' exists");
        rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (!(c instanceof ShareableComputer)) {
        LOGGER.warning("An attempt to return a node '" + request.getNodeName() + "' that is not reservable by "
                + request.getExecutorUrl());
        rsp.getWriter().println("No shareable node named '" + request.getNodeName() + "' exists");
        rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    ShareableComputer computer = (ShareableComputer) c;
    ReservationTask.ReservationExecutable executable = computer.getReservation();
    if (executable == null) {
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    String reservationOwnerUrl = executable.getParent().getOwner().getUrl().toExternalForm();
    if (!reservationOwnerUrl.equals(request.getExecutorUrl())) {
        rsp.getWriter().println("Executor '" + request.getExecutorUrl() + "' is not an owner of the host");
        rsp.setStatus(HttpServletResponse.SC_CONFLICT);
        return;
    }

    executable.complete();
    // TODO Report status
    rsp.setStatus(HttpServletResponse.SC_OK);
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadHandler.java

@Override
public void handle(String s, Request request, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {
    ServletOutputStream responseStream = null;
    String origin = httpRequest.getHeader("Origin"); // CORS request should have Origin header
    int statusCode = HttpServletResponse.SC_OK;

    // Origin header indicates a possible CORS requests
    if (origin != null) {
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // Needed to allow cookies
    } else {/* w w  w .  j  a va  2 s  .  c o m*/
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    }

    if (request != null) // In case handler is not called thru jetty
        request.setHandled(true);

    String method = httpRequest.getMethod();
    String sessionID = SessionService.getJSessionIDFromRequest(httpRequest);
    log.info("ID:" + Thread.currentThread().getId() + " User:" + httpRequest.getParameter("username") + " host:"
            + EPADSessionOperations.getSessionHost(sessionID) + " method:" + httpRequest.getMethod() + ", url: "
            + httpRequest.getPathInfo() + ", parameters: " + httpRequest.getQueryString() + " sessionId:"
            + sessionID);
    if ("GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method)) {
        try {
            if (sessionID == null || sessionID.length() == 0) {
                log.warning("JSESSIONID is Missing in client request");
                statusCode = HandlerUtil.invalidTokenJSONResponse(INVALID_SESSION_TOKEN_MESSAGE,
                        httpResponse.getWriter(), log);
            } else {
                String username = httpRequest.getParameter("username");
                responseStream = httpResponse.getOutputStream();

                if (SessionService.hasValidSessionID(httpRequest)) {
                    String[] filePaths = httpRequest.getParameterValues("filePath");
                    DownloadUtil.downloadFiles(httpResponse, filePaths, username);
                } else {
                    statusCode = HandlerUtil.invalidTokenResponse(INVALID_SESSION_TOKEN_MESSAGE, log);
                }
            }
        } catch (Throwable t) {
            statusCode = HandlerUtil.internalErrorResponse(INTERNAL_EXCEPTION_MESSAGE, log);
            log.warning("Error is Resources query", t);
        }
    } else {
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
        statusCode = HandlerUtil.warningResponse(HttpServletResponse.SC_METHOD_NOT_ALLOWED, INVALID_METHOD,
                log);
    }
    httpResponse.setStatus(statusCode);
}

From source file:edu.stanford.epad.epadws.handlers.dicom.WadoHandler.java

@Override
public void handle(String s, Request request, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {
    ServletOutputStream responseStream = null;
    String origin = httpRequest.getHeader("Origin"); // CORS request should have Origin header
    int statusCode;

    // Origin header indicates a possible CORS requests
    if (origin != null) {
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // Needed to allow cookies
    } else {/*from w  w  w.  ja  v a  2  s.  c  o m*/
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    }

    if (httpRequest.getQueryString().indexOf("dicom") != -1)
        httpResponse.setContentType("application/octet-stream");
    else
        httpResponse.setContentType("image/jpeg");

    if (request != null) // In case handler is not called thru jetty
        request.setHandled(true);

    String method = httpRequest.getMethod();
    if ("GET".equalsIgnoreCase(method)) {
        try {
            String sessionID = SessionService.getJSessionIDFromRequest(httpRequest);
            if (sessionID == null || sessionID.length() == 0) {
                log.warning("JSESSIONID is Missing in client request");
                //statusCode = HandlerUtil.invalidTokenJSONResponse(INVALID_SESSION_TOKEN_MESSAGE, httpResponse.getWriter(), log);
            }
            String username = httpRequest.getParameter("username");
            responseStream = httpResponse.getOutputStream();

            // if (XNATOperations.hasValidXNATSessionID(httpRequest)) {
            if (dummy()) { // TODO Re-enable authentication
                String queryString = httpRequest.getQueryString();
                queryString = URLDecoder.decode(queryString, "UTF-8");
                if (queryString != null) {
                    statusCode = performWADOQuery(queryString, responseStream, username, sessionID);
                } else {
                    statusCode = HandlerUtil.badRequestResponse(MISSING_QUERY_MESSAGE, log);
                    log.warning("Missing Wado query");
                }
            } else {
                statusCode = HandlerUtil.invalidTokenResponse(INVALID_SESSION_TOKEN_MESSAGE, log);
            }
            //}
        } catch (Throwable t) {
            statusCode = HandlerUtil.internalErrorResponse(INTERNAL_EXCEPTION_MESSAGE, log);
            log.warning("Error is Wado query", t);
        }
    } else {
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
        statusCode = HandlerUtil.warningResponse(HttpServletResponse.SC_METHOD_NOT_ALLOWED, INVALID_METHOD,
                log);
    }
    httpResponse.setStatus(statusCode);
}

From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java

/**
 * Method generateResponse.//  w w  w  .  j  ava 2 s  .c  o  m
 * 
 * @param resp
 * @param type
 * @param is
 * @return boolean
 * @throws IOException
 *           if generating the response fails
 */
public static boolean generateResponse(HttpServletResponse resp, Http11ResponseType type, InputStream is)
        throws IOException {

    /* first generate the response headers */
    generateHeaders(resp, type);

    /* adjust the statistics */
    ++stats[STATS_BODY_GENERATED];
    incResponseStats(type.type, bodyStats);

    /* generate the response body */
    try {
        if (resp.isCommitted())
            log.warn("Response is already committed!");
        switch (type.type) {
        case RESPONSE_OK:
            if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = null;
                try {
                    os = resp.getOutputStream();
                    IOUtils.copy(is, os);
                } catch (IOException e) {
                    if (RequestUtils.isCausedByClient(e))
                        return true;
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
            break;

        case RESPONSE_PARTIAL_CONTENT:
            if (type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Invalid partial content parameters");
                log.warn("Invalid partial content parameters");
            } else if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = resp.getOutputStream();
                if (is.skip(type.from) != type.from) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Premature end of input stream");
                    log.warn("Premature end of input stream");
                    break;
                }
                try {

                    /* get the temporary buffer for this thread */
                    byte[] tmp = buffer.get();
                    if (tmp == null) {
                        tmp = new byte[BUFFER_SIZE];
                        buffer.set(tmp);
                    }

                    int read = type.to - type.from;
                    int copy = read;
                    int write = 0;

                    read = is.read(tmp);
                    while (copy > 0 && read >= 0) {
                        copy -= read;
                        write = copy > 0 ? read : read + copy;
                        os.write(tmp, 0, write);
                        stats[STATS_BYTES_WRITTEN] += write;
                        read = is.read(tmp);
                    }
                    if (copy > 0) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Premature end of input stream");
                        log.warn("Premature end of input stream");
                        break;
                    }
                    os.flush();
                    os.close();
                } catch (SocketException e) {
                    log.debug("Request cancelled by client");
                }
            }
            break;

        case RESPONSE_NOT_MODIFIED:
            /* NOTE: we MUST NOT return any content (RFC 2616)!!! */
            break;

        case RESPONSE_PRECONDITION_FAILED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            else
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, type.err);
            break;

        case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            else
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, type.err);
            break;

        case RESPONSE_METHOD_NOT_ALLOWED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            else
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, type.err);
            break;

        case RESPONSE_INTERNAL_SERVER_ERROR:
        default:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            else
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, type.err);
        }
    } catch (IOException e) {
        if (e instanceof EOFException) {
            log.debug("Request canceled by client");
            return true;
        }
        ++stats[STATS_ERRORS];
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        log.warn("I/O exception while sending response: {}", message, cause);
        throw e;
    }

    return true;
}

From source file:org.apache.archiva.webdav.RepositoryServletRepositoryGroupTest.java

protected void assertResponseMethodNotAllowed(WebResponse response) {

    assertThat(response).isNotNull();

    assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}