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.ai.smart.common.helper.util.RequestUtils.java

public static Map<String, Object> getQueryParams(HttpServletRequest request) {
    Map<String, String[]> map;
    if (request.getMethod().equalsIgnoreCase(POST)) {
        map = request.getParameterMap();
    } else {// w w w . j  ava  2 s .c  om
        String s = request.getQueryString();
        if (StringUtils.isBlank(s)) {
            return new HashMap<String, Object>();
        }
        try {
            s = URLDecoder.decode(s, UTF8);
        } catch (UnsupportedEncodingException e) {
            log.error("encoding " + UTF8 + " not support?", e);
        }
        map = parseQueryString(s);
    }

    Map<String, Object> params = new HashMap<String, Object>(map.size());
    int len;
    for (Map.Entry<String, String[]> entry : map.entrySet()) {
        len = entry.getValue().length;
        if (len == 1) {
            params.put(entry.getKey(), entry.getValue()[0]);
        } else if (len > 1) {
            params.put(entry.getKey(), entry.getValue());
        }
    }
    return params;
}

From source file:com.vmware.identity.openidconnect.protocol.HttpRequest.java

public static HttpRequest from(HttpServletRequest httpServletRequest) {
    Validate.notNull(httpServletRequest, "httpServletRequest");

    Method method;// w  w w  .j  a va2s  . c  o m
    if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
        method = Method.POST;
    } else if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
        method = Method.GET;
    } else {
        throw new IllegalArgumentException(
                "unsupported http request method: " + httpServletRequest.getMethod());
    }

    URI uri = URIUtils.from(httpServletRequest);

    Map<String, String> parameters = new HashMap<String, String>();
    for (Map.Entry<String, String[]> entry : httpServletRequest.getParameterMap().entrySet()) {
        if (entry.getValue().length != 1) {
            throw new IllegalArgumentException(
                    "HttpServletRequest parameter map must have a single entry for every key. " + entry);
        }
        parameters.put(entry.getKey(), entry.getValue()[0]);
    }

    return new HttpRequest(method, uri, parameters, httpServletRequest);
}

From source file:io.apiman.test.common.mock.EchoResponse.java

/**
 * Create an echo response from the inbound information in the http server
 * request.//from  w w  w  . j a v  a  2s  .c  o  m
 * @param request
 * @param withBody 
 * @return a new echo response
 */
public static EchoResponse from(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    response.setResource(request.getRequestURI());
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1"); //$NON-NLS-1$
            byte[] data = new byte[1024];
            int read = 0;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}

From source file:com.icl.integrator.util.patch.ServletAnnotationMappingUtils.java

/**
 * Check whether the given request matches the specified request methods.
 * @param methods the HTTP request methods to check against
 * @param request the current HTTP request to check
 *//*from  w w w.  ja va  2s. co  m*/
public static boolean checkRequestMethod(RequestMethod[] methods, HttpServletRequest request) {
    if (ObjectUtils.isEmpty(methods)) {
        return true;
    }
    for (RequestMethod method : methods) {
        if (method.name().equals(request.getMethod())) {
            return true;
        }
    }
    return false;
}

From source file:com.kolich.havalo.filters.HavaloAuthenticationFilter.java

private static final String getStringToSign(final HttpServletRequest request) {
    final StringBuilder sb = new StringBuilder();
    // HTTP-Verb (GET, PUT, POST, or DELETE) + "\n"
    sb.append(request.getMethod().toUpperCase()).append(LINE_SEPARATOR_UNIX);
    // RFC822 Date (from 'Date' request header, must exist) + "\n" +
    final String dateHeader;
    if ((dateHeader = request.getHeader(DATE)) == null) {
        throw new BadCredentialsException(
                "Incoming request missing " + "required '" + DATE + "' request header.");
    }// w w w .  j  av a2s . c  o m
    sb.append(dateHeader).append(LINE_SEPARATOR_UNIX);
    // Content-Type (from 'Content-Type' request header, optional) + "\n" +
    final String contentType;
    if ((contentType = request.getHeader(CONTENT_TYPE)) != null) {
        sb.append(contentType);
    }
    sb.append(LINE_SEPARATOR_UNIX);
    // CanonicalizedResource
    sb.append(request.getRequestURI());
    return sb.toString();
}

From source file:com.ai.smart.common.helper.util.RequestUtils.java

/**
 * ?QueryString?URLDecoderUTF-8??post??/*from   w w w  .  ja va  2  s .  c o  m*/
 * HttpServletRequest#getParameter?
 *
 * @param request web
 * @param name    ???
 * @return
 */
public static String getQueryParam(HttpServletRequest request, String name) {
    if (StringUtils.isBlank(name)) {
        return null;
    }
    if (request.getMethod().equalsIgnoreCase(POST)) {
        return request.getParameter(name);
    }
    String s = request.getQueryString();
    if (StringUtils.isBlank(s)) {
        return null;
    }
    try {
        s = URLDecoder.decode(s, UTF8);
    } catch (UnsupportedEncodingException e) {
        log.error("encoding " + UTF8 + " not support?", e);
    }
    String[] values = parseQueryString(s).get(name);
    if (values != null && values.length > 0) {
        return values[values.length - 1];
    } else {
        return null;
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*from   w  ww  .j  a v  a 2s.  co  m*/

    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())).append("\n");
    log.append("---- Body END\n");

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

From source file:com.ebay.cloud.cms.service.resources.impl.CMSResourceUtils.java

public static Object getNext(IQueryResult queryResult, QueryContext context, HttpServletRequest request) {
    String method = request.getMethod();
    ObjectNode next = JsonNodeFactory.instance.objectNode();
    // build url//from   ww  w .j  av  a 2 s.  co m
    String url = "/repositories/%s/branches/%s/query/%s";
    next.put("method", method);
    if ("POST".equals(method)) {
        next.put("body", context.getQueryString());
        url = String.format(url, context.getRepositoryName(), context.getBranchName(), "");
    } else {
        url = String.format(url, context.getRepositoryName(), context.getBranchName(),
                CMSResourceUtils.urlEncoding(context.getQueryString()));
    }
    QueryCursor nextCursor = queryResult.getNextCursor();
    // append query parameters
    StringBuilder sb = new StringBuilder(url);
    // from context
    sb.append("?").append(QueryParameterEnum.allowFullTableScan.name()).append('=')
            .append(context.isAllowFullTableScan());
    sb.append("&").append(QueryParameterEnum.explain.name()).append('=').append(context.needExplain());
    if (context.getDal() != null) {
        sb.append("&").append(CMSResourceUtils.REQ_PARAM_DAL_IMPLEMENTATION).append('=')
                .append(context.getDal());
    }
    if (context.getPaginationMode() != null) {
        sb.append("&").append(CMSResourceUtils.REQ_PAGINATION_MODE).append('=')
                .append(context.getPaginationMode());
    }
    sb.append("&").append(CMSResourceUtils.REQ_SHOW_META).append('=').append(context.isShowDisplayMeta());
    // no count only
    // from cursor
    if (nextCursor.getLimits() != null) {
        sb.append("&").append(QueryParameterEnum.limit).append('=')
                .append(CMSResourceUtils.joinToParameter(nextCursor.getLimits()));
    }
    if (nextCursor.getSkips() != null) {
        sb.append("&").append(QueryParameterEnum.skip).append('=')
                .append(CMSResourceUtils.joinToParameter(nextCursor.getSkips()));
    }
    if (context.getPaginationMode() == PaginationMode.ID_BASED) {
        if (nextCursor.isJoinCursor()) {
            sb.append('&').append(QueryParameterEnum.cursor).append('=').append(
                    CMSResourceUtils.urlEncoding(listToArrayNode(nextCursor.getJoinCursorValues()).toString()));
        } else {
            sb.append('&').append(QueryParameterEnum.cursor).append('=')
                    .append(CMSResourceUtils.urlEncoding(nextCursor.getSingleCursorValue().toString()));
        }
    }
    if (nextCursor.hasSortOn()) {
        sb.append("&").append(QueryParameterEnum.sortOn.name()).append('=')
                .append(StringUtils.join(nextCursor.getSortOn(), ","));
    }
    if (nextCursor.hasSortOrder()) {
        sb.append("&").append(QueryParameterEnum.sortOrder.name()).append('=')
                .append(CMSResourceUtils.joinSortOrder(nextCursor.getSortOrder()));
    }
    if (nextCursor.hasHint()) {
        sb.append("&").append(QueryParameterEnum.hint.name()).append('=').append(nextCursor.getHint());
    }
    if (nextCursor.hasMaxFetch()) {
        sb.append("&").append(QueryParameterEnum.maxFetch.name()).append('=').append(nextCursor.getMaxFecth());
    }
    next.put("url", sb.toString());
    return next;
}

From source file:nu.yona.server.rest.GlobalExceptionMapping.java

public static String buildRequestInfo(HttpServletRequest request) {
    String queryString = request.getQueryString();
    String url = StringUtils.isBlank(queryString) ? request.getRequestURI()
            : request.getRequestURI() + "?" + queryString;
    return MessageFormat.format("{0} on URL {1}", request.getMethod(), url);
}

From source file:io.apiman.test.common.mock.EchoServlet.java

/**
 * Create an echo response from the inbound information in the http server
 * request.//  w  w w  . j a v  a  2 s.com
 * @param request the request
 * @param withBody if request is with body
 * @return a new echo response
 */
public static EchoResponse response(HttpServletRequest request, boolean withBody) {
    EchoResponse response = new EchoResponse();
    response.setMethod(request.getMethod());
    if (request.getQueryString() != null) {
        String[] normalisedQueryString = request.getQueryString().split("&");
        Arrays.sort(normalisedQueryString);
        response.setResource(
                request.getRequestURI() + "?" + SimpleStringUtils.join("&", normalisedQueryString));
    } else {
        response.setResource(request.getRequestURI());
    }
    response.setUri(request.getRequestURI());
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = request.getHeader(name);
        response.getHeaders().put(name, value);
    }
    if (withBody) {
        long totalBytes = 0;
        InputStream is = null;
        try {
            is = request.getInputStream();
            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            byte[] data = new byte[1024];
            int read;
            while ((read = is.read(data)) != -1) {
                sha1.update(data, 0, read);
                totalBytes += read;
            }
            ;

            byte[] hashBytes = sha1.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < hashBytes.length; i++) {
                sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            String fileHash = sb.toString();

            response.setBodyLength(totalBytes);
            response.setBodySha1(fileHash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return response;
}