List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java
/** * INTERNAL: Builds the Parameters object from an HttpServletRequest * object.//from www.j a va 2s. 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:es.logongas.encuestas.presentacion.controller.EncuestaController.java
@RequestMapping(value = { "/encuesta.html" }) public ModelAndView encuesta(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); String viewName;//from ww w . j a va2 s .c o m if (request.getCharacterEncoding() == null) { try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(EncuestaController.class.getName()).log(Level.WARNING, "no existe el juego de caracteres utf-8", ex); } } int idEncuesta; URI backURI; try { idEncuesta = Integer.parseInt(request.getParameter("idEncuesta")); } catch (NumberFormatException ex) { throw new BusinessException(new BusinessMessage(null, "El N de encuesta no es vlido")); } try { if ((request.getParameter("backURI") == null) || (request.getParameter("backURI").trim().equals(""))) { backURI = new URI(request.getContextPath() + "/"); } else { backURI = new URI(request.getParameter("backURI")); } } catch (Exception ex) { throw new BusinessException(new BusinessMessage(null, "El backURI no es vlido")); } Encuesta encuesta = (Encuesta) daoFactory.getDAO(Encuesta.class).read(idEncuesta); if (encuesta == null) { throw new BusinessException(new BusinessMessage(null, "La encuesta solicitada no existe")); } if (encuesta.isEncuestaHabilitada() == false) { throw new BusinessException( new BusinessMessage(null, "La encuesta solicitada no es posible realizarla actualmente")); } RespuestaEncuesta respuestaEncuesta = new RespuestaEncuesta(encuesta); EncuestaState encuestaState = new EncuestaState(respuestaEncuesta, backURI); setEncuestaState(request, encuestaState); Pregunta pregunta = respuestaEncuesta.getPrimeraPregunta(); if (pregunta == null) { throw new BusinessException(new BusinessMessage(null, "La encuesta no tiene preguntas")); } viewName = "redirect:/pregunta.html?idPregunta=" + pregunta.getIdPregunta(); return new ModelAndView(viewName, model); }
From source file:com.megaeyes.web.controller.UserController.java
@ControllerDescription(description = "?", isLog = false, isCheckSession = false) @RequestMapping("/getSubscribeNotifyUsers.xml") public void getSubscribeNotifyUsers(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); GetSubscribeNotifyUsersResponse resp = new GetSubscribeNotifyUsersResponse(); String code = (String) request.getAttribute("code"); if (StringUtils.isBlank(code)) { resp.setReason("missing parameter [code] !"); resp.setSuccess(GetSubscribeNotifyUsersResponse.FAIL); }// w w w . j ava 2 s.co m String event = (String) request.getAttribute("eventType"); if (StringUtils.isBlank(event)) { event = "alarm"; } if (GetSubscribeNotifyUsersResponse.SUCCESS.equals(resp.getSuccess())) { try { // ? Set<String> ids = interConnectManager.listNotifyUser(code, event); // ?SetList?ibatis in? List<String> idList = new ArrayList<String>(); for (String id : ids) { idList.add(id); } List<UserSessionVO> list = interConnectManager.listOnlineNotifyUsers(idList); List<GetSubscribeNotifyUsersResponse.User> users = new ArrayList<GetSubscribeNotifyUsersResponse.User>(); for (UserSessionVO u : list) { GetSubscribeNotifyUsersResponse.User user = resp.new User(); user.setNaming(u.getNaming()); user.setSessionId(u.getId()); user.setCode(code); users.add(user); } resp.setUsers(users); } catch (BusinessException e) { e.printStackTrace(); resp.setSuccess(GetSubscribeNotifyUsersResponse.FAIL); resp.setReason(e.getMessage()); } catch (Exception e) { e.printStackTrace(); resp.setSuccess(GetSubscribeNotifyUsersResponse.EXCEPTION); resp.setReason(e.getMessage()); } } Document doc = new Document(); Element root = new Element("Message"); doc.setRootElement(root); Element successElement = new Element("Success"); successElement.setText(resp.getSuccess()); root.addContent(successElement); if (!GetSubscribeNotifyUsersResponse.SUCCESS.equals(resp.getSuccess())) { Element reason = new Element("Reason"); reason.setText(resp.getReason()); root.addContent(reason); } Element usersElement = new Element("Users"); for (GetSubscribeNotifyUsersResponse.User u : resp.getUsers()) { Element userElement = new Element("User"); userElement.setAttribute("SessionId", u.getSessionId()); userElement.setAttribute("Naming", u.getNaming()); userElement.setAttribute("Code", u.getCode()); usersElement.addContent(userElement); } root.addContent(usersElement); writePageWithContentLength(response, doc); }
From source file:com.megaeyes.web.controller.UserController.java
@ControllerDescription(description = "", isLog = true, isCheckSession = false) @RequestMapping("/login.json") public void login(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf8"); UserLogonResponse resp = new UserLogonResponse(); // License//from ww w .j a va2s. com resp.setCode(checkLicence().toString()); String loginName = (String) request.getAttribute("loginName"); String password = request.getParameter("password"); String ip = request.getParameter("ip"); if (StringUtils.isBlank(ip)) { if (request.getHeader("X-Forwarded-For") != null) { ip = request.getHeader("X-Forwarded-For"); } else { ip = request.getRemoteAddr(); } } UserSessionVO data = new UserSessionVO(); String platformStatus = ""; if (ErrorCode.SUCCESS.equals(resp.getCode())) { try { data = userManager.logon(loginName, password, ip); platformStatus = userManager.getPlatformStatus(); request.getSession().setAttribute("user", data); } catch (BusinessException be) { resp.setCode(be.getCode()); resp.setMessage(be.getMessage()); } if (ErrorCode.SUCCESS.equals(resp.getCode())) { List<EpClientGateway> list = epClientGatewayManager.listEpClientGateway(); if (list.size() > 0) { // ??? EpClientGateway ecg = list.get(0); // IP if (data.getIsInnerUser().intValue() == 1) { resp.setClientGatewayIp(ecg.getIp1()); } // IP else { resp.setClientGatewayIp(ecg.getIp2()); } resp.setClientGatewayPort(ecg.getPort().toString()); } resp.setUserId(data.getUserId()); resp.setOrganId(data.getOrganId()); resp.setSessionId(data.getId()); resp.setUserName(data.getUserName()); resp.setNaming(data.getNaming()); resp.setPriority(data.getPriority() + ""); resp.setOrganName(data.getOrganName()); resp.setIsAdmin(data.getIsAdmin()); resp.setBranchId(data.getBranchId()); resp.setIsBranchAdmin(data.getIsBranchAdmin()); if (!StringUtils.isBlank(resp.getSessionId())) { request.getSession().setAttribute("sessionId", resp.getSessionId()); } resp.setPlatformStatus(platformStatus); List<EpOperation> operations = roleManager.listEpOperationByUserId(data.getUserId()); if (operations != null && !operations.isEmpty()) { String[] operationArray = new String[operations.size()]; for (int i = 0; i < operations.size(); i++) { operationArray[i] = operations.get(i).getOperationNumber(); } resp.setOperations(operationArray); } } } writePageNoZip(response, resp); }
From source file:com.openkm.servlet.admin.JcrRepositoryViewServlet.java
@Override 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"); String path = WebUtils.getString(request, "path"); Session session = null;/*ww w. j a v a 2s . c o m*/ updateSessionManager(request); try { session = JCRUtils.getSession(); if (action.equals("unlock")) { unlock(session, path, request, response); } else if (action.equals("checkin")) { checkin(session, path, request, response); } else if (action.equals("remove_content")) { removeContent(session, path, request, response); } else if (action.equals("remove_current")) { path = removeCurrent(session, path, request, response); } else if (action.equals("remove_mixin")) { removeMixin(session, path, request, response); } else if (action.equals("edit")) { edit(session, path, request, response); } else if (action.equals("textExtraction")) { textExtraction(session, path, request, response); } if (!action.equals("edit")) { list(session, path, 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); } finally { JCRUtils.logout(session); } }
From source file:com.ikon.servlet.admin.RepositoryViewServlet.java
@Override 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"); String path = WebUtils.getString(request, "path"); Session session = null;//from ww w .j a va2 s.c om updateSessionManager(request); try { session = JCRUtils.getSession(); if ("save".equals(action)) { save(session, path, request, response); list(session, path, 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); } finally { JCRUtils.logout(session); } }
From source file:org.kie.jbpm.designer.web.server.TransformerServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String formattedSvg = req.getParameter("fsvg"); String rawSvg = req.getParameter("rsvg"); String uuid = req.getParameter("uuid"); String profileName = req.getParameter("profile"); String transformto = req.getParameter("transformto"); String jpdl = req.getParameter("jpdl"); String gpd = req.getParameter("gpd"); String bpmn2in = req.getParameter("bpmn2"); String respaction = req.getParameter("respaction"); String pp = req.getParameter("pp"); String processid = req.getParameter("processid"); IDiagramProfile profile = ServletUtil.getProfile(req, profileName, getServletContext()); DroolsFactoryImpl.init();//from ww w. j a v a2s . com if (transformto != null && transformto.equals(TO_PDF)) { try { if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PDFTranscoder t = new PDFTranscoder(); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter().write("<object data=\"data:application/pdf;base64," + Base64.encodeBase64(bout.toByteArray()) + "\" type=\"application/pdf\"></object>"); } else { storeToGuvnor(uuid, profile, formattedSvg, rawSvg, transformto, processid); resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } PDFTranscoder t = new PDFTranscoder(); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(resp.getOutputStream()); t.transcode(input, output); } } catch (TranscoderException e) { resp.sendError(500, e.getMessage()); } } else if (transformto != null && transformto.equals(TO_PNG)) { try { if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); BASE64Encoder enc = new sun.misc.BASE64Encoder(); resp.getWriter() .write("<img src=\"data:image/png;base64," + enc.encode(bout.toByteArray()) + "\">"); } else { ParsedURL.registerHandler(new GuvnorParsedURLProtocolHandler(profile)); storeToGuvnor(uuid, profile, formattedSvg, rawSvg, transformto, processid); resp.setContentType("image/png"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\""); } PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(resp.getOutputStream()); t.transcode(input, output); } } catch (TranscoderException e) { resp.sendError(500, e.getMessage()); } } else if (transformto != null && transformto.equals(JPDL_TO_BPMN2)) { String bpmn2 = JbpmMigration.transform(jpdl); Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2); // add bpmndi info to Definitions with help of gpd addBpmnDiInfo(def, gpd); // hack for now revisitSequenceFlows(def, bpmn2); // another hack if id == name revisitNodeNames(def); // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet .createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String fullXmlModel = outputStream.toString(); // convert to json and write response String json = profile.createUnmarshaller().parseModel(fullXmlModel, profile, pp); resp.setContentType("application/json"); resp.getWriter().print(json); } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) { // fix package name if needed String[] packageAssetName = ServletUtil.findPackageAndAssetInfo(uuid, profile); String packageName = packageAssetName[0]; Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in); List<RootElement> rootElements = def.getRootElements(); for (RootElement root : rootElements) { if (root instanceof Process) { Process process = (Process) root; Iterator<FeatureMap.Entry> iter = process.getAnyAttribute().iterator(); FeatureMap.Entry toDeleteFeature = null; while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("packageName")) { String pname = (String) entry.getValue(); if (pname == null || !pname.equals(packageName)) { toDeleteFeature = entry; } } } if (toDeleteFeature != null) { process.getAnyAttribute().remove(toDeleteFeature); ExtendedMetaData metadata = ExtendedMetaData.INSTANCE; EAttributeImpl extensionAttribute = (EAttributeImpl) metadata .demandFeature("http://www.jboss.org/drools", "packageName", false, false); EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry( extensionAttribute, packageName); process.getAnyAttribute().add(extensionEntry); } } } // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet .createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String revisedXmlModel = outputStream.toString(); String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp); resp.setContentType("application/json"); resp.getWriter().print(json); } else if (transformto == null && respaction != null && respaction.equals(RESPACTION_SHOWEMBEDDABLE)) { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); String editorURL = ExternalInfo.getExternalProtocol(profile) + "://" + ExternalInfo.getExternalHost(profile) + "/" + profile.getExternalLoadURLSubdomain().substring(0, profile.getExternalLoadURLSubdomain().indexOf("/")) + "/org.drools.guvnor.Guvnor/standaloneEditorServlet?assetsUUIDs=" + uuid + "&client=oryx"; resp.getWriter() .write("<iframe id=\"processFrame\" src=\"" + editorURL + "\" width=\"650\" height=\"580\"/>"); } }
From source file:tw.com.sbi.product.controller.Product.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); ProductService productService = null; String groupId = request.getSession().getAttribute("group_id").toString(); String action = request.getParameter("action"); logger.debug("Action:" + action); if ("selectAll".equals(action)) { try {/*from w w w. jav a 2 s . c om*/ productService = new ProductService(); List<ProductVO> list = productService.selectByGroupId(groupId); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("search".equals(action)) { try { String productSpec = request.getParameter("product_spec"); logger.debug("productSpec:" + productSpec); productService = new ProductService(); List<ProductVO> list = productService.getProductBySpec(groupId, productSpec); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("insert".equals(action)) { try { String productSpec = request.getParameter("product_spec"); String photo = request.getParameter("photo"); String seed = request.getParameter("seed"); logger.debug("productSpec:" + productSpec); logger.debug("photo:" + photo); logger.debug("seed:" + seed); productService = new ProductService(); List<ProductVO> list = productService.addProduct(groupId, productSpec, photo, seed); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("update".equals(action)) { logger.debug("enter product update method"); try { String productId = request.getParameter("product_id"); String productSpec = request.getParameter("product_spec"); String photo = request.getParameter("photo"); String seed = request.getParameter("seed"); logger.debug("productId:" + productId); logger.debug("productSpec:" + productSpec); logger.debug("photo:" + photo); logger.debug("seed:" + seed); productService = new ProductService(); List<ProductVO> list = productService.updateProduct(groupId, productId, productSpec, photo, seed); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); logger.debug("jsonStrList: " + jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("delete".equals(action)) { try { String productId = request.getParameter("product_id"); logger.debug("productId:" + productId); productService = new ProductService(); List<ProductVO> list = productService.deleteProduct(groupId, productId); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("gen_identity".equals(action)) { try { String productId = request.getParameter("product_id"); logger.debug("productId:" + productId); productService = new ProductService(); List<ProductVO> list = productService.genIdentityID(groupId, productId); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("autocomplete_spec".equals(action)) { try { String term = request.getParameter("term"); logger.debug("term:" + term); productService = new ProductService(); List<ProductVO> list = productService.getProductBySpec(groupId, term); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java
/** * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed in the body of the * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml"). * <p/>//ww w . ja va 2 s .c o m * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/ * * @param request the servlet request (to retrieve the SPARQL 1.1 Query passed in the body of the POST request) * @param resultType the format for serializing the query results ("html", "json", or "xml") * @HTTP 200 in case the query was executed successfully * @HTTP 500 in case there was an error during the query evaluation * @return the query result in the format passed as argument */ @POST @Path(SELECT) public Response selectPost(@QueryParam("output") String resultType, @Context HttpServletRequest request) { try { if (resultType != null && outputMapper.containsKey(resultType)) resultType = outputMapper.get(resultType); if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("utf-8"); } String query = CharStreams.toString(request.getReader()); //String query = IOUtils.toString(request.getInputStream(),"utf-8"); log.debug("Query: {}", query); return select(query, resultType, request); } catch (IOException e) { log.error("body not found", e); return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } }