List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:org.chiba.web.servlet._HttpRequestHandler.java
/** * Parses a HTTP request. Returns an array containing maps for upload * controls, other controls, repeat indices, and trigger. The individual * maps may be null in case no corresponding parameters appear in the * request.//from w w w . j a v a 2 s .c o m * * @param request a HTTP request. * @return an array of maps containing the parsed request parameters. * @throws FileUploadException if an error occurred during file upload. * @throws UnsupportedEncodingException if an error occurred during * parameter value decoding. */ protected Map[] parseRequest(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { Map[] parameters = new Map[4]; if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { UploadListener uploadListener = new UploadListener(request, this.sessionKey); DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener); factory.setRepository(new File(this.uploadRoot)); ServletFileUpload upload = new ServletFileUpload(factory); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } Iterator iterator = upload.parseRequest(request).iterator(); FileItem item; while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (item.isFormField()) { LOGGER.info("request param: " + item.getFieldName() + " - value='" + item.getString() + "'"); } else { LOGGER.info("file in request: " + item.getName()); } parseMultiPartParameter(item, encoding, parameters); } } else { Enumeration enumeration = request.getParameterNames(); String name; String[] values; while (enumeration.hasMoreElements()) { name = (String) enumeration.nextElement(); values = request.getParameterValues(name); parseURLEncodedParameter(name, values, parameters); } } return parameters; }
From source file:org.apache.click.ClickRequestWrapper.java
/** * @see HttpServletRequestWrapper(HttpServletRequest) *//*from www . jav a 2s . com*/ ClickRequestWrapper(final HttpServletRequest request, final FileUploadService fileUploadService) { super(request); this.isMultipartRequest = ClickUtils.isMultipartRequest(request); this.request = request; if (isMultipartRequest) { Map<String, String[]> requestParams = new HashMap<String, String[]>(); Map<String, FileItem[]> fileItems = new HashMap<String, FileItem[]>(); try { List<FileItem> itemsList = new ArrayList<FileItem>(); try { itemsList = fileUploadService.parseRequest(request); } catch (FileUploadException fue) { request.setAttribute(FileUploadService.UPLOAD_EXCEPTION, fue); } for (FileItem fileItem : itemsList) { String name = fileItem.getFieldName(); String value = null; // Form fields are placed in the request parameter map, // while file uploads are placed in the file item map. if (fileItem.isFormField()) { if (request.getCharacterEncoding() == null) { value = fileItem.getString(); } else { try { value = fileItem.getString(request.getCharacterEncoding()); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } // Add the form field value to the parameters. addToMapAsString(requestParams, name, value); } else { // Add the file item to the list of file items. addToMapAsFileItem(fileItems, name, fileItem); } } } catch (Throwable t) { // Don't throw error here as it will break Context creation. // Instead add the error as a request attribute. request.setAttribute(Context.CONTEXT_FATAL_ERROR, t); } finally { fileItemMap = Collections.unmodifiableMap(fileItems); multipartParameterMap = Collections.unmodifiableMap(requestParams); } } else { fileItemMap = Collections.emptyMap(); multipartParameterMap = Collections.emptyMap(); } }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java
/** * Process request form//from w w w . j a v a 2 s . co m * @param request * @param versioningSC * @return * @throws Exception * @throws IOException */ private void saveNewDocument(HttpServletRequest request, VersioningSessionController versioningSC) throws Exception { SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()", "root.MSG_GEN_ENTER_METHOD"); int majorNumber = 0; int minorNumber = 1; String type = "dummy"; String physicalName = "dummy"; String logicalName = "dummy"; String mimeType = "dummy"; File dir = null; int size = 0; DocumentPK docPK = new DocumentPK(-1, versioningSC.getComponentId()); if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); int versionType = Integer.parseInt(FileUploadUtil.getParameter(items, "versionType", "0", encoding)); FileItem fileItem = FileUploadUtil.getFile(items, "file_upload"); boolean runOnUnix = !FileUtil.isWindows(); logicalName = fileItem.getName(); if (logicalName != null) { if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = FileUtil.getMimeType(logicalName); if (!StringUtil.isDefined(mimeType)) { mimeType = "unknown"; } dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName); size = new Long(fileItem.getSize()).intValue(); fileItem.write(dir); } if (versionType == VersioningSessionController.PUBLIC_VERSION) { majorNumber = 1; minorNumber = 0; } if (size == 0) { majorNumber = 0; minorNumber = 0; } DocumentVersion documentVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber, Integer.parseInt(versioningSC.getUserId()), new Date(), comments, versionType, DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, logicalName, mimeType, size, versioningSC.getComponentId()); boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); if (addXmlForm) { documentVersion.setXmlForm(versioningSC.getXmlForm()); } // Document docPK = new DocumentPK(-1, versioningSC.getComponentId()); String name = FileUploadUtil.getParameter(items, "name", "", encoding); String publicationId = FileUploadUtil.getParameter(items, "publicationId", "-1", encoding); String description = FileUploadUtil.getParameter(items, "description", "", encoding); PublicationPK pubPK = new PublicationPK(publicationId, versioningSC.getComponentId()); Document document = new Document(docPK, pubPK, name, description, Document.STATUS_CHECKINED, -1, new Date(), null, versioningSC.getComponentId(), null, null, 0, Integer.parseInt(VersioningSessionController.WRITERS_LIST_SIMPLE)); String docId = versioningSC.createDocument(document, documentVersion).getId(); if (addXmlForm) { // Save additional informations saveXMLData(versioningSC, documentVersion.getPk(), items); } versioningSC.setEditingDocument(document); versioningSC.setFileRights(); versioningSC.updateWorkList(document); versioningSC.updateDocument(document); // Specific case: 3d file to convert by Actify Publisher ResourceLocator attachmentSettings = new ResourceLocator( "com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = attachmentSettings.getBoolean("ActifyPublisherEnable", false); if (actifyPublisherEnable) { versioningSC.saveFileForActify(docId, documentVersion, attachmentSettings); } SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()", "root.MSG_GEN_EXIT_METHOD"); }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
/** * Processes the HTTP request./*from w ww . java2 s.c o m*/ * @param request the HTTP request * @param response HTTP response * @param context request context * @param method the method to executeUpdate GET|PUT|POST|DELETE * @throws ServletException if the request cannot be handled * @throws IOException if an I/O error occurs while handling the request */ private void execute(HttpServletRequest request, HttpServletResponse response, String method) throws ServletException, IOException { RequestContext context = null; try { String msg = "HTTP " + method + ", " + request.getRequestURL().toString(); if ((request.getQueryString() != null) && (request.getQueryString().length() > 0)) { msg += "?" + request.getQueryString(); } getLogger().fine(msg); String sEncoding = request.getCharacterEncoding(); if ((sEncoding == null) || (sEncoding.trim().length() == 0)) { request.setCharacterEncoding("UTF-8"); } context = RequestContext.extract(request); //redirect to new method for list parameter without any authentication if (method.equals("GET") && request.getParameter("list") != null) { this.executeGetList(request, response, context); return; } if (method.equals("GET") && request.getParameter("download") != null) { this.executeGetPackage(request, response, context); return; } /// estabish the publisher StringAttributeMap params = context.getCatalogConfiguration().getParameters(); String autoAuthenticate = Val.chkStr(params.getValue("BaseServlet.autoAuthenticate")); if (!autoAuthenticate.equalsIgnoreCase("false")) { Credentials credentials = getCredentials(request); if (credentials != null) { this.authenticate(context, credentials); } } Publisher publisher = new Publisher(context); // executeUpdate the appropriate action if (method.equals("GET")) { this.executeGet(request, response, context, publisher); } else if (method.equals("POST")) { this.executePost(request, response, context, publisher); } else if (method.equals("PUT")) { this.executePut(request, response, context, publisher); } else if (method.equals("DELETE")) { this.executeDelete(request, response, context, publisher); } } catch (CredentialsDeniedException e) { String sRealm = this.getRealm(context); response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (NotAuthorizedException e) { String sRealm = this.getRealm(context); response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (ValidationException e) { String sMsg = e.toString(); if (sMsg.contains("XSD violation.")) { sMsg = "XSD violation."; } else if (sMsg.contains("Invalid metadata document.")) { sMsg = "Invalid metadata document."; } else { sMsg = "Invalid metadata document."; } String json = Val.chkStr(request.getParameter("errorsAsJson")); if (json.length() > 0) { json = Val.escapeXmlForBrowser(json); FacesContextBroker fcb = new FacesContextBroker(request, response); MessageBroker msgBroker = fcb.extractMessageBroker(); ArrayList<String> validationMessages = new ArrayList<String>(); e.getValidationErrors().buildMessages(msgBroker, validationMessages, true); StringBuilder sb = new StringBuilder(); sb.append(json).append(" = {\r\n"); sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n"); sb.append("code: 409,\r\n"); sb.append("errors: [\r\n"); for (int i = 0; i < validationMessages.size(); i++) { if (i > 0) { sb.append(",\r\n"); } sb.append("\"").append(Val.escapeStrForJson(validationMessages.get(i))).append("\""); } if (validationMessages.size() > 0) { sb.append("\r\n"); } sb.append("]}"); LOGGER.log(Level.SEVERE, sb.toString()); response.getWriter().print(sb.toString()); } else { response.sendError(409, sMsg); } } catch (ServletException e) { String sMsg = e.getMessage(); int nCode = Val.chkInt(sMsg.substring(0, 3), 500); sMsg = Val.chkStr(sMsg.substring(4)); String json = Val.chkStr(request.getParameter("errorsAsJson")); if (json.length() > 0) { json = Val.escapeXmlForBrowser(json); StringBuilder sb = new StringBuilder(); sb.append(json).append(" = {\r\n"); sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n"); sb.append("code: ").append(nCode).append(",\r\n"); sb.append("errors: [\r\n"); sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\""); sb.append("]}"); LOGGER.log(Level.SEVERE, sb.toString()); response.getWriter().print(sb.toString()); } else { response.sendError(nCode, sMsg); } } catch (Throwable t) { String sMsg = t.toString(); String json = Val.chkStr(request.getParameter("errorsAsJson")); if (json.length() > 0) { json = Val.escapeXmlForBrowser(json); StringBuilder sb = new StringBuilder(); sb.append(json).append(" = {\r\n"); sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n"); sb.append("code: ").append(500).append(",\r\n"); sb.append("errors: [\r\n"); sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\""); sb.append("]}"); LOGGER.log(Level.SEVERE, sb.toString()); response.getWriter().print(sb.toString()); } else if (sMsg.contains("The document is owned by another user:")) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The document is owned by another user."); } else { //String sErr = "Exception occured while processing servlet request."; //getLogger().log(Level.SEVERE,sErr,t); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, // sMsg + sErr); } } finally { if (context != null) context.onExecutionPhaseCompleted(); } }
From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java
/** Performs initializations stuff. */ @SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type. private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize, String repositoryPath) {// w ww .j a va 2 s .c o m if (!ServletFileUpload.isMultipartContent(request)) { String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'"; MultipartRequestWrapper.Log.severe(errorText); throw new FacesException(errorText); } else { this.params = new HashMap<String, String[]>(); this.fileItems = new HashMap<String, FileItem>(); DiskFileItemFactory factory = null; ServletFileUpload upload = null; //factory = new DiskFileItemFactory(); factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(), thresholdSize, new File(repositoryPath)); //factory.setRepository(new File(repositoryPath)); //factory.setSizeThreshold(thresholdSize); upload = new ServletFileUpload(factory); upload.setSizeMax(maxSize); upload.setFileSizeMax(maxFileSize); String charset = request.getCharacterEncoding(); if (charset != null) { charset = ServletConstants.DefaultCharset; } upload.setHeaderEncoding(charset); List<FileItem> itemList = null; try { //itemList = (List<FileItem>) upload.parseRequest(request); itemList = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException fue) { MultipartRequestWrapper.Log.severe(fue.getMessage()); throw new FacesException(fue); } catch (ClassCastException cce) { // This shouldn't happen! MultipartRequestWrapper.Log.severe(cce.getMessage()); throw new FacesException(cce); } MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size()); for (FileItem item : itemList) { String key = item.getFieldName(); // { // String value = item.getString(); // if (value.length() > 100) { // value = value.substring(0, 100) + " [...]"; // } // MultipartRequestWrapper.Log.fine( // "Parameter : '" + key + "'='" + value + "' isFormField=" // + item.isFormField() + " contentType='" + item.getContentType() + "'" // ); // } if (item.isFormField()) { Object inStock = this.params.get(key); if (inStock == null) { String[] values = null; try { // TODO: enable configuration of 'accept-charset' values = new String[] { item.getString(ServletConstants.DefaultCharset) }; } catch (UnsupportedEncodingException uee) { MultipartRequestWrapper.Log.warning("Caught: " + uee); values = new String[] { item.getString() }; } this.params.put(key, values); } else if (inStock instanceof String[]) { // two or more parameters String[] oldValues = (String[]) inStock; String[] values = new String[oldValues.length + 1]; int i = 0; while (i < oldValues.length) { values[i] = oldValues[i]; i++; } try { // TODO: enable configuration of 'accept-charset' values[i] = item.getString(ServletConstants.DefaultCharset); } catch (UnsupportedEncodingException uee) { MultipartRequestWrapper.Log.warning("Caught: " + uee); values[i] = item.getString(); } this.params.put(key, values); } else { MultipartRequestWrapper.Log .severe("Program error. Unsupported class: " + inStock.getClass().getName()); } } else { //String fieldName = item.getFieldName(); //String fileName = item.getName(); //String contentType = item.getContentType(); //boolean isInMemory = item.isInMemory(); //long sizeInBytes = item.getSize(); //... this.fileItems.put(key, item); } } } }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w .j av a 2s. c om*/ snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType()); String charEncoding = null; if (mimeType.startsWith("text")) { charEncoding = request.getCharacterEncoding(); } Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); boolean created = false; if (n == null) { n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType); created = true; if (n == null) { throw new RuntimeException( "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE); } } else { NodeType nt = n.getPrimaryNodeType(); if (!JCRConstants.NT_FILE.equals(nt.getName())) { response.reset(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content Can only be put to a file, resource type is " + nt.getName()); return; } } GregorianCalendar gc = new GregorianCalendar(); long lastMod = request.getDateHeader(LAST_MODIFIED); if (lastMod > 0) { gc.setTimeInMillis(lastMod); } else { gc.setTime(new Date()); } InputStream in = request.getInputStream(); saveStream(n, in, mimeType, charEncoding, gc); in.close(); if (created) { response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } catch (UnauthorizedException ape) { // catch any Unauthorized exceptions and send a 401 response.reset(); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage()); } catch (PermissionDeniedException pde) { // catch any permission denied exceptions, and send a 403 response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage()); } catch (SDataException e) { sendError(request, response, e); LOG.error("Failed To service Request " + e.getMessage()); } catch (Exception e) { sendError(request, response, e); snoopRequest(request); LOG.error("Failed TO service Request ", e); } }
From source file:net.myrrix.web.servlets.IngestServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MyrrixRecommender recommender = getRecommender(); boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data"); Reader reader;//www . j a v a 2s. co m if (fromBrowserUpload) { Collection<Part> parts = request.getParts(); if (parts == null || parts.isEmpty()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data"); return; } Part part = parts.iterator().next(); String partContentType = part.getContentType(); InputStream in = part.getInputStream(); if ("application/zip".equals(partContentType)) { in = new ZipInputStream(in); } else if ("application/gzip".equals(partContentType)) { in = new GZIPInputStream(in); } else if ("application/x-gzip".equals(partContentType)) { in = new GZIPInputStream(in); } else if ("application/bzip2".equals(partContentType)) { in = new BZip2CompressorInputStream(in); } else if ("application/x-bzip2".equals(partContentType)) { in = new BZip2CompressorInputStream(in); } reader = new InputStreamReader(in, Charsets.UTF_8); } else { String charEncodingName = request.getCharacterEncoding(); Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName); String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING); if (contentEncoding == null) { reader = request.getReader(); } else if ("gzip".equals(contentEncoding)) { reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding); } else if ("zip".equals(contentEncoding)) { reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding); } else if ("bzip2".equals(contentEncoding)) { reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()), charEncoding); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding"); return; } } try { recommender.ingest(reader); } catch (IllegalArgumentException iae) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString()); return; } catch (NoSuchElementException nsee) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString()); return; } catch (TasteException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString()); getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te); return; } String referer = request.getHeader(HttpHeaders.REFERER); if (fromBrowserUpload && referer != null) { // Parsing avoids response splitting response.sendRedirect(new URL(referer).toString()); } }
From source file:org.sakaiproject.util.RequestFilter.java
/** * If setting character encoding is enabled for this filter, and there isn't already a character encoding on the request, then * set the encoding./* w ww . j a v a2 s . c o m*/ */ protected void handleCharacterEncoding(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException { if (m_characterEncodingEnabled && req.getCharacterEncoding() == null && m_characterEncoding != null && m_characterEncoding.length() > 0 && req.getAttribute(ATTR_CHARACTER_ENCODING_DONE) == null) { req.setAttribute(ATTR_CHARACTER_ENCODING_DONE, ATTR_CHARACTER_ENCODING_DONE); req.setCharacterEncoding(m_characterEncoding); } }
From source file:net.dkahn.web.controller.ExtendedMultiPartRequestHandler.java
/** * Parses the input stream and partitions the parsed items into a set of * form fields and a set of file items. In the process, the parsed items * are translated from Commons FileUpload <code>FileItem</code> instances * to Struts <code>FormFile</code> instances. * * @param request The multipart request to be processed. * * @throws ServletException if an unrecoverable error occurs. *//* ww w.j a v a 2s. c om*/ public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); //---------------------------------------------------------- // Changed this section of code, that is it. //----------------------------------------------------------- log.debug("Handling the request.."); UploadListener listener = new UploadListener(request, 1); log.debug("uploading file with optional monitoring.."); // Create a factory for disk-based file items FileItemFactory factory = new MonitoredDiskFileItemFactory(listener); log.debug("got the factory now get the ServletFileUpload"); ServletFileUpload upload = new ServletFileUpload(factory); log.debug("Should have the ServletFileUpload by now."); // The following line is to support an "EncodingFilter" // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); //---------------------------------------------------------------- // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }