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:org.esco.cas.client.CasSingleLogoutClusterFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    CasSingleLogoutClusterFilter.LOG.trace("Filtering with request: [{}] ; method: [{}]", request);

    if (!this.peers.isEmpty() && (request instanceof HttpServletRequest)) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        CasSingleLogoutClusterFilter.LOG.trace("Filtering with HTTP method: [{}] ; parameters: [{}] ",
                httpRequest.getMethod(), httpRequest.getParameterMap().toString());

        if ("POST".equals(httpRequest.getMethod())) {

            //This a CAS client method I use
            final String logoutRequest = CommonUtils.safeGetParameter(httpRequest,
                    CasSingleLogoutClusterFilter.CAS_LOGOUT_REQUEST_HTTP_PARAM);
            //final String logoutRequest = httpRequest.getParameter(CasSingleLogoutClusterFilter.CAS_LOGOUT_REQUEST_HTTP_PARAM);
            CasSingleLogoutClusterFilter.LOG.debug("{}: [{}]",
                    CasSingleLogoutClusterFilter.CAS_LOGOUT_REQUEST_HTTP_PARAM, logoutRequest);

            // Set a flag so an application getting a rebroadcast doesn't rebroadcast it. don't want a packet storm
            final String rebroadcast = httpRequest
                    .getHeader(CasSingleLogoutClusterFilter.X_FORWARDED_LOGOUT_HEADER);
            CasSingleLogoutClusterFilter.LOG.debug("rebroadcast: [{}]", rebroadcast);

            if (StringUtils.hasText(logoutRequest) && (rebroadcast == null)) {
                try {
                    final String path = httpRequest.getServletPath();
                    final String context = httpRequest.getContextPath();
                    final String protocol = httpRequest.getScheme();

                    CasSingleLogoutClusterFilter.LOG.debug(
                            "Got a single logout request ; protocol: [{}] ; context: [{}] ; path: [{}].",
                            new Object[] { protocol, context, path });

                    // Set up the http client connection
                    CasSingleLogoutClusterFilter.LOG.debug("Attempting to rebroadcast");

                    // Peers are set in the init() method
                    for (Peer peer : this.peers) {
                        if (!peer.getHostName().equals(this.clientHostName)) {
                            // don't rebroadcast to your self!
                            CasSingleLogoutClusterFilter.LOG.debug("Processing peer: [{}]", peer);

                            // set rebroadcast=false so peers don't rebroacast. Only first recipient reboradcasts
                            this.sendLogoutRequestToPeer(peer, context + path, logoutRequest, true);
                        }/*  w ww.j  av a 2  s .co m*/
                    }
                } catch (Exception e) {
                    CasSingleLogoutClusterFilter.LOG.error("Error while broadcasting logout request !", e);
                }
            }
        }
    }

    chain.doFilter(request, response);
}

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

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*  w  w w .  j  av a  2s  .c  o m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return "inventario/producto/nuevo";
    }

    try {

        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.crea(producto, usuario);

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    } catch (IOException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "producto.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() });

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:org.openmrs.module.clinicalsummary.web.controller.service.ResponseController.java

@RequestMapping(method = RequestMethod.POST)
public void processResponse(@RequestParam(required = false, value = USERNAME) String username,
        @RequestParam(required = false, value = PASSWORD) String password, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    log.info("Processing responses from the android devices ...");

    try {/*from  w  w  w.  j a  v  a 2  s.c  o m*/
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);

        UtilService utilService = Context.getService(UtilService.class);
        // TODO: wanna puke with this code!!!!! super hacky!!!!!!!
        Map parameterMap = request.getParameterMap();
        for (Object parameterName : parameterMap.keySet()) {
            // skip the username and password request parameter
            if (!StringUtils.equalsIgnoreCase(USERNAME, String.valueOf(parameterName))
                    && !StringUtils.equalsIgnoreCase(PASSWORD, String.valueOf(parameterName))) {

                String id = String.valueOf(parameterName);
                String[] parameterValues = (String[]) parameterMap.get(id);

                log.info("ID: " + id);
                for (String parameterValue : parameterValues)
                    log.info("Parameter Values: " + String.valueOf(parameterValue));

                Patient patient = Context.getPatientService().getPatient(NumberUtils.toInt(id));
                if (patient != null)
                    processResponse(utilService, parameterValues, patient);
                else
                    processDeviceLogs(utilService, id, parameterValues);
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (ContextAuthenticationException e) {
        log.error("Authentication failure!", e);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        log.error("Unspecified exception happened when processing the request!", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:adminServlets.AddClientServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from w  w  w  . j a v a2  s. c o  m*/
        //************* startAllaa **************/
        //************** EndAllaa **************/
        //************* startAdel ************
        //************** EndAdel **************/
        //************* startSherif **************/
        //************** EndSherif **************/
        //************* startMoamen **************/

        Client client = new Client();
        BeanUtils.populate(client, request.getParameterMap());
        ClientService clientService = new ClientService();
        if (clientService.addClient(client)) {
            PrintWriter out = response.getWriter();
            out.println("Client has been added");
            response.sendRedirect("/FlowerCart/AdminView/ClientAddition.jsp");
        } else {
            PrintWriter out = response.getWriter();
            out.println("Client has not been saved");
            response.sendRedirect("/FlowerCart/AdminView/ClientAddition.jsp");
        }
        //************** EndMoamen **************/
    } catch (IllegalAccessException ex) {
        Logger.getLogger(AddClientServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(AddClientServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:jipdbs.web.processors.OpenIDLoginProcessor.java

public Identifier verifyResponse(HttpServletRequest httpReq) throws ServletException {
    try {//from w ww.j  a v a 2 s  . c om
        // extract the parameters from the authentication response
        // (which comes in as a HTTP request from the OpenID provider)
        ParameterList response = new ParameterList(httpReq.getParameterMap());

        // retrieve the previously stored discovery information
        DiscoveryInformation discovered = (DiscoveryInformation) httpReq.getSession()
                .getAttribute("openid-disc");

        // extract the receiving URL from the HTTP request
        StringBuffer receivingURL = httpReq.getRequestURL();
        String queryString = httpReq.getQueryString();
        if (queryString != null && queryString.length() > 0)
            receivingURL.append("?").append(httpReq.getQueryString());

        // verify the response; ConsumerManager needs to be the same
        // (static) instance used to place the authentication request
        VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);

        // examine the verification result and extract the verified
        // identifier
        Identifier verified = verification.getVerifiedId();
        log.debug("Verified {}", verified);
        if (verified != null) {
            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

            receiveSimpleRegistration(httpReq, authSuccess);

            receiveAttributeExchange(httpReq, authSuccess);

            for (Iterator it = authSuccess.getExtensions().iterator(); it.hasNext();) {
                Object o = it.next();
                log.debug(o.toString());
            }
            return verified; // success
        }
    } catch (OpenIDException e) {
        // present error to the user
        throw new ServletException(e);
    }

    return null;
}

From source file:io.seldon.api.controller.JsClientController.java

@RequestMapping("/predict")
public @ResponseBody JSONPObject predict(HttpSession session, HttpServletRequest request,
        @RequestParam(value = "json", required = false) String json,
        @RequestParam("jsonpCallback") String callback) {
    final ConsumerBean consumerBean = retrieveConsumer(session);
    @SuppressWarnings("unchecked")
    Map<String, String[]> parameters = request.getParameterMap();

    return asCallback(callback, predictionBusinessService.predict(consumerBean, parameters));
}

From source file:ru.org.linux.user.UserEventController.java

@RequestMapping(value = "/show-replies.jsp", method = RequestMethod.GET)
public ModelAndView showReplies(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "nick", required = false) String nick,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @ModelAttribute("notifications") Action action) throws Exception {
    Template tmpl = Template.getTemplate(request);
    boolean feedRequested = request.getParameterMap().containsKey("output");

    if (nick == null) {
        if (tmpl.isSessionAuthorized()) {
            return new ModelAndView(new RedirectView("/notifications"));
        }//from   w  w  w .j  a  va2 s  . c o m
        throw new AccessViolationException("not authorized");
    } else {
        User.checkNick(nick);
        if (!tmpl.isSessionAuthorized() && !feedRequested) {
            throw new AccessViolationException("not authorized");
        }
        if (tmpl.isSessionAuthorized() && nick.equals(tmpl.getCurrentUser().getNick()) && !feedRequested) {
            return new ModelAndView(new RedirectView("/notifications"));
        }
        if (!feedRequested && !tmpl.isModeratorSession()) {
            throw new AccessViolationException(
                    "? ?  ?");
        }
    }

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();
    if (feedRequested) {
        topics = 50;
    }

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);

    User user = userDao.getUser(nick);

    boolean showPrivate = tmpl.isModeratorSession();

    User currentUser = tmpl.getCurrentUser();
    params.put("currentUser", currentUser);

    if (currentUser != null && currentUser.getId() == user.getId()) {
        showPrivate = true;
        params.put("unreadCount", user.getUnreadEvents());
        response.addHeader("Cache-Control", "no-cache");
    }

    List<UserEvent> list = userEventService.getRepliesForUser(user, showPrivate, topics, offset,
            UserEventFilterEnum.ALL);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, feedRequested, request.isSecure());

    params.put("isMyNotifications", false);
    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    ModelAndView result = new ModelAndView("show-replies", params);

    if (feedRequested) {
        result.addObject("feed-type", "rss");
        if ("atom".equals(request.getParameter("output"))) {
            result.addObject("feed-type", "atom");
        }
        result.setView(feedView);
    }
    return result;
}

From source file:fr.paris.lutece.plugins.workflow.modules.notifycrm.web.NotifyCRMTaskComponent.java

/**
 * {@inheritDoc}//from w  w w .  j  av a  2 s  . c  o m
 */
@Override
public String doSaveConfig(HttpServletRequest request, Locale locale, ITask task) {
    // In case there are no errors, then the config is created/updated
    boolean bCreate = false;
    TaskNotifyCRMConfig config = _taskNotifyCRMConfigService.findByPrimaryKey(task.getId());

    if (config == null) {
        config = new TaskNotifyCRMConfig();
        config.setIdTask(task.getId());
        bCreate = true;
    }

    try {
        BeanUtils.populate(config, request.getParameterMap());
    } catch (IllegalAccessException e) {
        AppLogService.error("NotifyCRMTaskComponent - Unable to fetch data from request", e);
    } catch (InvocationTargetException e) {
        AppLogService.error("NotifyCRMTaskComponent - Unable to fetch data from request", e);
    }

    String strApply = request.getParameter(NotifyCRMConstants.PARAMETER_APPLY);

    // Check if the AdminUser clicked on "Apply" or on "Save"
    if (StringUtils.isEmpty(strApply)) {
        // Check mandatory fields
        Set<ConstraintViolation<TaskNotifyCRMConfig>> constraintViolations = BeanValidationUtil
                .validate(config);

        if (constraintViolations.size() > 0) {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    }

    if (bCreate) {
        _taskNotifyCRMConfigService.create(config);
    } else {
        _taskNotifyCRMConfigService.update(config);
    }

    return null;
}

From source file:com.greenline.guahao.web.module.home.controllers.mobile.reservation.MobilePaymentController.java

/**
 * ??(??)//from   w ww . ja  v  a  2s . co m
 * 
 * @param model
 * @param request
 * @return String
 * @throws UnsupportedEncodingException
 */
@SuppressWarnings({ "rawtypes" })
@MethodRemark(value = "remark=??(??),method=GET")
@RequestMapping(value = MobileConstants.M_PAYMENT_RETURN_PATH, method = RequestMethod.GET)
public String paymentResult(ModelMap model, HttpServletRequest request) throws UnsupportedEncodingException {
    // ??GET????
    Map<String, String> params = new HashMap<String, String>();
    Map requestParams = request.getParameterMap();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
        String name = (String) iter.next();
        String[] values = (String[]) requestParams.get(name);
        String valueStr = "";
        for (int i = 0; i < values.length; i++) {
            valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
        }
        // ???mysignsign???
        valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
        params.put(name, valueStr);
    }
    // ?
    boolean verify_result = AlipayCore.verify(params);
    if (verify_result) {// ??
        String out_trade_no = request.getParameter("out_trade_no");
        model.put("out_trade_no", out_trade_no);
        // ????????
        String orderId = out_trade_no;
        OrderDO orderBrief = orderManager.getOrder(orderId);
        String orderResult = "";
        if (orderBrief == null) {
            orderResult = "?????????,??:"
                    + orderId;
            log.error(orderResult);
            model.put("orderResult", orderResult);
            return MobileConstants.M_PAYMENTERROR;
        } else {
            // ???hrs?
            ExpertDO expert = expertManager.getExpert(orderBrief.getExpertId());
            ShiftCaseVO shiftCaseVO = new ShiftCaseVO();
            if (null != expert) {
                shiftCaseVO.setExpertId(expert.getId());
            }
            shiftCaseVO.setDeptId(orderBrief.getHospDepartmentId());
            shiftCaseVO.setHospitalId(orderBrief.getHospitalId());
            model.put("shiftCaseVO", shiftCaseVO);
            model.put("orderNo", orderId);
            int orderState = orderBrief.getStatus();
            if (orderState == 6001) {
                // ?
                orderResult = "?????????????"
                        + orderId;
                log.error(orderResult);
                model.put("orderResult", orderResult);
                return MobileConstants.M_PAYMENTERROR;
            }
            // ??????????
        }
        return MobileConstants.M_RESERVATION_SUC;
    } else {
        model.put("orderResult", "?sign?");
        log.error("html5?sign?");
        return MobileConstants.M_PAYMENTERROR;
    }

}