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:it.geosolutions.httpproxy.service.impl.ProxyHelperImpl.java

/**
 * Prepare a proxy method execution// w  w  w.j a v  a  2 s  . c  o m
 * 
 * @param httpServletRequest
 * @param httpServletResponse
 * @param proxy
 * 
 * @return ProxyMethodConfig to execute the method
 * 
 * @throws IOException
 * @throws ServletException
 */
public ProxyMethodConfig prepareProxyMethod(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, ProxyService proxy) throws IOException, ServletException {
    URL url = null;
    String user = null, password = null;
    Map<?, ?> pars;
    String method = httpServletRequest.getMethod();

    if (HttpMethods.METHOD_GET.equals(method)) {
        // Obtain pars from parameter map
        pars = httpServletRequest.getParameterMap();
    } else {
        //Parse the queryString to not read the request body calling getParameter from httpServletRequest
        // so the method can simply forward the request body
        pars = splitQuery(httpServletRequest.getQueryString());
    }

    // Obtain ProxyMethodConfig from pars
    for (Object key : pars.keySet()) {

        String value = (pars.get(key) instanceof String) ? (String) pars.get(key)
                : ((String[]) pars.get(key))[0];

        if ("user".equals(key)) {
            user = value;
        } else if ("password".equals(key)) {
            password = value;
        } else if ("url".equals(key)) {
            url = new URL(value);
        }
    }

    // get url from the attribute if present
    if (url == null) {
        String urlString = (String) httpServletRequest.getAttribute("url");
        if (urlString != null)
            url = new URL(urlString);
    }

    if (url != null) {
        // init and return the config
        proxy.onInit(httpServletRequest, httpServletResponse, url);
        return new ProxyMethodConfig(url, user, password, method);
    } else {
        return null;
    }
}

From source file:ru.codemine.ccms.router.ExpencesRouter.java

@Secured("ROLE_OFFICE")
@RequestMapping(value = "/expences/savecell", method = RequestMethod.POST)
public @ResponseBody String expencesSavecell(HttpServletRequest request, @RequestParam Integer shopid,
        @RequestParam String dateYear) {
    Shop shop = shopService.getById(shopid);

    String expenceTypeName = request.getParameterMap().get("extypename")[0];
    if (expenceTypeName == null)
        return "{\"result\": \"error\"}";

    ExpenceType expenceType = expenceTypeService.getByName(expenceTypeName);
    if (expenceType == null)
        return "{\"result\": \"error\"}";

    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.M.YYYY");

    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        if (entry.getKey().startsWith("c")) {
            String cellname = entry.getKey();
            String cellval = entry.getValue()[0];
            if (cellval == null)
                return "{\"result\": \"error\"}";

            LocalDate startDate = formatter.parseLocalDate("01." + cellname.substring(1) + "." + dateYear);
            LocalDate endDate = startDate.dayOfMonth().withMaximumValue();

            Double value = Double.parseDouble(cellval);

            SalesMeta sm = salesService.getByShopAndDate(shop, startDate, endDate);
            sm.getExpences().put(expenceType, value);
            salesService.update(sm);/* w w  w  .ja v  a2  s . c  o  m*/
        }
    }

    return "{\"result\": \"success\"}";
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * POST can be used to modify a resource or to copy/move it.
 *
 * @param req/* w w w. j a va2s  . co  m*/
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String sourceURI = restUtils.extractRepositoryUri(req.getPathInfo());
    String destURI = restUtils.getDetinationUri(req);
    if (destURI != null) {
        if (req.getParameterMap().containsKey(restUtils.REQUEST_PARAMENTER_COPY_TO))
            resourcesManagementRemoteService.copyResource(sourceURI, destURI);
        else
            resourcesManagementRemoteService.moveResource(sourceURI, destURI);
    } else // Modify the resource...
    {
        HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);
        String resourceDescriptorXml = null;

        // get the resource descriptor...
        if (mreq instanceof MultipartHttpServletRequest)
            resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
        else {
            try {
                resourceDescriptorXml = IOUtils.toString(req.getInputStream());
            } catch (IOException ex) {
                throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
            }
        }
        if (resourceDescriptorXml == null) {
            String msg = "Missing parameter " + restUtils.REQUEST_PARAMENTER_RD + " "
                    + runReportService.getInputAttachments();
            restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, msg);
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, msg);
        }

        // Parse the resource descriptor...
        InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
        Document doc = null;
        ResourceDescriptor rd = null;
        try {
            doc = XMLUtil.getNewDocumentBuilder().parse(is);
            rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());

            // we force the rd to be new...
            rd.setIsNew(false);

            if (rd.getUriString() == null || !rd.getUriString().equals(sourceURI)) {
                throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                        "Request URI and descriptor URI are not equals");
            }
            resourcesManagementRemoteService.updateResource(sourceURI, rd, true);

            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");

        } catch (SAXException ex) {
            log.error("error parsing...", ex);
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } catch (ServiceException ex) {
            log.error("error executing the service...", ex);
            throw ex;
        } catch (ParserConfigurationException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (IOException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}

From source file:net.sf.jasperreports.web.servlets.ReportActionServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType(JSON_CONTENT_TYPE);
    setNoExpire(response);//  w w  w.j  a v  a  2s.c  o m

    PrintWriter out = response.getWriter();
    String contextId = request.getParameter(WebReportContext.REQUEST_PARAMETER_REPORT_CONTEXT_ID);

    if (contextId != null && request.getHeader("accept").indexOf(JSON_ACCEPT_HEADER) >= 0
            && request.getParameterMap().containsKey(REQUEST_PARAMETER_ACTION)) {
        WebReportContext webReportContext = WebReportContext.getInstance(request, false);

        if (webReportContext != null) {
            try {
                runAction(request, webReportContext);

                // FIXMEJIVE: actions shoud return their own ActionResult that would contribute with JSON object to the output
                JsonNode actionResult = (JsonNode) webReportContext
                        .getParameterValue("net.sf.jasperreports.web.actions.result.json");
                if (actionResult != null) {
                    out.println("{\"contextid\": \"" + webReportContext.getId() + "\", \"actionResult\": "
                            + actionResult + "}");
                    webReportContext.setParameterValue("net.sf.jasperreports.web.actions.result.json", null);
                } else {
                    out.println("{\"contextid\": \"" + webReportContext.getId() + "\"}");
                }

            } catch (Exception e) {
                log.error("Error on page status update", e);
                response.setStatus(404);
                out.println("{\"msg\": \"JasperReports encountered an error on context creation!\",");
                out.println("\"devmsg\": \"" + JRStringUtil.escapeJavaStringLiteral(e.getMessage()) + "\"}");
            }
        } else {
            response.setStatus(404);
            out.println("{\"msg\": \"Resource with id '" + contextId + "' not found!\"}");
            return;
        }

    } else {
        response.setStatus(400);
        out.println("{\"msg\": \"Wrong parameters!\"}");
    }
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Usuario usuario,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam Boolean enviaCorreo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from   ww w  .  jav a2  s  .c o m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    }

    String password = null;
    try {
        log.debug("Evaluando roles {}", request.getParameterValues("roles"));
        String[] roles = request.getParameterValues("roles");
        if (roles == null || roles.length == 0) {
            log.debug("Asignando ROLE_USER por defecto");
            roles = new String[] { "ROLE_USER" };
        }
        Long almacenId = (Long) request.getSession().getAttribute("almacenId");
        password = KeyGenerators.string().generateKey();
        usuario.setPassword(password);
        usuario = usuarioDao.crea(usuario, almacenId, roles);

        if (enviaCorreo) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(usuario.getCorreo());
            helper.setSubject(messageSource.getMessage("envia.correo.password.titulo.message", new String[] {},
                    request.getLocale()));
            helper.setText(messageSource.getMessage("envia.correo.password.contenido.message",
                    new String[] { usuario.getNombre(), usuario.getUsername(), password }, request.getLocale()),
                    true);
            mailSender.send(message);
        }

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al usuario", e);
        errors.rejectValue("username", "campo.duplicado.message", new String[] { "username" }, null);
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    } catch (MessagingException e) {
        log.error("No se pudo enviar la contrasena por correo", e);

        redirectAttributes.addFlashAttribute("message", "usuario.creado.sin.correo.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername(), password });

        return "redirect:/admin/usuario/ver/" + usuario.getId();
    }

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

    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

From source file:mx.edu.um.mateo.rh.web.SolicitudVacacionesEmpleadoController.java

@Transactional
@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response,
        @Valid SolicitudVacacionesEmpleado vacaciones, BindingResult bindingResult, Errors errors, Model modelo,
        RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from   w ww. j a v  a2 s.c  o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return Constantes.PATH_SOLICITUDVACACIONESEMPLEADO_NUEVO;
    }
    Usuario usuario = ambiente.obtieneUsuario();
    log.debug("obtuvo usuario");
    Empleado empleado = (Empleado) request.getSession().getAttribute(Constantes.EMPLEADO_KEY);
    log.debug("obtuvo empleado");
    vacaciones.setEmpleado(empleado);
    vacaciones.setFechaAlta(new Date());
    vacaciones.setUsuarioAlta(usuario);
    log.debug("paso llenar datos");
    try {
        log.debug("paso try");
        manager.graba(vacaciones, usuario);
        log.debug("paso grabar");
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear dia feriado", e);
        return Constantes.PATH_SOLICITUDVACACIONESEMPLEADO_NUEVO;
    }

    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "vacaciones.graba.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { vacaciones.getObservaciones() });

    return "redirect:" + Constantes.PATH_SOLICITUDVACACIONESEMPLEADO_LISTA + "/";
}

From source file:com.formkiq.core.form.service.FormCalculatorServiceImpl.java

/**
 * Build Parameter Map from {@link HttpServletRequest}.
 * @param request {@link HttpServletRequest}
 * @param form {@link FormJSON}/*from   w w w  .  ja v  a  2s  .c  om*/
 * @return {@link Map}
 * @throws IOException IOException
 */
private Map<String, String[]> buildParameterMap(final HttpServletRequest request, final FormJSON form)
        throws IOException {

    Map<String, String[]> values = new HashMap<>();

    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
        if (!ArrayUtils.isEmpty(e.getValue())) {
            values.put(e.getKey(), e.getValue());
        }
    }

    return values;
}

From source file:mx.edu.um.mateo.rh.web.ClaveEmpleadoController.java

@Transactional
@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response,
        @Valid ClaveEmpleado claveEmpleado, BindingResult bindingResult, Errors errors, Model modelo,
        RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from   ww  w  .  j av a  2 s.  co  m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return Constantes.PATH_CLAVEEMPLEADO_NUEVO;
    }
    Usuario usuario = ambiente.obtieneUsuario();
    Empleado empleado = (Empleado) request.getSession().getAttribute(Constantes.EMPLEADO_KEY);
    claveEmpleado.setEmpleado(empleado);
    claveEmpleado.setFechaAlta(new Date());
    claveEmpleado.setUsuarioAlta(usuario);
    try {
        manager.graba(claveEmpleado, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear nacionalidad", e);
        return Constantes.PATH_CLAVEEMPLEADO_NUEVO;
    }

    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "claveEmpleado.graba.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { claveEmpleado.getClave() });

    return "redirect:" + Constantes.PATH_CLAVEEMPLEADO_LISTA + "/";
}

From source file:it.marcoberri.mbmeteo.action.chart.GetMinOrMax.java

/**
 *
 * @param request/*from  w  w  w .j a  v  a2 s.  com*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");
    final String type = Default.toString(params.get("type"), "min");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, type);

    for (MapReduceMinMax m : mapReduceResult) {
        try {
            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());

            if (tmpDate == null) {
                continue;
            }

            final Method method = m.getClass().getMethod(chartEnum.getMethod());
            final Number n = (Number) method.invoke(m);
            dataset.addValue(n, chartEnum.getType(), DateTimeUtil.dateFormat(formatOut, tmpDate));

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final JFreeChart chart = ChartFactory.createBarChart(chartEnum.getTitle(), // chart title
            "", // domain axis label
            chartEnum.getUm(), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();
    final CategoryAxis domain = xyPlot.getDomainAxis();

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        xyPlot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    } else {
        xyPlot.getRangeAxis().setAutoRange(true);
    }

    domain.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (Exception e) {
        log.error(e);
    } finally {
        boolean delete = f.delete();
    }

}

From source file:eu.semlibproject.annotationserver.servlets.OpenIDAuthentication.java

private User verifyResponse(HttpServletRequest httpReq) throws ServletException {
    try {//from www  . j  a  v  a  2 s  . c  o m
        // 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(SemlibConstants.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 = consumerManager.verify(receivingURL.toString(), response, discovered);

        // examine the verification result and extract the verified identifier
        Identifier verified = verification.getVerifiedId();
        if (verified != null) {

            User cUser = new User(verified);
            cUser.setAuthenticated(true);

            // Compute the user ID
            String openIDIdentifier = verified.getIdentifier();
            String openIDHash = UtilsManager.getInstance().CRC32(openIDIdentifier);
            cUser.setID(openIDHash);

            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
            parseAttributesExchangeValues(cUser, authSuccess);

            return cUser; // success
        }
    } catch (OpenIDException e) {
        // present error to the user
        throw new ServletException(e);
    }

    return null;
}