List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding
public void setCharacterEncoding(String charset);
From source file:com.taobao.diamond.server.controller.BaseStoneController.java
@RequestMapping(params = "method=postConfig", method = RequestMethod.POST) public String postConfig(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;// ww w. ja va2 s .co 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 (Exception e) { log.error("response:" + e.getMessage(), e); } return "536"; } // this.configService.addConfigInfo(dataId, group, content); try { // this.aggregationService.aggregation(dataId, group); } catch (Exception e) { log.error("", e); } try { // this.realTimeNotify(dataId, group); } catch (Exception e) { log.error("", e); } try { // ipdataIdredis this.addIpToDataIdAndGroup(remoteIp, dataId, group); } catch (Exception e) { log.error("redis", e); } return "200"; }
From source file:org.motechproject.server.outbox.web.VxmlOutboxController.java
public ModelAndView save(HttpServletRequest request, HttpServletResponse response) { logger.info("Saving messageL..."); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String messageId = request.getParameter(MESSAGE_ID_PARAM); String language = request.getParameter(LANGUAGE_PARAM); ModelAndView mav = new ModelAndView(); String contextPath = request.getContextPath(); mav.setViewName(MESSAGE_SAVED_CONFIRMATION_TEMPLATE_NAME); mav.addObject("contextPath", contextPath); mav.addObject("language", language); mav.addObject("escape", new StringEscapeUtils()); logger.info("Message ID: " + messageId); if (messageId == null) { logger.error("Invalid request - missing parameter: " + MESSAGE_ID_PARAM); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; }//from w w w .j ava 2s. c o m try { voiceOutboxService.saveMessage(messageId); } catch (Exception e) { logger.error("Can not mark the message with ID: " + messageId + " as saved in the outbox", e); mav.setViewName(SAVE_MESSAGE_ERROR_TEMPLATE_NAME); return mav; } //TODO - get party ID proper way from security principal or authentication context when it is available String partyId; try { OutboundVoiceMessage message = voiceOutboxService.getMessageById(messageId); partyId = message.getPartyId(); } catch (Exception e) { logger.error("Can not obtain message ID: " + messageId + " to get party ID"); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } mav.addObject("days", voiceOutboxService.getNumDayskeepSavedMessages()); mav.addObject("partyId", partyId); return mav; }
From source file:org.springsource.ide.eclipse.boot.maven.analyzer.server.AetherialController.java
/** * Helper method to send a 'Future' as a response to the client. * If the future is 'done' actual content (or error) is sent. Otherwise * a 'try later' result is sent instead. *///from www .j a v a2 s . c o m private void sendResponse(HttpServletResponse resp, Future<byte[]> result) throws IOException, UnsupportedEncodingException { if (!result.isDone()) { //Return something quickly to let client know we are working on their request but // it may be a while. resp.setStatus(HttpServletResponse.SC_ACCEPTED); resp.setContentType("text/plain"); resp.setCharacterEncoding("utf8"); resp.getWriter().println("I'm working on it... ask me again later"); } else { //Done: could be a actual result or an error try { byte[] resultData = result.get(); //this will throw in case of an error in processing. resp.setStatus(HttpServletResponse.SC_OK); //resp.setContentType(contentType); //resp.setCharacterEncoding("utf8"); resp.getOutputStream().write(resultData); } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.setContentType("text/plain"); resp.setCharacterEncoding("utf8"); e.printStackTrace(new PrintStream(resp.getOutputStream(), true, "utf8")); } } }
From source file:com.shangde.common.util.FCKConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w w w .j a v a2s .co m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; 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"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = null; String typeDirPath = null; String otherFilePath = this.getServletConfig().getServletContext().getRealPath("/"); System.out.println("===========" + otherFilePath); String fckSavePath = (String) request.getSession().getAttribute("fckSavePath"); if (fckSavePath != null && !fckSavePath.trim().equals("")) { typeDirPath = otherFilePath + "/upload/" + fckSavePath + "/"; } else { typeDirPath = otherFilePath + "/upload/public/"; } // if("article".equals((request.getSession().getAttribute("fckSavePath")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // }else if("exam".equals((request.getSession().getAttribute("exam")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // } // else{ // typeDirPath = otherFilePath + "/back/upload/fckimage/"; // } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time, FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID() + "." + extension;// if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) {//???? newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } } else {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } } // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { logger.error(e.getMessage()); ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:tw.com.sbi.product.controller.Service.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); ServiceService serviceService = null; String groupId = request.getSession().getAttribute("group_id").toString(); String action = request.getParameter("action"); logger.debug("Action: " + action); if ("selectAll".equals(action)) { } else if ("selectByProductId".equals(action)) { try {/*from w w w . j a v a 2s . co m*/ serviceService = new ServiceService(); String product_id = request.getParameter("product_id"); List<ProductServiceVO> list = serviceService.selectByProductId(product_id); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("selectByProductSpec".equals(action)) { try { serviceService = new ServiceService(); String product_spec = request.getParameter("product_spec"); List<ProductServiceVO> list = serviceService.selectByProductSpec(product_spec); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } else if ("genService".equals(action)) { try { String productId = request.getParameter("product_id"); String quantity = request.getParameter("quantity"); logger.debug("Product ID: " + productId); logger.debug("Quantity: " + quantity); serviceService = new ServiceService(); List<ProductServiceVO> list = serviceService.genServiceID(groupId, productId, quantity); Gson gson = new Gson(); String jsonStrList = gson.toJson(list); response.getWriter().write(jsonStrList); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * set response headers. Not user in this command. * * @param response response/*from w ww . j a va 2s . c o m*/ * @param sc servlet context */ @Override public void setResponseHeader(final HttpServletResponse response, final ServletContext sc) { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); }
From source file:controlador.CPersona.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j av a 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); }
From source file:in.raster.oviyam.servlet.DcmAttributeRetrieve.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Reads the parameters from the request. response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String dicomURL = "http://" + ((ServerConfiguration) (getServletContext().getAttribute("serverConfig"))).getHostName() + ":" + ((ServerConfiguration) (getServletContext().getAttribute("serverConfig"))).getWadoPort() + "/wado?requestType=WADO&"; String seriesUID = request.getParameter("series"); String objectUID = request.getParameter("object"); String studyUID = request.getParameter("study"); // Generates the URL for the requested DICOM Dataset page. dicomURL += "contentType=application/dicom&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1"; dicomURL = dicomURL.replace("+", "%2B"); InputStream is = null;//from ww w .j av a2s .co m DicomInputStream dis = null; try { //Initialize the URL for the requested page. URL url = new URL(dicomURL); //opens the inputStream of the URL. is = url.openStream(); dis = new DicomInputStream(is); DicomObject dob = dis.readDicomObject(); DicomElement sopClassUID = dob.get(Tag.SOPClassUID); DicomElement nativeRows = dob.get(Tag.Rows); DicomElement nativeColumns = dob.get(Tag.Columns); DicomElement windowCenter = dob.get(Tag.WindowCenter); DicomElement windowWidth = dob.get(Tag.WindowWidth); DicomElement patientName = dob.get(Tag.PatientName); String sopClassUIDValue = sopClassUID == null ? null : new String(sopClassUID.getBytes()).trim(); int nativeRowsValueNum = nativeRows == null ? 0 : nativeRows.getInt(false); int nativeColumnsValueNum = nativeColumns == null ? 0 : nativeColumns.getInt(false); String windowCenterValue = windowCenter == null ? null : new String(windowCenter.getBytes()); String windowWidthValue = windowWidth == null ? null : new String(windowWidth.getBytes()); String pixelSpaceAttributeName = null; String pixelMessage = null; // Message to be displayed to the user about the measurement // Different types of modalities store pixel data in different attributes DicomElement spacing = null; DicomElement imagerSpacing = null; DicomElement pixelSpacing = null; if ((sopClassUID != null) && (sopClassUIDValue.equals(CT) || sopClassUIDValue.equals(MR))) { spacing = dob.get(Tag.PixelSpacing); pixelSpaceAttributeName = "Pixel Spacing"; } else if ((sopClassUID != null) && (sopClassUIDValue.equals(CR) || sopClassUIDValue.equals(XA))) { // Projection Radiography // This logic is taken from CP 586 pixelSpacing = dob.get(Tag.PixelSpacing); imagerSpacing = dob.get(Tag.ImagerPixelSpacing); String pixelSpacingStr = getDcmStrAttrVal(pixelSpacing); if (!pixelSpacingStr.equals("")) { String imagerSpacingStr = getDcmStrAttrVal(imagerSpacing); if (!imagerSpacingStr.equals("")) { if (imagerSpacingStr.equals(pixelSpacingStr)) { // Spacing attributes are equal spacing = imagerSpacing; pixelSpaceAttributeName = "Imager Pixel Spacing"; pixelMessage = "Measurements are at the detector plane."; } else { // We will use Pixel Spacing, check to see if we can determine what type of calibration was done. spacing = pixelSpacing; pixelSpaceAttributeName = "Pixel Spacing"; pixelMessage = "Measurement has been calibrated, details: " + getCalibrationDetails(dob); } } else { // Only pixel spacing is present, we can check for a calibration type, but in the end // it is not clear what this actually means spacing = pixelSpacing; pixelSpaceAttributeName = "Pixel Spacing"; pixelMessage = "Warning: Measurement MAY have been calibrated, details: " + getCalibrationDetails(dob); pixelMessage += " It is not clear what this measurement represents."; } } else { // Only Imager Spacing has been specified spacing = imagerSpacing; pixelSpaceAttributeName = "Imager Pixel Spacing"; pixelMessage = "Measurements are at the detector plane."; } } String spacingValue = spacing == null ? null : new String(spacing.getBytes()); double xSpacingValueNum = 0; double ySpacingValueNum = 0; double windowWidthValueNum = 0; double windowCenterValueNum = 0; if ((windowCenter != null) && (windowCenter.vm(null) == 2)) { windowCenterValueNum = new Double(windowCenterValue.split("\\\\")[0].trim()).doubleValue(); } else if (windowCenter != null) { windowCenterValueNum = new Double(windowCenterValue.trim()); } if ((windowWidth != null) && (windowWidth.vm(null) == 2)) { windowWidthValueNum = new Double(windowWidthValue.split("\\\\")[0].trim()).doubleValue(); } else if (windowWidth != null) { windowWidthValueNum = new Double(windowWidthValue.trim()).doubleValue(); } if ((spacing != null) && (spacing.vm(null) == 2)) { String[] spacingValues = spacingValue.split("\\\\"); // From dicom correction item CP-626 // The order of values in the Pixel Spacing and Imager Pixel Spacing is // Row Spacing\Column Spacing // This translates to // Distance between center of Y pixels/ Distance between center of X pixel // for this application ySpacingValueNum = new Double(spacingValues[0].trim()).doubleValue(); xSpacingValueNum = new Double(spacingValues[1].trim()).doubleValue(); } else if ((spacing != null) && (spacing.vm(null) == 1)) { // If only one is specifed, assuming a square pixel. ySpacingValueNum = new Double(spacingValue.trim()).doubleValue(); xSpacingValueNum = ySpacingValueNum; } dis.close(); JSONObject jsonResponse = new JSONObject(); // set the window center and window width attributes jsonResponse.put(WINDOW_CENTER_PARAM, windowCenterValueNum); jsonResponse.put(WINDOW_WIDTH_PARAM, windowWidthValueNum); jsonResponse.put(X_PIXEL_SPACING, xSpacingValueNum); jsonResponse.put(Y_PIXEL_SPACING, ySpacingValueNum); jsonResponse.put(PIXEL_SPACING_ATTRIBUTE, pixelSpaceAttributeName); jsonResponse.put(PIXEL_MESSAGE, pixelMessage); jsonResponse.put(NATIVE_ROWS, nativeRowsValueNum); jsonResponse.put(NATIVE_COLUMNS, nativeColumnsValueNum); jsonResponse.put(PATIENT_NAME, patientName); jsonResponse.put("status", "success"); is.close(); dis.close(); out.println(jsonResponse.toString()); out.close(); } catch (Exception e) { is.close(); dis.close(); out.println("{\"status\":\"error\"}"); out.close(); System.out.println(e); log.error("Unable to read and send the DICOM dataset page", e); } }
From source file:com.azaptree.services.command.http.WebXmlRequestCommand.java
@Override protected void writeResponseMessage(final HttpServletResponse httpResponse, final Object message) { Assert.notNull(httpResponse, "httpResponse is required"); Assert.notNull(message, "message is required"); final Optional<JAXBContext> jaxbContext = getJaxbContext(); Assert.isTrue(jaxbContext.isPresent(), "JAXBContext is required"); httpResponse.setContentType("application/xml"); httpResponse.setCharacterEncoding("UTF-8"); Marshaller marshaller;//from ww w .ja va 2 s. c o m try { marshaller = jaxbContext.get().createMarshaller(); } catch (final JAXBException e) { throw new IllegalStateException("failed to create JAXB marshaller", e); } try { marshaller.marshal(message, httpResponse.getOutputStream()); } catch (JAXBException | IOException e) { throw new RuntimeException("Failed to write JAXB message response", e); } }
From source file:com.starit.diamond.server.controller.AdminController.java
/** * ??/*from w w w. j ava 2s .co m*/ * * @param request * @param dataId * @param group * @param content * @param modelMap * @return */ @RequestMapping(value = "/postConfig", method = RequestMethod.POST) public String postConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("description") String description, @RequestParam("content") String content, ModelMap modelMap) { response.setCharacterEncoding("GBK"); boolean checkSuccess = true; String errorMessage = "?"; if (!StringUtils.hasLength(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "DataId"; } if (!StringUtils.hasLength(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = ""; } if (!StringUtils.hasLength(content)) { checkSuccess = false; errorMessage = ""; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); try { response.sendError(FORBIDDEN_403, errorMessage); } catch (IOException ioe) { log.error(ioe.getMessage(), ioe.getCause()); } return "/admin/confignew"; } String userName = (String) request.getSession().getAttribute("user"); this.configService.addConfigInfo(dataId, group, userName, content, description); request.getSession().setAttribute("message", "???!"); return "redirect:" + listConfig(request, response, null, null, 1, 10, modelMap); }