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:codes.thischwa.c5c.requestcycle.Context.java

/**
 * Initializes the base parameters./*from  w  w  w.  j a  va2s . com*/
 * 
 * @param servletRequest
 * 
 * @throws C5CException thrown if the parameter 'mode' couldn't be resolved
 */
Context(HttpServletRequest servletRequest) throws C5CException {
    this.servletRequest = servletRequest;
    urlPath = servletRequest.getParameter("path");
    String paramMode = servletRequest.getParameter("mode");
    if (paramMode == null && servletRequest.getMethod().equals("POST")) {
        try {
            paramMode = IOUtils.toString(servletRequest.getPart("mode").getInputStream());
        } catch (Exception e) {
            logger.error("Couldn't retrieve the 'mode' parameter from multipart.");
            throw new C5CException(
                    UserObjectProxy.getFilemanagerErrorMessage(FilemanagerException.Key.ModeError));
        }
    } else {
        paramMode = servletRequest.getParameter("mode");
    }
    try {
        mode = FilemanagerAction.valueOfIgnoreCase(paramMode);
    } catch (IllegalArgumentException e) {
        logger.error("Unknown 'mode': {}", paramMode);
        throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(FilemanagerException.Key.ModeError));
    }
}

From source file:org.jasig.cas.web.support.AbstractThrottledSubmissionHandlerInterceptorAdapter.java

@Override
public final void postHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object o, final ModelAndView modelAndView) throws Exception {
    if (!"POST".equals(request.getMethod())) {
        return;/*from w  w w.  j  ava  2 s .c  om*/
    }

    final RequestContext context = (RequestContext) request.getAttribute("flowRequestContext");

    if (context == null || context.getCurrentEvent() == null) {
        return;
    }

    // User successfully authenticated
    if (SUCCESSFUL_AUTHENTICATION_EVENT.equals(context.getCurrentEvent().getId())) {
        return;
    }

    // User submitted invalid credentials, so we update the invalid login count
    recordSubmissionFailure(request);
}

From source file:com.jaspersoft.jasperserver.war.util.StandardRequestMatcher.java

public boolean matches(HttpServletRequest request) {
    if (log.isDebugEnabled()) {
        log.debug("Matching request " + request + " against " + this);
    }/*from  www .  j  a  va2  s .c o  m*/

    if (method != null && !matchesValue(request.getMethod(), method)) {
        if (log.isDebugEnabled()) {
            log.debug("Request method " + request.getMethod() + " does not match method " + method);
        }
        return false;
    }

    if (scheme != null && !matchesValue(request.getScheme(), scheme)) {
        if (log.isDebugEnabled()) {
            log.debug("Request scheme " + request.getScheme() + " does not match scheme " + scheme);
        }
        return false;
    }

    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            String header = headerEntry.getKey();
            String headerPattern = headerEntry.getValue();
            String value = request.getHeader(header);
            if (!matchesValue(value, headerPattern)) {
                if (log.isDebugEnabled()) {
                    log.debug("Request header " + header + ": " + value + " does not match " + headerPattern);
                }
                return false;
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Request " + request + " matches " + this);
    }

    return true;
}

From source file:io.kamax.mxisd.controller.DefaultExceptionHandler.java

@ExceptionHandler(RemoteLoginException.class)
public String handle(HttpServletRequest request, HttpServletResponse response, RemoteLoginException e) {
    if (e.getErrorBodyMsgResp() != null) {
        response.setStatus(e.getStatus());
        log.info("Request {} {} - Error {}: {}", request.getMethod(), request.getRequestURL(), e.getErrorCode(),
                e.getError());/* w  ww. j a v  a 2s . c  o  m*/
        return gson.toJson(e.getErrorBodyMsgResp());
    }
    return handleGeneric(request, response, e);
}

From source file:com.bh.subject.std.common.security.cors.CORSFilter.java

private String getOriginDomain(HttpServletRequest request) {
    String result = null;// w  ww  .j  ava  2s .co  m
    String origin = request.getHeader("Origin");

    if ("OPTIONS".equals(request.getMethod())) {
        result = origin;
    } else {
        String referer = request.getHeader("referer");
        String tmpResult = null;

        if (origin == null || "".equals(origin)) {
            tmpResult = referer != null && !"".equals(referer) ? referer.substring(0, referer.indexOf("/", 8))
                    : null;
        } else {
            tmpResult = origin;
        }

        result = tmpResult == null || "".equals(tmpResult) ? defaultOriginDomain : tmpResult;
    }

    return result;
}

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }/*www.  ja  v  a2  s . com*/

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

private void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;//from  w w w .j a v a 2s .  c om

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:ru.mystamps.web.support.spring.security.AuthenticationFailureListener.java

@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
    HttpServletRequest request = getRequest();
    if (request == null) {
        LOG.warn("Can't get http request object");
        return;/*  ww  w. j a  v  a 2  s.c o m*/
    }

    // TODO: log more info (login for example) (#59)
    // TODO: sanitize all user's values (#60)
    String method = request.getMethod();
    String page = request.getRequestURI();
    String ip = request.getRemoteAddr();
    String referer = request.getHeader("referer");
    String agent = request.getHeader("user-agent");
    Date date = new Date(event.getTimestamp());

    siteService.logAboutFailedAuthentication(page, method, null, ip, referer, agent, date);
}

From source file:snoopware.api.UserGridProxyServlet.java

/**
 * Override to add Authorization to requests that need it.
 * @param req/* www .java2s.  co  m*/
 * @param proxyReq
 */
@Override
protected void copyRequestHeaders(HttpServletRequest req, HttpRequest proxyReq) {
    super.copyRequestHeaders(req, proxyReq);

    boolean hasAccessToken = req.getQueryString() == null ? false
            : req.getQueryString().contains("access_token=");

    if (!hasAccessToken && ("POST".equalsIgnoreCase(req.getMethod()) || "GET".equalsIgnoreCase(req.getMethod()))
            && req.getPathInfo().contains("/" + applicationName + "/user")) {

        String header = "Bearer " + client.getAccessToken();
        proxyReq.setHeader("Authorization", header);
        log.debug("Added header {} to URL {}", header, req.getRequestURL().toString());
    } else {
        log.debug("Not adding header to request with " + req.getRequestURL().toString());
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;/*from  www . j a  v  a2 s .c o  m*/
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}