List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = buildUrl(req);/*from w ww . j a v a 2 s .c o m*/ resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); if ("/list".equals(path)) { List<String> names = new ArrayList<String>(); try { for (Class<? extends Service> sc : serviceClasses) { Method m; m = sc.getMethod("getName"); @SuppressWarnings("unchecked") Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass()); String result = instance.getName(); names.add(result); } serializer.deepSerialize(names, resp.getWriter()); } catch (Exception e) { Map<String, String> resultMap = new HashMap<String, String>(); Throwable t = e; if (e instanceof InvocationTargetException) { t = e.getCause(); } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); resultMap.put("outcome", "error"); resultMap.put("message", t.getMessage()); resultMap.put("type", t.getClass().getCanonicalName()); resultMap.put("stacktrace", stringWriter.getBuffer().toString()); serializer.deepSerialize(resultMap, resp.getWriter()); } } else { Method m = findRestMethod(RESTMethod.GET, path); @SuppressWarnings("unchecked") Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass()); try { Object result = m.invoke(instance); serializer.deepSerialize(result, resp.getWriter()); } catch (Exception e) { Map<String, String> resultMap = new HashMap<String, String>(); Throwable t = e; if (e instanceof InvocationTargetException) { t = e.getCause(); } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); resultMap.put("outcome", "error"); resultMap.put("message", t.getMessage()); resultMap.put("type", t.getClass().getCanonicalName()); resultMap.put("stacktrace", stringWriter.getBuffer().toString()); serializer.deepSerialize(resultMap, resp.getWriter()); } } }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java
protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); if (logger.isInfoEnabled()) { logger.info("Handling request for ui.extjs: ", request.getPathInfo()); }//w ww . ja v a2s.co m String server = request.getServerName(); int port = request.getServerPort(); // String contextPath = request.getContextPath(); // String path = request.getServletPath(); String userRolesStr = null; try { ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); IUser user = su.getUser(); IUserSettings prefs = user.getSettings(); Session.user.set(user); model.put("constantsJsFragment", this.getConstantsJsFragment()); model.put("user", user); DateFormatAttribute[] masks = DateFormatAttribute.values(); Map<String, String> dateFormatMasks = new HashMap<String, String>(); for (int i = 0, len = masks.length; i < len; i++) { DateFormatAttribute mask = masks[i]; if (mask.isForJs()) { dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormat(mask.name())); } } model.put("dateFormatMasks", dateFormatMasks); model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT)); model.put("decimalSeparator", prefs.getDecimalSeparator()); model.put("thousandSeparator", prefs.getThousandSeparator()); StringBuffer sb = new StringBuffer(); int i = 0; for (String role : user.getProfile().getRoles()) { if (i > 0) { sb.append(","); } sb.append("\"" + role + "\""); i++; } userRolesStr = sb.toString(); } catch (ClassCastException e) { // not authenticated } String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server + ((port != 80) ? (":" + port) : "");// + contextPath; model.put("productName", this.getSettings().getProductName()); model.put("productVersion", this.getSettings().getProductVersion()); model.put("hostUrl", hostUrl); // themes model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes()); // DNet extjs components in core and modules model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore()); model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules()); model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSupath()); // translations for core and modules model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n()); model.put("urlUiExtjsModulesI18n", getUiExtjsSettings().getUrlModulesI18n()); model.put("shortLanguage", this.resolveLang(request, response)); model.put("theme", this.resolveTheme(request, response)); model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE)); model.put("userRolesStr", userRolesStr); }
From source file:com.socialization.util.ConnectorServlet.java
/** * Manage the <code>GET</code> requests (<code>GetFolders</code>, * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/> * /*ww w . ja v a 2s .co m*/ * The servlet accepts commands sent in the following format:<br/> * <code>connector?Command=<CommandName>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * <p> * It executes the commands and then returns the result to the client in XML format. * </p> */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering ConnectorServlet#doGet"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); // ? currentFolderStr = new String(currentFolderStr.getBytes("iso8859-1"), "utf-8"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); XmlResponse xr; if (!RequestCycleHandler.isEnabledForFileBrowsing(request)) xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING); else if (!CommandHandler.isValidForGet(commandStr)) xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER); else { CommandHandler command = CommandHandler.getCommand(commandStr); ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typeDirPath = null; if ("File".equals(typeStr)) { // ${application.path}/WEB-INF/userfiles/ typeDirPath = getServletContext().getRealPath("WEB-INF/userfiles/"); } else { String typePath = UtilsFile.constructServerSidePath(request, resourceType); typeDirPath = getServletContext().getRealPath(typePath); } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME); else { xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl( request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl())); if (command.equals(CommandHandler.GET_FOLDERS)) xr.setFolders(currentDir); else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES)) xr.setFoldersAndFiles(currentDir); else if (command.equals(CommandHandler.CREATE_FOLDER)) { String tempStr = request.getParameter("NewFolderName"); tempStr = new String(tempStr.getBytes("iso8859-1"), "UTF-8"); String newFolderStr = UtilsFile.sanitizeFolderName(tempStr); logger.debug("Parameter NewFolderName: {}", newFolderStr); File newFolder = new File(currentDir, newFolderStr); int errorNumber = XmlResponse.EN_UKNOWN; if (newFolder.exists()) errorNumber = XmlResponse.EN_ALREADY_EXISTS; else { try { errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK : XmlResponse.EN_INVALID_FOLDER_NAME; } catch (SecurityException e) { errorNumber = XmlResponse.EN_SECURITY_ERROR; } } xr.setError(errorNumber); } } } out.print(xr); out.flush(); out.close(); logger.debug("Exiting ConnectorServlet#doGet"); }
From source file:com.taobao.diamond.server.controller.BaseStoneController.java
@RequestMapping(params = "method=updateConfig", method = RequestMethod.POST) public String updateConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content) { response.setCharacterEncoding("GBK"); String remoteIp = getRemoteIp(request); boolean checkSuccess = true; String errorMessage = ""; if (!StringUtils.hasLength(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false;//from ww w . ja v a2 s . c om errorMessage = "DataId"; } if (!StringUtils.hasLength(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = ""; } if (!StringUtils.hasLength(content)) { checkSuccess = false; errorMessage = ""; } if (!checkSuccess) { try { response.sendError(INVALID_PARAM, errorMessage); } catch (IOException e) { log.error("response", e); } return "536"; } // this.updateConfigInfo(dataId, group, content); try { this.addIpToDataIdAndGroup(remoteIp, dataId, group); } catch (Exception e) { log.error("redis", e); } return "200"; }
From source file:com.taobao.diamond.server.controller.BaseStoneController.java
@RequestMapping(params = "method=updateAll", method = RequestMethod.POST) public String updateConfigAll(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content) { response.setCharacterEncoding("GBK"); String remoteIp = getRemoteIp(request); boolean checkSuccess = true; String errorMessage = ""; if (!StringUtils.hasLength(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false;/*from w ww.jav a 2 s .c o m*/ errorMessage = "DataId"; } if (!StringUtils.hasLength(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = ""; } if (!StringUtils.hasLength(content)) { checkSuccess = false; errorMessage = ""; } if (!checkSuccess) { try { response.sendError(INVALID_PARAM, errorMessage); } catch (IOException e) { log.error("response", e); } return "536"; } // this.updateAllConfigInfo(dataId, group, content); try { // ipdataIdredis this.addIpToDataIdAndGroup(remoteIp, dataId, group); } catch (Exception e) { log.error("redis", e); } return "200"; }
From source file:com.cemso.action.FileUploadAction.java
public String execute() { try {/* w w w . ja va2s . c o m*/ if (log.isDebugEnabled()) { log.debug("start to upload file..."); } ActionContext context = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = ServletActionContext.getResponse(); Map<String, Object> session = context.getSession(); response.setCharacterEncoding("GBK"); // String type = request.getParameter("type"); if (type != null && type.equals("register")) { log.debug("upload license"); SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String datetime = tempDate.format(new java.util.Date()); String desFilePath = XmlOperationTool.CONFIG_FOLDER + datetime + "_LICENSE.TXT"; boolean bool = false; if (uploadify != null) { FileOperationTool.ChannelCopy(uploadify, new File(desFilePath)); InputStreamReader isr = new InputStreamReader(new FileInputStream(desFilePath), "GBK"); BufferedReader br = new BufferedReader(isr); long current = System.currentTimeMillis(); String firstLine = br.readLine(); String data = ""; int months = 1; if (firstLine.startsWith("1")) { data = firstLine.substring(2); months = Integer.parseInt(firstLine.substring(1, 2)); } if (firstLine.startsWith("2")) { data = firstLine.substring(3); months = Integer.parseInt(firstLine.substring(1, 3)); } if (firstLine.startsWith("3")) { data = firstLine.substring(4); months = Integer.parseInt(firstLine.substring(1, 4)); } String startdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current)); String expdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(current + 30l * months * 24 * 3600 * 1000)); String key = ""; List<RegisterDTO> registers = new ArrayList<RegisterDTO>(); if (data != null && !data.trim().isEmpty()) { if (Long.parseLong(data) >= current) { log.warn("Invalid License file"); registerService.addChecklog(ConstantUtil.CheckLogs.INVALID, ConstantUtil.CheckLogs.TYPE_INVALID); response.getWriter().print("License"); return null; } key = data; data = br.readLine(); } else { log.warn("Invalid License file"); registerService.addChecklog(ConstantUtil.CheckLogs.INVALID, ConstantUtil.CheckLogs.TYPE_INVALID); response.getWriter().print("License"); return null; } while (data != null && !data.trim().isEmpty()) { int indexid = SequenceUtil.getInstance() .getNextKeyValue(ConstantUtil.SequenceName.REGISTER_SEQUENCE); String device = data.trim(); RegisterDTO rd = new RegisterDTO(indexid, startdate, expdate, key, device, ConstantUtil.Register.NO); registers.add(rd); data = br.readLine(); } br.close(); isr.close(); //registerService.updateToDelete(); // delete the old devices /* boolean f = deviceService.deleteAllDevices(); if(log.isDebugEnabled()){ log.debug("Delete all devices result is : " + f); } */ bool = registerService.add(registers); if (log.isDebugEnabled()) { log.debug("Add register devices result is : " + bool); } } try { if (bool) { // return response response.getWriter().print(uploadifyFileName + " "); registerService.addChecklog(ConstantUtil.CheckLogs.VALID, ConstantUtil.CheckLogs.TYPE_VALID); if (log.isDebugEnabled()) { log.debug("upload file successfully"); } } else { if (log.isErrorEnabled()) { log.error("Add License failed !"); } } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("upload file failed !!!"); log.error(e.getMessage()); } } return null; } String desFilePath = null; String currentMillins = Long.toString(System.currentTimeMillis()); String resourceId = "resource_" + currentMillins; if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.IMAGETYPE)) { resource.setResourceType("image"); desFilePath = FileOperationTool.DEFAULT_IMG_DES_PATH + currentMillins + "_" + uploadifyFileName; } if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.AUDIOTYPE)) { resource.setResourceType("audio"); desFilePath = FileOperationTool.DEFAULT_AUDIO_DES_PATH + currentMillins + "_" + uploadifyFileName; } if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.TEXTTYPE)) { resource.setResourceType("text"); desFilePath = FileOperationTool.DEFAULT_TEXT_DES_PATH + currentMillins + "_" + uploadifyFileName; } if (FileOperationTool.getResourceType(uploadifyFileName).equals(FileOperationTool.VIDEOTYPE)) { resource.setResourceType("video"); desFilePath = FileOperationTool.DEFAULT_VIDEO_DES_PATH + currentMillins + "_" + uploadifyFileName; } FileOperationTool.ChannelCopy(uploadify, new File(desFilePath)); // if resource type is video, convert it to flv format if (resource.getResourceType().equals("video") && XmlOperationTool.isWindos) { VideoConverter.convert(currentMillins + "_" + uploadifyFileName); } if (uploadify != null) { resource.setId(resourceId); resource.setResourceName(currentMillins + "_" + uploadifyFileName); if (!resource.getResourceType().equals("text")) { resource.setParamRemark(uploadifyFileName); } else { String txtContent = FileOperationTool.getContentOfTxt(desFilePath); resource.setParamRemark(txtContent); } resource.setParamCreateby(((UserDTO) session.get("user")).getId()); resource.setParamCreatetime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(uploadify.lastModified())); resource.setCanBeDelete(true); if (new File(desFilePath).exists()) { resourceService.AddResource(resource); } } try { // return response response.getWriter().print(uploadifyFileName + " "); if (log.isDebugEnabled()) { log.debug("upload file successfully"); } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("upload file failed !!!"); log.error(e.getMessage()); } } return null; } catch (Exception e) { if (log.isErrorEnabled()) { log.error("upload file failed !!!"); log.error(e.getMessage()); } return ERROR; } }
From source file:se.vgregion.sitemap.servlet.DefaultSitemapServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//* w w w . j a v a2s . c o m*/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { getLogger().debug("doGet(): Starting to put together the sitemap."); long startTimeMillis = System.currentTimeMillis(); String sitemapContent = getSitemapService().getSitemapContent(); long endTimeMillis = System.currentTimeMillis(); getLogger() .debug("Generation finished. It took: " + (endTimeMillis - startTimeMillis) / 1000 + " seconds."); response.setCharacterEncoding(ENCODING_UTF8); PrintWriter pw = response.getWriter(); pw.write(sitemapContent); pw.flush(); pw.close(); }
From source file:com.wxxr.nirvana.json.JSONValidationInterceptor.java
private void setupEncoding(HttpServletResponse response, HttpServletRequest request) { if (isSetEncoding(request)) { if (LOG.isDebugEnabled()) { LOG.debug("Default encoding not set!"); }//from ww w. jav a 2s. c o m } else { if (LOG.isDebugEnabled()) { LOG.debug("Setting up encoding to: [" + DEFAULT_ENCODING + "]!"); } response.setCharacterEncoding(DEFAULT_ENCODING); } }
From source file:com.tongji.collaborationteam.pagecontrollers.ProjectMainViewController.java
@RequestMapping("download/{name}/{ext}") public String downloadOneFile(@PathVariable(value = "name") String fileName, @PathVariable(value = "ext") String ext, @PathVariable(value = "projectid") int projectid, HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + "." + ext); try {//from ww w . j a v a 2 s . co m File file = new File(fileName + "." + ext); // System.out.println(file.getAbsolutePath()); HttpClient client = new HttpClient(); GetMethod get = new GetMethod("http://localhost:8081/SnowFlakes/uploaded/" + projectid + "/" + file); client.executeMethod(get); OutputStream os = response.getOutputStream(); os.write(get.getResponseBody()); } catch (FileNotFoundException e) { e.printStackTrace(); pms.redirectErrorPage("Cannot find this file on the server"); } catch (IOException e) { e.printStackTrace(); pms.redirectErrorPage("Download failed"); } Query q = em.createNamedQuery("UploadedFile.findByName").setParameter("name", fileName); List<UploadedFile> l = q.getResultList(); UploadedFile f = (UploadedFile) l.get(0); f.setDownloadCounts(f.getDownloadCounts() + 1); try { fjc.edit(f); } catch (Exception ex) { Logger.getLogger(ProjectMainViewController.class.getName()).log(Level.SEVERE, null, ex); pms.redirectErrorPage("Unknown database problems"); } // return "show"; }
From source file:edu.cornell.mannlib.vitro.webapp.sparql.GetAllPrefix.java
/** * The doGet method of the servlet. <br> * //from w w w . ja v a 2 s .co m * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_MISCELLANEOUS_PAGES.ACTION)) { return; } VitroRequest vreq = new VitroRequest(request); Map<String, String> prefixMap = getPrefixMap(vreq.getUnfilteredWebappDaoFactory()); response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String respo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; respo += "<options>"; List<String> prefixList = new ArrayList<String>(); prefixList.addAll(prefixMap.keySet()); Collections.sort(prefixList, vreq.getCollator()); for (String prefix : prefixList) { respo += makeOption(prefix, prefixMap.get(prefix)); } respo += "</options>"; out.println(respo); out.flush(); out.close(); }