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:org.geomajas.gwt2.example.base.server.mvc.AjaxProxyController.java

@RequestMapping(value = "/")
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 DefaultHttpClient();
    try {//from   w ww.j av  a 2  s . c o m
        HttpRequestBase proxyRequest;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!paramName.equalsIgnoreCase("url")) {
                    url = addParam(url, paramName, request.getParameter(paramName));
                }
            }

            proxyRequest = new HttpGet(url);
        } else if ("POST".equals(request.getMethod())) {
            proxyRequest = new HttpPost(url);

            // Set any eventual parameters that came with our original
            HttpParams params = new BasicHttpParams();
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!"url".equalsIgnoreCase("url")) {
                    params.setParameter(paramName, request.getParameter(paramName));
                }
            }
            proxyRequest.setParams(params);
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        HttpResponse proxyResponse = client.execute(proxyRequest);

        // Set the content type, as it comes from the server
        Header[] headers = proxyResponse.getAllHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.jasig.cas.support.pac4j.web.flow.ClientBackChannelAction.java

private void log(HttpServletRequest request) {

    logger.debug("=========================================================");
    logger.debug("ClientBackChannelAction.doExecute: ");
    logger.debug("request.method: " + request.getMethod());
    logger.debug("request.requestURI: " + request.getRequestURI());
    logger.debug("request.queryString: " + request.getQueryString());
    logger.debug("request. host port remoteaddress: " + request.getRemoteHost() + " " + request.getRemotePort()
            + " " + request.getRemoteAddr());
    logger.debug("request. parameter:");
    Enumeration enParams = request.getParameterNames();
    while (enParams.hasMoreElements()) {
        String paramName = (String) enParams.nextElement();
        logger.debug(paramName + ": " + request.getParameter(paramName));
    }//from   ww  w. j  a va 2s .com

    logger.debug("request. attribute:");
    Enumeration enParams2 = request.getAttributeNames();
    while (enParams2.hasMoreElements()) {
        String paramName2 = (String) enParams2.nextElement();
        logger.debug(paramName2 + ": " + request.getAttribute(paramName2));
    }
    logger.debug("=========================================================");
}

From source file:org.openbaton.nfvo.security.authentication.SimpleCorsFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "x-requested-with, authorization, content-type, Cache-Control");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {//ww w  . j  ava2 s. c o m
        chain.doFilter(req, res);
    }
}

From source file:com.iflytek.edu.cloud.frame.support.ServiceRequestLogging.java

/**
 * @param request//w  w  w  .j  av a2 s .  co m
 * @param response
 */
public void recoredLog(HttpServletRequest request, HttpServletResponse response) {
    String clientIp = ServiceUtil.getRemoteAddr(request);
    String locale = ((Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE)).getDisplayName();
    String format = (String) request.getAttribute(Constants.SYS_PARAM_KEY_FORMAT);
    String appkey = (String) request.getParameter(Constants.SYS_PARAM_KEY_APPKEY);
    String httpMethod = request.getMethod();
    String serviceMethod = request.getParameter(Constants.SYS_PARAM_KEY_METHOD);
    String serviceVersion = request.getParameter(Constants.SYS_PARAM_KEY_VERSION);
    int responseStatus = response.getStatus();
    Long requestTimeMillis = (Long) request.getAttribute(ServiceMetricsFilter.SERVICE_EXEC_TIME);

    String mainErrorCode = (String) request.getAttribute(Constants.MAIN_ERROR_CODE);

    RestContext context = RestContextHolder.getContext();
    if (StringUtils.hasText(mainErrorCode)) {
        LOGGER.warn("service request information : mainErrorCode={}, clientIp={}, httpMethod={}, locale={},"
                + " appkey={}, serviceMethod={}, serviceVersion={}, format={}, responseStatus={}, requestTimeMillis={},"
                + " callCycoreCount={}, callCycoreTime={}", mainErrorCode, clientIp, httpMethod, locale, appkey,
                serviceMethod, serviceVersion, format, responseStatus, requestTimeMillis,
                context.getCallCycoreCount(), context.getCallCycoreTime());
    } else {
        LOGGER.info("service request information : clientIp={}, httpMethod={}, locale={},"
                + " appkey={}, serviceMethod={}, serviceVersion={}, format={}, responseStatus={}, requestTimeMillis={}"
                + " callCycoreCount={}, callCycoreTime={}", clientIp, httpMethod, locale, appkey, serviceMethod,
                serviceVersion, format, responseStatus, requestTimeMillis, context.getCallCycoreCount(),
                context.getCallCycoreTime());
    }
}

From source file:org.nubomedia.marketplace.api.SimpleCorsFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    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",
            "Auth-token, x-requested-with, authorization, content-type, origin");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {//from  w  w  w .j av  a 2s  .c o  m
        chain.doFilter(req, res);
    }
}

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())//from   w  ww.  j  a  v  a2 s .  c  o m
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}

From source file:com.flipkart.poseidon.filters.RequestGzipFilter.java

@Override
public void doFilter(final ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest servletRequest = (HttpServletRequest) request;
    HttpServletResponse servletResponse = (HttpServletResponse) response;
    boolean isGzipped = servletRequest.getHeader(HttpHeaders.CONTENT_ENCODING) != null
            && servletRequest.getHeader(HttpHeaders.CONTENT_ENCODING).contains("gzip");
    boolean requestTypeSupported = HttpMethod.POST.toString().equals(servletRequest.getMethod())
            || HttpMethod.PUT.toString().equals(servletRequest.getMethod())
            || HttpMethod.PATCH.toString().equals(servletRequest.getMethod());
    if (isGzipped && !requestTypeSupported) {
        throw new IllegalStateException(new StringBuilder().append(servletRequest.getMethod())
                .append(" is not supports gzipped body of parameters.")
                .append(" Only POST requests are currently supported.").toString());
    }// w w  w. j  ava2 s . c om
    if (isGzipped) {
        servletRequest = new GzippedInputStreamWrapper(servletRequest);
    }
    chain.doFilter(servletRequest, servletResponse);
}

From source file:org.sakaiproject.lap.controller.MainController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    if (!fileService.isValidFileSystem()) {
        model.put("invalid", extractorService.getMessage("message.error.invalid.file.system",
                new String[] { fileService.getStoragePath() }));
    }//  w w  w  .  ja  v a2 s.  c  om

    if (StringUtils.equalsIgnoreCase("POST", request.getMethod())) {
        if (request.getParameter("status-type") != null) {
            String statusType = request.getParameter("status-type");
            if (StringUtils.equalsIgnoreCase("success", statusType)) {
                model.put("success", extractorService.getMessage("message.success.extraction.files.creation",
                        new String[] {}));
            } else {
                model.put("error", extractorService.getMessage("message.error.extraction.files.creation",
                        new String[] { request.getParameter("status-error-thrown") }));
            }
        }
    }

    return new ModelAndView("main", model);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Dump out things from HttpServletRequest object
 * /*from  w ww . j  ava2  s.  c  om*/
 * @param req
 * @return
 */
public static String dumpRequest(HttpServletRequest req) {
    if (req == null)
        return null;
    char column = ':', rtn = '\n', space = ' ';
    StringBuilder builder = new StringBuilder(req.getMethod());
    builder.append(space).append(req.getRequestURL().toString()).append(space).append(req.getProtocol())
            .append(rtn);
    Enumeration<String> headers = req.getHeaderNames();
    builder.append("HEADERS:\n");
    String header;
    for (; headers.hasMoreElements();) {
        header = headers.nextElement();
        builder.append(header).append(column).append(req.getHeader(header)).append(rtn);
    }
    builder.append("COOKIES:\n");
    Cookie cookie;
    Cookie[] cookies = req.getCookies();
    if (!ValidationUtils.isEmpty(cookies)) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            builder.append(cookie.getName()).append(column).append(GsonUtils.format(cookie)).append(rtn);
        }
    }
    builder.append("BODY:\n");
    Map<String, String[]> params = req.getParameterMap();
    for (String name : params.keySet()) {
        builder.append(name).append(ShenStrings.DELIMITER_DOT);
        builder.append(name.matches(PASS_PATTERN) ? params.get(SECRET_STRING) : params.get(name));
    }
    return builder.toString();

}

From source file:com.erudika.para.security.JWTRestfulAuthFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (authenticationRequestMatcher.matches(request)) {
        if (HttpMethod.POST.equals(request.getMethod())) {
            newTokenHandler(request, response);
        } else if (HttpMethod.GET.equals(request.getMethod())) {
            refreshTokenHandler(request, response);
        } else if (HttpMethod.DELETE.equals(request.getMethod())) {
            revokeAllTokensHandler(request, response);
        }/*ww w  . j a  va 2  s  .c om*/
        return;
    } else if (RestRequestMatcher.INSTANCE_STRICT.matches(request)
            && SecurityContextHolder.getContext().getAuthentication() == null) {
        try {
            // validate token if present
            JWTAuthentication jwt = getJWTfromRequest(request);
            if (jwt != null) {
                Authentication auth = authenticationManager.authenticate(jwt);
                // success!
                SecurityContextHolder.getContext().setAuthentication(auth);
            } else {
                response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
            }
        } catch (AuthenticationException authenticationException) {
            response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"");
            logger.debug("AuthenticationManager rejected JWT Authentication.", authenticationException);
        }
    }

    chain.doFilter(request, response);
}