Example usage for javax.servlet.http HttpServletRequest getMethod

List of usage examples for javax.servlet.http HttpServletRequest getMethod

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getMethod.

Prototype

public String getMethod();

Source Link

Document

Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.

Usage

From source file:com.xpn.xwiki.web.XWikiPortlet.java

protected HttpServletRequest processMultipart(HttpServletRequest request) {
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        return (request);
    }/*from ww w. j  a v  a2s  .  c  o m*/

    String contentType = request.getContentType();

    if ((contentType != null) && contentType.startsWith("multipart/form-data")) {
        return (new MultipartRequestWrapper(request));
    } else {
        return (request);
    }
}

From source file:org.ktunaxa.referral.server.mvc.ProxyController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/proxy")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new HttpClient();
    try {//  www  . j a  va 2 s.  co m

        HttpMethod method = null;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {

            method = new GetMethod(url);
            NameValuePair[] pairs = new NameValuePair[request.getParameterMap().size()];
            int i = 0;
            for (Object name : request.getParameterMap().keySet()) {
                pairs[i++] = new NameValuePair((String) name, request.getParameter((String) name));
            }
            method.setQueryString(pairs);

        } else if ("POST".equals(request.getMethod())) {

            method = new PostMethod(url);

            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {

                String paramName = (String) paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }

        } else {

            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if (header.getName().equalsIgnoreCase("Content-Type")) {

                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        response.getOutputStream().write(method.getResponseBody());

    } catch (HttpException e) {

        // log.error("Oops, something went wrong in the HTTP proxy", null, e);
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;

    } catch (IOException e) {

        e.printStackTrace();
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;
    }
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * ?//from ww  w. java  2  s.c o m
 * (PATCH ?????? HttpServlet.service() ?)
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    if (method.equals("GET")) {
        doGet(request, response);
    } else if (method.equals("POST")) {
        doPost(request, response);
    } else if (method.equals("PUT")) {
        doPut(request, response);
    } else if (method.equals("PATCH")) {
        doPatch(request, response);
    } else if (method.equals("DELETE")) {
        doDelete(request, response);
    } else {
        this.errorResponse(response, HttpServletResponse.SC_FORBIDDEN, null,
                MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
    }
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;/*from w  w  w .  j a va  2s  .c  o m*/

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:cz.jirutka.spring.exhandler.handlers.AbstractRestExceptionHandler.java

/**
 * Logs the exception; on ERROR level when status is 5xx, otherwise on INFO level without stack
 * trace, or DEBUG level with stack trace. The logger name is
 * {@code cz.jirutka.spring.exhandler.handlers.RestExceptionHandler}.
 *
 * @param ex The exception to log./*from  w  w w  .  ja  v a 2  s.c  om*/
 * @param req The current web request.
 */
protected void logException(E ex, HttpServletRequest req) {

    if (LOG.isErrorEnabled() && getStatus().value() >= 500 || LOG.isInfoEnabled()) {
        Marker marker = MarkerFactory.getMarker(ex.getClass().getName());

        String uri = req.getRequestURI();
        if (req.getQueryString() != null) {
            uri += '?' + req.getQueryString();
        }
        String msg = String.format("%s %s ~> %s", req.getMethod(), uri, getStatus());

        if (getStatus().value() >= 500) {
            LOG.error(marker, msg, ex);

        } else if (LOG.isDebugEnabled()) {
            LOG.debug(marker, msg, ex);

        } else {
            LOG.info(marker, msg);
        }
    }
}

From source file:com.ar.dev.tierra.api.config.SimpleCORSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {//  ww  w  . j a  v a  2s . co m
        chain.doFilter(req, resp);
    }

}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

protected RPCRequest readRpcRequest(HttpServletRequest request) throws IOException, ServletException {
    RPCRequest rpcRequest;//from  w w  w  . j a v a 2  s.com

    rpcRequest = getRpcRequest(request);
    if (rpcRequest == null) {
        final String requestPayload;

        if (isPostOnly() && !POST_METHOD.equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        requestPayload = readContent(request);
        rpcRequest = RPC.decodeRequest(requestPayload, getServiceInterface(),
                new ExtendedSerializationPolicyProviderDelegate(getSerializationPolicyProvider(), request));
        request.setAttribute(GWT_RPC_REQUEST_ATTR_NAME, rpcRequest);
    }

    return rpcRequest;
}

From source file:com.hypersocket.server.handlers.impl.ContentHandlerImpl.java

@Override
public void handleHttpRequest(HttpServletRequest request, HttpServletResponse response,
        HttpResponseProcessor responseProcessor) throws IOException {

    try {/*from ww w.  j  a v  a  2s . c o  m*/
        if (request.getMethod() != HttpMethod.GET.toString()) {
            response.sendError(HttpStatus.SC_METHOD_NOT_ALLOWED);
            return;
        }

        String path = translatePath(sanitizeUri(request.getRequestURI()));
        if (path.startsWith("/"))
            path = path.substring(1);

        if (path == null) {
            response.sendError(HttpStatus.SC_FORBIDDEN);
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Resolving " + getResourceName() + " resource in " + basePath + ": "
                    + request.getRequestURI());
        }

        int status = getResourceStatus(path);

        if (status != HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Resource not found in " + basePath + " [" + status + "]: " + request.getRequestURI());
            }
            response.sendError(status);
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Resource found in " + basePath + ": " + request.getRequestURI());
        }

        // Cache Validation
        String ifModifiedSince = request.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
        if (ifModifiedSince != null && !ifModifiedSince.equals("")) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
            try {
                Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

                // Only compare up to the second because the datetime format we send to the client does
                // not have milliseconds
                long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
                long fileLastModifiedSeconds = getLastModified(path) / 1000;
                if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                    if (log.isDebugEnabled()) {
                        log.debug(path + " has not been modified since "
                                + HypersocketUtils.formatDateTime(ifModifiedSinceDate));
                    }
                    sendNotModified(response);
                    return;
                }
            } catch (Throwable e) {
                response.sendError(HttpStatus.SC_BAD_REQUEST);
                return;
            }
        }

        long fileLength = getResourceLength(path);
        long actualLength = 0;
        InputStream in = getInputStream(path, request);

        if (fileLength <= 131072) {
            int r;
            byte[] buf = new byte[4096];
            while ((r = in.read(buf)) > -1) {
                response.getOutputStream().write(buf, 0, r);
                if (fileLength < 0) {
                    actualLength += r;
                }

            }
            response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(actualLength));

        } else {
            request.setAttribute(CONTENT_INPUTSTREAM, in);
        }

        setContentTypeHeader(response, path);
        setDateAndCacheHeaders(response, path);

        response.setStatus(HttpStatus.SC_OK);
    } catch (RedirectException e) {
        response.sendRedirect(
                server.resolvePath(basePath + (e.getMessage().startsWith("/") ? "" : "/") + e.getMessage()));
    } finally {
        responseProcessor.sendResponse(request, response, false);
    }

}

From source file:com.tce.spring.oauth2.filters.CorsFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Authorization");
    response.setHeader("Access-Control-Max-Age", "3600");
    if (!"OPTIONS".equals(request.getMethod())) {
        filterChain.doFilter(request, response);
    } else {/*from w w w. ja v  a2  s  .  co  m*/
    }
}