List of usage examples for javax.servlet.http HttpServletRequest getParameterMap
public Map<String, String[]> getParameterMap();
From source file:it.geosolutions.operations.FileBrowserOperationController.java
@Override public String getJsp(ModelMap model, HttpServletRequest request, List<MultipartFile> files) { System.out.println("getJSP di FileBrowser"); String baseDir = getDefaultBaseDir(); FileBrowser fb = new FileBrowser(); Object gotParam = model.get("gotParam"); @SuppressWarnings("unchecked") Map<String, String[]> parameters = request.getParameterMap(); for (String key : parameters.keySet()) { System.out.println(key); // debug String[] vals = parameters.get(key); for (String val : vals) // debug System.out.println(" -> " + val); // debug if (key.equalsIgnoreCase("d")) { String dirString = parameters.get(key)[0].trim(); // prevent directory traversing dirString = dirString.replace("..", ""); // clean path dirString = dirString.replace("/./", "/"); dirString = dirString.replaceAll("/{2,}", "/"); if (dirString.startsWith("/")) { dirString = dirString.substring(1); }//from ww w.j ava 2 s. co m //remove last slash if (dirString.lastIndexOf("/") >= 0 && dirString.lastIndexOf("/") == (dirString.length() - 1)) { System.out.println("stripping last slash"); // debug dirString = dirString.substring(0, dirString.length() - 1); } //second check if (dirString.lastIndexOf("/") >= 0) { model.addAttribute("directoryBack", dirString.substring(0, dirString.lastIndexOf("/"))); } else { model.addAttribute("directoryBack", ""); } dirString = dirString.concat("/"); baseDir = baseDir + dirString; model.addAttribute("directory", dirString); } } if (gotParam != null) { System.out.println(gotParam); // debug } String gotAction = request.getParameter("action"); String fileToDel = request.getParameter("toDel"); if (gotAction != null && gotAction.equalsIgnoreCase("delete") && fileToDel != null) { String deleteFileString = baseDir + fileToDel; boolean res = deleteFile(deleteFileString); System.out.println("Deletted " + deleteFileString + ": " + res); // debug } model.addAttribute("operationName", this.operationName); model.addAttribute("operationRESTPath", this.getRESTPath()); fb.setBaseDir(baseDir); fb.setRegex(null); fb.setScanDiretories(canNavigate); if (null != files && files.size() > 0) { List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); if (!"".equalsIgnoreCase(fileName)) { try { multipartFile.transferTo(new File(baseDir + fileName)); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } fileNames.add(fileName); } System.out.println(fileName); } } model.addAttribute("fileBrowser", fb); model.addAttribute("operations", getAvailableOperations()); model.addAttribute("canDelete", this.canDelete); model.addAttribute("canUpload", this.canUpload); model.addAttribute("containerId", uniqueKey.toString().substring(0, 8)); model.addAttribute("formId", uniqueKey.toString().substring(27, 36)); return operationJSP; }
From source file:org.motechproject.mobile.web.IncomingMessageServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request// w w w. java2s . c om * @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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { ApplicationContext appContext = (ApplicationContext) request.getSession().getServletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebManager webManager = (WebManager) appContext.getBean("webManagerBean"); IncomingMessageRequestWorker imrWorker = webManager.createIMRWorker(); String responseString = imrWorker.doRequest(request.getParameterMap()); out.print(responseString.replaceAll("\n", "<br />")); } finally { out.close(); } }
From source file:org.openinfobutton.responder.controller.OpenInfobuttonResponderController.java
/** * * @param request/*from w w w .j a va2s. c o m*/ * @param response * @param model * @return * @throws MissingServletRequestParameterException * @throws HttpMediaTypeNotSupportedException * @throws IllegalArgumentException */ @RequestMapping("/responder") public String openInfobuttonRequestHandler(final HttpServletRequest request, final HttpServletResponse response, final ModelMap model) throws MissingServletRequestParameterException, HttpMediaTypeNotSupportedException, IllegalArgumentException { response.setHeader("Cache-Control", "no-cache"); // todo: if authorization is required return 401 when not authorized setRequiredResponseObjects(); // throws IllegalArgumentException Map<String, String> requestParameters = responderService .getKnowledgeRequestParameterMap(request.getParameterMap()); // throws MissingServletRequestParameterException responderService.requestContainsRequiredParameters(requestParameters); Collection<Asset> matchedAssets = responderService.findAssetsByInfobuttonRequest(requestParameters); model.addAttribute("atomFeedMetadata", this.atomFeedMetadata); model.addAttribute("indexPropertyInterpretationMap", this.indexPropertyInterpretationMap); model.addAttribute("requestParameters", requestParameters); model.addAttribute("assets", matchedAssets); String viewType = requestParameters.get("knowledgeResponseType"); if (viewType == null) { // default return ATOM_PAGE; } else if ("text/html".equals(viewType)) { return HTML_PAGE; } else if ("text/xml".equals(viewType)) { return ATOM_PAGE; } else { throw new HttpMediaTypeNotSupportedException("Unsupported knowledgeResponseType: " + viewType); } }
From source file:com.krawler.formbuilder.servlet.ModuleBuilderController.java
private Map prepareData(HttpServletRequest request, List fileItems) throws ServiceException { Map temp;/*w w w .j ava 2s .c o m*/ if (ServletFileUpload.isMultipartContent(request)) { temp = parseRequest(request, fileItems); } else { temp = getParamList(request.getParameterMap()); } return temp; }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
/** * From {@link ServletServerHttpRequest}: * Use {@link javax.servlet.ServletRequest#getParameterMap()} to reconstruct the * body of a form 'POST' providing a predictable outcome as opposed to reading * from the body, which can fail if any other code has used ServletRequest * to access a parameter thus causing the input stream to be "consumed". *//*from ww w . j a v a2s . co m*/ private InputStream getBodyFromServletRequestParameters(HttpServletRequest request, String charset) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); Writer writer = new OutputStreamWriter(bos, charset); @SuppressWarnings("unchecked") Map<String, String[]> form = request.getParameterMap(); for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) { String name = nameIterator.next(); List<String> values = Arrays.asList(form.get(name)); for (Iterator<String> valueIterator = values.iterator(); valueIterator.hasNext();) { String value = valueIterator.next(); writer.write(URLEncoder.encode(name, charset)); if (value != null) { writer.write('='); writer.write(URLEncoder.encode(value, charset)); if (valueIterator.hasNext()) { writer.write('&'); } } } if (nameIterator.hasNext()) { writer.append('&'); } } writer.flush(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.geowebcache.service.wms.WMSService.java
@Override public ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException { final String encoding = request.getCharacterEncoding(); final Map requestParameterMap = request.getParameterMap(); String[] keys = { "layers", "request", "tiled", "cached", "metatiled", "width", "height" }; Map<String, String> values = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding, keys); // Look for layer String layers = values.get("layers"); // Get the TileLayer TileLayer tileLayer = null;/*from w ww . j a v a 2 s . co m*/ if (layers != null) { tileLayer = tld.getTileLayer(layers); } // Look for requests that are not getmap String req = values.get("request"); if (req != null && !req.equalsIgnoreCase("getmap")) { // One more chance if (layers == null || layers.length() == 0) { layers = ServletUtils.stringFromMap(requestParameterMap, encoding, "layer"); values.put("LAYERS", layers); if (layers != null) { tileLayer = tld.getTileLayer(layers); } } Map<String, String> filteringParameters = null; // If tileLayer is not null, then request parameters are extracted from it- if (tileLayer != null) { filteringParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding); } // Creation of a Conveyor Tile with a fake Image/png format and the associated parameters. ConveyorTile tile = new ConveyorTile(sb, layers, null, null, ImageMime.png, filteringParameters, request, response); tile.setHint(req.toLowerCase()); tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE); return tile; } if (layers == null) { throw new ServiceException("Unable to parse layers parameter from request."); } // Check whether this request is missing tiled=true final boolean tiled = Boolean.valueOf(values.get("tiled")); if (proxyNonTiledRequests && tiled) { ConveyorTile tile = new ConveyorTile(sb, layers, request, response); tile.setHint(req); tile.setRequestHandler(Conveyor.RequestHandler.SERVICE); return tile; } String[] paramKeys = { "format", "srs", "bbox" }; final Map<String, String> paramValues = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding, paramKeys); final Map<String, String> fullParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding); final MimeType mimeType; String format = paramValues.get("format"); try { mimeType = MimeType.createFromFormat(format); } catch (MimeException me) { throw new ServiceException("Unable to determine requested format, " + format); } final SRS srs; { String requestSrs = paramValues.get("srs"); if (requestSrs == null) { throw new ServiceException("No SRS specified"); } srs = SRS.getSRS(requestSrs); } final BoundingBox bbox; { String requestBbox = paramValues.get("bbox"); try { bbox = new BoundingBox(requestBbox); if (bbox == null || !bbox.isSane()) { throw new ServiceException( "The bounding box parameter (" + requestBbox + ") is missing or not sane"); } } catch (NumberFormatException nfe) { throw new ServiceException("The bounding box parameter (" + requestBbox + ") is invalid"); } } final int tileWidth = Integer.parseInt(values.get("width")); final int tileHeight = Integer.parseInt(values.get("height")); final List<GridSubset> crsMatchingSubsets = tileLayer.getGridSubsetsForSRS(srs); if (crsMatchingSubsets.isEmpty()) { throw new ServiceException("Unable to match requested SRS " + srs + " to those supported by layer"); } long[] tileIndexTarget = new long[3]; GridSubset gridSubset; { GridSubset bestMatch = findBestMatchingGrid(bbox, crsMatchingSubsets, tileWidth, tileHeight, tileIndexTarget); if (bestMatch == null) { // proceed as it used to be gridSubset = crsMatchingSubsets.get(0); tileIndexTarget = null; } else { gridSubset = bestMatch; } } if (fullWMS) { // If we support full WMS we need to do a few tests to determine whether // this is a request that requires us to recombine tiles to respond. long[] tileIndex = null; if (tileIndexTarget == null) { try { tileIndex = gridSubset.closestIndex(bbox); } catch (GridMismatchException gme) { // Do nothing, the null is info enough } } else { tileIndex = tileIndexTarget; } if (tileIndex == null || gridSubset.getTileWidth() != tileWidth || gridSubset.getTileHeight() != tileHeight || !bbox.equals(gridSubset.boundsFromIndex(tileIndex), 0.02)) { log.debug("Recombinining tiles to respond to WMS request"); ConveyorTile tile = new ConveyorTile(sb, layers, request, response); tile.setHint("getmap"); tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE); return tile; } } long[] tileIndex = tileIndexTarget == null ? gridSubset.closestIndex(bbox) : tileIndexTarget; gridSubset.checkTileDimensions(tileWidth, tileHeight); return new ConveyorTile(sb, layers, gridSubset.getName(), tileIndex, mimeType, fullParameters, request, response); }
From source file:mx.edu.um.mateo.inventario.web.SalidaController.java
@Transactional @RequestMapping(value = "/crea", method = RequestMethod.POST) public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Salida salida, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) { for (String nombre : request.getParameterMap().keySet()) { log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre)); }//from w w w . j a v a2 s . com if (bindingResult.hasErrors()) { log.debug("Hubo algun error en la forma, regresando"); return "inventario/salida/nueva"; } if (salida.getCliente() == null || salida.getCliente().getId() == null) { log.warn("No introdujo un cliente correcto, regresando"); errors.rejectValue("cliente", "salida.no.eligio.cliente.message", null, null); return "inventario/salida/nueva"; } try { Usuario usuario = ambiente.obtieneUsuario(); if (request.getParameter("cliente.id") == null) { log.warn("No se puede crear la salida si no ha seleccionado un cliente"); errors.rejectValue("cliente", "salida.sin.cliente.message"); return "inventario/salida/nueva"; } Cliente cliente = clienteDao.obtiene(new Long(request.getParameter("cliente.id"))); salida.setCliente(cliente); salida.setAtendio(usuario.getApPaterno() + ", " + usuario.getApMaterno() + ", " + usuario.getNombre()); salida = salidaDao.crea(salida, usuario); } catch (ConstraintViolationException e) { log.error("No se pudo crear la salida", e); errors.rejectValue("factura", "campo.duplicado.message", new String[] { "factura" }, null); return "inventario/salida/nueva"; } redirectAttributes.addFlashAttribute("message", "salida.creada.message"); redirectAttributes.addFlashAttribute("messageAttrs", new String[] { salida.getFolio() }); return "redirect:/inventario/salida/ver/" + salida.getId(); }
From source file:mx.edu.um.mateo.general.web.EmpresaController.java
@SuppressWarnings("unchecked") @RequestMapping//from w w w . j av a2s. co m public String lista(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) String filtro, @RequestParam(required = false) Long pagina, @RequestParam(required = false) String tipo, @RequestParam(required = false) String correo, @RequestParam(required = false) String order, @RequestParam(required = false) String sort, Model modelo) { log.debug("Mostrando lista de empresas"); Map<String, Object> params = this.convierteParams(request.getParameterMap()); Long organizacionId = (Long) request.getSession().getAttribute("organizacionId"); params.put("organizacion", organizacionId); if (StringUtils.isNotBlank(tipo)) { params.put("reporte", true); params = empresaDao.lista(params); try { generaReporte(tipo, (List<Empresa>) params.get("empresas"), response, "empresas", Constantes.ORG, organizacionId); return null; } catch (ReporteException e) { log.error("No se pudo generar el reporte", e); } } if (StringUtils.isNotBlank(correo)) { params.put("reporte", true); params = empresaDao.lista(params); params.remove("reporte"); try { enviaCorreo(correo, (List<Empresa>) params.get("empresas"), request, "empresas", Constantes.ORG, organizacionId); modelo.addAttribute("message", "lista.enviada.message"); modelo.addAttribute("messageAttrs", new String[] { messageSource.getMessage("empresa.lista.label", null, request.getLocale()), ambiente.obtieneUsuario().getUsername() }); } catch (ReporteException e) { log.error("No se pudo enviar el reporte por correo", e); } } params = empresaDao.lista(params); modelo.addAttribute("empresas", params.get("empresas")); this.pagina(params, modelo, "empresas", pagina); return "admin/empresa/lista"; }
From source file:org.mocksy.rules.http.HttpProxyRule.java
protected HttpRequestBase getProxyMethod(HttpServletRequest request) { String proxyUrl = this.proxyUrl; proxyUrl += request.getPathInfo();//from w w w . ja v a 2 s . c o m if (request.getQueryString() != null) { proxyUrl += "?" + request.getQueryString(); } HttpRequestBase method = null; if ("GET".equals(request.getMethod())) { method = new HttpGet(proxyUrl); method.addHeader("Cache-Control", "no-cache"); method.addHeader("Pragma", "no-cache"); } else if ("POST".equals(request.getMethod())) { method = new HttpPost(proxyUrl); Map<String, String[]> paramMap = request.getParameterMap(); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String paramName : paramMap.keySet()) { String[] values = paramMap.get(paramName); for (String value : values) { NameValuePair param = new BasicNameValuePair(paramName, value); params.add(param); } } try { ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params)); } catch (UnsupportedEncodingException e) { // don't worry, this won't happen } } Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("If-Modified-Since".equals(header) || "Content-Length".equals(header) || "Transfer-Encoding".equals(header)) continue; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); method.addHeader(header, value); } } return method; }
From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestServlet.java
/** * {@inheritDoc}/* w w w . j a va2 s .com*/ */ @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); String idpDestination; String relayState; KeyStore.PrivateKeyEntry spIdentity = null; String language; AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService(); if (null != service) { idpDestination = service.getIdPDestination(); relayState = service.getRelayState(request.getParameterMap()); spIdentity = service.getSPIdentity(); language = service.getLanguage(); } else { idpDestination = this.idpDestination; relayState = null; language = this.language; } // sp-destination String spDestination = null; if (null != service) { spDestination = service.getSPDestination(); } if (null == spDestination) { // not provided by the service, check web.xml... if (null != this.spDestination) { spDestination = this.spDestination; } else { spDestination = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + this.spDestinationPage; } } // issuer String issuer = null; if (null != service) { issuer = service.getIssuer(); } if (null == issuer) { issuer = spDestination; } // generate and send an authentication request AuthnRequest authnRequest = AuthenticationRequestUtil.sendRequest(issuer, idpDestination, spDestination, relayState, spIdentity, response, language); // save state on session setRequestIssuer(authnRequest.getIssuer().getValue(), request.getSession()); setRequestId(authnRequest.getID(), request.getSession()); setRecipient(authnRequest.getAssertionConsumerServiceURL(), request.getSession()); setRelayState(relayState, request.getSession()); }