List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:com.ikon.servlet.admin.LanguageServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); boolean persist = WebUtils.getBoolean(request, "persist"); String userId = request.getRemoteUser(); Session dbSession = null;/* w w w. ja v a2s. c o m*/ updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Language lang = new Language(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("lg_id")) { lang.setId(item.getString("UTF-8")); } else if (item.getFieldName().equals("lg_name")) { lang.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("persist")) { persist = true; } } else { is = item.getInputStream(); data = IOUtils.toByteArray(is); lang.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { lang.setImageContent(SecureStore.b64Encode(data)); LanguageDAO.create(lang); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_CREATE", lang.getId(), null, lang.toString()); } else if (action.equals("edit")) { lang.setImageContent(SecureStore.b64Encode(data)); LanguageDAO.update(lang); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_EDIT", lang.getId(), null, lang.toString()); } else if (action.equals("delete")) { LanguageDAO.delete(lang.getId()); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_DELETE", lang.getId(), null, null); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importLanguage(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_IMPORT", null, null, null); } } else if (action.equals("translate")) { translate(userId, request, response); } else if (action.equals("addTranslation")) { addTranslation(userId, request, response); } if (!action.equals("addTranslation") && (action.equals("") || action.equals("import") || persist)) { list(userId, request, response); } } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { HibernateUtil.close(dbSession); } }
From source file:mercury.Controller.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("processRequest start: " + this.getMemoryInfo()); String submitButton = null;/*w ww.ja v a2 s .c o m*/ String jspURL = null; HashMap<String, String> requestParametersHash = null; String thisPage = null; String lastVisitedPage = null; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { //--- gets all request parameters, either multipart or not this.putAllRequestParametersInAttributes(request); requestParametersHash = (HashMap<String, String>) request.getAttribute("REQUEST_PARAMETERS"); //--- sets the last visited page to errorJsp if it is the first time the controller runs lastVisitedPage = (String) request.getSession().getAttribute("LAST_VISITED_PAGE"); if (StringUtils.isBlank(lastVisitedPage)) { lastVisitedPage = errorJsp; jspURL = lastVisitedPage; request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL); } submitButton = requestParametersHash.get("submitButton"); thisPage = requestParametersHash.get("thisPage"); AuthorizationPoints atps = (AuthorizationPoints) request.getSession().getAttribute("LOGGED_USER_ATPS"); if (atps == null) { atps = new AuthorizationPoints(null); request.getSession().setAttribute("LOGGED_USER_ATPS", atps); } AuthorizationBO authBO = new AuthorizationBO(); String handlerName = Controller.targetHandlers.getProperty(thisPage); if (submitButton.equals("i18n")) { request.getSession().setAttribute("I18N", requestParametersHash.get("i18n")); jspURL = lastVisitedPage; } else if (authBO.authorize(atps, handlerName, submitButton)) { BaseHandler handler = (BaseHandler) Class.forName(handlerName).newInstance(); jspURL = handler.process(request, response); } else { Dialog.showWarning(request, "ERROR_NO_PERMISSION"); jspURL = lastVisitedPage; } } catch (ClassNotFoundException e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 1: " + e); Dialog.showError(request, "DIALOG_VOID"); jspURL = lastVisitedPage; } catch (ExceptionUser e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 2: " + e.getKeyText()); Dialog.showError(request, e.getKeyText()); jspURL = lastVisitedPage; } catch (DAOException e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 3: " + e); Dialog.showError(request, "ERROR_DATABASE"); jspURL = lastVisitedPage; } catch (Exception e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 4: " + e); e.printStackTrace(); Dialog.showError(request, "DIALOG_VOID"); jspURL = lastVisitedPage; } finally { if (jspURL == null || jspURL.equals("")) { jspURL = errorJsp; request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL); return; } else if (jspURL.equals("x-download")) { return; } else if (jspURL.equals("x-json")) { return; } else { request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL); request.getRequestDispatcher(jspURL).forward(request, response); return; } } }
From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // explicitly set character encoding req.setCharacterEncoding("UTF-8"); res.setCharacterEncoding("UTF-8"); SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req); String credentialsId = creds.getUserID(); log.debug("credentialsId={}", credentialsId); String jcrUserId = req.getParameter("jcrUserId"); String jcrPath = req.getParameter("jcrPath"); log.info("jcrUserId={}, jcrPath={}", jcrUserId, jcrPath); Session jcrSession = null;// w w w . ja va2s. c om Session impersonateSession = null; Map<String, Object> templateParams = new HashMap<String, Object>(); try { if (creds.getUserID() == null || creds.getUserID().length() == 0) { jcrSession = repository.login(); } else { jcrSession = repository.login(creds); } log.debug("jcrSession={}", jcrSession); User user = ((HippoSession) jcrSession).getUser(); if (user.isSystemUser()) { final InetAddress address = InetAddress.getByName(req.getRemoteHost()); if (!address.isAnyLocalAddress() && !address.isLoopbackAddress()) { throw new LoginException(); } } templateParams.put("jcrSession", jcrSession); templateParams.put("jcrUserId", jcrUserId); templateParams.put("jcrPath", jcrPath); Credentials impersonateCredentials = new SimpleCredentials(jcrUserId, "".toCharArray()); impersonateSession = jcrSession.impersonate(impersonateCredentials); Privilege[] privileges = getPrivileges(impersonateSession, jcrPath); log.info("========= " + ((SimpleCredentials) impersonateCredentials).getUserID() + " =============="); Map<String, String> privilegesMap = new HashMap<>(); for (Privilege p : privileges) { privilegesMap.put(p.getName(), "true"); log.info("p=" + p.getName()); } templateParams.put("privilegesMap", privilegesMap); String[] allPermissions = { "jcr:read", "jcr:write", "hippo:author", "hippo:editor", "hippo:admin", "jcr:setProperties", "jcr:setAccessControlPolicy", "jcr:addChildNodes", "jcr:getAccessControlPolicy", "jcr:removeChildNodes" }; templateParams.put("allPermissions", allPermissions); } catch (LoginException ex) { BasicAuth.setRequestAuthorizationHeaders(res, "Repository"); log.error("Error logging in to repository", ex); } catch (Exception ex) { templateParams.put("exception", ex); log.error("Error retrieving permissions", ex); } finally { try { if (jcrSession != null) { renderTemplatePage(req, res, getRenderTemplate(req), templateParams); } } catch (Exception te) { log.warn("Failed to render freemarker template.", te); } finally { if (jcrSession != null) { jcrSession.logout(); } if (impersonateSession != null) { impersonateSession.logout(); } } } }
From source file:webim.controller.WebimController.java
@RequestMapping(value = "/message", method = RequestMethod.POST) @ResponseBody/*from w w w .ja v a 2 s . c o m*/ public Map<String, String> message(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); Map<String, String> rtData = new HashMap<String, String>(); WebimEndpoint endpoint = currentEndpoint(request, response); String uid = endpoint.getId(); String ticket = request.getParameter("ticket"); String type = request.getParameter("type"); if (type == null) type = "chat"; String offline = request.getParameter("offline"); String to = request.getParameter("to"); String body = request.getParameter("body"); String style = request.getParameter("style"); if (style == null) style = ""; if (!this.model.isBuddy(uid, to)) { this.model.addBuddy(uid, to); } if (!plugin.checkCensor(body)) { rtData.put("status", "error"); rtData.put("message", "?????"); return rtData; } if (plugin.isRobotSupport() && plugin.isFromRobot(to)) { WebimClient c = this.client(endpoint, request, null); WebimMessage requestMsg = new WebimMessage(to, c.getEndpoint().getNick(), body, style, System.currentTimeMillis()); this.model.insertHistory(uid, requestMsg); String answer = plugin.getRobot().answer(body); WebimMessage answermsg = new WebimMessage(uid, plugin.getRobot().getNick(), answer, "", System.currentTimeMillis()); c.push(to, answermsg); this.model.insertHistory(to, answermsg); } else { WebimClient c = this.client(endpoint, request, ticket); WebimMessage msg = new WebimMessage(to, c.getEndpoint().getNick(), body, style, System.currentTimeMillis()); msg.setType(type); msg.setOffline("true".equals(offline) ? true : false); c.publish(msg); if (body != null && !body.startsWith("webim-event:")) { this.model.insertHistory(uid, msg); } } rtData.put("status", "ok"); return rtData; }
From source file:com.openkm.servlet.admin.OmrServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);//from w w w . j a va 2 s . c o m try { if (ServletFileUpload.isMultipartContent(request)) { String fileName = null; InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Set<String> properties = new HashSet<String>(); Omr om = new Omr(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("om_id")) { om.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("om_name")) { om.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("om_properties")) { properties.add(item.getString("UTF-8")); } else if (item.getFieldName().equals("om_active")) { om.setActive(true); } } else { is = item.getInputStream(); fileName = item.getName(); } } om.setProperties(properties); if (action.equals("create") || action.equals("edit")) { // Store locally template file to be used later if (is != null && is.available() > 0) { // Case update only name byte[] data = IOUtils.toByteArray(is); File tmp = FileUtils.createTempFile(); FileOutputStream fos = new FileOutputStream(tmp); IOUtils.write(data, fos); IOUtils.closeQuietly(fos); // Store template file om.setTemplateFileName(FilenameUtils.getName(fileName)); om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName)); om.setTemplateFilContent(data); IOUtils.closeQuietly(is); // Create training files Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp); File ascFile = trainingMap.get(OMRHelper.ASC_FILE); File configFile = trainingMap.get(OMRHelper.CONFIG_FILE); // Store asc file om.setAscFileName(om.getTemplateFileName() + ".asc"); om.setAscFileMime(MimeTypeConfig.MIME_TEXT); is = new FileInputStream(ascFile); om.setAscFileContent(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); // Store config file om.setConfigFileName(om.getTemplateFileName() + ".config"); om.setConfigFileMime(MimeTypeConfig.MIME_TEXT); is = new FileInputStream(configFile); om.setConfigFileContent(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); // Delete temporal files FileUtils.deleteQuietly(tmp); FileUtils.deleteQuietly(ascFile); FileUtils.deleteQuietly(configFile); } if (action.equals("create")) { long id = OmrDAO.getInstance().create(om); // Activity log UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString()); } else if (action.equals("edit")) { OmrDAO.getInstance().updateTemplate(om); om = OmrDAO.getInstance().findByPk(om.getId()); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString()); } list(userId, request, response); } else if (action.equals("delete")) { OmrDAO.getInstance().delete(om.getId()); // Activity log UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("editAsc")) { Omr omr = OmrDAO.getInstance().findByPk(om.getId()); omr.setAscFileContent(IOUtils.toByteArray(is)); omr.setAscFileMime(MimeTypeConfig.MIME_TEXT); omr.setAscFileName(omr.getTemplateFileName() + ".asc"); OmrDAO.getInstance().update(omr); omr = OmrDAO.getInstance().findByPk(om.getId()); IOUtils.closeQuietly(is); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("editFields")) { Omr omr = OmrDAO.getInstance().findByPk(om.getId()); omr.setFieldsFileContent(IOUtils.toByteArray(is)); omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT); omr.setFieldsFileName(omr.getTemplateFileName() + ".fields"); OmrDAO.getInstance().update(omr); omr = OmrDAO.getInstance().findByPk(om.getId()); IOUtils.closeQuietly(is); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("check")) { File form = FileUtils.createTempFile(); OutputStream formFile = new FileOutputStream(form); formFile.write(IOUtils.toByteArray(is)); IOUtils.closeQuietly(formFile); formFile.close(); Map<String, String> results = OMRHelper.process(form, om.getId()); FileUtils.deleteQuietly(form); IOUtils.closeQuietly(is); UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null); results(userId, request, response, action, results, om.getId()); } } } catch (Exception e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:dk.statsbiblioteket.doms.licensemodule.servlets.ConfigurationServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); request.setCharacterEncoding("UTF-8"); String event = request.getParameter("event"); log.info("New event for ConfigurationServlet:" + event); try {//from www .jav a 2 s.c o m // tab 0 is list licenses if ("save_presentationtype".equals(event)) { request.setAttribute("tab", "1"); String key = request.getParameter("key_presentationtype"); String value = request.getParameter("value_presentationtype"); String value_en = request.getParameter("value_en_presentationtype"); log.debug("Saving new presentationtype:" + key); LicenseModuleFacade.persistDomLicensePresentationType(key, value, value_en); } else if ("save_grouptype".equals(event)) { request.setAttribute("tab", "2"); String key = request.getParameter("key_grouptype"); String value_dk = request.getParameter("value_grouptype"); String value_en = request.getParameter("value_en_grouptype"); String description = request.getParameter("value_groupdescription"); String description_en = request.getParameter("value_en_groupdescription"); String query = request.getParameter("value_groupquery"); String isMustGroupStr = request.getParameter("mustGroupCheck"); boolean isMustGroup = false; log.debug("Saving new grouptype:" + key); if (isMustGroupStr != null) { // Checkbox is checked isMustGroup = true; } LicenseModuleFacade.persistDomLicenseGroupType(key, value_dk, value_en, description, description_en, query, isMustGroup); } else if ("save_attributetype".equals(event)) { request.setAttribute("tab", "3"); String value = request.getParameter("value_attributetype"); log.debug("Saving new attributetype:" + value); LicenseModuleFacade.persistDomAttributeType(value); } else if ("validate".equals(event)) { log.debug("validate called"); request.setAttribute("tab", "4"); String validation_attribute_values = request.getParameter("validation_attribute_values"); String validation_groups = request.getParameter("validation_groups"); String validation_presentationtype = request.getParameter("validation_presentationtype"); request.setAttribute("validation_attribute_values", validation_attribute_values); request.setAttribute("validation_groups", validation_groups); request.setAttribute("validation_presentationtype", validation_presentationtype); String result = decomposeValidateAccess(validation_attribute_values, validation_groups, validation_presentationtype); request.setAttribute("validation_result", result); } else if ("validateQuery".equals(event)) { log.debug("validateQuery called"); request.setAttribute("tab", "5"); String validationQuery_attribute_values = request.getParameter("validationQuery_attribute_values"); String validationQuery_presentationtype = request.getParameter("validationQuery_presentationtype"); request.setAttribute("validationQuery_attribute_values", validationQuery_attribute_values); request.setAttribute("validationQuery_presentationtype", validationQuery_presentationtype); String result = decomposeValidateQuery(validationQuery_attribute_values, validationQuery_presentationtype); request.setAttribute("validationQuery_result", result); } else if ("checkAccessIds".equals(event)) { log.debug("checkAccessIds called"); request.setAttribute("tab", "6"); String checkAccessIds_attribute_values = request.getParameter("checkAccessIds_attribute_values"); String checkAccessIds_presentationtype = request.getParameter("checkAccessIds_presentationtype"); String checkAccessIds_ids = request.getParameter("checkAccessIds_ids"); request.setAttribute("checkAccessIds_attribute_values", checkAccessIds_attribute_values); request.setAttribute("checkAccessIds_presentationtype", checkAccessIds_presentationtype); request.setAttribute("checkAccessIds_ids", checkAccessIds_ids); String result = decomposCheckAccessIds(checkAccessIds_attribute_values, checkAccessIds_presentationtype, checkAccessIds_ids); request.setAttribute("checkAccessIds_result", result); } else if ("deletePresentationType".equals(event)) { log.debug("deletePresentationType called"); request.setAttribute("tab", "1"); String typeName = request.getParameter("typeName"); LicenseModuleFacade.deleteDomPresentationType(typeName); } else if ("deleteGroupType".equals(event)) { log.debug("deleteGroup called"); request.setAttribute("tab", "2"); String typeName = request.getParameter("typeName"); LicenseModuleFacade.deleteDomLicenseGroupType(typeName); } else if ("deleteAttributeType".equals(event)) { log.debug("deleteAttributeType called"); request.setAttribute("tab", "3"); String typeName = request.getParameter("typeName"); LicenseModuleFacade.deleteDomAttributeType(typeName); } else if ("updateGroup".equals(event)) { log.debug("updateGroup called"); request.setAttribute("tab", "2"); String id = request.getParameter("id"); //String key = request.getParameter("key");//Not used. Update by ID. String value = request.getParameter("value_grouptype"); String value_en = request.getParameter("value_en_grouptype"); String description = request.getParameter("value_groupdescription"); String description_en = request.getParameter("value_en_groupdescription"); String query = request.getParameter("value_groupquery"); String isMustGroupStr = request.getParameter("mustGroupCheck"); boolean isMustGroup = false; if (isMustGroupStr != null) { // Checkbox is checked isMustGroup = true; } log.debug("Updating license group with id:" + id); LicenseModuleFacade.updateDomLicenseGroupType(Long.parseLong(id), value, value_en, description, description_en, query, isMustGroup); } else if ("updatePresentationType".equals(event)) { log.debug("updatePresentationType called"); request.setAttribute("tab", "1"); String id = request.getParameter("id"); //String key = request.getParameter("key");//Not used. Update by ID. String value = request.getParameter("value_presentationtype"); String value_en = request.getParameter("value_en_presentationtype"); log.debug("Updating presentatintype with id:" + id); LicenseModuleFacade.updateDomPresentationType(Long.parseLong(id), value, value_en); } else { log.error("Unknown event:" + event); request.setAttribute("message", "Unknown event:" + event); } } catch (Exception e) {//various server errors log.error("unexpected error", e); request.setAttribute("message", e.getMessage()); returnFormPage(request, response); return; } returnFormPage(request, response); return; }
From source file:es.logongas.encuestas.presentacion.controller.EncuestaController.java
@RequestMapping(value = { "/siguiente.html" }) public ModelAndView siguiente(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); String viewName;/*from w w w . j ava 2 s. co m*/ try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("no existe el juego de caracteres utf-8", ex); } int idPregunta; try { idPregunta = Integer.parseInt(request.getParameter("idPregunta")); } catch (NumberFormatException ex) { throw new BusinessException(new BusinessMessage(null, "El N de pregunta no es vlido")); } Pregunta pregunta = (Pregunta) daoFactory.getDAO(Pregunta.class).read(idPregunta); if (pregunta == null) { throw new BusinessException(new BusinessMessage(null, "La pregunta solicitada no existe")); } RespuestaEncuesta respuestaEncuesta = getEncuestaState(request).getRespuestaEncuesta(); if (respuestaEncuesta.isPreguntaValida(pregunta) == false) { throw new BusinessException( new BusinessMessage(null, "La pregunta solicitada no es vlida en esta encuesta")); } RespuestaPregunta respuestaPregunta = respuestaEncuesta.getRespuestaPregunta(pregunta); populateRespuestaFromRequest(request, respuestaPregunta); List<BusinessMessage> businessMessages = respuestaPregunta.validate(); if ((businessMessages != null) && (businessMessages.size() > 0)) { model.put("businessMessages", businessMessages); model.put("respuestaPregunta", respuestaPregunta); viewName = "encuestas/pregunta"; } else { Pregunta siguientePregunta = respuestaEncuesta.getRespuestaPregunta(pregunta).siguiente(); if (siguientePregunta != null) { viewName = "redirect:/pregunta.html?idPregunta=" + siguientePregunta.getIdPregunta(); } else { //Era la ltima pregunta.Vamos a la pgina de finalizar viewName = "redirect:/finalizar.html"; } } return new ModelAndView(viewName, model); }
From source file:com.hphoto.server.ApiServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get parameters from request request.setCharacterEncoding("UTF-8"); // the query language String lang = request.getParameter("hl"); String kind = request.getParameter("kind"); String alt = request.getParameter("alt"); String owner = request.getParameter("user"); String feed = request.getParameter("feed"); String albumid = request.getParameter("album"); if (lang != null) { if (lang.indexOf('_') == -1) { //throw }/*from ww w. j a v a 2s. c o m*/ String language = lang.substring(0, lang.indexOf('_')); String count = lang.substring(lang.indexOf('_') + 1); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().newDocument(); Element rss = addNode(doc, doc, "rss"); addAttribute(doc, rss, "version", "2.0"); addAttribute(doc, rss, "xmlns:opensearch", (String) NS_MAP.get("opensearch")); addAttribute(doc, rss, "xmlns:atom", (String) NS_MAP.get("atom")); addAttribute(doc, rss, "xmlns:photo", (String) NS_MAP.get("photo")); addAttribute(doc, rss, "xmlns:media", (String) NS_MAP.get("media")); Element channel = addNode(doc, rss, "channel"); if (kind.equals("album")) { addCategory(doc, channel, request); } else if (kind.equals("photo")) { addPhoto(doc, channel, request); } else { response.getOutputStream().println("Invalid paramenter."); return; } if (alt.equals("json")) { String value = null; try { value = org.json.XML.toJSONObject(doc.toString()).toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (value != null) response.getOutputStream().print(value); return; } // dump DOM tree DOMSource source = new DOMSource(doc); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); StreamResult result = new StreamResult(response.getOutputStream()); response.setContentType("text/xml"); transformer.transform(source, result); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new ServletException(e); } catch (javax.xml.transform.TransformerException e) { throw new ServletException(e); } }
From source file:com.openkm.servlet.admin.StampServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doGet({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); Session session = null;/*w ww.j ava2 s. c o m*/ updateSessionManager(request); try { session = JCRUtils.getSession(); if (action.equals("textCreate")) { textCreate(session, request, response); } else if (action.equals("imageCreate")) { imageCreate(session, request, response); } else if (action.equals("textEdit")) { textEdit(session, request, response); } else if (action.equals("imageEdit")) { imageEdit(session, request, response); } else if (action.equals("textDelete")) { textDelete(session, request, response); } else if (action.equals("textColor")) { textColor(session, request, response); } else if (action.equals("textTest")) { textTest(session, request, response); } else if (action.equals("imageDelete")) { imageDelete(session, request, response); } else if (action.equals("textActive")) { textActive(session, request, response); } else if (action.equals("imageActive")) { imageActive(session, request, response); } else if (action.equals("imageView")) { imageView(session, request, response); } else if (action.equals("imageTest")) { imageTest(session, request, response); } if (action.equals("") || action.equals("textList") || action.equals("textActive") || (action.startsWith("text") && WebUtils.getBoolean(request, "persist"))) { textList(session, request, response); } else if (action.equals("imageList") || action.equals("imageActive")) { imageList(session, request, response); } } catch (LoginException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (RepositoryException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (PrincipalAdapterException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DocumentException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (EvalError e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { JCRUtils.logout(session); } }
From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getCharacterEncoding() == null) req.setCharacterEncoding("UTF-8"); resp.setContentType("application/json; charset=utf-8"); resp.setCharacterEncoding("UTF-8"); resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Methods", "GET, POST"); resp.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Requested-With, Accept"); if (null == req.getPathInfo() || "/".equalsIgnoreCase(req.getPathInfo())) { handleSenseiRequest(req, resp, _senseiBroker); } else if ("/get".equalsIgnoreCase(req.getPathInfo())) { handleStoreGetRequest(req, resp); } else if ("/sysinfo".equalsIgnoreCase(req.getPathInfo())) { handleSystemInfoRequest(req, resp); } else if (req.getPathInfo().startsWith("/admin/jmx/")) { handleJMXRequest(req, resp);/* w w w . j av a 2 s . c om*/ } else if (req.getPathInfo().startsWith("/federatedBroker/")) { if (federatedBroker == null) { try { writeEmptyResponse(req, resp, new SenseiError("The federated broker wasn't initialized", ErrorType.FederatedBrokerUnavailable)); } catch (Exception e) { throw new RuntimeException(e); } } handleSenseiRequest(req, resp, federatedBroker); } else { handleSenseiRequest(req, resp, _senseiBroker); } }