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.energyos.espi.thirdparty.web.filter.CORSFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (logger.isInfoEnabled()) {
        logger.info("CORSFilter processing: Checking for Cross Origin pre-flight OPTIONS message");
    }//from   w w w.j ava  2  s.  c om

    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if ("OPTIONS".equals(req.getMethod())) {
            if (checkOrigin(req, resp)) {
                for (Map.Entry<String, String> e : optionsHeaders.entrySet()) {

                    resp.setHeader(e.getKey(), e.getValue());
                }
            }

            // We need to return here since we don't want the chain to
            // further process
            // a preflight request since this can lead to unexpected
            // processing of the preflighted
            // request or a 40x - Response Code
            return;

        } else if (checkOrigin(req, resp)) {
            if (exposeHeaders != null) {
                resp.setHeader("Access-Control-Expose-Headers", exposeHeaders);
            }
        }
    }
    filterChain.doFilter(request, response);
}

From source file:belajar.nfc.controller.OptionsController.java

@RequestMapping(method = RequestMethod.OPTIONS)
public void handleOptionsUser(HttpServletRequest request, HttpServletResponse response) {
    String host = request.getHeader("Host");
    String origin = request.getHeader("Origin");
    LOGGER.info("Options Controller URI [{}] method [{}] headers [{}] ipserver [{}]",
            new Object[] { request.getRequestURI(), request.getMethod(), origin, host });
}

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

/**
 * with no expectations set, and a request made, the handler throws an error upon verification
 *//*from ww w. j a  v  a  2s  . c  om*/
@Test
public void testUnexpectedRequest() throws IOException, ServletException {

    Request mockRequest = mock(Request.class);
    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);

    when(mockHttpRequest.getMethod()).thenReturn("POST");
    when(mockHttpRequest.getPathInfo()).thenReturn("yarr");
    when(mockHttpRequest.getQueryString()).thenReturn("gooo=gredge");
    when(mockHttpRequest.getInputStream()).thenReturn(new DummyServletInputStream(IOUtils.toInputStream("")));

    try {
        sut.handle("", mockRequest, mockHttpRequest, mockHttpResponse);
        Assert.fail();
    } catch (ClientDriverFailedExpectationException e) {
        assertThat(e.getMessage(), containsString("1 unexpected request(s):"));
        assertThat(e.getMessage(), containsString("POST yarr; PARAMS: [gooo=[gredge]];"));
    }
}

From source file:io.kamax.mxisd.controller.identity.v1.SessionRestController.java

@RequestMapping(value = "/validate/{medium}/requestToken")
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium)
        throws IOException {
    log.info("Request {}: {}", request.getMethod(), request.getRequestURL(), request.getQueryString());
    if (ThreePidMedium.Email.is(medium)) {
        SessionEmailTokenRequestJson req = parser.parse(request, SessionEmailTokenRequestJson.class);
        return gson.toJson(
                new Sid(mgr.create(request.getRemoteHost(), new ThreePid(req.getMedium(), req.getValue()),
                        req.getSecret(), req.getAttempt(), req.getNextLink())));
    }//from w  ww  .jav a 2 s.  c om

    if (ThreePidMedium.PhoneNumber.is(medium)) {
        SessionPhoneTokenRequestJson req = parser.parse(request, SessionPhoneTokenRequestJson.class);
        ThreePid threepid = new ThreePid(req.getMedium(), req.getValue());

        String sessionId = mgr.create(request.getRemoteHost(), threepid, req.getSecret(), req.getAttempt(),
                req.getNextLink());

        JsonObject res = new JsonObject();
        res.addProperty("sid", sessionId);
        res.addProperty(threepid.getMedium(), threepid.getAddress());
        return gson.toJson(res);
    }

    JsonObject obj = new JsonObject();
    obj.addProperty("errcode", "M_INVALID_3PID_TYPE");
    obj.addProperty("error", medium + " is not supported as a 3PID type");
    response.setStatus(HttpStatus.SC_BAD_REQUEST);
    return gson.toJson(obj);
}

From source file:psiprobe.controllers.jsp.RecompileJspController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession(false);
    Summary summary = (Summary) session.getAttribute(DisplayJspController.SUMMARY_ATTRIBUTE);

    if (request.getMethod().equalsIgnoreCase("post") && summary != null) {
        List<String> names = new ArrayList<>();
        for (String name : Collections.list(request.getParameterNames())) {
            if ("on".equals(request.getParameter(name))) {
                names.add(name);//from www  .j a  va  2s .  com
            }
        }
        getContainerWrapper().getTomcatContainer().recompileJsps(context, summary, names);
        session.setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary);
    } else if (summary != null && contextName.equals(summary.getName())) {
        String name = ServletRequestUtils.getStringParameter(request, "source", null);
        if (name != null) {
            List<String> names = new ArrayList<>();
            names.add(name);
            getContainerWrapper().getTomcatContainer().recompileJsps(context, summary, names);
            session.setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary);
        } else {
            logger.error("source is not passed, nothing to do");
        }
    }
    return new ModelAndView(new RedirectView(
            request.getContextPath() + ServletRequestUtils.getStringParameter(request, "view", getViewName())
                    + "?" + request.getQueryString()));
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

private static RequestType getFromRequestContentType(HttpServletRequest request) {
    assert request != null;

    String contentType = request.getContentType();
    String contentTypeLowercase = "";
    if (contentType != null) {
        contentTypeLowercase = contentType.toLowerCase();
    }/*w w w .ja  v a  2s .c  o  m*/

    String pathInfo = request.getPathInfo();

    if (!StringUtils.isEmpty(pathInfo) && pathInfo.startsWith(PollRequestProcessor.PATHINFO_POLL_PREFIX)) {
        return RequestType.POLL;
    } else if (contentTypeLowercase.startsWith("application/json")) {
        return RequestType.JSON;
    } else if (contentTypeLowercase.startsWith("application/x-www-form-urlencoded")
            && request.getMethod().toLowerCase().equals("post")) {
        return RequestType.FORM_SIMPLE_POST;
    } else if (ServletFileUpload.isMultipartContent(request)) {
        return RequestType.FORM_UPLOAD_POST;
    } else {
        String requestInfo = ServletUtils.getDetailedRequestInformation(request);
        RequestException ex = RequestException.forRequestFormatNotRecognized();
        logger.error("Error during file uploader: " + ex.getMessage() + "\nAdditional request information: "
                + requestInfo, ex);
        throw ex;
    }
}

From source file:org.mitre.oauth2.web.CorsFilter.java

@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    response.addHeader("Access-Control-Allow-Origin", "*");
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers",
                "X-Requested-With,Origin,Content-Type, Accept, Authorization");
    }/* w w  w .ja  v  a2s  .c om*/
    filterChain.doFilter(request, response);
}

From source file:no.dusken.common.spring.ExceptionHandler.java

private String getBody(HttpServletRequest request, Exception ex) {
    StringBuilder builder = new StringBuilder();
    builder.append("Method: ");
    builder.append(request.getMethod());
    builder.append('\n');
    builder.append("Servletpath: ");
    builder.append(request.getServletPath());
    builder.append('\n');
    builder.append("URI: ");
    builder.append(request.getRequestURI());
    builder.append('\n');
    builder.append("Query: ");
    builder.append(request.getQueryString());
    builder.append('\n');
    builder.append("User-Agent: ");
    builder.append(request.getHeader("User-Agent"));
    builder.append('\n');
    builder.append("Accept: ");
    builder.append(request.getHeader("Accept"));
    builder.append('\n');
    builder.append("Accept-Encoding: ");
    builder.append(request.getHeader("Accept-Encoding"));
    builder.append('\n');

    builder.append("Stacktrace:");
    builder.append('\n');

    String stacktrace = getStackTraceAsString(ex.getStackTrace())
            + (ex.getMessage() == null ? "" : "| Message: " + ex.getMessage());
    builder.append(stacktrace);//  w w w. j a va2  s  . c o  m
    return builder.toString();
}

From source file:org.smigo.log.LogHandler.java

public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) {
    StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ")
            .append(request.getRequestURL()).append(separator);
    s.append("Auth type:").append(request.getAuthType()).append(separator);
    s.append("Principal:").append(request.getUserPrincipal()).append(separator);
    s.append(Log.create(request, response).toString()).append(separator);
    s.append("Headers:").append(separator);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator);
    }//  w ww  . j a v a  2 s. c  o  m
    s.append(separator);
    s.append("####RESPONSE").append(separator);
    s.append("Status:").append(response.getStatus()).append(separator);
    s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator);
    s.append("Locale:").append(response.getLocale()).append(separator);
    s.append("Content type:").append(response.getContentType()).append(separator);

    s.append("Headers:").append(separator);
    s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh))
            .collect(Collectors.joining(separator)));

    final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER);
    if (start != null) {
        final long elapsedTime = System.nanoTime() - start;
        s.append(separator).append("####Request time elapsed:").append(elapsedTime);
        s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator);
    }
    return s.toString();
}

From source file:org.craftercms.security.processors.impl.LoginProcessor.java

protected boolean isLoginRequest(HttpServletRequest request) {
    return HttpUtils.getRequestUriWithoutContextPath(request).equals(loginUrl)
            && request.getMethod().equals(loginMethod);
}