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:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java
/** * To validate key value pair control// w w w . jav a 2s . c o m * @param parameter * @param returnFlag * @return */ private static ActionResponse mapControlValidate(Parameter parameter, HttpServletRequest request, ActionResponse actionResponse) { List<Child> childs = parameter.getChilds().getChild(); String[] keys = request.getParameterValues(childs.get(0).getKey()); String[] values = request.getParameterValues(childs.get(1).getKey()); String childLabel = ""; for (int i = 0; i < keys.length; i++) { if (StringUtils.isEmpty(keys[i]) && Boolean.parseBoolean(childs.get(0).getRequired())) { childLabel = childs.get(0).getName().getValue().getValue(); actionResponse.setErrorFound(true); actionResponse.setConfigErrorMsg(childLabel + " " + "is missing"); actionResponse.setParameterKey(parameter.getKey()); actionResponse.setStatus(RESPONSE_STATUS_SUCCESS); actionResponse.setResponseCode(PHR8C00001); break; } else if (StringUtils.isEmpty(values[i]) && Boolean.parseBoolean(childs.get(1).getRequired())) { childLabel = childs.get(1).getName().getValue().getValue(); actionResponse.setErrorFound(true); actionResponse.setConfigErrorMsg(childLabel + " " + "is missing"); actionResponse.setParameterKey(parameter.getKey()); actionResponse.setStatus(RESPONSE_STATUS_SUCCESS); actionResponse.setResponseCode(PHR8C00001); break; } } return actionResponse; }
From source file:fr.paris.lutece.plugins.directory.modules.pdfproducerarchive.web.ZipBasketJspBean.java
/** * Add zip to basket or return error message * @param request request/*w w w . jav a 2s . c o m*/ * @return message of confirmation or error * @throws AccessDeniedException exception if the user does not have the right */ public String addZipToBasket(HttpServletRequest request) throws AccessDeniedException { String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY); if (!RBACService.isAuthorized(Directory.RESOURCE_TYPE, strIdDirectory, DirectoryPDFProducerArchiveResourceIdService.PERMISSION_GENERATE_ZIP, getUser())) { return AdminMessageService.getMessageUrl(request, Messages.USER_ACCESS_DENIED, AdminMessage.TYPE_CONFIRMATION); } String[] listIdsRecord = request.getParameterValues(PARAMETER_ID_DIRECTORY_RECORD); // Check parameteres if ((listIdsRecord == null) || (listIdsRecord.length == 0) || StringUtils.isBlank(strIdDirectory)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } // Fetch directory int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory); ZipItem item = new ZipItem(); item.setIdAdminUser(getUser().getUserId()); item.setIdDirectory(nIdDirectory); item.setListIdRecord(listIdsRecord); item.setLocale(AdminUserService.getLocale(request)); AddZipToBasketDaemon.addItemToQueue(item); UrlItem url = new UrlItem(getJspManageDirectoryRecord(request, nIdDirectory)); return AdminMessageService.getMessageUrl(request, MESSAGE_ADD_ZIP_TO_BASKET, url.getUrl(), AdminMessage.TYPE_INFO); }
From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object.//from w w w . jav a2s .c om * @since 2.0 */ public static Parameters decodeParameters(HttpServletRequest request, String charenc) throws ServletException, IOException { String ctype = request.getHeader("content-type"); log.debug("Content-type: " + ctype); Parameters params = new Parameters(); if (ctype != null && ctype.startsWith("multipart/form-data")) { // special file upload request, so use FileUpload to decode log.debug("Decoding with FileUpload; charenc=" + charenc); try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); Iterator iterator = upload.parseRequest(request).iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); log.debug("Reading: " + item); if (item.isFormField()) { if (charenc != null) params.addParameter(item.getFieldName(), item.getString(charenc)); else params.addParameter(item.getFieldName(), item.getString()); } else params.addParameter(item.getFieldName(), new FileParameter(item)); } } catch (FileUploadException e) { throw new ServletException(e); } } else { // ordinary web request, so retrieve info and stuff into Parameters object log.debug("Normal parameter decode, charenc=" + charenc); if (charenc != null) request.setCharacterEncoding(charenc); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String param = (String) enumeration.nextElement(); params.addParameter(param, request.getParameterValues(param)); } } return params; }
From source file:ke.co.tawi.babblesms.server.servlet.sms.send.SendSMS.java
/** * Method to handle form processing/* ww w .ja v a2 s . c o m*/ * * @param request * @param response * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) * * @throws IOException */ @SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Respond as soon as possible to the client request HttpSession session = request.getSession(true); session.setAttribute(SessionConstants.SENT_SUCCESS, "success"); response.sendRedirect("sendsms.jsp"); // Get the relevant account Account account = new Account(); String username = request.getParameter("username"); Element element; if ((element = accountsCache.get(username)) != null) { account = (Account) element.getObjectValue(); } TawiGateway smsGateway = gatewayDAO.get(account); // Retrieve the web parameters String[] groupselected = request.getParameterValues("groupselected"); String[] phones = request.getParameterValues("phones"); String source = request.getParameter("source"); String message = request.getParameter("message"); // Deal with the case where one or more Groups has been selected // Get phones of all the Contacts in the Group(s) SetUniqueList phoneList = SetUniqueList.decorate(new LinkedList<Phone>()); // Does not allow duplicates Group group; List<Contact> contactList; List<OutgoingGrouplog> outgoingGroupList = new LinkedList<>(); if (groupselected != null) { OutgoingGrouplog groupLog; for (String groupUuid : groupselected) { group = new Group(); group.setUuid(groupUuid); contactList = ctgrpDAO.getContacts(group); for (Contact contact : contactList) { phoneList.addAll(phoneDAO.getPhones(contact)); } // Save an outgoing log for the group groupLog = new OutgoingGrouplog(); groupLog.setMessagestatusUuid(MsgStatus.SENT); groupLog.setSender(account.getUuid()); groupLog.setDestination(group.getUuid()); groupLog.setMessage(message); outgoingGroupList.add(groupLog); } // end 'for(String groupUuid : groupselected)' } // end 'if(groupselected != null)' // This is the case where individual Contacts may have been selected if (phones == null) { phones = new String[0]; } phones = StringUtil.removeDuplicates(phones); for (String phone : phones) { phoneList.add(phoneDAO.getPhone(phone)); } // Determine whether a shortcode or mask is the source SMSSource smsSource; Shortcode shortcode = shortcodeDAO.get(source); Mask mask = null; if (shortcode == null) { mask = maskDAO.get(source); smsSource = mask; } else { smsSource = shortcode; } // Set the network in the groups (if any) and save the log for (OutgoingGrouplog log : outgoingGroupList) { log.setNetworkUuid(smsSource.getNetworkuuid()); log.setOrigin(smsSource.getUuid()); groupLogDAO.put(log); } // Filter the phones to the Network of the source (mask or short code) List<Phone> validPhoneList = new LinkedList<>(); validPhoneList.addAll( CollectionUtils.select(phoneList, new PhonesByNetworkPredicate(smsSource.getNetworkuuid()))); // Break down the phone list to go out to manageable sizes, each sublist // being sent to the SMS Gateway in one URL POST List<List<Phone>> phonePartition = ListPartitioner.partition(validPhoneList, 10); // Send the lists one by one PostSMS postThread; for (List<Phone> list : phonePartition) { postThread = new PostSMS(smsGateway, list, smsSource, message, account, true); postThread.start(); } // Deduct credit smsBalanceDAO.deductBalance(account, smsSource, validPhoneList.size()); }
From source file:fr.paris.lutece.plugins.workflow.modules.automaticassignment.web.AutomaticAssignmentTaskComponent.java
/** * {@inheritDoc}//from w ww . ja v a 2s . co m */ @Override public String doSaveConfig(HttpServletRequest request, Locale locale, ITask task) { String strError = WorkflowUtils.EMPTY_STRING; String strTitle = request.getParameter(PARAMETER_TITLE); String strIsNotification = request.getParameter(PARAMETER_IS_NOTIFICATION); String strSenderName = request.getParameter(PARAMETER_SENDER_NAME); String strMessage = request.getParameter(PARAMETER_MESSAGE); String strSubject = request.getParameter(PARAMETER_SUBJECT); String strIdDirectory = request.getParameter(PARAMETER_DIRECTORY); String[] tabWorkgroups = request.getParameterValues(PARAMETER_WORKGROUPS); String strViewRecord = request.getParameter(PARAMETER_VIEW_RECORD); String strLabelLinkViewRecord = request.getParameter(PARAMETER_LABEL_LINK_VIEW_RECORD); String strRecipientsCc = request.getParameter(PARAMETER_RECIPIENTS_CC); String strRecipientsBcc = request.getParameter(PARAMETER_RECIPIENTS_BCC); String[] tabSelectedPositionsEntryFile = request .getParameterValues(PARAMETER_LIST_POSITION_ENTRY_FILE_CHECKED); int nIdDirectory = -1; if ((strTitle == null) || strTitle.trim().equals(WorkflowUtils.EMPTY_STRING)) { strError = FIELD_TITLE; } if ((strIsNotification != null) && ((strSubject == null) || strSubject.equals(""))) { strError = FIELD_MAILINGLIST_SUBJECT; } if ((strIsNotification != null) && ((strMessage == null) || strMessage.equals(""))) { strError = FIELD_MAILINGLIST_MESSAGE; } if ((strIsNotification != null) && ((strSenderName == null) || strSenderName.equals(""))) { strError = FIELD_MAILINGLIST_SENDER_NAME; } if (StringUtils.isNotBlank(strViewRecord) && StringUtils.isBlank(strLabelLinkViewRecord)) { strError = FIELD_LABEL_LINK_VIEW_RECORD; } if (!strError.equals(WorkflowUtils.EMPTY_STRING)) { Object[] tabRequiredFields = { I18nService.getLocalizedString(strError, locale) }; return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP); } if (strIdDirectory != null) { nIdDirectory = Integer.parseInt(strIdDirectory); } TaskAutomaticAssignmentConfig config = _taskAutomaticAssignmentConfigService.findByPrimaryKey(task.getId()); Boolean bCreate = false; if (config == null) { config = new TaskAutomaticAssignmentConfig(); config.setIdTask(task.getId()); bCreate = true; } // Add workgroups List<WorkgroupConfig> listWorkgroupConfig = new ArrayList<WorkgroupConfig>(); WorkgroupConfig workgroupConfig; if (tabWorkgroups != null) { for (int i = 0; i < tabWorkgroups.length; i++) { workgroupConfig = new WorkgroupConfig(); workgroupConfig.setIdTask(task.getId()); workgroupConfig.setWorkgroupKey(tabWorkgroups[i]); if (strIsNotification != null) { if (WorkflowUtils.convertStringToInt( request.getParameter(PARAMETER_ID_MAILING_LIST + "_" + tabWorkgroups[i])) != -1) { workgroupConfig.setIdMailingList(WorkflowUtils.convertStringToInt( request.getParameter(PARAMETER_ID_MAILING_LIST + "_" + tabWorkgroups[i]))); } else { return AdminMessageService.getMessageUrl(request, MESSAGE_NO_MAILINGLIST_FOR_WORKGROUP, AdminMessage.TYPE_STOP); } } listWorkgroupConfig.add(workgroupConfig); } } config.setWorkgroups(listWorkgroupConfig); config.setTitle(strTitle); config.setNotify(strIsNotification != null); config.setMessage(strMessage); config.setSubject(strSubject); config.setSenderName(strSenderName); config.setViewRecord(strViewRecord != null); config.setLabelLinkViewRecord(strLabelLinkViewRecord); config.setRecipientsCc(StringUtils.isNotEmpty(strRecipientsCc) ? strRecipientsCc : StringUtils.EMPTY); config.setRecipientsBcc(StringUtils.isNotEmpty(strRecipientsBcc) ? strRecipientsBcc : StringUtils.EMPTY); if (config.getIdDirectory() != nIdDirectory) { config.setIdDirectory(nIdDirectory); if (!bCreate) { UrlItem url = new UrlItem(JSP_DO_UPDATE_DIRECTORY); url.addParameter(PARAMETER_ID_DIRECTORY, nIdDirectory); url.addParameter(PARAMETER_ID_TASK, task.getId()); return AdminMessageService.getMessageUrl(request, MESSAGE_CONFIRM_DIRECTORY_UPDATE, url.getUrl(), AdminMessage.TYPE_CONFIRMATION); } } if ((tabSelectedPositionsEntryFile != null) && (tabSelectedPositionsEntryFile.length > 0)) { List<Integer> listSelectedPositionEntryFile = new ArrayList<Integer>(); for (int i = 0; i < tabSelectedPositionsEntryFile.length; i++) { listSelectedPositionEntryFile .add(WorkflowUtils.convertStringToInt(tabSelectedPositionsEntryFile[i])); } config.setListPositionsEntryFile(listSelectedPositionEntryFile); } else { config.setListPositionsEntryFile(null); } if (bCreate) { _taskAutomaticAssignmentConfigService.create(config); } else { _taskAutomaticAssignmentConfigService.update(config); } return null; }
From source file:controller.CommercialController.java
@RequestMapping("regub/commercial/contrats/comajoutcontrat") public String ajoutcontratAction(HttpServletRequest request, HttpSession session, Model model, @RequestParam("file") MultipartFile file) throws ParseException, InterruptedException { //Pour pouvoir conserver l'Id du client pour lequel //l'ajout du contrat est fait int id = cleclient; String[] choixrayon = request.getParameterValues("rayon"); String[] choixregion = request.getParameterValues("region"); String titrecontrat = request.getParameter("titre"); String freqcontrat = request.getParameter("frequence"); String durecontrat = request.getParameter("duree"); String datedebutcontrat = request.getParameter("datedebut"); String datefincontrat = request.getParameter("datefin"); String daterecepcontrat = request.getParameter("datereception"); String datevalidcontrat = request.getParameter("datevalidation"); String tarifcontrat = request.getParameter("tarif"); String choixstatut = request.getParameter("statut"); Set<Region> mySetregion = tableaureg(choixregion); Set<Typerayon> mySettyperayon = tableauray(choixrayon); Client client = ClientDAO.Charge(id).get(0); Compte comcompt = (Compte) session.getAttribute("compteConnected"); DateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy"); Date currentDate = new Date(); String datecourante = dateformat.format(currentDate); Video vid = new Video(client, comcompt, titrecontrat, Integer.parseInt(freqcontrat), Integer.parseInt(durecontrat), ConvertToSqlDate(datedebutcontrat), ConvertToSqlDate(datefincontrat), ConvertToSqlDate(daterecepcontrat), ConvertToSqlDate(datecourante), Double.parseDouble(tarifcontrat), Integer.parseInt(choixstatut), mySetregion, mySettyperayon); int videoid = VidBDD.addComContrat(vid);// appelle de la mthode pr inserer dans la table video et recup de l'id de l'element qui a t insr if (!file.isEmpty()) { try {//from w w w . ja va 2 s . c o m byte[] bytes = file.getBytes(); // Creating the directory to store file String rootPath = System.getProperty("catalina.home"); //System.out.println(""+rootPath+File.separator); //System.out.println(""+file.getOriginalFilename()); // Create the file on server //file.getOriginalFilename() permet de recup le nom du fichier original selectionn //Mon chemein de test //File serverFile = new File("A:\\test"+ File.separator + 20 + ".mp4");//a marche //Chemin officiel du serveur File serverFile = new File(rootPath + File.separator + "webapps" + File.separator + "manager" + File.separator + "videos" + File.separator + videoid + ".mp4"); System.out.println("" + serverFile); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("You failed to upload "); } //return "redirect:/regub/commercial"; return "redirect:/regub/commercial/contrats/" + vid.getClient().getIdClient(); }
From source file:com.virtusa.akura.student.controller.StudentSubjectController.java
/** * Redirects to the Student_subject.jsp. * /*from w ww. ja v a2s .c om*/ * @param request Http request. * @param map model map to set data. * @return String value of jsp page to direct. * @throws AkuraAppException throw exception if occur. */ @RequestMapping(method = RequestMethod.POST, value = REQ_VALUE_SAVEORUPDATESTUDENTSUBJECT) public String saveorupdatestudentsubjectlist(HttpServletRequest request, ModelMap map) throws AkuraAppException { String classGradeId = request.getParameter(REQ_SELECT); int clsGradeId = Integer.parseInt(classGradeId); String year = request.getParameter(REQ_YEAR); int intYear = Integer.parseInt(year); // ArrayList flagTermId = new ArrayList<Integer>(); String message; try { String[] studentSubjectIDs = request.getParameterValues(REQ_GRADESUBJECTCHECK); if (studentSubjectIDs != null) { Set<String> newTermMarkIdSet = new HashSet<String>(); List<Term> terms = this.commonService.getTermList(); Iterator<Term> termIter = terms.iterator(); List<Integer> termIdListToDelete = new ArrayList<Integer>(); while (termIter.hasNext()) { List<StudentTermMark> termMarkList = new ArrayList<StudentTermMark>(); Term objTerm = (Term) termIter.next(); boolean isMarkComplete = studentService.isMarkingCompletedForTerm(clsGradeId, objTerm.getTermId(), intYear); if (!isMarkComplete) { // term which is not marks completed // flagTermId.add(objTerm.getTermId()); for (String strStudentSubjectID : studentSubjectIDs) { String[] arguments = strStudentSubjectID.split(","); String gradeSubjectID = arguments[0]; String studentClassID = arguments[1]; String termmarkID = arguments[2]; int intTermMarkID = Integer.parseInt(termmarkID); if (intTermMarkID == -1) { StudentTermMark termMark = new StudentTermMark(); termMark.setStudentClassInfoId(Integer.parseInt(studentClassID)); termMark.setGradeSubjectId(Integer.parseInt(gradeSubjectID)); termMark.setTermId(objTerm.getTermId()); termMarkList.add(termMark); } else { newTermMarkIdSet.add(gradeSubjectID + "," + studentClassID); } } if (termMarkList.size() > 0) { List<StudentSubTermMark> subtermMarkList = new ArrayList<StudentSubTermMark>(); List<StudentTermMark> changedTermMarkList = new ArrayList<StudentTermMark>(); changedTermMarkList = studentService.saveOrUpdateStudentSubjectList(termMarkList); List<SubTerm> subterms = this.commonService.getSubTermList(); Iterator<SubTerm> subTermIter = subterms.iterator(); while (subTermIter.hasNext()) { SubTerm objSubTerm = (SubTerm) subTermIter.next(); for (StudentTermMark objStudentTermMark : changedTermMarkList) { if (objSubTerm.getTermId() == objStudentTermMark.getTermId()) { StudentSubTermMark subtermMark = new StudentSubTermMark(); subtermMark.setStuTermMarkID(objStudentTermMark.getStudentTermMarkId()); subtermMark.setSubtermID(objSubTerm.getSubTermId()); subtermMarkList.add(subtermMark); } } } studentService.generateSubtermMarkRecords(subtermMarkList); } @SuppressWarnings("unchecked") Map<Integer, String> termMarkIdMap = (Map<Integer, String>) request.getSession() .getAttribute(REQ_TERM_MARK_ID_MAP); for (int key : termMarkIdMap.keySet()) { String[] arguments = termMarkIdMap.get(key).split(","); String sessionPara = arguments[0] + "," + arguments[1]; String termID = arguments[2]; String strYear = arguments[3]; String gradeSubjectId = arguments[0]; int intTerm = Integer.parseInt(termID); String formatedYear = year + "-01" + "-01"; if ((formatedYear.equalsIgnoreCase(strYear)) && (objTerm.getTermId() == intTerm)) { if (!newTermMarkIdSet.contains(sessionPara)) { if (commonService.findGradeSubject(Integer.parseInt(gradeSubjectId)) .getIsOptionalSubject()) { termIdListToDelete.add(key); } } } } } else { ErrorMsgLoader errorMsgLoader = new ErrorMsgLoader(); message = errorMsgLoader.getErrorMessage(ERROR_MSG); map.addAttribute(MESSAGE, message); } } if (termIdListToDelete.size() > 0) { studentService.deleteStudentTermMark(termIdListToDelete); } } else { ErrorMsgLoader errorMsgLoader = new ErrorMsgLoader(); message = errorMsgLoader.getErrorMessage(ERROR_MSG_KEY); map.addAttribute(MESSAGE, message); } request.getSession().removeAttribute(REQ_STUDENTSUBJECTMAP); map.addAttribute(MODEL_ATT_THIS_YEAR, DateUtil.currentYearOnly()); // make open the student subject panel after processing. generateStudentSubjectView(clsGradeId, intYear, request, map); return VIEW_ADMIN_STUDENT_SUBJECT; } catch (NumberFormatException ex) { throw new AkuraAppException(AkuraConstant.DATE_CONVERSION_ERROR, ex); } catch (DataAccessException ex) { LOG.error("StudentSubjectController - error occured while Update syudent Subjects "); throw new AkuraAppException(AkuraWebConstant.HIBERNATE_INVALID_DEL_OPERATION, ex); } catch (AkuraAppException ex) { LOG.error("StudentSubjectController - error occured while Update syudent Subjects "); throw new AkuraAppException(AkuraWebConstant.HIBERNATE_INVALID_DEL_OPERATION, ex); } finally { request.getSession().removeAttribute(REQ_STUDENTSUBJECTMAP); } }
From source file:com.photon.phresco.framework.actions.settings.Settings.java
public String delete() { if (debugEnabled) { S_LOGGER.debug("Entering Method Settings.delete()"); }//from w w w. j a v a2s . c o m try { ProjectAdministrator administrator = getProjectAdministrator(); HttpServletRequest request = getHttpRequest(); List<String> settingNames = new ArrayList<String>(); String[] selectedNames = request.getParameterValues(REQ_SELECTED_ITEMS); Map<String, List<String>> deleteConfigs = new HashMap<String, List<String>>(); for (int i = 0; i < selectedNames.length; i++) { String[] split = selectedNames[i].split(","); String envName = split[0]; List<String> configNames = deleteConfigs.get(envName); if (configNames == null) { configNames = new ArrayList<String>(3); } configNames.add(split[1]); deleteConfigs.put(envName, configNames); } administrator.deleteSettingsInfos(deleteConfigs); for (String name : selectedNames) { if (debugEnabled) { S_LOGGER.debug("To be deleted settings name " + name); } settingNames.add(name); } addActionMessage(SUCCESS_SETTING_DELETE); getHttpRequest().setAttribute(REQ_SELECTED_MENU, SETTINGS); } catch (Exception e) { if (debugEnabled) { S_LOGGER.error( "Entered into catch block of Settings.delete()" + FrameworkUtil.getStackTraceAsString(e)); } new LogErrorReport(e, "Settings delete"); } return list(); }
From source file:aspect.servlet.Comparison.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww. j a va 2s. co m*/ * * @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"); response.setContentType("application/json"); //response.setCharacterEncoding("UTF-8"); System.out.println("787"); //response.setContentType("application/json"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ /*String keyword1 = request.getParameter("product1"); String keyword2 = request.getParameter("product2"); String keyword3 = request.getParameter("product3"); System.out.println(keyword1); System.out.println(keyword2); System.out.println(keyword3);*/ String[] prod = request.getParameterValues("s"); for (String prod1 : prod) { System.out.println("ParaValue: " + prod1); } JSONObject json = new JSONObject(); JSONObject recomm = new JSONObject(); JSONObject jsonrecomm = new JSONObject(); JSONObject jsonDetailComplete = new JSONObject(); List<String> arrayrecomm = new ArrayList<>(); productForComparison = new ArrayList<>(); if (prod.length > 0 && prod.length <= 3) { productForComparison.addAll(Arrays.asList(prod)); } /*if (keyword1!=null) { productForComparison.add(keyword1); } if (keyword2!=null) { productForComparison.add(keyword2); } if (keyword3!=null) { productForComparison.add(keyword3); } */ recommendationSB = new RecommendationSB(); JSONObject myJson = recommendationSB.convertToJSON(productForComparison); try { int i = 1; for (int j = 0; j < productForComparison.size(); j++) { String r = "s"; r += i; jsonrecomm.put(r, productForComparison.get(j)); arrayrecomm.add(j, productForComparison.get(j)); i++; System.out.println("You're welcome "); } JSONArray jsonarray = new JSONArray(arrayrecomm); recomm.put("jsonrecomm", jsonrecomm); recomm.put("arrayrecomm", jsonarray); jsonDetailComplete.put("productlist", recomm); jsonDetailComplete.put("productdetails", myJson); out.println(jsonDetailComplete); //out.println("1erer1"); } catch (JSONException ex) { System.out.println("Error: " + ex); } } finally { out.close(); } }
From source file:edu.vt.middleware.ldap.servlets.AttributeServlet.java
/** * Handle all requests sent to this servlet. * * @param request <code>HttpServletRequest</code> * @param response <code>HttpServletResponse</code> * * @throws ServletException if an error occurs * @throws IOException if an error occurs *///from w ww .jav a2 s. co m public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String attribute = request.getParameter("attr"); byte[] value = null; final String content = request.getParameter("content-type"); if (content != null && content.equalsIgnoreCase("octet")) { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + attribute + ".bin\""); } else { response.setContentType("text/plain"); } try { Ldap ldap = null; try { ldap = this.pool.checkOut(); final Iterator<SearchResult> i = ldap.search(new SearchFilter(request.getParameter("query")), request.getParameterValues("attr")); final LdapResult r = this.beanFactory.newLdapResult(); r.addEntries(i); for (LdapEntry e : r.getEntries()) { final LdapAttribute a = e.getLdapAttributes().getAttribute(attribute); if (a != null && a.getValues().size() > 0) { final Object rawValue = a.getValues().iterator().next(); if (rawValue instanceof String) { final String stringValue = (String) rawValue; value = stringValue.getBytes(); } else { value = (byte[]) rawValue; } } } } finally { this.pool.checkIn(ldap); } if (value != null) { final OutputStream out = response.getOutputStream(); out.write(value); out.flush(); out.close(); } } catch (Exception e) { if (this.logger.isErrorEnabled()) { this.logger.error("Error performing search", e); } throw new ServletException(e.getMessage()); } }