List of usage examples for javax.servlet.http HttpServletRequest getParameterValues
public String[] getParameterValues(String name);
String
objects containing all of the values the given request parameter has, or null
if the parameter does not exist. From source file:org.attribyte.api.pubsub.impl.server.NotificationMetricsServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String joinString = Strings.nullToEmpty(request.getParameter("joinWith")).trim(); if (joinString.isEmpty()) joinString = "_"; boolean allowSlashInPrefix = true; if (request.getParameter("allowSlash") != null) { allowSlashInPrefix = request.getParameter("allowSlash").trim().equalsIgnoreCase("true"); }// www. j a va 2s . c o m List<String> path = splitPath(request); String obj = path.size() > 0 ? path.get(0) : null; String[] topics = request.getParameterValues("name"); if (obj == null) { MetricRegistry registry = new MetricRegistry(); registry.register("", endpoint.getGlobalNotificationMetrics()); String json = mapper.writer().writeValueAsString(registry); response.setContentType("application/json"); response.getWriter().print(json); response.getWriter().flush(); } else if (obj.equals("topic")) { final List<NotificationMetrics> metrics; if (topics != null && topics.length > 0) { metrics = Lists.newArrayListWithExpectedSize(topics.length); for (String topicName : topics) { Topic topic = resolveTopic(topicName); if (topic != null) { NotificationMetrics topicMetrics = endpoint.getNotificationMetrics(topic.getId()); if (topicMetrics != null) metrics.add(topicMetrics); } } } else { String sortStr = request.getParameter("sort"); if (sortStr == null) sortStr = ""; NotificationMetrics.Sort sort = sortMap.get(sortStr); if (sort == null) sort = NotificationMetrics.Sort.THROUGHPUT_DESC; String limitStr = request.getParameter("limit"); int limit = 25; if (limitStr != null) { try { limit = Integer.parseInt(limitStr); } catch (NumberFormatException nfe) { limit = 25; } } metrics = endpoint.getNotificationMetrics(sort, limit); } MetricRegistry registry = new MetricRegistry(); for (NotificationMetrics callbackMetrics : metrics) { String prefix = getTopicPrefix(callbackMetrics.topicId, joinString, allowSlashInPrefix); if (prefix != null) { registry.register(prefix, callbackMetrics); } } String json = mapper.writer().writeValueAsString(registry); response.setContentType("application/json"); response.getWriter().print(json); response.getWriter().flush(); } else { response.sendError(404); } }
From source file:ke.co.tawi.babblesms.server.servlet.contactmgmt.AddContact.java
/** * * @param request//w w w .ja v a 2 s . c o m * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); Account account = new Account(); String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY); Element element; if ((element = accountsCache.get(username)) != null) { account = (Account) element.getObjectValue(); } String name = request.getParameter("name").trim(); String[] phoneArray = request.getParameterValues("phones"); String[] networkArray = request.getParameterValues("networks"); String[] emailArray = request.getParameterValues("emails"); for (String str : emailArray) { System.out.println("Email is: " + str); } String description = request.getParameter("description"); String[] groupArray = request.getParameterValues("groups"); if (StringUtils.isBlank(name)) { session.setAttribute(SessionConstants.ADD_ERROR, "Please provide a contact name."); } else if (phoneArray.length < 1) { session.setAttribute(SessionConstants.ADD_ERROR, "Please provide at least one phone number."); } else if (networkArray.length < 1) { session.setAttribute(SessionConstants.ADD_ERROR, "Please select a network."); } else if (emailArray.length > 0 && StringUtils.isNotBlank(emailArray[0]) && !StringUtil.validateEmails(emailArray)) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_INVALID_EMAIL); } else { Contact contact = new Contact(); contact.setName(name); contact.setDescription(description); contact.setStatusUuid(Status.ACTIVE); contact.setAccountUuid(account.getUuid()); if (contactDAO.putContact(contact)) { session.setAttribute(SessionConstants.ADD_SUCCESS, ADD_SUCCESS); } else { session.setAttribute(SessionConstants.ADD_ERROR, "Contact add Failed."); } // Save emails Email email; for (String email2 : emailArray) { email = new Email(); email.setAddress(email2); email.setContactuuid(contact.getUuid()); email.setStatusuuid(Status.ACTIVE); emailDAO.putEmail(email); } // Save phone numbers Phone phone; int count = 0; for (String phonenum : phoneArray) { phone = new Phone(); phone.setPhonenumber(phonenum); phone.setContactUuid(contact.getUuid()); phone.setNetworkuuid(networkArray[count]); phone.setStatusuuid(Status.ACTIVE); phoneDAO.putPhone(phone); count++; } // Associate the Contact with the Groups chosen Group group; if (groupArray != null) { for (String groupUuud : groupArray) { group = new Group(); group.setUuid(groupUuud); cgDAO.putContact(contact, group); } } // Update the cache contactCache.put(new Element(contact.getUuid(), contact)); // UUID as the key } response.sendRedirect("addcontact.jsp"); }
From source file:com.adito.security.actions.ShowAvailableAccountsDispatchAction.java
/** * @param mapping/*from w ww . ja va 2 s . co m*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward enable(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request); String[] accounts = request.getParameterValues("username"); ActionMessages mesgs = new ActionMessages(); if (accounts == null || accounts.length == 0) { mesgs.add(Globals.ERROR_KEY, new ActionMessage("availableAccounts.atLeastOneAccountNotSelected")); saveErrors(request, mesgs); } else { UserDatabase udb = UserDatabaseManager.getInstance() .getUserDatabase(getSessionInfo(request).getUser().getRealm()); for (int i = 0; accounts != null && i < accounts.length; i++) { User user = udb.getAccount(accounts[i]); boolean disabled = !PolicyUtil.isEnabled(user); SessionInfo session = this.getSessionInfo(request); if (disabled) { if (LOG.isInfoEnabled()) { LOG.info("Re-enabling user " + user.getPrincipalName()); } PolicyUtil.setEnabled(user, true, null, session); } LogonControllerFactory.getInstance().unlockUser(user.getPrincipalName()); } } return list(mapping, form, request, response); }
From source file:GuestBookServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); Locale loc = getLocale(req);/* w w w . ja va 2 s . co m*/ String name, email, comment; Connection conn = null; Exception err = null; int id = -1; String[] tmp; // get the form values tmp = req.getParameterValues("name"); if (tmp == null || tmp.length != 1) { name = null; } else { name = tmp[0]; } tmp = req.getParameterValues("email"); if (tmp == null || tmp.length != 1) { email = null; } else { email = tmp[0]; } tmp = req.getParameterValues("comments"); if (tmp == null || tmp.length != 1) { comment = null; } else { comment = tmp[0]; } res.setContentType("text/html"); // validate values if (name.length() < 1) { out.println("You must specify a valid name!"); printCommentForm(out, loc); return; } if (email.length() < 3) { out.println("You must specify a valid email address!"); printCommentForm(out, loc); return; } if (email.indexOf("@") < 1) { out.println("You must specify a valid email address!"); printCommentForm(out, loc); return; } if (comment.length() < 1) { out.println("You left no comments!"); printCommentForm(out, loc); return; } try { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.US); java.util.Date date = new java.util.Date(); ResultSet result; Statement stmt; conn = DriverManager.getConnection(jdbcURL, connectionProperties); // remove the "setAutoCommit(false)" line for mSQL or MySQL conn.setAutoCommit(false); stmt = conn.createStatement(); // generate a new comment ID // more on ID generation in Chapter 4 result = stmt.executeQuery("SELECT NEXT_SEQ " + "FROM SEQGEN " + "WHERE NAME = 'COMMENT_ID'"); if (!result.next()) { throw new ServletException("Failed to generate id."); } id = result.getInt(1) + 1; stmt.close(); // closing the statement closes the result stmt = conn.createStatement(); stmt.executeUpdate("UPDATE SEQGEN SET NEXT_SEQ = " + id + " WHERE NAME = 'COMMENT_ID'"); stmt.close(); stmt = conn.createStatement(); comment = fixComment(comment); stmt.executeUpdate( "INSERT INTO COMMENT " + "(COMMENT_ID, EMAIL, NAME, COMMENT, " + "CMT_DATE) " + "VALUES (" + id + ", '" + email + "', '" + name + "', '" + comment + "', '" + fmt.format(date) + "')"); conn.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); err = e; } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { } } } if (err != null) { out.println("An error occurred on save: " + err.getMessage()); } else { printCommentForm(out, loc); printComments(out, loc); } }
From source file:com.redoute.datamap.servlet.picture.FindAllPicture.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a va 2 s. c om*/ * * @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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); try { String page[] = null; String application[] = null; String picture[] = null; String implemented[] = null; String stream[] = null; if (request.getParameterValues("page") != null) { page = request.getParameterValues("page"); } if (request.getParameterValues("picture") != null) { picture = request.getParameterValues("picture"); } if (request.getParameterValues("application") != null) { application = request.getParameterValues("application"); } if (request.getParameterValues("impl") != null) { implemented = request.getParameterValues("impl"); } if (request.getParameterValues("stream") != null) { stream = request.getParameterValues("stream"); } List<String> sArray = new ArrayList<String>(); List<String> sArrayJ = new ArrayList<String>(); if (page != null) { String spage = " ("; for (int a = 0; a < page.length - 1; a++) { spage += " p.`page` like '%" + page[a] + "%' or"; } spage += " p.`page` like '%" + page[page.length - 1] + "%') "; sArray.add(spage); } if (application != null) { String sapplication = " ("; for (int a = 0; a < application.length - 1; a++) { sapplication += " p.`application` like '%" + application[a] + "%' or"; } sapplication += " p.`application` like '%" + application[application.length - 1] + "%') "; sArray.add(sapplication); } if (picture != null) { String spicture = " ("; for (int a = 0; a < picture.length - 1; a++) { spicture += " p.`picture` like '%" + picture[a] + "%' or"; } spicture += " p.`picture` like '%" + picture[picture.length - 1] + "%') "; sArray.add(spicture); } if (implemented != null) { String simplemented = " ("; for (int a = 0; a < implemented.length - 1; a++) { simplemented += " d.`implemented` like '%" + implemented[a] + "%' or"; } simplemented += " d.`implemented` like '%" + implemented[implemented.length - 1] + "%') "; sArrayJ.add(simplemented); } if (stream != null) { String sstream = " ("; for (int a = 0; a < stream.length - 1; a++) { sstream += " d.`stream` like '%" + stream[a] + "%' or"; } sstream += " d.`stream` like '%" + stream[stream.length - 1] + "%') "; sArrayJ.add(sstream); } StringBuilder individualSearch = new StringBuilder(); if (sArray.size() >= 1) { for (int i = 0; i < sArray.size(); i++) { individualSearch.append(" and "); individualSearch.append(sArray.get(i)); } } StringBuilder joinedSearch = new StringBuilder(); if (sArrayJ.size() >= 1) { for (int i = 0; i < sArrayJ.size(); i++) { joinedSearch.append(" and "); joinedSearch.append(sArrayJ.get(i)); } } String inds = String.valueOf(individualSearch); String joined = String.valueOf(joinedSearch); JSONArray data = new JSONArray(); //data that will be shown in the table ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); IPictureService pictureService = appContext.getBean(IPictureService.class); IDatamapService datamapService = appContext.getBean(IDatamapService.class); List<Picture> datamapList = pictureService.findPictureListByCriteria(inds, joined); JSONObject jsonResponse = new JSONObject(); for (Picture datamap : datamapList) { boolean isImpl = datamapService.allImplementedByCriteria("picture", datamap.getPicture()); JSONArray row = new JSONArray(); row.put(datamap.getId()).put(datamap.getApplication()).put(datamap.getPage()) .put(datamap.getPicture()) .put(isImpl == true ? "Y" : "N"); data.put(row); } jsonResponse.put("aaData", data); response.setContentType("application/json"); response.getWriter().print(jsonResponse.toString()); } catch (JSONException ex) { Logger.log(FindAllPicture.class.getName(), Level.FATAL, ex.toString()); } finally { out.close(); } }
From source file:com.adito.security.actions.ShowAvailableAccountsDispatchAction.java
/** * @param mapping/* ww w .j a v a2 s .c om*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward disable(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN, request); String[] accounts = request.getParameterValues("username"); ActionMessages mesgs = new ActionMessages(); if (accounts == null || accounts.length == 0) { mesgs.add(Globals.ERROR_KEY, new ActionMessage("availableAccounts.atLeastOneAccountNotSelected")); saveErrors(request, mesgs); } else { UserDatabase udb = UserDatabaseManager.getInstance() .getUserDatabase(getSessionInfo(request).getUser().getRealm()); for (int i = 0; accounts != null && i < accounts.length; i++) { User user = udb.getAccount(accounts[i]); SessionInfo info = this.getSessionInfo(request); boolean disabled = !PolicyUtil.isEnabled(user); if (!disabled) { if (LOG.isInfoEnabled()) { LOG.info("Disabling user " + user.getPrincipalName()); } PolicyUtil.setEnabled(user, false, null, info); if (LogonControllerFactory.getInstance().isAdministrator(user)) { mesgs.add(Globals.MESSAGE_KEY, new ActionMessage("info.superUserDisabled")); saveErrors(request, mesgs); } } } } return list(mapping, form, request, response); }
From source file:org.openmrs.module.iqchartimport.web.controller.MappingsController.java
/** * Handles a save request on the drugs form * @param request/*from w w w. j a v a 2 s. c o m*/ */ @SuppressWarnings("unchecked") private void handleDrugMappingsSave(HttpServletRequest request) { DrugMapping.clear(); HttpSession httpSession = request.getSession(); List<String> iqDrugs = (List<String>) httpSession.getAttribute("iqDrugs"); for (String param : (Set<String>) request.getParameterMap().keySet()) { if (param.startsWith("drugs-")) { // Get index and lookup up IQChart drug list to get drug name int iqDrugID = Integer.parseInt(param.substring(6)); String iqDrug = iqDrugs.get(iqDrugID); // Get OpenMRS drug concept ids String[] conceptStrIds = request.getParameterValues(param); List<Integer> conceptIds = new ArrayList<Integer>(0); for (String conceptStrId : conceptStrIds) { int drugConceptId = Integer.parseInt(conceptStrId); conceptIds.add(drugConceptId); } DrugMapping.setConcepts(iqDrug, conceptIds); } } DrugMapping.save(); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Drug mappings saved"); }
From source file:org.esgf.legacydatacart.LegacyOldFileTemplateController.java
/** * //from ww w.j a v a 2 s . c om * @param request * @return */ private static String preassembleQueryStringUsingSearchAPI(HttpServletRequest request, String indexPeer) { String queryString = ""; queryString += "format=application%2Fsolr%2Bjson"; queryString += "&type=File"; //System.out.println("INDEX PEER: " + indexPeer); if (!indexPeer.equals("undefined")) { queryString += "&shards=" + indexPeer + ":8983/solr"; } if (request.getParameter("showAll").equals("false")) { //System.out.println("Showall is false"); //get the 'fq' params from the servlet query string here String[] fqParams = request.getParameterValues("fq[]"); //get the 'q' param from the servlet query string here //String qParam = request.getParameter("q"); String fullText = ""; if (fqParams != null) { //System.out.println("fqParams is not null"); //append the 'fq' params to the query string for (int i = 0; i < fqParams.length; i++) { String fqParam = fqParams[i]; //System.out.println("fqParam: " + fqParam); if (!fqParam.equals("") && !fqParam.equals(" ")) { //System.out.println("\tfqParam not <space>"); if (!fqParam.contains("query")) { queryString += "&" + fqParam; } else { //System.out.println("") String[] clause = fqParam.split("="); fullText += clause[1] + "%20"; } } } if (!fullText.equals("") && !fullText.equals(" ")) { //System.out.println("FULLTEXT: " + fullText); queryString += "&query=" + fullText;//fullText.substring(0,fullText.length()); } } else { //System.out.println("fqParams is null"); } } //System.out.println("\n\nQUERYSTRING: " + queryString + "\n\n"); return queryString; }
From source file:com.turn.splicer.SplicerServlet.java
/** * Parses a TsQuery out of request, divides into subqueries, and writes result * from openTsdb/*from w w w .jav a2s. c o m*/ * * Format for GET request: * start - required start time of query * end - optional end time of query, if not provided will use current time as end * x - expression (functions + metrics) * m - metrics only - no functions, [aggregator]:[optional_downsampling]:metric{optional tags} * either x or m must be provided, otherwise nothing to query! * ms - optional for millisecond resolution * padding - optional pad front of value's with 0's * *example: * /api/query?start=1436910725795&x=abs(sum:1m-avg:tcollector.collector.lines_received)" * @param request * @param response * @throws IOException */ private void doGetWork(HttpServletRequest request, HttpServletResponse response) throws IOException { LOG.info(request.getQueryString()); final TsQuery dataQuery = new TsQuery(); dataQuery.setStart(request.getParameter("start")); dataQuery.setEnd(request.getParameter("end")); dataQuery.setPadding(Boolean.valueOf(request.getParameter("padding"))); if (request.getParameter("ms") != null) { dataQuery.setMsResolution(true); } List<ExpressionTree> expressionTrees = null; final String[] expressions = request.getParameterValues("x"); if (expressions != null) { expressionTrees = new ArrayList<ExpressionTree>(); List<String> metricQueries = new ArrayList<String>(); SplicerUtils.syntaxCheck(expressions, dataQuery, metricQueries, expressionTrees); } //not supporting metric queries from GET yet... //TODO: fix this or decide if we need to support "m" type queries if (request.getParameter("m") != null) { final List<String> legacy_queries = Arrays.asList(request.getParameterValues("m")); for (String q : legacy_queries) { SplicerUtils.parseMTypeSubQuery(q, dataQuery); } } LOG.info("Serving query={}", dataQuery); LOG.info("Original TsQuery Start time={}, End time={}", Const.tsFormat(dataQuery.startTime()), Const.tsFormat(dataQuery.endTime())); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); try (RegionChecker checker = REGION_UTIL.getRegionChecker()) { List<TsdbResult[]> exprResults = Lists.newArrayList(); if (expressionTrees == null || expressionTrees.size() == 0) { System.out.println("expression trees == null...figure this out later"); response.getWriter().write("No expression or error parsing expression"); } else { try { List<Future<TsdbResult[]>> futureList = new ArrayList<Future<TsdbResult[]>>( expressionTrees.size()); TsQuery prev = null; for (ExpressionTree expressionTree : expressionTrees) { futureList.add(pool.submit(new ExpressionTreeWorker(expressionTree))); } for (Future<TsdbResult[]> future : futureList) { exprResults.add(future.get()); } response.getWriter().write(TsdbResult.toJson(SplicerUtils.flatten(exprResults))); } catch (Exception e) { LOG.error("Could not evaluate expression tree", e); e.printStackTrace(); } } } }
From source file:com.swiftcorp.portal.user.web.UserDispatchAction.java
public ActionForward removeUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws SystemException, BusinessRuleViolationException, Exception { log.info("removeUser() : Enter"); DynaValidatorActionForm userForm = (DynaValidatorActionForm) form; // UserDTO userDTO = (UserDTO) userForm.get ( "user" ); String[] userIdList = request.getParameterValues("deleteCheck"); String userRemoved = ""; for (int i = 0; i < userIdList.length; i++) { log.info("userId to delete::" + userIdList[i]); String userComponentId = userIdList[i]; if (userComponentId != null && !userComponentId.equals("null") && userComponentId.length() > 0) { UserDTO userDTO = (UserDTO) userService.get(Long.parseLong(userComponentId)); userService.remove(userDTO); if (userRemoved != null && !userRemoved.equals("null") && userRemoved.length() > 0) { userRemoved += "," + userDTO.getUniqueCode(); }/*from w w w . j av a 2 s . c om*/ } System.out.println("userId to delete::" + userIdList[i]); } System.out.println("userRemoved::" + userRemoved); String[][] messageArgValues = { { // userDTO.getUniqueCode () "User" + userRemoved } }; // userService.remove ( userDTO ); WebUtils.setSuccessMessages(request, MessageKeys.REMOVE_SUCCESS_MESSAGE_KEYS, messageArgValues); return promptUserSearchGroupLevel(mapping, form, request, response); }