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:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * Get a resource based of the requested URI.
 * If the parameter file is set, it will be used to retrieve the content of the file.
 * /*from w  w w.ja v a  2s .co  m*/
 * @param req
 * @param resp
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    // Get the uri of the resource
    String uri = restUtils.extractRepositoryUri(req.getPathInfo());
    if (!validParameters(req.getParameterMap().keySet())) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "request contains unsupported parameters");
    }

    // by default get the root...
    if (uri == null || uri.length() == 0)
        uri = "/";

    // get the resources....
    // Add all the options...
    Map<String, Object> options = new HashMap<String, Object>();

    // This options allow to get the informations about an input control
    // including the data to fill the input control....
    if (req.getParameter(Argument.IC_GET_QUERY_DATA) != null) {
        options.put(Argument.IC_GET_QUERY_DATA, req.getParameter(Argument.IC_GET_QUERY_DATA));

        // Extract parameters
        Map<String, Object> parameters = restUtils.extractParameters(req);

        // Add the parsed parameters to the options map (only if it makes sense)
        if (parameters.size() > 0) {
            options.put(Argument.PARAMS_ARG, parameters);
        }
    }

    options.put(restUtils.SWITCH_PARAM_GET_LOCAL_RESOURCE,
            restUtils.isLocalResource(uri) && req.getParameterMap().containsKey(restUtils.FILE_DATA));
    if (log.isDebugEnabled()) {
        log.debug("adding the local resource with data flag");
    }

    ResourceDescriptor rd = null;
    try {
        rd = resourcesManagementRemoteService.getResource(uri, options);
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex.getMessage());
    }

    // This check should not be useful, since an execption should have been thrown by service.getReporse
    if (rd == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find resource: " + uri);
        }
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "Could not find resource: " + uri);
    }

    // If the client specified a specific file, return the file
    if (Boolean.parseBoolean(req.getParameter(restUtils.FILE_DATA))) {
        if (runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()),
                    resp);
        else if (runReportService.getReportAttachments(rd.getUriString())
                .get(FileResourceHandler.MAIN_ATTACHMENT_ID) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString())
                    .get(FileResourceHandler.MAIN_ATTACHMENT_ID), resp);
        return;

    } else // else return the resource descriptor
    {

        Marshaller m = new Marshaller();
        String xml = m.writeResourceDescriptor(rd);

        resp.setContentType("text/xml");
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, xml);
    }
    return;
}

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

/**
 * Processes requests for both HTTP//www.  j a v  a2s  .  co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
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");

    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) {
            log.debug("get file from cache id: " + c.getGridId());
            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 (final IOException e) {
                    log.error(e);
                }

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

    final String titleChart = ChartEnumHelper.getByName(field).getTitle();
    final String umChart = ChartEnumHelper.getByName(field).getUm();
    final Query q = ds.createQuery(Meteolog.class);
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo);

    final List<Meteolog> meteoLogList = q.asList();
    final TimeSeries series = new TimeSeries(umChart);

    for (Meteolog m : meteoLogList) {
        final Millisecond t = new Millisecond(m.getTime());
        try {
            //violenza di una reflection
            final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod());
            final Number n = (Number) method.invoke(m);
            series.add(t, n);
        } catch (final NoSuchMethodException ex) {
            log.error(ex);
        } catch (final InvocationTargetException ex) {
            log.error(ex);
        } catch (final IllegalAccessException ex) {
            log.error(ex);
        } catch (final SecurityException ex) {
            log.error(ex);
        }

    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false,
            false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm"));
    axis.setVerticalTickLabels(true);

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

    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 (final IOException e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:br.mdarte.exemplo.academico.accessControl.Login.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    loadUseCaseInfo();/*from  w w w.j  a va 2  s .  c o  m*/

    org.apache.commons.beanutils.BeanUtils.populate(form, request.getParameterMap());

    ActionForward forward = null;
    if (request.getSession().getAttribute(Constantes.TROCA_SENHA_OBRIGATORIA) != null
            && request.getParameter(Constantes.BUTTON_TROCA_SENHA) == null) {
        forward = _verificaTrocaSenhaObrigatoria(mapping, form, request, response);
    } else {
        forward = _validarSessao(mapping, form, request, response);
    }
    try {
        request.getSession().setAttribute("mapping", mapping);
        request.getSession().setAttribute("form", form);
    } catch (java.lang.Exception exception) {
        Object formObj = org.andromda.presentation.bpm4struts.PageSessionObjectUtil.getPageForm(request,
                "${action.useCase.name}");

        if (formObj != null) {
            try {
                formObj.getClass()
                        .getMethod("resetCheckBoxes",
                                new Class[] { org.apache.struts.action.ActionMapping.class,
                                        javax.servlet.http.HttpServletRequest.class })
                        .invoke(formObj, new Object[] { null, null });
            } catch (Exception e2) {
                // ignoring
            }

            final java.util.Map parameters = new java.util.HashMap();
            for (final java.util.Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
                final String name = String.valueOf(names.nextElement());
                parameters.put(name, request.getParameterValues(name));
            }
            try {
                org.apache.commons.beanutils.BeanUtils.populate(formObj, parameters);
            } catch (java.lang.Exception populateException) {
                // ignore if we have an exception here (we just don't populate).
            }
        }
        throw exception;
    }

    request.getSession().setAttribute("form", form);

    Boolean aplicacaoGerenciaTrocaDePortas = (Boolean) request.getSession().getServletContext()
            .getAttribute("aplicacaoGerenciaTrocaDePortas");
    if (aplicacaoGerenciaTrocaDePortas) {
        if (forward != null && !(forward.getPath().contains("ForwardAction"))) {
            if (forward != null && forward.getPath().startsWith("/secure")) {
                forward = new ActionForward("https://" + (request.getServerName() + ":"
                        + request.getSession().getServletContext().getAttribute("httpsPort")
                        + "//sistemaacademico" + forward.getPath()).replaceAll("//", "/"), true);
            } else {
                if (forward != null && request.getScheme().equals("https")) {
                    if (!forward.getPath().startsWith("http")) {
                        forward = new ActionForward(
                                "http://" + (request.getServerName() + ":"
                                        + request.getSession().getServletContext().getAttribute("httpPort")
                                        + request.getContextPath() + forward.getPath()).replaceAll("//", "/"),
                                true);
                    }
                    if (forward.getPath().startsWith("https")) {
                        String httpPort = (String) request.getSession().getServletContext()
                                .getAttribute("httpPort");
                        String httpsPort = (String) request.getSession().getServletContext()
                                .getAttribute("httpsPort");
                        forward = new ActionForward(
                                forward.getPath().replaceAll("https", "http").replaceAll(httpsPort, httpPort),
                                true);
                    }
                }
            }
        }
    }

    // invalida sessao https ao trocar para http (passa a ter somente uma sessao para ambos)
    if (request.getScheme().equals("https") && forward != null && forward.getPath().startsWith("http://"))
        request.getSession().invalidate();

    return forward;

}

From source file:com.nkapps.billing.controllers.OverpaymentController.java

@RequestMapping(value = "/list", method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> list(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, Object> resMap = new LinkedHashMap<String, Object>();

    try {//www  .j a v a2  s.  c o  m
        // for saving search parameters
        searchService.execSearchBy(request, response);
        searchService.execSearchWithinDate(request, response);
        searchService.execSearchByDate(request, response);

        Map<String, String[]> map = request.getParameterMap();
        HashMap<String, String> parameters = new HashMap<>();

        for (String key : map.keySet()) {
            String[] mapValue = map.get(key);
            parameters.put(key, mapValue[0]);
        }

        resMap.put("success", true);
        resMap.put("draw", request.getParameter("draw"));

        resMap.put("data", overpaymentService.getList(parameters));

    } catch (Exception e) {
        logger.error(e.getMessage());
        resMap.put("success", false);
        resMap.put("reason", e.getMessage());
    }

    return resMap;
}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

private void handleOpenidResponse(HttpServletRequest request, HttpServletResponse response)
        throws IOException, Oops {
    ConsumerManager manager = new ConsumerManager();
    manager.setAllowStateless(false);// w w w .j av  a 2 s  . c o  m
    ParameterList params = new ParameterList(request.getParameterMap());
    try {
        VerificationResult verification = manager.verify(request.getRequestURL().toString(), params, null);
        if (null == verification.getVerifiedId() || !isBlank(verification.getStatusMsg()))
            throw new Oops("OpenID authentication failed. "
                    + ((null != verification.getStatusMsg()) ? verification.getStatusMsg() : ""));
        // We're authenticated!  Now approve the request token.
        handleAuthenticated(verification, request, response);
    } catch (OpenIDException e) {
        logger.info("Exception verifying OpenID response.", e);
        throw new Oops("Unable to verify OpenID response: " + e.getMessage());
    }
}

From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java

public String getDetinationUri(HttpServletRequest req) { // for action that specify the destination of the action in the request
    if (req.getParameterMap().containsKey(REQUEST_PARAMENTER_MOVE_TO))
        return req.getParameter(REQUEST_PARAMENTER_MOVE_TO);

    if (req.getParameterMap().containsKey(REQUEST_PARAMENTER_COPY_TO))
        return req.getParameter(REQUEST_PARAMENTER_COPY_TO);

    return null;/*  w w w. j a  v a2 s.co m*/
}

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

@Transactional
@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response, @Valid Dependiente dependiente,
        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  .ja  v a 2s. c  o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return Constantes.PATH_DEPENDIENTE_NUEVO;
    }

    try {

        //Aqui quedaba para agregar el empleado//

        dependienteManager.graba(dependiente);

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear dependiente", e);
        return Constantes.PATH_DEPENDIENTE_NUEVO;
    }

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

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

From source file:com.ctb.prism.report.api.ReportActionServlet.java

/**
 *
 *//* w  w  w.  j av a  2  s .c  om*/
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType(JSON_CONTENT_TYPE);
    setNoExpire(response);

    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, response, webReportContext);
                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:io.seldon.api.controller.JsClientController.java

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

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

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

@RequestMapping("/historial/{id}")
public String historial(HttpServletRequest request, @PathVariable Long id,
        @RequestParam(required = false) Long pagina, Model modelo) {
    log.debug("Mostrando historial del producto {}", id);
    Map<String, Object> params = this.convierteParams(request.getParameterMap());
    params = productoDao.historial(id, params);

    modelo.addAttribute("historial", params.get("historial"));

    // inicia paginado
    if (params.containsKey("pagina")) {
        pagina = (Long) params.get("pagina");
    } else {/* ww w  .j a v a 2s.  c  o m*/
        pagina = 1L;
    }
    this.pagina(params, modelo, "historial", pagina);
    // termina paginado

    return "inventario/producto/historial";
}