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.rh.web.JefeRHController.java

@Transactional
@RequestMapping(value = "/graba", method = RequestMethod.POST)
public String graba(HttpServletRequest request, HttpServletResponse response, @Valid Jefe jefe,
        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.c  o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return Constantes.PATH_JEFE_NUEVO;
    }
    Usuario usuario = ambiente.obtieneUsuario();
    CentroCosto cc = cCostoDao.obtiene(request.getParameter("centroCosto.nombre"), usuario);
    Empleado empleado = empleadoManager.getEmpleado(jefe.getJefe());
    jefe.setCentroCosto(cc);
    jefe.setJefe(empleado);
    jefe.setSubjefe(empleado);
    try {
        manager.graba(jefe, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear dia feriado", e);
        return Constantes.PATH_JEFE_NUEVO;
    }

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

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

From source file:de.iteratec.turm.servlets.TurmServlet.java

/**
 * Log the parameters contained in the given request for
 * debugging purposes.//from  ww  w  . j  ava  2  s .  co  m
 * 
 * @param request The current Serlvet Request
 */
@SuppressWarnings("unchecked")
private void logRequestParameters(HttpServletRequest request) {
    if (!LOGGER.isDebugEnabled()) {
        return;
    }
    LOGGER.debug("-------------- Parameters in request --------------");
    Map<String, String[]> parameterMap = request.getParameterMap();
    for (Iterator<Map.Entry<String, String[]>> it = parameterMap.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String[]> entry = it.next();
        LOGGER.debug(entry.getKey() + ": ");
        String[] value = entry.getValue();
        String parametersValues = "\t";
        for (int i = 0; i < value.length; i++) {
            if (i > 0) {
                parametersValues += ", ";
            }
            parametersValues += value[i];
        }
        LOGGER.debug(parametersValues);
    }
    LOGGER.debug("---------------------------------------------------");
}

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

@SuppressWarnings("unchecked")
@RequestMapping(value = "/clientes", params = "term", produces = "application/json")
public @ResponseBody List<LabelValueBean> clientes(HttpServletRequest request,
        @RequestParam("term") String filtro) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//  ww  w. ja v  a2s .c  o m
    Map<String, Object> params = new HashMap<>();
    params.put("empresa", request.getSession().getAttribute("empresaId"));
    params.put("filtro", filtro);
    params = clienteDao.lista(params);
    List<LabelValueBean> valores = new ArrayList<>();
    List<Cliente> clientes = (List<Cliente>) params.get("clientes");
    for (Cliente cliente : clientes) {
        StringBuilder sb = new StringBuilder();
        sb.append(cliente.getNombre());
        sb.append(" | ");
        sb.append(cliente.getRfc());
        sb.append(" | ");
        sb.append(cliente.getNombreCompleto());
        valores.add(new LabelValueBean(cliente.getId(), sb.toString(), cliente.getNombre()));
    }
    return valores;
}

From source file:com.stormpath.sdk.servlet.mvc.FormController.java

protected void validate(HttpServletRequest request, HttpServletResponse response, Form form) {

    validateCsrfToken(request, response, form);

    // check for request body and no parameters
    if (request.getParameterMap().size() == 0 && request.getContentLength() > 0) {
        // Read from request to see if social information exists
        ProviderAccountRequest accountRequest = getAccountProviderRequest(request);
        if (accountRequest != null) {
            ProviderAccountResult result = getApplication(request).getAccount(accountRequest);
            Account account = result.getAccount();
            if (account.getStatus().equals(AccountStatus.ENABLED)) {
                request.setAttribute(Account.class.getName(), account);
                return;
            }/*from  w ww . j av  a 2s.c om*/
        }
    }

    //ensure required fields are present:
    List<Field> fields = form.getFields();
    for (Field field : fields) {
        if (field.isRequired() && field.isEnabled()) {
            String value = form.getFieldValue(field.getName());
            if (value == null) {
                String key = "stormpath.web." + getControllerKey() + ".form.fields." + field.getName()
                        + ".required";
                String msg = i18n(request, key);
                throw new ValidationException(msg);
            }
        }
    }

    //If JSON ensure we are not posting undeclared fields according to the spec
    if (isJsonPreferred(request, response)) {
        Map<String, Object> postedJsonFields = fieldValueResolver.getAllFields(request);

        for (String fieldName : postedJsonFields.keySet()) {
            if (form.getField(fieldName) == null && !"customData".equals(fieldName)) {
                String key = "stormpath.web.form.fields.unknown";
                String msg = i18n(request, key, fieldName);
                throw new ValidationException(msg);
            }
        }
    }
}

From source file:com.manydesigns.portofino.stripes.ForbiddenAccessResolution.java

public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    //TODO ElementsActionBeanContext
    ElementsActionBeanContext context = new ElementsActionBeanContext();
    context.setRequest(request);//from ww w .  ja  v  a 2 s.c  o  m
    String originalPath = context.getActionPath();
    UrlBuilder urlBuilder = new UrlBuilder(Locale.getDefault(), originalPath, false);
    Map<?, ?> parameters = request.getParameterMap();
    urlBuilder.addParameters(parameters);
    String returnUrl = urlBuilder.toString();
    boolean ajax = "true".equals(request.getParameter("ajax"));
    ServletContext servletContext = ElementsThreadLocals.getServletContext();
    Configuration configuration = (Configuration) servletContext
            .getAttribute(BaseModule.PORTOFINO_CONFIGURATION);
    if (!subject.isAuthenticated() && !ajax) {
        logger.info("Anonymous user not allowed. Redirecting to login.");
        String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
        RedirectResolution redirectResolution = new RedirectResolution(loginPage, true);
        redirectResolution.addParameter("returnUrl", returnUrl);
        redirectResolution.execute(request, response);
    } else {
        if (ajax) {
            logger.debug("AJAX call while user disconnected");
            //TODO where to redirect?
            String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
            UrlBuilder loginUrlBuilder = new UrlBuilder(Locale.getDefault(), loginPage, false);
            response.setStatus(UNAUTHORIZED);
            new StreamingResolution("text/plain", loginUrlBuilder.toString()).execute(request, response);
        } else {
            logger.warn("User not authorized for url {}.", returnUrl);
            new ErrorResolution(UNAUTHORIZED, errorMessage).execute(request, response);
        }
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/*from   w  w  w .  j  av a 2 s  .c  om*/
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:com.formkiq.core.api.FolderFilesController.java

/**
 * Email File.//from  w  w  w. j  a va  2  s. c  o m
 * @param request {@link HttpServletRequest}
 * @return {@link ApiMessageResponse}
 * @throws IOException IOException
 */
@Transactional
@RequestMapping(value = API_FOLDER_FILE_EMAIL, method = POST)
public ApiMessageResponse emailFolderFile(final HttpServletRequest request) throws IOException {

    ApiMessageResponse msg = new ApiMessageResponse("Email sent");

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

    String to = getParameter(map, "to", true);
    String subject = getParameter(map, "subject", true);
    String body = getParameter(map, "body", true);
    String folder = getParameter(map, "folder", true);
    String uuid = getParameter(map, "uuid", true);

    this.workflowService.emailForm(request, folder, uuid, to, subject, body);

    return msg;
}

From source file:fr.ensimag.biblio.controllers.StatImg.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from ww  w. j  av  a2s  .com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    //int val1 = 40;
    //int val2 = 60;
    try {
        DefaultPieDataset dataset = new DefaultPieDataset();
        String title = "Statistiques";
        boolean legend = true;

        Map<String, String[]> params = request.getParameterMap();
        for (Map.Entry<String, String[]> param : params.entrySet()) {
            String key = param.getKey();
            String[] value = param.getValue();
            System.out.println("key : " + key + "value : " + value[0]);
            if (key.equals("legend"))
                legend = Boolean.parseBoolean(value[0]);
            else
                dataset.setValue(key, Double.parseDouble(value[0]));
        }

        //dataset.setValue("Valeur 1", val1);
        //dataset.setValue("Valeur 2", val2);
        JFreeChart chart = ChartFactory.createPieChart(title, dataset, legend, false, false);
        chart.setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(out, chart, 500, 300);
    } finally {
        out.close();
    }
}

From source file:org.oncoblocks.centromere.web.controller.AbstractApiController.java

/**
 * Queries the repository using inputted query string paramters, defined within a annotated 
 *   {@link Model} classes.  Supports hypermedia, pagination, sorting, field 
 *   filtering, and field exclusion./*from www .ja va  2 s  .c om*/
 * 
 * @param pagedResourcesAssembler {@link PagedResourcesAssembler}
 * @param request {@link HttpServletRequest}
 * @return
 */
@RequestMapping(value = "", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE,
        ApiMediaTypes.APPLICATION_HAL_JSON_VALUE, ApiMediaTypes.APPLICATION_HAL_XML_VALUE,
        MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE })
public HttpEntity<?> find(@PageableDefault(size = 1000) Pageable pageable,
        PagedResourcesAssembler<T> pagedResourcesAssembler, HttpServletRequest request) {
    ResponseEnvelope envelope;
    Set<String> fields = RequestUtils.getFilteredFieldsFromRequest(request);
    Set<String> exclude = RequestUtils.getExcludedFieldsFromRequest(request);
    pageable = RequestUtils.remapPageable(pageable, model);
    Map<String, String[]> parameterMap = request.getParameterMap();
    List<QueryCriteria> criterias = RequestUtils.getQueryCriteriaFromRequest(model, request);
    String mediaType = request.getHeader("Accept");
    Link selfLink = new Link(linkTo(this.getClass()).slash("").toString()
            + (request.getQueryString() != null ? "?" + request.getQueryString() : ""), "self");
    if (parameterMap.containsKey("page") || parameterMap.containsKey("size")) {
        Page<T> page = repository.find(criterias, pageable);
        if (ApiMediaTypes.isHalMediaType(mediaType)) {
            PagedResources<FilterableResource> pagedResources = pagedResourcesAssembler.toResource(page,
                    assembler, selfLink);
            envelope = new ResponseEnvelope(pagedResources, fields, exclude);
        } else {
            envelope = new ResponseEnvelope(page, fields, exclude);
        }
    } else {
        Sort sort = pageable.getSort();
        List<T> entities = null;
        if (sort != null) {
            entities = (List<T>) repository.find(criterias, sort);
        } else {
            entities = (List<T>) repository.find(criterias);
        }
        if (ApiMediaTypes.isHalMediaType(mediaType)) {
            List<FilterableResource> resourceList = assembler.toResources(entities);
            Resources<FilterableResource> resources = new Resources<>(resourceList);
            resources.add(selfLink);
            envelope = new ResponseEnvelope(resources, fields, exclude);
        } else {
            envelope = new ResponseEnvelope(entities, fields, exclude);
        }
    }
    return new ResponseEntity<>(envelope, HttpStatus.OK);
}

From source file:mx.edu.um.mateo.colportor.web.PedidoColportorController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response,
        @Valid PedidoColportor pedidoColportor, BindingResult bindingResult, Errors errors, Model modelo,
        RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*  w  w  w.  j a  v a  2s .  c  om*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");

        //Obtener la lista de clientes
        Map<String, Object> params = new HashMap<>();
        params.put("empresa", request.getSession().getAttribute("empresaId"));
        modelo.addAttribute(Constantes.CLIENTE_COLPORTOR_LIST,
                clienteColportorDao.lista(params).get(Constantes.CLIENTE_COLPORTOR_LIST));
        modelo.addAttribute("formasPago", FormaPago.values());

        return Constantes.PEDIDO_COLPORTOR_PATH_NUEVO;
    }

    try {
        //Se supone que el colportor lo registra
        Usuario usuario = ambiente.obtieneUsuario();
        pedidoColportor.setColportor(colportorDao.obtiene(ambiente.obtieneUsuario().getId()));
        pedidoColportor.setCliente(clienteColportorDao.obtiene(pedidoColportor.getCliente().getId()));
        pedidoColportor.setStatus(Constantes.STATUS_ACTIVO);
        pedidoColportor = pedidoColportorDao.crea(pedidoColportor);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al pedidoColportor", e);

        //Obtener la lista de clientes
        Map<String, Object> params = new HashMap<>();
        params.put("empresa", request.getSession().getAttribute("empresaId"));
        modelo.addAttribute(Constantes.CLIENTE_COLPORTOR_LIST,
                clienteColportorDao.lista(params).get(Constantes.CLIENTE_COLPORTOR_LIST));

        modelo.addAttribute("formasPago", FormaPago.values());

        return Constantes.PEDIDO_COLPORTOR_PATH_NUEVO;
    }

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

    return "redirect:" + Constantes.PEDIDO_COLPORTOR_PATH_VER + "/" + pedidoColportor.getId();
}