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.tbodt.jswerve.servlet.JSwerveServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getMethod().equals("OPTIONS")) {
        serviceOptions(req, resp);/*  w ww  .  ja  va  2s.  c o  m*/
        return;
    }

    HttpMethod method = HttpMethod.valueOf(req.getMethod());
    URI uri = extractUri(req);
    Headers headers = translateHeaders(req);
    Content content = new Content(IOUtils.toByteArray(req.getInputStream()), req.getContentType());
    Request request = new Request(method, uri, headers, content);
    try {
        Response response = website.service(request);
        resp.setStatus(response.getStatus().getCode());
        for (Map.Entry<String, String> header : response.getHeaders())
            resp.setHeader(header.getKey(), header.getValue());
        resp.getOutputStream().write(response.getBody().getData());
    } catch (StatusCodeException ex) {
        resp.setStatus(ex.getStatusCode().getCode());
        ex.printStackTrace(resp.getWriter());
    }
}

From source file:io.lavagna.web.security.login.LdapLogin.java

@Override
public boolean doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (!"POST".equalsIgnoreCase(req.getMethod())) {
        return false;
    }/*  w w w.  j av  a2  s  .c  o  m*/

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    if (authenticate(username, password)) {
        // FIXME refactor out
        String url = Redirector.cleanupRequestedUrl(req.getParameter("reqUrl"), req);
        User user = users.findUserByName(USER_PROVIDER, username);
        sessionHandler.setUser(user.getId(), user.isAnonymous(), req, resp);
        Redirector.sendRedirect(req, resp, url, Collections.<String, List<String>>emptyMap());
    } else {
        Redirector.sendRedirect(req, resp, req.getContextPath() + "/" + removeStart(errorPage, "/"),
                Collections.<String, List<String>>emptyMap());
    }
    return true;

}

From source file:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java

/**
 * Sets the headers and does some checking for if this request
 * is meant for the server or for the proxy. This check is done
 * by looking at the Max-Forwards header.
 * /* www. j  a v  a2s.  c  o m*/
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {
    HttpMethodBase method = null;

    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("TRACE")) {
        method = new TraceMethod(url);
    } else {
        return null;
    }

    try {
        int max = request.getIntHeader("Max-Forwards");
        if (max == 0 || request.getRequestURI().equals("*")) {
            setAllHeaders(method, request);
            method.abort();
        } else if (max != -1) {
            setHeaders(method, request);
            method.setRequestHeader("Max-Forwards", "" + max--);
        } else {
            setHeaders(method, request);
        }
    } catch (NumberFormatException e) {
    }

    return method;
}

From source file:info.rmapproject.api.auth.AuthenticationInterceptor.java

/**
 * Gets basic authentication information from request and validates key
 * throws an error if key is invalid.//www. j a v a  2 s.  c  o m
 *
 * @param message http message
 */
public void handleMessage(Message message) {

    try {
        //only authenticate if you are trying to write to the db... 
        HttpServletRequest req = (HttpServletRequest) message.get("HTTP.REQUEST");
        String method = req.getMethod();

        if (method != HttpMethod.GET && method != HttpMethod.OPTIONS && method != HttpMethod.HEAD) {

            AuthorizationPolicy policy = apiUserService.getCurrentAuthPolicy();
            String accessKey = policy.getUserName();
            String secret = policy.getPassword();

            if (accessKey == null || accessKey.length() == 0 || secret == null || secret.length() == 0) {
                throw new RMapApiException(ErrorCode.ER_NO_USER_TOKEN_PROVIDED);
            }

            apiUserService.validateKey(accessKey, secret);
        }

    } catch (RMapApiException ex) {
        //generate a response to intercept default message
        RMapApiExceptionHandler exceptionhandler = new RMapApiExceptionHandler();
        Response response = exceptionhandler.toResponse(ex);
        message.getExchange().put(Response.class, response);
    }

}

From source file:com.enonic.cms.web.portal.PortalServlet.java

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    final String requestMethod = req.getMethod();

    if (!ALLOWED_HTTP_METHODS.contains(requestMethod)) {
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;// w ww.  ja va  2  s  .com
    }

    if (requestMethod.equals("OPTIONS")) {
        doOptions(req, res);
        return;
    }

    ServletRequestAccessor.setRequest(req);
    OriginalUrlResolver.resolveOriginalUrl(req);

    this.dispatcher.handle(req, res);
}

From source file:cf.spring.VarzHandlerMapping.java

public VarzHandlerMapping(final VarzAggregator aggregator, final HttpBasicAuthenticator authenticator,
        int order) {
    setOrder(order);//from w  w w. ja v a  2s.  c o m
    registerHandler("/varz", new HttpRequestHandler() {
        @Override
        public void handleRequest(HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse) throws ServletException, IOException {
            if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
                if (authenticator.authenticate(httpServletRequest, httpServletResponse)) {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    final ObjectNode varz = aggregator.aggregateVarz();
                    mapper.writeValue(httpServletResponse.getOutputStream(), varz);
                }
            } else {
                httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
    });
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java

private boolean login(Subject subject, HttpServletRequest request) {
    if ("get".equalsIgnoreCase(request.getMethod())) {
        return false;
    }/*from   w  ww.  j a  v  a  2s  .c  om*/
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return false;
    }

    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);
        return true;
    } catch (Exception e) {
        throw new RuntimeException("login error: " + e.getMessage());
    }
}

From source file:org.createnet.raptor.auth.service.jwt.JsonUsernamePasswordFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    if (!request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }// w w  w . j  a  va2s .co m

    if (!request.getContentType().equals(MediaType.APPLICATION_JSON)) {
        throw new AuthenticationServiceException("Only Content-Type " + MediaType.APPLICATION_JSON
                + " is supported. Provided is " + request.getContentType());
    }

    LoginForm loginForm;
    try {
        InputStream body = request.getInputStream();
        loginForm = jacksonObjectMapper.readValue(body, LoginForm.class);
    } catch (IOException ex) {
        throw new AuthenticationServiceException("Error reading body", ex);
    }

    if (loginForm.username == null) {
        loginForm.username = "";
    }

    if (loginForm.password == null) {
        loginForm.password = "";
    }

    loginForm.username = loginForm.username.trim();

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            loginForm.username, loginForm.password);
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:grails.plugin.cache.web.filter.DefaultWebKeyGenerator.java

public String generate(HttpServletRequest request) {

    String uri = WebUtils.getForwardURI(request);

    StringBuilder key = new StringBuilder();
    key.append(request.getMethod().toUpperCase());

    String format = WebUtils.getFormatFromURI(uri);
    if (StringUtils.hasLength(format) && !"all".equals(format)) {
        key.append(":format:").append(format);
    }/*from  www .  j  a v a2s.  c  o  m*/

    if (supportAjax) {
        String requestedWith = request.getHeader(X_REQUESTED_WITH);
        if (StringUtils.hasLength(requestedWith)) {
            key.append(':').append(X_REQUESTED_WITH).append(':').append(requestedWith);
        }
    }

    key.append(':').append(uri);
    if (StringUtils.hasLength(request.getQueryString())) {
        key.append('?').append(request.getQueryString());
    }

    return key.toString();
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private HttpUriRequest prepareRequest(HttpServletRequest req, String target) throws IOException {
    String method = req.getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        return new HttpGet(target);
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        HttpPost post = new HttpPost(target);
        post.setEntity(new ByteArrayEntity(readInputStream(req.getInputStream(), req.getContentLength()),
                ContentType.parse(req.getContentType())));
        return post;
    }/*from  ww w.j a  v a 2s .co  m*/
    throw new UnsupportedOperationException("Only GET and POST are supported by this proxy.");
}