Example usage for javax.servlet.http HttpServletRequest getParameterMap

List of usage examples for javax.servlet.http HttpServletRequest getParameterMap

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getParameterMap.

Prototype

public Map<String, String[]> getParameterMap();

Source Link

Document

Returns a java.util.Map of the parameters of this request.

Usage

From source file:in.xebia.poc.FileUploadUtils.java

public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile,
        Map<String, String> params) throws Exception {
    log.debug("Request class? " + request.getClass().toString());
    log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request));
    log.debug("Request method: " + request.getMethod());
    log.debug("Request params: ");
    for (Object key : request.getParameterMap().keySet()) {
        log.debug((String) key);/*from  w  w  w  .  j a v  a2 s.  co m*/
    }
    log.debug("Request attribute names: ");

    boolean filedataInAttributes = false;
    Enumeration attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        log.debug(attrName);
        if ("filedata".equals(attrName)) {
            filedataInAttributes = true;
        }
    }

    if (filedataInAttributes) {
        log.debug("Found filedata in request attributes, getting it out...");
        log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString());
        FileItem item = (FileItem) request.getAttribute("filedata");
        item.write(outputFile);
        for (Object key : request.getParameterMap().keySet()) {
            params.put((String) key, request.getParameter((String) key));
        }
        return true;
    }

    /*ServletFileUpload upload = new ServletFileUpload();
    //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE);
    FileItemIterator iter = upload.getItemIterator(request);
    while(iter.hasNext()){
       FileItemStream item = iter.next();
       InputStream stream = item.openStream();
               
       //If this item is a file
       if(!item.isFormField()){
             
     log.debug("Found non form field in upload request with field name = " + item.getFieldName());
             
     String name = item.getName();
     if(name == null){
         throw new Exception("File upload did not have filename specified");
     }
             
        // Some browsers, including IE, return the full path so trim off everything but the file name
        name = getFileNameFromPath(name);
                 
    //Enforce required file extension, if present
    if(!name.toLowerCase().endsWith( ".zip" )){
       throw new Exception("File uploaded did not have required extension .zip");
    }
            
      bufferedCopyStream(stream, new FileOutputStream(outputFile));
       }
       else {
    params.put(item.getFieldName(), Streams.asString(stream));
       }
    }
    return true;*/

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            log.debug("Found non form field in upload request with field name = " + item.getFieldName());

            String name = item.getName();
            if (name == null) {
                throw new Exception("File upload did not have filename specified");
            }

            // Some browsers, including IE, return the full path so trim off everything but the file name
            name = getFileNameFromPath(name);

            item.write(outputFile);
        } else {
            params.put(item.getFieldName(), item.getString());
        }
    }
    return true;
}

From source file:com.cubeia.backoffice.report.RequestBean.java

public static RequestBean parse(HttpServletRequest req) {
    /*/*from   ww  w. j  a v a2  s  .c  om*/
     * Trim the path (which becomes the report name)
     */
    String path = trim(req.getPathInfo());
    /*
     * check the format and do default if needed
     */
    String form = req.getParameter("format");
    if (form == null) {
        form = Format.CSV.name();
    }
    /*
     * Convert parameter map to a simple string-string map
     */
    @SuppressWarnings("rawtypes")
    Map params = req.getParameterMap();
    Map<String, String> tmp = new HashMap<String, String>(params.size());
    for (Object key : params.keySet()) {
        tmp.put(key.toString(), req.getParameter(key.toString()));
    }
    /*
     * Continue parsing
     */
    return parse(path, tmp, form);
}

From source file:com.gtwm.pb.servlets.ServletUtilMethods.java

/**
 * Like HttpServlet#getRequestQuery(request) but works for POST as well as
 * GET: In the case of POST requests, constructs a query string from
 * parameter names & values//from   w  ww. j  ava 2 s . c  o m
 * 
 * @see HttpServletRequest#getQueryString()
 */
public static String getRequestQuery(HttpServletRequest request) {
    String requestQuery = request.getQueryString();
    if (requestQuery != null) {
        return "GET: " + requestQuery;
    }
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        return "POST: file upload";
    }
    requestQuery = "POST: ";
    Map<String, String[]> parameterMap = request.getParameterMap();
    for (Map.Entry<String, String[]> parameterEntry : parameterMap.entrySet()) {
        requestQuery += "&" + parameterEntry.getKey() + "=" + parameterEntry.getValue()[0];
    }
    return requestQuery;
}

From source file:CertStreamCallback.java

public static void toJustepBiz(HttpServletRequest request, HttpServletResponse response, String url)
        throws FileUploadException, IOException {
    Callback callback = new CertStreamCallback(request, response);
    String accept = NetUtils.getAccept(request);
    String contentType = NetUtils.getContentType(request);
    String language = NetUtils.getLanguage(request);
    String sessionID = null;//ww w  . j  a v a  2 s  . c  o  m
    StringBuffer params = new StringBuffer();
    for (Object n : request.getParameterMap().keySet()) {
        String p = URLEncoder.encode(request.getParameter((String) n), "UTF-8");
        if (0 != params.length()) {
            params.append("&" + n + "=" + p);
        } else {
            params.append(n + "=" + p);
        }
    }
    if (NetUtils.isRequestMultipart(request)) {
        Part[] parts = NetUtils.generateParts(request);
        invokeActions(url, params.toString(), null, parts, accept, contentType, sessionID, language, "post",
                callback);
    } else {
        String postData = JavaServer.getPostData(request);
        invokeActions(url, params.toString(), postData.getBytes("UTF-8"), null, accept, contentType, sessionID,
                language, "post", callback);
    }
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Extracts request parameters and matches them to available database query parameters, as defined
 *   in the {@code model} class definition.
 *
 * @param request {@link HttpServletRequest}
 * @return/*  ww  w  .ja v a  2 s. c o  m*/
 */
public static List<QueryCriteria> getQueryCriteriaFromRequest(Class<? extends Model<?>> model,
        HttpServletRequest request) {
    logger.info(String.format("Generating QueryCriteria for request parameters: model=%s params=%s",
            model.getName(), request.getQueryString()));
    List<QueryCriteria> criteriaList = new ArrayList<>();
    Map<String, QueryParameterDescriptor> paramMap = getAvailableQueryParameters(model);
    for (Map.Entry entry : request.getParameterMap().entrySet()) {
        String paramName = (String) entry.getKey();
        String[] paramValue = ((String[]) entry.getValue())[0].split(",");
        if (!excludedParameters.contains(paramName)) {
            if (paramMap.containsKey(paramName)) {
                QueryParameterDescriptor descriptor = paramMap.get(paramName);
                QueryCriteria criteria = createCriteriaFromRequestParameter(descriptor.getFieldName(),
                        paramValue, descriptor.getType(), descriptor.getEvaluation());
                criteriaList.add(criteria);
            } else {
                logger.warn(String.format("Unable to map request parameter to available model parameters: %s",
                        paramName));
                throw new InvalidParameterException("Invalid request parameter: " + paramName);
            }
        }
    }
    logger.info(String.format("Generated QueryCriteria for request: %s", criteriaList.toString()));
    return criteriaList;
}

From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java

private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req)
        throws GuacamoleException {
    try {//from  w  w  w  .  j  a  va  2s. co  m
        if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) {
            final GuacamoleConfiguration config = new GuacamoleConfiguration();
            final String protocol = req.getParameter("protocol");
            if (protocol == null)
                throw new GuacamoleException("required parameter \"protocol\" is missing");
            config.setProtocol(protocol);
            for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
                String[] values = param.getValue();
                if (values.length > 0)
                    config.setParameter(param.getKey(), values[0]);
            }
            return Optional.of(config);
        } else {
            final ServletInputStream is = req.getInputStream();
            if (!is.isReady()) {
                MediaType contentType = MediaType.parse(req.getContentType());
                boolean invalidContentType = true;
                if (contentType.type().equals("application")) {
                    if (contentType.subtype().equals("json")) {
                        invalidContentType = false;
                    } else if (contentType.subtype().equals("x-www-form-urlencoded")
                            && req.getParameter("token") != null) {
                        return Optional.<GuacamoleConfiguration>absent();
                    }
                }
                if (invalidContentType)
                    throw new GuacamoleException(String.format("expecting application/json, got %s",
                            contentType.withoutParameters()));
                final GuacamoleConfiguration config = new GuacamoleConfiguration();
                try {
                    final ObjectMapper mapper = new ObjectMapper();
                    JsonNode root = (JsonNode) mapper.readTree(
                            createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper));
                    {
                        final JsonNode protocol = root.get("protocol");
                        if (protocol == null)
                            throw new GuacamoleException("required parameter \"protocol\" is missing");
                        final JsonNode parameters = root.get("parameters");
                        if (parameters == null)
                            throw new GuacamoleException("required parameter \"parameters\" is missing");
                        config.setProtocol(protocol.asText());
                        {
                            for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) {
                                Entry<String, JsonNode> member = i.next();
                                config.setParameter(member.getKey(), member.getValue().asText());
                            }
                        }
                    }
                } catch (ClassCastException e) {
                    throw new GuacamoleException("error occurred during parsing configuration", e);
                }
                return Optional.of(config);
            } else {
                return Optional.<GuacamoleConfiguration>absent();
            }
        }
    } catch (IOException e) {
        throw new GuacamoleException("error occurred during retrieving configuration from the request body", e);
    }
}

From source file:com.vmware.identity.SsoController.java

/**
 * reconstruct original query string minus RelyingPartyEntityId plus csp
 * @param request/* w ww .j  a v  a 2  s  .  c o  m*/
 * @return
 * @throws MalformedURLException
 */
static String ssoSSLDummyQueryString(HttpServletRequest request) throws MalformedURLException {
    StringBuilder result = new StringBuilder();

    Map<String, String[]> parameterMap = request.getParameterMap();
    boolean appendAmpersand = false;
    for (Entry<String, String[]> entry : parameterMap.entrySet()) {
        String key = entry.getKey();
        if (Shared.RELYINGPARTY_ENTITYID.equals(key)) {
            continue;
        }
        String[] values = entry.getValue();
        for (String value : values) {
            if (appendAmpersand) {
                result.append("&");
            }
            if (value == null || value.length() == 0) {
                result.append(String.format("%s", key));
            } else {
                result.append(String.format("%s=%s", key, value));
            }
            appendAmpersand = true;
        }
    }

    if (appendAmpersand) {
        result.append("&");
    }
    result.append("csp");

    return result.toString();
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 *
 * @param factsheetActionBean//from   w  ww.  j  a  v  a 2  s  .  c  om
 * @param predicateUri
 * @return
 */
public static String predicateCollapseLink(FactsheetActionBean factsheetActionBean, String predicateUri) {

    StringBuilder link = new StringBuilder();
    link.append(FactsheetActionBean.class.getAnnotation(UrlBinding.class).value()).append("?");

    HttpServletRequest request = factsheetActionBean.getContext().getRequest();
    Map<String, String[]> paramsMap = request.getParameterMap();
    if (paramsMap != null && !paramsMap.isEmpty()) {

        for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {

            String paramName = entry.getKey();
            String[] paramValues = entry.getValue();
            if (paramValues == null || paramValues.length == 0) {
                try {
                    link.append(URLEncoder.encode(paramName, "UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    throw new CRRuntimeException("Unsupported encoding", e);
                }
            } else {
                boolean isPageParam = factsheetActionBean.isPredicatePageParam(paramName);
                for (String paramValue : paramValues) {
                    if (!isPageParam || !paramValue.equals(predicateUri)) {
                        try {
                            link.append(URLEncoder.encode(paramName, "UTF-8")).append("=")
                                    .append(URLEncoder.encode(paramValue, "UTF-8")).append("&");
                        } catch (UnsupportedEncodingException e) {
                            throw new CRRuntimeException("Unsupported encoding", e);
                        }
                    }
                }
            }
        }
    }

    return StringUtils.removeEnd(link.toString(), "&");
}

From source file:com.comcast.cqs.util.Util.java

public static List<String> fillAllGetAttributesRequests(HttpServletRequest request) {

    List<String> filterRequests = new ArrayList<String>();
    Map<String, String[]> requestParams = request.getParameterMap();

    for (String k : requestParams.keySet()) {

        if (k.contains(CQSConstants.ATTRIBUTE_NAME)) {
            filterRequests.add(requestParams.get(k)[0]);
        }//from   w ww  .  ja  va  2 s . c o m
    }

    return filterRequests;
}

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

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

    Method method;//from   w  ww . ja  v a2 s . c  om
    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);
}