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:fr.aliasource.webmail.server.invitation.GoingInvitationProxyImpl.java

@SuppressWarnings("unchecked")
@Override/*from ww w  .  j  av  a  2s  . com*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java

@SuppressWarnings("unchecked")
protected RESTResource getHeadingForNameRequest(HttpServletRequest request) {

    return this.getHeading(request.getParameterMap(), this.getUrlPathHelper().getServletPath(request));

}

From source file:com.ugam.collage.plus.controller.people_count.TeamStructureController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> save(HttpServletRequest httpServletRequest,
        @ModelAttribute("pcTeamStructureVo") PCTeamStructureVo pcTeamStructureVo, Locale locale, Model model) {

    Map<String, Object> returnData = new HashMap<String, Object>();
    try {/*from  w w w .  j a  va 2s  .  c  o  m*/

        int loggedInUserId = authService.getLoggedInUserDetails().getId();
        if (loggedInUserId != pcTeamStructureVo.getMgrEmployeeId() && !authService.userHasAccessLevel("L3")) {

            return returnData;
        }

        Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
        pcTeamStructureVo.extractAssignedEmployees(parameterMap);
        pcTeamStructureVo.extractProjectEmpCount(parameterMap);
        pcTeamStructureVo.extractEmpRules(parameterMap);
        pcTeamStructureVo.extractProportions(parameterMap);
        pcTeamStructureVo.extractApportionApproachs(parameterMap);

        teamStructureService.saveTeamStructure(pcTeamStructureVo);

        returnData.put("success", "true");
        returnData.put("message", "Saved");
    } catch (Exception e) {
        returnData.put("success", "false");
        returnData.put("message", "Error reading/saving Data from UI - " + e.getLocalizedMessage());
        logger.error("Error reading/saving Data from UI", e);
    }

    return returnData;

}

From source file:mx.edu.um.mateo.inventario.web.EntradaController.java

@RequestMapping(value = "/productos", params = "term", produces = "application/json")
public @ResponseBody List<LabelValueBean> productos(HttpServletRequest request,
        @RequestParam("term") String filtro) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from   w  w w  .  jav  a  2  s .c  o m
    Map<String, Object> params = new HashMap<>();
    params.put("almacen", request.getSession().getAttribute("almacenId"));
    params.put("filtro", filtro);
    params = productoDao.lista(params);
    List<LabelValueBean> valores = new ArrayList<>();
    @SuppressWarnings("unchecked")
    List<Producto> productos = (List<Producto>) params.get("productos");
    for (Producto producto : productos) {
        StringBuilder sb = new StringBuilder();
        sb.append(producto.getSku());
        sb.append(" | ");
        sb.append(producto.getNombre());
        sb.append(" | ");
        sb.append(producto.getDescripcion());
        sb.append(" | ");
        sb.append(producto.getExistencia()).append(" ").append(producto.getUnidadMedida());
        sb.append(" | ");
        sb.append(producto.getPrecioUnitario());
        valores.add(new LabelValueBean(producto.getId(), sb.toString()));
    }
    return valores;
}

From source file:fll.web.UploadSpreadsheet.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();
    String nextPage;/* w  w w  .  java 2s. c  o  m*/
    try {
        UploadProcessor.processUpload(request);
        final String uploadRedirect = (String) request.getAttribute("uploadRedirect");
        if (null == uploadRedirect) {
            throw new RuntimeException(
                    "Missing parameter 'uploadRedirect' params: " + request.getParameterMap());
        }
        session.setAttribute("uploadRedirect", uploadRedirect);

        final FileItem fileItem = (FileItem) request.getAttribute("file");
        final String extension = Utilities.determineExtension(fileItem.getName());
        final File file = File.createTempFile("fll", extension);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Wrote data to: " + file.getAbsolutePath());
        }
        fileItem.write(file);
        session.setAttribute(SPREADSHEET_FILE_KEY, file.getAbsolutePath());

        if (ExcelCellReader.isExcelFile(file)) {
            final List<String> sheetNames = ExcelCellReader.getAllSheetNames(file);
            if (sheetNames.size() > 1) {
                session.setAttribute("sheetNames", sheetNames);
                nextPage = "promptForSheetName.jsp";
            } else {
                session.setAttribute(SHEET_NAME_KEY, sheetNames.get(0));
                nextPage = uploadRedirect;
            }
        } else {
            nextPage = uploadRedirect;
        }

    } catch (final FileUploadException e) {
        message.append("<p class='error'>Error processing team data upload: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error processing team data upload", e);
    } catch (final Exception e) {
        message.append("<p class='error'>Error saving team data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving team data into the database", e);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(nextPage));
}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * Returns the value of the requested parameter from the request, or null
 *
 * @param request//from w  w w .ja v a 2  s.  c o  m
 *            the request object
 * @param aliases
 *            array of query arg names by which the request may be specified
 * @return the value of the param, or null if it is not specified under the
 *         specified names
 */
protected static String getParameter(HttpServletRequest request, String[] aliases) {
    final String sourceMethod = "getParameter"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), sourceMethod,
                new Object[] { request.getQueryString(), Arrays.asList(aliases) });
    }
    Map<String, String[]> params = request.getParameterMap();
    String result = null;
    for (Map.Entry<String, String[]> entry : params.entrySet()) {
        String name = entry.getKey();
        for (String alias : aliases) {
            if (alias.equalsIgnoreCase(name)) {
                String[] values = entry.getValue();
                result = values[values.length - 1]; // return last value in array
            }
        }
    }
    if (isTraceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, result);
    }
    return result;
}

From source file:com.openmeap.admin.web.servlet.AdminServlet.java

@SuppressWarnings("unchecked")
@Override//  www .  j av a 2s  .c  o  m
public void service(HttpServletRequest request, HttpServletResponse response) {

    logger.trace("Entering service()");

    try {
        DocumentProcessor documentProcessor = null;

        logger.debug("Request uri: {}", request.getRequestURI());
        logger.debug("Request url: {}", request.getRequestURL());
        logger.debug("Query string: {}", request.getQueryString());
        if (logger.isDebugEnabled()) {
            logger.debug("Parameter map: {}", ParameterMapUtils.toString(request.getParameterMap()));
        }

        if (request.getParameter("logout") != null) {
            logger.trace("Executing logout");
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/interface/");
        }

        if (request.getParameter("refreshContext") != null && context instanceof AbstractApplicationContext) {
            logger.trace("Refreshing context");
            ((AbstractApplicationContext) context).refresh();
        }

        // support for clearing the persistence context
        if (request.getParameter("clearPersistenceContext") != null
                && context instanceof AbstractApplicationContext) {
            logger.trace("Clearing the persistence context");
            ModelServiceImpl ms = (ModelServiceImpl) ((AbstractApplicationContext) context)
                    .getBean("modelService");
            ms.clearPersistenceContext();
        }

        // default to the mainOptionPage, unless otherwise specified
        String pageBean = null;
        if (request.getParameter(FormConstants.PAGE_BEAN) != null)
            pageBean = request.getParameter(FormConstants.PAGE_BEAN);
        else
            pageBean = FormConstants.PAGE_BEAN_MAIN;
        logger.debug("Using page bean: {}", pageBean);
        documentProcessor = (DocumentProcessor) context.getBean(pageBean);

        ModelManager mgr = getModelManager();
        Map<Object, Object> map = new HashMap<Object, Object>();

        // TODO: I'm not really happy with this hacky work-around for the login form not being in actual request scope
        if (documentProcessor.getProcessesFormData()) {
            GlobalSettings settings = mgr.getGlobalSettings();
            map = ServletUtils.cloneParameterMap(settings.getMaxFileUploadSize(),
                    settings.getTemporaryStoragePath(), request);
            map.put("userPrincipalName", new String[] { request.getUserPrincipal().getName() });
            AuthorizerImpl authorizer = (AuthorizerImpl) context.getBean("authorizer");
            authorizer.setRequest(request);
        }

        response.setContentType(FormConstants.CONT_TYPE_HTML);

        Map<Object, Object> defaultTemplateVars = new HashMap<Object, Object>();
        defaultTemplateVars.put("request", new BeanModel(request, new DefaultObjectWrapper()));
        documentProcessor.setTemplateVariables(defaultTemplateVars);
        documentProcessor.handleProcessAndRender(map, response.getWriter());

        response.getWriter().flush();
        response.getWriter().close();
    } catch (IOException te) {
        throw new RuntimeException(te);
    }

    logger.trace("Leaving service()");
}

From source file:io.mapzone.arena.share.ShareInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//w  w  w.  ja  va  2 s  .  c  o m
        // log.info( "QueryString: " + req.getQueryString() );
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String header = headerNames.nextElement();
        // log.info( "HEADER '" + header + "': '" + req.getHeader( header ) + "'"
        // );
        // }

        if (req.getParameterMap().isEmpty() || StringUtils.isBlank(req.getParameter(PARAMETER_LAYERS))
                || StringUtils.isBlank(req.getParameter(PARAMETER_BBOX))) {
            resp.sendError(400, "No parameters found! Please specify at least '" + PARAMETER_LAYERS + "' and '"
                    + PARAMETER_BBOX + "'.");
            return;
        }

        final String layers = req.getParameter(PARAMETER_LAYERS);
        final String bbox = req.getParameter(PARAMETER_BBOX);
        final String authToken = req.getParameter(PARAMETER_AUTHTOKEN);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("text/html;charset=utf-8");

        final String projectName = ArenaConfig.getAppTitle();
        // FIXME add the project description here
        final String description = ArenaConfig.getAppTitle();
        final String arenaUrl = ArenaPlugin.instance().config().getProxyUrl() + ArenaPlugin.ALIAS;
        final StringBuilder imageUrl = new StringBuilder(ArenaPlugin.instance().config().getProxyUrl());
        imageUrl.append(GeoServerStarter.ALIAS);
        imageUrl.append(
                "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&CRS=EPSG%3A3857&STYLES=&WIDTH=1200&HEIGHT=630");
        imageUrl.append("&LAYERS=").append(URLEncoder.encode(layers, "utf-8"));
        imageUrl.append("&BBOX=").append(URLEncoder.encode(bbox, "utf-8"));
        if (!StringUtils.isBlank(authToken)) {
            imageUrl.append("&authToken=").append(URLEncoder.encode(authToken, "utf-8"));
        }

        //            log.info( "IMGURL" + imageUrl.toString() );
        // convert addresses to result json
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
        writer.write("<html>\n");
        writer.write(" <head>\n");
        writer.write("  <title>mapzone - " + projectName + "</title>\n");
        writer.write("  <meta name='author' content='mapzone' />\n");
        writer.write("  <meta name='description' content='" + description + "' />\n");
        writer.write(
                "  <meta name='keywords' content='location, geo, web, osm, map, maps, styling, wms, csv, xls, georeference, geofence, geocode' />\n");
        writer.write("  <meta name='robots' content='index,follow' />\n");
        writer.write("  <meta name='audience' content='all' />\n");
        // writer.write( " <meta name='revisit-after' content='5 days' />\n");
        // facebook/opengraph
        writer.write("  <meta property='og:locality' content='Leipzig'/>\n");
        writer.write("  <meta property='og:country-name' content='Germany'/>\n");
        writer.write("  <meta property='og:latitude' content='51.32794'/>\n");
        writer.write("  <meta property='og:longitude' content='12.33126'/>\n");
        writer.write("  <meta property='og:image:url' content='" + imageUrl.toString() + "' />\n");
        writer.write("  <meta property='og:image:type' content='image/png' />\n");
        writer.write("  <meta property='og:image:width' content='1200' />\n");
        writer.write("  <meta property='og:image:height' content='630' />\n");
        writer.write("  <meta property='og:type' content='article' />\n");
        writer.write("  <meta property='og:site_name' content='mapzone - " + projectName + "' />\n");
        // wird grad nicht von Facebook untersttzt
        // writer.write( " <meta property='fb:app_id' content='1754931524765083'
        // />\n");
        // writer.write( " <meta property='fb:admins' content='739545402735248'
        // />\n");
        writer.write(
                "  <meta property='article:publisher' content='https://www.facebook.com/mapzoneio-1401853630109662' />\n");
        writer.write("  <meta property='article:author' content='https://www.facebook.com/stundzig' />\n");

        // writer.write( " <meta property='og:url' content='" + arenaUrl + "'
        // />\n");

        // perform a redirect after 10ms
        writer.write("  <script type='text/javascript'>window.setTimeout(function(){window.location.href = '"
                + arenaUrl + "'; },10);</script>\n");
        writer.write(" </head>\n");
        writer.write(" <body>\n");
        // writer.write( " <iframe src='" + arenaUrl
        // + "' width='100%' height='520' frameborder='0'
        // allowfullscreen='allowfullscreen'></iframe>\n");
        writer.write(" </body>\n");
        writer.write("<head>\n");
        writer.flush();
        writer.close();

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.motechproject.server.decisiontree.web.VxmlController.java

/**
 * Handles Decision Tree Node HTTP requests and generates a VXML document based on a Velocity template.
 * The HTTP request should contain the Tree ID, Node ID, Patient ID and Selected Transition Key (optional) parameters
 *
 *//* w  w  w  .j  av  a  2s.com*/
public ModelAndView node(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generating decision tree node VXML");

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    Node node = null;
    String transitionPath = null;
    Map<String, Object> params = convertParams(request.getParameterMap());

    String patientId = request.getParameter(PATIENT_ID_PARAM);
    String language = request.getParameter(LANGUAGE_PARAM);
    String treeNameString = request.getParameter(TREE_NAME_PARAM);
    String encodedParentTransitionPath = request.getParameter(TRANSITION_PATH_PARAM);
    String transitionKey = request.getParameter(TRANSITION_KEY_PARAM);

    logger.info(" Node HTTP  request parameters: " + PATIENT_ID_PARAM + ": " + patientId + ", " + LANGUAGE_PARAM
            + ": " + language + ", " + TREE_NAME_PARAM + ": " + treeNameString + ", " + TRANSITION_PATH_PARAM
            + ": " + encodedParentTransitionPath + ", " + TRANSITION_KEY_PARAM + ": " + transitionKey);

    if (StringUtils.isBlank(patientId) || StringUtils.isBlank(language)
            || StringUtils.isBlank(treeNameString)) {

        logger.error("Invalid HTTP request - the following parameters: " + PATIENT_ID_PARAM + ", "
                + LANGUAGE_PARAM + " and " + TREE_NAME_PARAM + " are mandatory");
        return getErrorModelAndView(Errors.NULL_PATIENTID_LANGUAGE_OR_TREENAME_PARAM);
    }

    String[] treeNames = treeNameString.split(TREE_NAME_SEPARATOR);
    String currentTree = treeNames[0];
    // put only one tree name in params
    params.put(TREE_NAME_PARAM, currentTree);

    if (transitionKey == null) { // get root node
        try {
            String rootTransitionPath = TreeNodeLocator.PATH_DELIMITER;
            node = decisionTreeService.getNode(currentTree, rootTransitionPath);
            transitionPath = rootTransitionPath;
        } catch (Exception e) {
            logger.error("Can not get node by Tree Name: " + currentTree + " transition path: " + patientId, e);
        }
    } else { // get not root node
        String parentTransitionPath = null;
        try {
            if (encodedParentTransitionPath == null) {

                logger.error(
                        "Invalid HTTP request - the  " + TRANSITION_PATH_PARAM + " parameter is mandatory");
                return getErrorModelAndView(Errors.NULL_TRANSITION_PATH_PARAM);
            }

            parentTransitionPath = new String(Base64.decodeBase64(encodedParentTransitionPath));
            Node parentNode = decisionTreeService.getNode(currentTree, parentTransitionPath);

            Transition transition = parentNode.getTransitions().get(transitionKey);

            if (transition == null) {
                logger.error("Invalid Transition Key. There is no transition with key: " + transitionKey
                        + " in the Node: " + parentNode);
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY);
            }

            treeEventProcessor.sendActionsAfter(parentNode, parentTransitionPath, params);

            treeEventProcessor.sendTransitionActions(transition, params);

            node = transition.getDestinationNode();

            if (node == null || (node.getPrompts().isEmpty() && node.getActionsAfter().isEmpty()
                    && node.getActionsBefore().isEmpty() && node.getTransitions().isEmpty())) {
                if (treeNames.length > 1) {
                    //reduce the current tree and redirect to the next tree
                    treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
                    String view = String.format(
                            "redirect:/tree/vxml/node?" + PATIENT_ID_PARAM + "=%s&" + TREE_NAME_PARAM + "=%s&"
                                    + LANGUAGE_PARAM + "=%s",
                            patientId, StringUtils.join(treeNames, TREE_NAME_SEPARATOR), language);
                    ModelAndView mav = new ModelAndView(view);
                    return mav;
                } else {
                    //TODO: Add support for return url
                    ModelAndView mav = new ModelAndView(EXIT_TEMPLATE_NAME);
                    return mav;
                }

            } else {
                transitionPath = parentTransitionPath
                        + (TreeNodeLocator.PATH_DELIMITER.equals(parentTransitionPath) ? ""
                                : TreeNodeLocator.PATH_DELIMITER)
                        + transitionKey;
            }

        } catch (Exception e) {
            logger.error("Can not get node by Tree ID : " + currentTree + " and Transition Path: "
                    + parentTransitionPath, e);
        }
    }

    if (node != null) {

        //validate node
        for (Map.Entry<String, Transition> transitionEntry : node.getTransitions().entrySet()) {

            try {
                Integer.parseInt(transitionEntry.getKey());
            } catch (NumberFormatException e) {
                logger.error("Invalid node: " + node
                        + "\n In order  to be used in VXML transition keys should be an Integer");
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY_TYPE);
            }

            Transition transition = transitionEntry.getValue();
            if (transition.getDestinationNode() == null) {
                logger.error(
                        "Invalid node: " + node + "\n Null Destination Node in the Transition: " + transition);
                return getErrorModelAndView(Errors.NULL_DESTINATION_NODE);
            }
        }

        treeEventProcessor.sendActionsBefore(node, transitionPath, params);

        ModelAndView mav = new ModelAndView();
        if (node.getTransitions().size() > 0) {
            mav.setViewName(NODE_TEMPLATE_NAME);
            mav.addObject("treeName", treeNameString);
        } else { // leaf
            //reduce the current tree and redirect to the next tree
            treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
            mav.setViewName(LEAF_TEMPLATE_NAME);
            mav.addObject("treeName", StringUtils.join(treeNames, TREE_NAME_SEPARATOR));
        }
        mav.addObject("contentPath", request.getContextPath());
        mav.addObject("node", node);
        mav.addObject("patientId", patientId);
        mav.addObject("language", language);
        mav.addObject("transitionPath", Base64.encodeBase64URLSafeString(transitionPath.getBytes()));
        mav.addObject("escape", new StringEscapeUtils());

        return mav;
    } else {
        return getErrorModelAndView(Errors.GET_NODE_ERROR);
    }

}

From source file:eu.europeana.core.util.web.ClickStreamLoggerImpl.java

@Override
public void logApiBriefView(HttpServletRequest request, BriefBeanView briefBeanView, SolrQuery solrQuery) {
    //TODO: finish this
    String query = briefBeanView.getPagination().getPresentationQuery().getUserSubmittedQuery(); //
    String queryConstraints = "";
    if (solrQuery.getFilterQueries() != null) {
        queryConstraints = StringUtils.join(solrQuery.getFilterQueries(), ",");
    }// w  w w.  j  ava  2  s . c o  m
    UserAction userAction = UserAction.API_BRIEF;
    Map params = request.getParameterMap();
    int pageNr = briefBeanView.getPagination().getPageNumber();
    int nrResults = briefBeanView.getPagination().getNumFound();
    String languageFacets = briefBeanView.getFacetLogs().get("LANGUAGE");
    String countryFacet = briefBeanView.getFacetLogs().get("COUNTRY");
    log.info(MessageFormat.format(
            "[action={0}, query={1}, queryType={2}, queryConstraints=\"{3}\", page={4}, "
                    + "numFound={5}, langFacet={6}, countryFacet={7}, {8}]",
            userAction, query, solrQuery.getQueryType(), queryConstraints, pageNr, nrResults, languageFacets,
            countryFacet, printLogAffix(request)));

}