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:mx.edu.um.mateo.inventario.web.ProductoController.java

@SuppressWarnings("unchecked")
@RequestMapping/*from ww  w . ja  v  a  2  s .  c om*/
public String lista(HttpServletRequest request, HttpServletResponse response, Usuario usuario, Errors errors,
        Model modelo) throws ParseException {
    log.debug("Mostrando lista de productos");
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Map<String, Object> params = this.convierteParams(request.getParameterMap());
    Long almacenId = (Long) request.getSession().getAttribute("almacenId");
    params.put("almacen", almacenId);

    boolean buscarPorFecha = false;
    if (params.containsKey("fecha")) {
        log.debug("Fecha: {}", params.get("fecha"));
        params.put("fecha", sdf.parse((String) params.get("fecha")));
        buscarPorFecha = true;
    }

    if (params.containsKey("inactivo")) {
        params.put("inactivo", Boolean.valueOf((String) params.get("inactivo")));
    }

    if (params.containsKey("tipo") && StringUtils.isNotBlank((String) params.get("tipo"))) {
        params.put("reporte", true);
        if (!buscarPorFecha) {
            params = productoDao.lista(params);
        } else {
            log.debug("Buscando por fecha {}", params.get("fecha"));
            params = productoDao.obtieneHistorial(params);
        }
        try {
            generaReporte((String) params.get("tipo"), (List<Producto>) params.get("productos"), response,
                    "productos", Constantes.ALM, almacenId);
            return null;
        } catch (ReporteException e) {
            log.error("No se pudo generar el reporte", e);
            params.remove("reporte");
            errors.reject("error.generar.reporte");
        }
    }

    if (params.containsKey("correo") && StringUtils.isNotBlank((String) params.get("correo"))) {
        params.put("reporte", true);
        if (!buscarPorFecha) {
            params = productoDao.lista(params);
        } else {
            log.debug("Buscando por fecha {}", params.get("fecha"));
            params = productoDao.obtieneHistorial(params);
        }

        params.remove("reporte");
        try {
            enviaCorreo((String) params.get("correo"), (List<Producto>) params.get("productos"), request,
                    "productos", Constantes.ALM, almacenId);
            modelo.addAttribute("message", "lista.enviada.message");
            modelo.addAttribute("messageAttrs",
                    new String[] { messageSource.getMessage("producto.lista.label", null, request.getLocale()),
                            ambiente.obtieneUsuario().getUsername() });
        } catch (ReporteException e) {
            log.error("No se pudo enviar el reporte por correo", e);
        }
    }
    if (!buscarPorFecha) {
        params = productoDao.lista(params);
    } else {
        log.debug("Buscando por fecha {}", params.get("fecha"));
        params = productoDao.obtieneHistorial(params);
    }
    modelo.addAttribute("productos", params.get("productos"));

    Long pagina = 1l;
    if (params.containsKey("pagina")) {
        pagina = (Long) params.get("pagina");
    }
    this.pagina(params, modelo, "productos", pagina);

    return "inventario/producto/lista";
}

From source file:fr.paris.lutece.plugins.workflow.modules.appointment.service.TaskNotifyAppointment.java

/**
 * {@inheritDoc}//from   www . ja  va  2s  .com
 */
@Override
public void processTask(int nIdResourceHistory, HttpServletRequest request, Locale locale) {
    String sServerMailLang = AppPropertiesService.getProperty(PROPERTY_MAIL_LANG_SERVER);

    ResourceHistory resourceHistory = _resourceHistoryService.findByPrimaryKey(nIdResourceHistory);
    TaskNotifyAppointmentConfig config = _taskNotifyAppointmentConfigService.findByPrimaryKey(this.getId());
    Appointment appointment = AppointmentHome.findByPrimaryKey(resourceHistory.getIdResource());

    if (request != null) {
        Map<String, String[]> parameters = request.getParameterMap();
        String strCancelMotif = null;
        for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
            if (entry.getKey().startsWith(MARK_MOTIF_CANCEL)) {
                String[] tabAllParamsStartedWithCommentValue = entry.getValue();
                strCancelMotif = tabAllParamsStartedWithCommentValue[0];
                config.setCancelMotif(strCancelMotif);
                break;
            }
        }
    }

    String strEmail;

    if (config != null && config.getIsSms()) {
        strEmail = getEmailForSmsFromAppointment(appointment);
    } else {
        strEmail = appointment.getEmail();
    }

    if (StringUtils.isNotBlank(strEmail)) {
        Locale lEmailLocale = null;
        if (!sServerMailLang.isEmpty()) {
            lEmailLocale = new Locale(sServerMailLang.split("_")[0], sServerMailLang.split("_")[1]);
        } else {
            lEmailLocale = locale;
        }

        if (appointment.getStatus() > 0 && StringUtils.isNotEmpty(config.getCancelMotif())) {
            config.setMessage(ERROR_CANCEL_APPOINTMENT_MSG);
        }

        if (this.sendEmail(appointment, resourceHistory, request, lEmailLocale, config, strEmail) != null) {
            if ((config.getIdActionCancel() > 0)
                    && (config.getIdActionCancel() != appointment.getIdActionCancel())) {
                appointment.setIdActionCancel(config.getIdActionCancel());
                AppointmentHome.update(appointment);
            }
        }
    }
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same standard
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a standard request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the data to be sent via the {@link EntityEnclosingMethod}
 */// www  . ja  v a2  s  .  c om
@SuppressWarnings("unchecked")
private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest)
        throws IOException {
    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {
        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {
            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
    }
    RequestEntity entity = null;
    String contentType = httpServletRequest.getContentType();
    if (contentType != null) {
        contentType = contentType.toLowerCase();
        if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application")
                || contentType.contains("text")) {
            String body = IOHelpers.readFully(httpServletRequest.getReader());
            entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding());
            entityEnclosingMethod.setRequestEntity(entity);
        }
    }
    NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {});
    if (entity != null) {
        // TODO add as URL parameters?
        //postMethodProxyRequest.addParameters(parameters);
    } else {
        // Set the proxy request POST data
        if (entityEnclosingMethod instanceof PostMethod) {
            ((PostMethod) entityEnclosingMethod).setRequestBody(parameters);
        }
    }
}

From source file:com.gradecak.alfresco.mvc.aop.AuthenticationAdvice.java

private String getTicket() {

    String ticket = "";
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();// ww  w . j ava  2s .  c om

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie != null && "TICKET".equals(cookie.getName().toUpperCase())) {
                ticket = cookie.getValue();
            }
        }
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> parameterMap = request.getParameterMap();

    if (parameterMap != null) {
        for (Object parameter : parameterMap.keySet()) {
            if (parameter != null && "TICKET".equals(((String) parameter).toUpperCase())) {
                ticket = (String) parameterMap.get(parameter);
            }
        }
    }

    // HttpSession session = request.getSession();
    // if (session != null) {
    // // TODO dgradecak: FIX THIS
    // User user = (User)session.getAttribute("_alfAuthTicket");
    // ticket = user.getTicket();
    // }

    return ticket;
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Main GET method//from ww  w  .  ja v a  2  s. co m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}

From source file:mecha.http.servlets.ProcServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   w  w w .ja v a 2s  .co  m*/
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        final JSONObject params = new JSONObject();
        Map<String, String[]> requestParamMap = request.getParameterMap();
        for (String k : requestParamMap.keySet()) {
            String[] values = requestParamMap.get(k);
            if (values.length == 1) {
                params.put(k, values[0]);
            } else {
                params.put(k, values);
            }
        }

        String[] parts = request.getPathInfo().substring(1).split("/");

        String subsystem = parts[0];

        JSONObject result;

        long t_start = System.currentTimeMillis();

        /*
         * /proc/metrics
        */
        if (subsystem.equals("metrics")) {
            result = doMetricsRequest(parts, params);

            /*
             * /proc/top
            */
        } else if (subsystem.equals("top")) {
            result = doTopRequest(parts, params);

            /*
             * /proc/node
            */
        } else if (subsystem.equals("node")) {
            result = doNodeRequest(parts, params);

            /* 
             * /proc/config
            */
        } else if (subsystem.equals("config")) {
            result = doConfigRequest(parts, params);

            /*
             * /proc/cluster
            */
        } else if (subsystem.equals("cluster")) {
            result = doClusterRequest(parts, params);

            /*
             * /proc/riak
            */
        } else if (subsystem.equals("riak")) {
            result = doRiakRequest(parts, params);

            /*
             * unknown request
            */
        } else {
            response.getWriter().println("bad request\n");
            return;
        }
        long t_elapsed = System.currentTimeMillis() - t_start;

        JSONObject resultObj = new JSONObject();
        resultObj.put("elapsed", t_elapsed);
        resultObj.put("result", result);
        response.getWriter().println(resultObj.toString(2));
    } catch (Exception ex) {
        Mecha.getMonitoring().error("mecha.http.servlets.macro-servlet", ex);
        ex.printStackTrace();
    }
}

From source file:org.smigo.user.authentication.RestAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    response.setStatus(HttpStatus.FORBIDDEN.value());
    List<ObjectError> errors = new ArrayList<ObjectError>();
    if (exception instanceof BadCredentialsException) {
        errors.add(new ObjectError("bad-credentials", "msg.badcredentials"));
    } else {//w ww .j  ava 2s  .  c om
        errors.add(new ObjectError("username", "msg.unknownerror"));
    }
    String responseBody = objectMapper.writeValueAsString(errors);
    response.getWriter().append(responseBody);

    final String username = Arrays.toString(request.getParameterMap().get("username"));
    final String note = "Authentication Failure:" + username + System.lineSeparator() + exception;
    log.info(note);
    mailHandler.sendAdminNotification("authentication failure", note);
}

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

/**
 * ?url// ww  w. java2s  .c  o m
 * 
 * @param model
 * @param request
 * @param response
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@MethodRemark(value = "remark=?url,method=POST")
@RequestMapping(value = MobileConstants.M_PAYMENT_NOTIFY_PATH, method = RequestMethod.POST)
public void paymentNofity(ModelMap model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.info("html5?...");
    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] + ",";
        }
        params.put(name, valueStr);
    }
    String sign = request.getParameter("sign");
    log.info("sign:" + sign);
    ;
    String sec_id = request.getParameter("sec_id");
    log.info("sec_id:" + sec_id);
    String notify_data = request.getParameter("notify_data");// ?
    log.info("notify_data:" + notify_data);
    Document doc_notify_data = DocumentHelper.parseText(notify_data);
    String payment_type = doc_notify_data.selectSingleNode("//notify/payment_type").getText();
    log.info("payment_type:" + payment_type);
    String subject = doc_notify_data.selectSingleNode("//notify/subject").getText();
    log.info("subject:" + subject);
    String trade_no = doc_notify_data.selectSingleNode("//notify/trade_no").getText();
    log.info("trade_no:" + trade_no);
    String buyer_email = doc_notify_data.selectSingleNode("//notify/buyer_email").getText();
    log.info("buyer_email:" + buyer_email);
    String gmt_create = doc_notify_data.selectSingleNode("//notify/gmt_create").getText();
    log.info("gmt_create:" + gmt_create);
    String notify_type = doc_notify_data.selectSingleNode("//notify/notify_type").getText();
    log.info("notify_type:" + notify_type);
    String quantity = doc_notify_data.selectSingleNode("//notify/quantity").getText();
    log.info("quantity:" + quantity);
    String out_trade_no = doc_notify_data.selectSingleNode("//notify/out_trade_no").getText();
    log.info("out_trade_no:" + out_trade_no);
    String notify_time = doc_notify_data.selectSingleNode("//notify/notify_time").getText();
    log.info("notify_time:" + notify_time);
    String seller_id = doc_notify_data.selectSingleNode("//notify/seller_id").getText();
    log.info("seller_id:" + seller_id);
    String trade_status = doc_notify_data.selectSingleNode("//notify/trade_status").getText();
    log.info("trade_status:" + trade_status);
    String is_total_fee_adjust = doc_notify_data.selectSingleNode("//notify/is_total_fee_adjust").getText();
    log.info("is_total_fee_adjust:" + is_total_fee_adjust);
    String total_fee = doc_notify_data.selectSingleNode("//notify/total_fee").getText();
    log.info("total_fee:" + total_fee);
    String gmt_payment = "";
    if (doc_notify_data.selectSingleNode("//notify/gmt_payment") != null) {
        gmt_payment = doc_notify_data.selectSingleNode("//notify/gmt_payment").getText();
    }
    log.info("gmt_payment:" + gmt_payment);
    String seller_email = doc_notify_data.selectSingleNode("//notify/seller_email").getText();
    log.info("seller_email:" + seller_email);
    String price = doc_notify_data.selectSingleNode("//notify/price").getText();
    log.info("price:" + price);
    String buyer_id = doc_notify_data.selectSingleNode("//notify/buyer_id").getText();
    log.info("buyer_id:" + buyer_id);
    String notify_id = doc_notify_data.selectSingleNode("//notify/notify_id").getText();
    log.info("notify_id:" + notify_id);
    String use_coupon = doc_notify_data.selectSingleNode("//notify/use_coupon").getText();
    log.info("use_coupon:" + use_coupon);
    // 1????url
    // 2????
    AlipayParamDTO param = new AlipayParamDTO();
    param.setBuyerEmail(buyer_email);
    param.setBuyerId(buyer_id);
    param.setSallerEmail(seller_email);
    param.setSallerId(seller_id);
    param.setChannelType("directPay");
    param.setOrderId(out_trade_no);
    param.setTradeNo(trade_no);
    param.setTradeStatus(trade_status);
    param.setGmtPayment(gmt_payment);
    param.setGmtTradeCreate(gmt_create);
    param.setOrderTitle(subject);
    param.setOrderId(out_trade_no);
    param.setPayType(1);
    ResponseDTO<ConfirmResultDTO> pdt = paymentManager.aliPaySucConfirm(param);
    if (pdt == null) {
        log.error("hession??:?null");
        return;
    }
    try {
        if (ResponseCode.isSuccess(pdt.getCode())) {
            log.info("??");
            response.getWriter().print("success");

        } else {
            log.error("?:" + pdt.getMessage());
        }
    } catch (IOException e) {
        log.error("hession??", e);
    }

}

From source file:controler.category.UpdateCategoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Category category = new Category();
    int proNum = Integer.parseInt(request.getParameter("productNum").trim());
    category.setName(request.getParameter("name").trim());
    category.setId(Integer.parseInt(request.getParameter("id").trim()));
    if (request.getParameter("description") != null)
        category.setDescription(request.getParameter("description").trim());
    category.setProductNum(proNum);//from  w  w  w  .jav  a2 s  .c  om
    CategoryDAO categoryDAO = new CategoryDAO();
    try {
        BeanUtils.populate(category, request.getParameterMap());
        if (categoryDAO.connect()) {
            categoryDAO.updateCategory(category);
        }

    } catch (IllegalAccessException ex) {
        Logger.getLogger(UpdateCategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(UpdateCategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        categoryDAO.disconnect();
        response.sendRedirect("AdminViewCategory");

    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.MainResourceController.java

/**
 * @param request//w  w w. j av  a  2  s .c om
 * @param response
 * @return
 * @throws ResponseException
 */
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/{resource}", method = RequestMethod.GET)
@ResponseBody
public SimpleObject get(@PathVariable("resource") String resource, HttpServletRequest request,
        HttpServletResponse response) throws ResponseException {
    baseUriSetup.setup(request);
    Object res = restService.getResourceByName(buildResourceName(resource));
    Converter conv = res instanceof Converter ? (Converter) res : null;

    RequestContext context = RestUtil.getRequestContext(request, response, Representation.REF);

    @SuppressWarnings("unchecked")
    SearchHandler searchHandler = restService.getSearchHandler(buildResourceName(resource),
            request.getParameterMap());
    if (searchHandler != null) {
        return searchHandler.search(context).toSimpleObject(conv);
    }

    Enumeration parameters = request.getParameterNames();
    while (parameters.hasMoreElements()) {
        if (!RestConstants.SPECIAL_REQUEST_PARAMETERS.contains(parameters.nextElement())) {
            if (res instanceof Searchable) {
                return ((Searchable) res).search(context);
            } else {
                throw new ResourceDoesNotSupportOperationException(
                        res.getClass().getSimpleName() + " is not searchable");
            }
        }
    }

    if (res instanceof Listable) {
        return ((Listable) res).getAll(context);
    } else {
        throw new ResourceDoesNotSupportOperationException(res.getClass().getSimpleName() + " is not listable");
    }
}