List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.openkm.servlet.admin.UnitTestingServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doGet({}, {})", request, response); String test = WebUtils.getString(request, "test"); response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); OutputStream os = response.getOutputStream(); PrintStream ps = new PrintStream(os); header(ps, "Unit testing", breadcrumb); ps.flush();// w ww .j a v a2s . c om RunListener listener = new CustomListener(ps); JUnitCore junit = new JUnitCore(); junit.addListener(listener); if (test != null && !test.isEmpty()) { try { Class<?> clazz = Class.forName(test); ps.println("<b>" + clazz.getCanonicalName() + "</b><br/>"); ps.flush(); ps.println("<pre>"); ps.flush(); junit.run(clazz); ps.println("</pre>"); ps.flush(); } catch (ClassNotFoundException e) { warn(ps, e.getMessage()); } } else { for (Class<?> clazz : new Reflections("com.openkm.test.api").getSubTypesOf(TestCase.class)) { ps.println("<a style=\"color: black; font-weight:bold;\" href=\"UnitTesting?test=" + clazz.getCanonicalName() + "\">" + clazz.getCanonicalName() + "</a><br/>"); ps.flush(); ps.println("<pre>"); ps.flush(); junit.run(clazz); ps.println("</pre>"); ps.flush(); } } ps.println( "<span style=\"color: blue; font-weight:bold;\">>>> End Of Unit Testing <<<</span>"); footer(ps); ps.flush(); IOUtils.closeQuietly(ps); IOUtils.closeQuietly(os); }
From source file:com.thoughtworks.go.server.controller.GoConfigAdministrationController.java
@RequestMapping(value = "/admin/restful/configuration/file/GET/historical-xml", method = RequestMethod.GET) public void getConfigRevision(@RequestParam(value = "version", required = true) String version, HttpServletResponse response) throws Exception { GoConfigRevision configRevision = goConfigService.getConfigAtVersion(version); String md5 = configRevision.getMd5(); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); response.setHeader(X_CRUISE_CONFIG_MD5, md5); if (configRevision.isByteArrayBacked()) { IOUtils.write(configRevision.getConfigXmlBytes(), response.getOutputStream()); } else {//www .j a v a 2 s . c o m response.getWriter().write(configRevision.getContent()); } }
From source file:controller.categoryServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String catimage = ""; String nameCategory = ""; String command = ""; int catogory_id = 0; String catogory_imagehidden = ""; String catogory_image = ""; if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();/*from ww w . j a v a 2 s.co m*/ return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { catimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + catimage; File storeFile = new File(filePath); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameCategory = item.getString(); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("catid")) { catogory_id = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogery_imagehidden")) { catogory_imagehidden = item.getString(); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameCategory.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } HttpSession session = request.getSession(); try { if (error.length() == 0) { CategoryEntity c = new CategoryEntity(nameCategory, catimage); switch (command) { case "insert": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.insertCategory(c); request.setAttribute("er", "thanh cong"); url = "/java/admin/ql-category.jsp"; } break; case "update": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.updateCategory(nameCategory, catimage, catogory_id); url = "/java/admin/ql-category.jsp"; } break; } } else { url = "/java/admin/add-category.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:controller.servlet.PostServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w . j ava 2 s . co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PostDAOService postService = PostDAO.getInstance(); String title = null; String shortTitle = null; String sCategoryID = null; String content = null; String link = null; String action = null; // String pathImage; String imageName = ""; boolean isUploadSuccess = false; ServletFileUpload fileUpload = new ServletFileUpload(); try { FileItemIterator itr = fileUpload.getItemIterator(request); while (itr.hasNext()) { FileItemStream fileItemStream = itr.next(); if (fileItemStream.isFormField()) { String fieldName = fileItemStream.getFieldName(); InputStream is = fileItemStream.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b, "UTF-8"); if (fieldName.equals("action")) { action = value; } if (fieldName.equals("title")) { title = value; } if (fieldName.equals("content")) { content = value; } if (fieldName.equals("short-title")) { shortTitle = value; } if (fieldName.equals("category-id")) { sCategoryID = value; } if (fieldName.equals("link")) { link = value; } } else { String realPath = getServletContext().getRealPath("/"); String filePath = realPath.replace("\\build\\web", "\\web\\image\\post");//Duong dan luu file anh imageName = fileItemStream.getName(); StringTokenizer token = new StringTokenizer(imageName, "."); String fileNameExtension = ""; while (token.hasMoreElements()) { fileNameExtension = token.nextElement().toString(); } System.out.println("img: " + imageName); if (!imageName.equals("")) { imageName = Support.randomString(); isUploadSuccess = FileUpload.processFile(filePath, fileItemStream, imageName, fileNameExtension); imageName += "." + fileNameExtension; } } } Post currentPost = new Post(); currentPost.setPostID(postService.nextID()); currentPost.setTitle(title); currentPost.setShortTitle(shortTitle); currentPost.setCategory(new Category(Integer.valueOf(sCategoryID), "", false)); currentPost.setContent(content); currentPost.setDatePost(Support.getDatePost()); currentPost.setUser((User) request.getSession().getAttribute(Constants.CURRENT_USER)); currentPost.setLink(link); currentPost.setActive(false); request.setAttribute(Constants.CURRENT_POST, currentPost); request.setAttribute(Constants.LIST_CATEGORY, CategoryDAO.getInstance().getCategories()); if (action != null) { switch (action) { case "up-load": upLoad(request, response, imageName, isUploadSuccess); break; case "add-topic": addTopic(request, response, currentPost); break; } } } catch (IOException | org.apache.tomcat.util.http.fileupload.FileUploadException e) { response.getWriter().println(e.toString()); } }
From source file:com.enonic.cms.server.service.admin.mvc.controller.SiteDebugInfoController.java
/** * Serve bootstrap info./*w ww .j a v a2 s . c om*/ */ private void serveJavaScriptFile(RenderTraceInfo info, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/javascript; charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter writer = new PrintWriter(response.getWriter()); writer.println(localizeScript(request, readStaticFile("admin/ice/ice.js"))); writer.println("cms.ice.Setup.setBaseUrl('" + getAdminBaseUrl(request) + "');"); writer.println(createSetPageInfoStatement(info.getKey(), info.getPageInfo(), request)); for (PagePortletTraceInfo objectInfo : info.getPageInfo().getPortlets()) { writer.println(createAddPageObjectInfoStatement(info.getKey() + "-" + objectInfo.getKey(), objectInfo, request)); } writer.close(); }
From source file:nl.flotsam.calendar.web.CalendarIcalView.java
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Calendar calendar = getCalendarToBeRendered(model); if (calendar == null) { throw new ServletException("Failed to locate Calendar to be rendered."); }/*w w w. j a va 2 s .co m*/ response.setContentType("text/calendar"); // TODO: We can leverage data from the Calendar here response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); Writer writer = response.getWriter(); calendar.toIcal(writer); writer.flush(); }
From source file:cn.trymore.core.web.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); try {/*from www . ja v a2 s . c o m*/ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); diskFileItemFactory.setRepository(new File(this.tempPath)); String fileIds = ""; ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request); Iterator<FileItem> itor = fileList.iterator(); Iterator<FileItem> itor1 = fileList.iterator(); String file_type = ""; while (itor1.hasNext()) { FileItem item = itor1.next(); if (item.isFormField() && "file_type".equals(item.getFieldName())) { file_type = item.getString(); } } FileItem fileItem; while (itor.hasNext()) { fileItem = itor.next(); if (fileItem.getContentType() == null) { continue; } // obtains the file path and name String filePath = fileItem.getName(); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); // generates new file name with the current time stamp. String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName); // ensure the directory existed before creating the file. File dir = new File( this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1)); if (!dir.exists()) { dir.mkdirs(); } // stream writes to the destination file fileItem.write(new File(this.uploadPath + "/" + newFileName)); ModelFileAttach fileAttach = null; if (request.getParameter("noattach") == null) { // storages the file into database. fileAttach = new ModelFileAttach(); fileAttach.setFileName(fileName); fileAttach.setFilePath(newFileName); fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize())); fileAttach.setNote(this.getStrFileSize(fileItem.getSize())); fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1)); fileAttach.setCreatetime(new Date()); fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL); fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat); ModelAppUser user = ContextUtil.getCurrentUser(); if (user != null) { fileAttach.setCreatorId(Long.valueOf(user.getId())); fileAttach.setCreator(user.getFullName()); } else { fileAttach.setCreator("Unknow"); } this.serviceFileAttach.save(fileAttach); } //add by Tang ??fileIds????? if (fileAttach != null) { fileIds = (String) request.getSession().getAttribute("fileIds"); if (fileIds == null) { fileIds = fileAttach.getId(); } else { fileIds = fileIds + "," + fileAttach.getId(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.println( "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"") + ", \"url\":\"" + newFileName + "\"}}"); } request.getSession().setAttribute("fileIds", fileIds); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\""); } }
From source file:com.mirth.connect.server.servlets.UserServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MIRTH-1745 response.setCharacterEncoding("UTF-8"); UserController userController = ControllerFactory.getFactory().createUserController(); EventController eventController = ControllerFactory.getFactory().createEventController(); PrintWriter out = response.getWriter(); Operation operation = Operations.getOperation(request.getParameter("op")); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); if (operation.equals(Operations.USER_LOGIN)) { String username = request.getParameter("username"); String password = request.getParameter("password"); String version = request.getParameter("version"); response.setContentType(TEXT_PLAIN); serializer.toXML(login(request, response, userController, eventController, username, password, version), out);//from w w w. ja v a 2 s. c o m } else if (!isUserLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { try { Map<String, Object> parameterMap = new HashMap<String, Object>(); if (operation.equals(Operations.USER_LOGOUT)) { // Audit the logout request but don't block it isUserAuthorized(request, null); logout(request, userController, eventController); } else if (operation.equals(Operations.USER_GET)) { /* * If the requesting user does not have permission, only * return themselves. */ response.setContentType(APPLICATION_XML); User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (!isUserAuthorized(request, parameterMap)) { user = new User(); user.setId(getCurrentUserId(request)); } serializer.toXML(userController.getUser(user), out); } else if (operation.equals(Operations.USER_UPDATE)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) { userController.updateUser(user); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_CHECK_OR_UPDATE_PASSWORD)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) { String plainPassword = request.getParameter("plainPassword"); serializer.toXML(userController.checkOrUpdateUserPassword(user.getId(), plainPassword), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_REMOVE)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap)) { // Try to remove the user and then invalidate the // session if it succeeded userController.removeUser(user, (Integer) request.getSession().getAttribute(SESSION_USER)); UserSessionCache.getInstance().invalidateAllSessionsForUser(user); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_IS_USER_LOGGED_IN)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap)) { response.setContentType(TEXT_PLAIN); out.print(userController.isUserLoggedIn(user)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_PREFERENCES_GET)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); // Allow if the user is requesting his own preferences. // Check this first so a current user call is not audited. if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) { response.setContentType(TEXT_PLAIN); serializer.toXML(userController.getUserPreferences(user), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_PREFERENCES_SET)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); // Allow if the user is setting his own preferences. Check // this first so a current user call is not audited. if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) { String name = request.getParameter("name"); String value = request.getParameter("value"); userController.setUserPreference(user, name, value); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } } catch (RuntimeIOException rio) { logger.debug(rio); } catch (Throwable t) { logger.error(ExceptionUtils.getStackTrace(t)); throw new ServletException(t); } } }
From source file:com.flexive.war.servlet.ExportServlet.java
/** * Export types as a Groovy script; request session attribute "groovyScriptCode" set from StructureExportBean * * @param request request/*from www.ja va 2 s . c o m*/ * @param response reponse * @throws IOException on errors */ private void exportGroovy(HttpServletRequest request, HttpServletResponse response) throws IOException { final String groovyCode = (String) request.getSession().getAttribute("groovyScriptCode"); final String fileName = "structures"; response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".groovy;"); try { response.getOutputStream().write(groovyCode.getBytes(Charsets.UTF_8)); } finally { response.getOutputStream().close(); } }
From source file:com.library.essay.tinymce.spellchecker.TinyMCESpellCheckerServlet.java
/** * @param response response/*w w w .ja v a 2s . c om*/ */ private void setResponeHeaders(HttpServletResponse response) { response.setContentType("text/plain; charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Cache-Control", "no-store, no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", System.currentTimeMillis()); }