List of usage examples for javax.servlet.http HttpServletRequest getParameterMap
public Map<String, String[]> getParameterMap();
From source file:com.jaspersoft.jasperserver.war.action.ReportExecutionController.java
public ModelAndView runReportAction(HttpServletRequest req, HttpServletResponse res) throws Exception { String reportContextId = req.getParameter("jr_ctxid"); // FIXME use constant Map<String, Object> result = new LinkedHashMap<String, Object>(); if (reportContextId != null && req.getParameterMap().containsKey("jr_action")) { boolean shouldRefreshExecutionOutput = false; ReportContext reportContext = reportContextAccessor.getContextById(req, reportContextId); JasperReportsContext currentJasperReportsContext = jasperReportsContext; if (reportContext == null) { ReportUnitResult reportUnitResult = reportExecutionAccessor.getReportUnitResult(reportContextId); if (reportUnitResult != null) { reportContext = reportUnitResult.getReportContext(); currentJasperReportsContext = reportExecutionAccessor.getJasperReportsContext(reportContextId); shouldRefreshExecutionOutput = true; }/*from w ww .j a va 2 s. com*/ } if (reportContext == null) { res.setStatus(400); result.put("msg", "Wrong parameters!"); } else { Action action = getAction(req, reportContext, currentJasperReportsContext); JSController controller = new JSController(currentJasperReportsContext); try { // clear search stuff before performing an action if (action.requiresRefill()) { reportContext.setParameterValue("net.sf.jasperreports.search.term.highlighter", null); } controller.runAction(reportContext, action); result.put("contextid", reportContextId); // FIXMEJIVE: actions shoud return their own ActionResult that would contribute with JSON object to the output JsonNode actionResult = (JsonNode) reportContext .getParameterValue("net.sf.jasperreports.web.actions.result.json"); if (actionResult != null) { result.put("actionResult", actionResult); reportContext.setParameterValue("net.sf.jasperreports.web.actions.result.json", null); } } catch (JRInteractiveException e) { res.setStatus(500); result = new LinkedHashMap<String, Object>(); result.put("msg", "The server encountered an error!"); //FIXME use i18n for messages result.put("devmsg", e.getMessage()); } finally { if (shouldRefreshExecutionOutput) { reportExecutionAccessor.refreshOutput(reportContextId); } } } } else { res.setStatus(400); result.put("msg", "Wrong parameters!"); } return new ModelAndView("json:result", Collections.singletonMap("result", result)); }
From source file:contestWebsite.Registration.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap()); for (Entry<String, String[]> param : params.entrySet()) { if (!"studentData".equals(param.getKey())) { params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) }); }//from ww w . j a v a2 s . c o m } String registrationType = params.get("registrationType")[0]; String account = "no"; if (params.containsKey("account")) { account = "yes"; } String email = params.containsKey("email") && params.get("email")[0].length() > 0 ? params.get("email")[0].toLowerCase().trim() : null; String schoolLevel = params.get("schoolLevel")[0]; String schoolName = params.get("schoolName")[0].trim(); String name = params.get("name")[0].trim(); String classification = params.containsKey("classification") ? params.get("classification")[0] : ""; String studentData = req.getParameter("studentData"); String password = null; String confPassword = null; UserCookie userCookie = UserCookie.getCookie(req); boolean loggedIn = userCookie != null && userCookie.authenticate(); if ((!loggedIn || !userCookie.isAdmin()) && email == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "E-Mail Address parameter ('email') must be specified"); return; } HttpSession sess = req.getSession(true); sess.setAttribute("registrationType", registrationType); sess.setAttribute("account", account); sess.setAttribute("account", account); sess.setAttribute("name", name); sess.setAttribute("classification", classification); sess.setAttribute("schoolName", schoolName); sess.setAttribute("schoolLevel", schoolLevel); sess.setAttribute("email", email); sess.setAttribute("studentData", studentData); boolean reCaptchaResponse = false; if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); reCaptchaResponse = JSONResponse.getBoolean("success"); } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) { resp.sendRedirect("/registration?captchaError=1"); } else { if (account.equals("yes")) { password = params.get("password")[0]; confPassword = params.get("confPassword")[0]; } Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly(); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) { if (users.size() != 0) { resp.sendRedirect("/registration?userError=1"); } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) { resp.sendRedirect("/registration?passwordError=1"); } else { resp.sendRedirect("/registration?updated=1"); } } else { Entity registration = new Entity("registration"); registration.setProperty("registrationType", registrationType); registration.setProperty("account", account); registration.setProperty("schoolName", schoolName); registration.setProperty("schoolLevel", schoolLevel); registration.setProperty("name", name); registration.setProperty("classification", classification); registration.setProperty("studentData", new Text(studentData)); registration.setProperty("email", email); registration.setProperty("paid", ""); registration.setProperty("timestamp", new Date()); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) contestInfo.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); if (account.equals("yes") && password != null && password.length() > 0 && email != null) { Entity user = new Entity("user"); String hash = Password.getSaltedHash(password); user.setProperty("name", name); user.setProperty("school", schoolName); user.setProperty("schoolLevel", schoolLevel); user.setProperty("user-id", email); user.setProperty("salt", hash.split("\\$")[0]); user.setProperty("hash", hash.split("\\$")[1]); datastore.put(user); } txn.commit(); sess.setAttribute("props", registration.getProperties()); if (email != null) { Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); String url = req.getRequestURL().toString(); url = url.substring(0, url.indexOf("/", 7)); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name)); msg.setSubject("Thank you for your registration!"); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("url", url); context.put("cost", cost); context.put("title", contestInfo.getProperty("title")); context.put("account", account.equals("yes")); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "registrationEmail", ((Text) contestInfo.getProperty("registrationEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } resp.sendRedirect("/registration?updated=1"); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } } }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Performs an HTTP POST request/*from www . j ava 2s. c o m*/ * @param httpServletRequest The {@link HttpServletRequest} object passed * in by the servlet engine representing the * client request to be proxied * @param httpServletResponse The {@link HttpServletResponse} object by which * we can send a proxied response to the client */ public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { URL url = null; String user = null, password = null, method = "GET", post = null; int timeout = 0; Set entrySet = httpServletRequest.getParameterMap().entrySet(); Map headers = new HashMap(); for (Object anEntrySet : entrySet) { Map.Entry header = (Map.Entry) anEntrySet; String key = (String) header.getKey(); String value = ((String[]) header.getValue())[0]; if ("user".equals(key)) { user = value; } else if ("password".equals(key)) { password = value; } else if ("timeout".equals(key)) { timeout = Integer.parseInt(value); } else if ("method".equals(key)) { method = value; } else if ("post".equals(key)) { post = value; } else if ("url".equals(key)) { url = new URL(value); } else { headers.put(key, value); } } if (url != null) { // String digest=null; // if (user != null && password!=null) { // digest = "Basic " + new String(Base64.encodeBase64((user+":"+password).getBytes())); // } // Create a standard POST request PostMethod postMethodProxyRequest = new PostMethod( /*this.getProxyURL(httpServletRequest)*/ url.toExternalForm()); // Forward the request headers setProxyRequestHeaders(url, httpServletRequest, postMethodProxyRequest); // Check if this is a mulitpart (file upload) POST if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipartPost(postMethodProxyRequest, httpServletRequest); } else { this.handleStandardPost(postMethodProxyRequest, httpServletRequest); } // Execute the proxy request this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse, user, password); } }
From source file:RestrictedService.java
/** * When the servlet receives a POST request. * //from w w w. ja v a 2s. c o m * SIMILIAR DOCUMENTATION AS SAGAtoNIF PROJECT */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = ""; String eurosentiment = ""; HttpEntity entity = null; //HttpResponse responseMARL = null; HttpSession session = request.getSession(); RequestDispatcher view; // Get a map of the request parameters Map parameters = request.getParameterMap(); if (parameters.containsKey("input")) { if (parameters.containsKey("intype") && parameters.containsKey("informat") && parameters.containsKey("outformat")) { if (!request.getParameter("intype").equalsIgnoreCase("direct")) { forward = RESPONSE_JSP; eurosentiment = "intype should be direct"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } if (!request.getParameter("informat").equalsIgnoreCase("text")) { forward = RESPONSE_JSP; eurosentiment = "informat should be text"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } if (!request.getParameter("outformat").equalsIgnoreCase("json-ld")) { forward = RESPONSE_JSP; eurosentiment = "outformat should be json-ld"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } //Check that in not url or the other type forward = RESPONSE_JSP; String textToAnalize = request.getParameter("input"); try { if (parameters.containsKey("algo")) { if (request.getParameter("algo").equalsIgnoreCase("enFinancial")) { entity = callSAGA(textToAnalize, "enFinancial"); } else if (request.getParameter("algo").equalsIgnoreCase("enFinancialEmoticon")) { entity = callSAGA(textToAnalize, "enFinancialEmoticon"); } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010All")) { entity = callANEW(textToAnalize, "ANEW2010All"); } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010Men")) { entity = callANEW(textToAnalize, "ANEW2010Men"); } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010Women")) { entity = callANEW(textToAnalize, "ANEW2010Women"); } } if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader in = new BufferedReader(new InputStreamReader(instream)); String inputLine; StringBuffer marl = new StringBuffer(); while ((inputLine = in.readLine()) != null) { marl.append(inputLine); marl.append("\n"); } in.close(); eurosentiment = marl.toString(); session.setAttribute("eurosentiment", eurosentiment); } finally { instream.close(); } } } catch (Exception e) { System.err.println(e); } } else { forward = RESPONSE_JSP; eurosentiment = "There is no intype, informat or outformat especified"; session.setAttribute("eurosentiment", eurosentiment); } } else { forward = RESPONSE_JSP; eurosentiment = "There is no input"; session.setAttribute("eurosentiment", eurosentiment); } view = request.getRequestDispatcher(forward); view.forward(request, response); }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *//*from ww w.j a v a 2 s .c om*/ @SuppressWarnings("unchecked") private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) { // 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); } } // Set the proxy request POST data postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {})); }
From source file:org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultPostAuthenticationHandler.java
private void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException { if (log.isDebugEnabled()) { log.debug("Starting to process the response with missing claims"); }//from w ww . j av a2s.co m Map<String, String> claims = new HashMap<String, String>(); Map<String, String> claimsForContext = new HashMap<String, String>(); Map<String, String[]> requestParams = request.getParameterMap(); boolean persistClaims = false; AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser(); Map<String, String> carbonToSPClaimMapping = new HashMap<>(); Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING); if (spToCarbonClaimMappingObject instanceof Map) { Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject; for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) { carbonToSPClaimMapping.put(entry.getValue(), entry.getKey()); } } for (String key : requestParams.keySet()) { if (key.startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) { String localClaimURI = key .substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length()); claims.put(localClaimURI, requestParams.get(key)[0]); if (spToCarbonClaimMappingObject != null) { String spClaimURI = carbonToSPClaimMapping.get(localClaimURI); claimsForContext.put(spClaimURI, requestParams.get(key)[0]); } else { claimsForContext.put(localClaimURI, requestParams.get(key)[0]); } } } Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext); authenticatedUserAttributes.putAll(user.getUserAttributes()); for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) { StepConfig stepConfig = entry.getValue(); if (stepConfig.isSubjectAttributeStep()) { if (stepConfig.getAuthenticatedUser() != null) { user = stepConfig.getAuthenticatedUser(); } if (!user.isFederatedUser()) { persistClaims = true; } else { String associatedID = null; UserProfileAdmin userProfileAdmin = UserProfileAdmin.getInstance(); String subject = user.getAuthenticatedSubjectIdentifier(); try { associatedID = userProfileAdmin.getNameAssociatedWith(stepConfig.getAuthenticatedIdP(), subject); if (StringUtils.isNotBlank(associatedID)) { String fullQualifiedAssociatedUserId = FrameworkUtils .prependUserStoreDomainToName(associatedID + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain()); user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier( fullQualifiedAssociatedUserId); persistClaims = true; } } catch (UserProfileException e) { throw new FrameworkException("Error while getting association for " + subject, e); } } break; } } if (persistClaims) { if (log.isDebugEnabled()) { log.debug("Local user mapping found. Claims will be persisted"); } try { String tenantDomain = context.getSequenceConfig().getApplicationConfig().getServiceProvider() .getOwner().getTenantDomain(); String spName = context.getSequenceConfig().getApplicationConfig().getApplicationName(); ApplicationManagementServiceImpl applicationManagementService = ApplicationManagementServiceImpl .getInstance(); Map<String, String> claimMapping = applicationManagementService .getServiceProviderToLocalIdPClaimMapping(spName, tenantDomain); Map<String, String> localIdpClaims = new HashMap<>(); for (Map.Entry<String, String> entry : claims.entrySet()) { String localClaim = claimMapping.get(entry.getKey()); localIdpClaims.put(localClaim, entry.getValue()); } if (log.isDebugEnabled()) { log.debug("Updating user profile of user : " + user.getUserName()); } UserRealm realm = getUserRealm(user.getTenantDomain()); UserStoreManager userStoreManager = realm.getUserStoreManager() .getSecondaryUserStoreManager(user.getUserStoreDomain()); userStoreManager.setUserClaimValues(user.getUserName(), localIdpClaims, null); } catch (UserStoreException e) { throw new FrameworkException("Error while updating claims for local user. Could not update profile", e); } catch (IdentityApplicationManagementException e) { throw new FrameworkException( "Error while retrieving application claim mapping. Could not update profile", e); } } context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes); context.setProperty(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED, true); }
From source file:Service.java
/** * When the servlet receives a POST request. *//*from w w w . j a va 2 s. c om*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = ""; // Which jsp page is going to be return. String eurosentiment = ""; // This is the analysis response. // Auxiliar variables. HttpEntity entity = null; HttpSession session = request.getSession(); RequestDispatcher view; // Get a map of the request parameters Map parameters = request.getParameterMap(); if (parameters.containsKey("input")) { // If the request contains a parameter named input if (parameters.containsKey("intype") && parameters.containsKey("informat") && parameters.containsKey("outformat")) { // If the request contains a parameter named intype, informat and outformat. if (!request.getParameter("intype").equalsIgnoreCase("direct")) { // If intype is not direct. // The response contains only the following message. forward = RESPONSE_JSP; eurosentiment = "intype should be direct"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } if (!request.getParameter("informat").equalsIgnoreCase("text")) { // If informat is not text // The response contains only the following message. forward = RESPONSE_JSP; eurosentiment = "informat should be text"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } if (!request.getParameter("outformat").equalsIgnoreCase("json-ld")) { // If outformat is not json-ld // The response contains only the following message. forward = RESPONSE_JSP; eurosentiment = "outformat should be json-ld"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } // If there is input, intype = direct, informat = text and outformat = json-ld, forward = RESPONSE_JSP; // response.jsp String textToAnalize = request.getParameter("input"); // Text to be analyzed. try { if (parameters.containsKey("algo")) { // If the request contains a parameter named algo (algorithm) if (request.getParameter("algo").equalsIgnoreCase("spFinancial")) { // If algo = spFinancial entity = callSAGA(textToAnalize, "spFinancial"); // The corresponding GATE module is called and a MARL entity is generated. } else if (request.getParameter("algo").equalsIgnoreCase("emoticon")) { // If algo = Emoticon entity = callSAGA(textToAnalize, "emoticon"); // The corresponding GATE module is called and a MARL entity is generated. } else if (request.getParameter("algo").equalsIgnoreCase("spFinancialEmoticon")) { // If algo = spFinancialEmoticon entity = callSAGA(textToAnalize, "spFinancialEmoticon"); // The corresponding GATE module is called and a MARL entity is generated. } else { // If the request contains a non-valid algorithm. forward = RESPONSE_JSP; eurosentiment = "Introduce a valid algorithm"; session.setAttribute("eurosentiment", eurosentiment); view = request.getRequestDispatcher(forward); view.forward(request, response); return; } } // If a GATE module has been called and a MARL entity has been generated. if (entity != null) { // The MARL entity is processed to be added to the response.jsp InputStream instream = entity.getContent(); try { // The entity is parsed into a StringBuffer. BufferedReader in = new BufferedReader(new InputStreamReader(instream)); String inputLine; StringBuffer marl = new StringBuffer(); while ((inputLine = in.readLine()) != null) { marl.append(inputLine); marl.append("\n"); } in.close(); // The variable eurosentiment (String) is setted with the MARL response. eurosentiment = marl.toString(); session.setAttribute("eurosentiment", eurosentiment); } finally { instream.close(); } } } catch (Exception e) { System.err.println(e); } } else { // If there is no intype, informat or outformat specified. forward = RESPONSE_JSP; eurosentiment = "There is no intype, informat or outformat specified"; session.setAttribute("eurosentiment", eurosentiment); } } else { // If there is no input. forward = RESPONSE_JSP; eurosentiment = "There is no input"; session.setAttribute("eurosentiment", eurosentiment); } view = request.getRequestDispatcher(forward); view.forward(request, response); }
From source file:edu.fullerton.ldvw.LdvDispatcher.java
public LdvDispatcher(HttpServletRequest request, HttpServletResponse response, Database db, Page vpage, ViewUser vuser) {//from ww w. j av a 2 s . c om super(db, vpage, vuser); startTime = System.currentTimeMillis(); setParamMap(request.getParameterMap()); this.request = request; this.response = response; }
From source file:eu.freme.common.rest.RestHelper.java
/** * Get NIFParameterSet from a HttpServletRequest. Throws an * BadRequestException in case the input is not valid NIF. * // w w w . j av a2 s.c o m * @param request * the request * @param allowEmptyInput * Specifies if it is allowed to send empty input text. * @return the new NifParameterSet */ public NIFParameterSet normalizeNif(HttpServletRequest request, boolean allowEmptyInput) { try { BufferedReader reader = request.getReader(); StringBuilder bldr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { bldr.append(line); bldr.append("\n"); } String postBody = bldr.toString(); String acceptHeader = request.getHeader("accept"); String contentTypeHeader = request.getHeader("content-type"); Map<String, String> parameters = new HashMap<>(); for (String key : request.getParameterMap().keySet()) { parameters.put(key, request.getParameter(key)); } return normalizeNif(postBody, acceptHeader, contentTypeHeader, parameters, allowEmptyInput); } catch (IOException e) { logger.error(e); throw new InternalServerErrorException(); } }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java
/** * @param req/* www .ja v a 2 s . c o m*/ * @param request * @throws GVException */ private void parseRequest(HttpServletRequest req, String methodName, PatternResolver pr, GVBuffer request) throws GVException { try { Map<String, String[]> params = req.getParameterMap(); Iterator<String> i = params.keySet().iterator(); while (i.hasNext()) { String n = i.next(); String v = params.get(n)[0]; request.setProperty(n, ((v != null) && !"".equals(v)) ? v : "NULL"); } String ct = Optional.ofNullable(req.getContentType()).orElse(""); request.setProperty("HTTP_REQ_CONTENT_TYPE", ct.isEmpty() ? ct : "NULL"); String acc = req.getHeader("Accept"); request.setProperty("HTTP_REQ_ACCEPT", (acc != null) ? acc : "NULL"); if (methodName.equals("POST") || methodName.equals("PUT")) { if (!ct.startsWith(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)) { Object requestContent = IOUtils.toByteArray(req.getInputStream()); if (ct.startsWith(AdapterHttpConstants.APPXML_MIMETYPE_NAME) || ct.startsWith(AdapterHttpConstants.APPJSON_MIMETYPE_NAME) || ct.startsWith("text/")) { /* GESTIRE ENCODING!!! */ requestContent = new String((byte[]) requestContent); } request.setObject(requestContent); } } if (pr.isExtractHdr()) { XMLUtils parser = null; try { parser = XMLUtils.getParserInstance(); Document doc = parser.newDocument("Hdr"); Element root = doc.getDocumentElement(); Enumeration<?> hn = req.getHeaderNames(); while (hn.hasMoreElements()) { Element h = parser.insertElement(root, "h"); String name = (String) hn.nextElement(); String val = req.getHeader(name); parser.setAttribute(h, "n", name); parser.setAttribute(h, "v", val); } request.setProperty("HTTP_REQ_HEADERS", parser.serializeDOM(doc, true, false)); } finally { XMLUtils.releaseParserInstance(parser); } } } catch (Exception exc) { throw new AdapterHttpExecutionException("RESTHttpServletMapping - Error parsing request data", exc); } }