List of usage examples for javax.servlet ServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:com.bluexml.xforms.chiba.XFormsFilter.java
@Override public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain) throws IOException, ServletException { //ensure correct Request encoding if (srvRequest.getCharacterEncoding() == null) { srvRequest.setCharacterEncoding(defaultRequestEncoding); }/* ww w. jav a 2 s . c om*/ HttpServletRequest request = (HttpServletRequest) srvRequest; HttpServletResponse response = (HttpServletResponse) srvResponse; HttpSession session = request.getSession(true); if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter("submissionResponse") != null) { doSubmissionResponse(request, response); } else { /* before servlet request */ if (isXFormUpdateRequest(request)) { LOG.info("Start Update XForm"); try { XFormsSession xFormsSession = WebUtil.getXFormsSession(request, session); xFormsSession.setRequest(request); xFormsSession.setResponse(response); xFormsSession.handleRequest(); } catch (XFormsException e) { throw new ServletException(e); } LOG.info("End Update XForm"); } else { /* do servlet request */ LOG.info("Passing to Chain"); BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper( (HttpServletResponse) srvResponse); filterChain.doFilter(srvRequest, bufResponse); LOG.info("Returned from Chain"); // response is already committed to the client, so nothing is to // be done if (bufResponse.isCommitted()) return; //set mode of operation (scripted/nonscripted) by config if (this.mode == null) this.mode = "true"; if (this.mode.equalsIgnoreCase("true")) { request.setAttribute(WebFactory.SCRIPTED, "true"); } else if (this.mode.equalsIgnoreCase("false")) { request.setAttribute(WebFactory.SCRIPTED, "false"); } /* dealing with response from chain */ if (handleResponseBody(request, bufResponse)) { byte[] data = prepareData(bufResponse); if (data.length > 0) { request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data)); } } if (handleRequestAttributes(request)) { bufResponse.getOutputStream().close(); LOG.info("Start Filter XForm"); XFormsSession xFormsSession = null; try { XFormsSessionManager sessionManager = DefaultXFormsSessionManagerImpl .getXFormsSessionManager(); xFormsSession = sessionManager.createXFormsSession(request, response, session); xFormsSession.setBaseURI(request.getRequestURL().toString()); xFormsSession.setXForms(); xFormsSession.init(); // FIXME patch for upload XFormsSessionBase xFormsSessionBase = (XFormsSessionBase) xFormsSession; reconfigure(xFormsSessionBase); xFormsSession.handleRequest(); } catch (Exception e) { LOG.error(e.getMessage(), e); if (xFormsSession != null) { xFormsSession.close(e); } throw new ServletException(e.getMessage()); } LOG.info("End Render XForm"); } else { srvResponse.getOutputStream().write(bufResponse.getData()); srvResponse.getOutputStream().close(); } } } }
From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java
private void writeResponse(ServletRequest req, ServletResponse res, UploadFileFilterResult result) throws IOException { res.setContentType("text/plain;charset=" + req.getCharacterEncoding()); OutputStream out = res.getOutputStream(); out.write(JSON.encode(result).getBytes(req.getCharacterEncoding())); }
From source file:com.ultrapower.eoms.common.plugin.ecside.filter.ECSideFilter.java
public void doEncoding(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (useEncoding || (request.getCharacterEncoding() == null)) { if (encoding != null) //Set the same character encoding for the request and the response request.setCharacterEncoding(encoding); // response.setCharacterEncoding(encoding); }//w w w. j a v a 2 s. c o m }
From source file:de.betterform.agent.web.filter.XFormsFilter.java
/** * The actual filtering method/*from ww w.j a v a2 s . c o m*/ * todo: add request attribute to set baseURI * * @see http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html#doFilter(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse,%20javax.servlet.FilterChain) */ public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain) throws IOException, ServletException { //ensure correct Request encoding if (srvRequest.getCharacterEncoding() == null) { srvRequest.setCharacterEncoding(defaultRequestEncoding); } HttpServletRequest request = (HttpServletRequest) srvRequest; HttpServletResponse response = (HttpServletResponse) srvResponse; HttpSession session = request.getSession(true); /* if header "betterform-internal is present this means that the internal http client of the processor is the originator of the incoming request. Since this may not be processed we skip these requests by simply calling the servlet chain. As the contenttype may not be present for such requests we have to determine the mimetype by the file ending of the requested resource. */ //Check if MEDIATYPE is set if so we will handle response as XForms if (request.getHeader(BetterFORMConstants.BETTERFORM_INTERNAL) != null) { LOG.warn("Request from internal betterForm HTTP Client arrived in XFormsFilter"); String requestURI = request.getRequestURI(); String mimeType = webFactory.getServletContext().getMimeType(requestURI); if (LOG.isDebugEnabled()) { LOG.debug("request URI: " + requestURI); LOG.debug("mimeType: " + mimeType); } if (mimeType != null) { srvResponse.setContentType(mimeType); } else { LOG.warn("no contenttype set for internal request"); // throw new ServletException("Contenttype of " + requestURI + " unknown. Please configure your webcontainer appropriately."); } filterChain.doFilter(srvRequest, srvResponse); return; } if (request.getParameter("source") != null) { srvResponse.setContentType("text/plain"); // override setContentType to keep "text/plain" as content type. HttpServletResponseWrapper resp = new HttpServletResponseWrapper((HttpServletResponse) srvResponse) { public void setContentType(String s) { return; } }; filterChain.doFilter(srvRequest, resp); return; } if (request.getParameter("isUpload") != null) { //Got an upload... handleUpload(request, response, session); //TODO: XFORMS PROCESSING: do we need to exit? } else if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE) != null) { doSubmissionReplaceAll(request, response); } else if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE_XFORMS) != null) { doSubmissionReplaceAllXForms(request, response, session); } else { /* do servlet request */ LOG.info("Passing to Chain"); BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper( (HttpServletResponse) srvResponse); filterChain.doFilter(srvRequest, bufResponse); LOG.info("Returned from Chain"); //handleResponse(srvResponse, request, response, session, bufResponse, webFactory); // response is contains no betterFORM relevant content so it is not buffered and cannot be processed if (!bufResponse.isBuffered()) { return; } // response is already committed to the client, so nothing is to // be done if (bufResponse.isCommitted()) { return; } //pass to request object request.setAttribute(WebFactory.USER_AGENT, XFormsFilter.USERAGENT); /* dealing with response from chain */ if (handleResponseBody(request, bufResponse)) { byte[] data = prepareData(bufResponse); if (data.length > 0) { request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data)); } } if (handleRequestAttributes(request)) { bufResponse.getOutputStream().close(); LOG.info("Start Filter XForm"); processXForms(request, response, session); LOG.info("End Render XForm"); } else { srvResponse.getOutputStream().write(bufResponse.getData()); srvResponse.getOutputStream().close(); } } }
From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // ????/* w w w . ja v a 2 s.c o m*/ if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; // ?????????? if (!ServletFileUpload.isMultipartContent(httpReq)) { chain.doFilter(req, res); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); factory.setSizeThreshold(thresholdSize); sfu.setSizeMax(maxSize); // sfu.setHeaderEncoding(req.getCharacterEncoding()); try { @SuppressWarnings("unchecked") Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator(); List<String> keys = new ArrayList<String>(); List<String> names = new ArrayList<String>(); List<String> fieldNames = new ArrayList<String>(); List<Long> fileSize = new ArrayList<Long>(); while (ite.hasNext()) { String name = null; FileItem item = ite.next(); // ???? if (!(item.isFormField())) { name = item.getName(); name = name.substring(name.lastIndexOf('\\') + 1); if (StringUtils.isEmpty(name)) { continue; } File f = null; // CHECKSTYLE:OFF // ??????????. while ((f = new File(createTempFilePath())).exists()) { } // CHECKSTYLE:ON if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) { // ???? names.add(name); keys.add(UploadedFile.KEY_FILENAME_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (item.getSize() == 0) { // 0 names.add(name); keys.add(UploadedFile.KEY_SIZE_ZERO); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (maxFileSize > 0 && item.getSize() > maxFileSize) { // ? // ?0??????Validation names.add(name); keys.add(UploadedFile.KEY_SIZE_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else { item.write(f); names.add(name); keys.add(f.getName()); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } f.deleteOnExit(); } } // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_OK); result.setNames(names.toArray(new String[names.size()])); result.setKeys(keys.toArray(new String[keys.size()])); result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()])); result.setFileSize(fileSize.toArray(new Long[fileSize.size()])); writeResponse(req, res, result); } catch (Exception e) { e.printStackTrace(); // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_NG); writeResponse(req, res, result); } }
From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java
/** {@inheritDoc} */ @SuppressWarnings(value = "unchecked") public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (this.config == null) { return;/*w ww .ja va2s . c o m*/ } // Just pass through to next filter if we're not at TRACE level if (!logger.isTraceEnabled()) { chain.doFilter(request, response); return; } // Create a variable to hold the (possibly different) request // passed to downstream filters ServletRequest downstreamRequest = request; // Render the generic servlet request properties final StringWriter sw = new StringWriter(); final PrintWriter writer = new PrintWriter(sw); writer.println("Dumping request..."); writer.println("-----------------------------------------------------"); writer.println("REQUEST received " + Calendar.getInstance().getTime()); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); final Enumeration<Locale> locales = request.getLocales(); for (int i = 0; locales.hasMoreElements(); i++) { if (i > 0) { writer.print(", "); } writer.print(locales.nextElement()); } writer.println(); final Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { final String name = paramNames.nextElement(); writer.print(" parameter=" + name + "="); final String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { writer.print(", "); } writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { final HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } final Enumeration<String> headerNames = hrequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); // Create a wrapped request that contains the request body // and that we will pass to downstream filters final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest); downstreamRequest = wrappedRequest; writer.println(wrappedRequest.getRequestBodyAsString()); } writer.println("-----------------------------------------------------"); // Log the resulting string writer.flush(); logger.trace(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(downstreamRequest, response); }
From source file:com.doculibre.constellio.filters.SetCharacterEncodingFilter.java
/** * Select and set (if specified) the character encoding to be used to * interpret request parameters for this request. * //from w w w . j ava 2s. c om * @param request * The servlet request we are processing * @param result * The servlet response we are creating * @param chain * The filter chain we are processing * @exception IOException * if an input/output error occurs * @exception ServletException * if a servlet error occurs */ @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (false) { chain.doFilter(request, response); } else { String lookupCharSet = lookupCharSet(request); SimpleParams simpleParams = new SimpleParams(); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); String convertedParamName = convertIfNeeded(paramName, lookupCharSet); String[] paramValues = request.getParameterValues(paramName); List<String> convertedParamValues = new ArrayList<String>(); if (paramValues != null) { for (String paramValue : paramValues) { String convertedParamValue = convertIfNeeded(paramValue, lookupCharSet); if (convertedParamValue != null) { convertedParamValues.add(convertedParamValue); } } } simpleParams.add(convertedParamName, convertedParamValues.toArray(new String[0])); } HttpServletRequest requestWrapper = new SimpleParamsHttpServletRequestWrapper( (HttpServletRequest) request, simpleParams); // Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String encoding = selectEncoding(request); if (encoding != null) { request.setCharacterEncoding(encoding); } } // Pass control on to the next filter chain.doFilter(requestWrapper, response); } }
From source file:org.ajax4jsf.context.AjaxContextImpl.java
/** * @param context// w ww . j a v a 2s .co m * @throws AbortProcessingException */ public void renderAjax(FacesContext context) throws FacesException { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.RENDER_AJAX_REQUEST, getSubmittedRegionClientId())); } try { // Just in case... setSelfRender(true); setAjaxRequest(true); // create response writer. ExternalContext extContext = context.getExternalContext(); RenderKit renderKit = context.getRenderKit(); String encoding; // Depends if we talk about servlets, portlets, ... if (extContext.getRequest() instanceof ServletRequest) { ServletRequest request = (ServletRequest) extContext.getRequest(); ServletResponse response = (ServletResponse) extContext.getResponse(); // Setup encoding and content type String contentType = "text/xml"; // get the encoding - must be setup by faces context or filter. encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } response.setContentType(contentType + ";charset=" + encoding); } else encoding = "UTF-8"; PrintWriter servletWriter; servletWriter = getWriter(extContext); ResponseWriter writer = renderKit.createResponseWriter(servletWriter, null, encoding); context.setResponseWriter(writer); // make response writer.startDocument(); encodeAjaxBegin(context); context.getViewRoot().encodeAll(context); saveViewState(context); encodeAjaxEnd(context); writer.endDocument(); writer.flush(); writer.close(); servletWriter.close(); // Save tree state. } catch (IOException e) { throw new FacesException( Messages.getMessage(Messages.RENDERING_AJAX_REGION_ERROR, getSubmittedRegionClientId()), e); } finally { context.responseComplete(); // component.setRendererType(defaultRenderer); } }
From source file:org.apache.myfaces.custom.ajax.api.AjaxDecodePhaseListener.java
private void encodeAjax(UIComponent component, FacesContext context) { ServletResponse response = (ServletResponse) context.getExternalContext().getResponse(); ServletRequest request = (ServletRequest) context.getExternalContext().getRequest(); UIViewRoot viewRoot = context.getViewRoot(); Map requestMap = context.getExternalContext().getRequestParameterMap(); String charset = (String) requestMap.get("charset"); /* Handle character encoding as of section 2.5.2.2 of JSF 1.1: * At the beginning of the render-response phase, the ViewHandler must ensure * that the response Locale is set to that of the UIViewRoot, for exampe by * calling ServletResponse.setLocale() when running in the servlet environment. * Setting the response Locale may affect the response character encoding. */*ww w . j a v a 2 s. c om*/ * Since there is no 'Render Response' phase for AJAX requests, we have to handle * this manually. */ response.setLocale(viewRoot.getLocale()); if (component instanceof DeprecatedAjaxComponent) { try { String contentType = getContentType("text/xml", charset); response.setContentType(contentType); StringBuffer buff = new StringBuffer(); buff.append("<?xml version=\"1.0\"?>\n"); buff.append("<response>\n"); PrintWriter out = response.getWriter(); out.print(buff); // imario@apache.org: setup response writer, otherwise the component will fail with an NPE. I dont know why this worked before. context.setResponseWriter( new HtmlResponseWriterImpl(out, contentType, request.getCharacterEncoding())); if (component instanceof HtmlCommandButtonAjax) { buff = new StringBuffer(); buff.append("<triggerComponent id=\""); buff.append(component.getClientId(context)); buff.append("\" />\n"); out.print(buff); // special treatment for this one, it will try to update the entire form // 1. get surrounding form //String elname = (String) requestMap.get("elname"); FormInfo fi = RendererUtils.findNestingForm(component, context); UIComponent form = fi.getForm(); //System.out.println("FOUND FORM: " + form); if (form != null) { // special case, add responses from all components in form encodeChildren(form, context, requestMap); } } else if (component instanceof AjaxComponent) { // let component render xml response // NOTE: probably don't need an encodeAjax in each component, but leaving it in until that's for sure ((AjaxComponent) component).encodeAjax(context); } else { // just get latest value AjaxRendererUtils.encodeAjax(context, component); } // end response out.print("</response>"); out.flush(); } catch (IOException e) { log.error("Exception while rendering ajax-response", e); } } else if (component instanceof AjaxComponent) { try { if (context.getResponseWriter() == null) { String contentType = getContentType("text/html", charset); response.setContentType(contentType); PrintWriter writer = response.getWriter(); context.setResponseWriter( new HtmlResponseWriterImpl(writer, contentType, response.getCharacterEncoding())); } ((AjaxComponent) component).encodeAjax(context); } catch (IOException e) { log.error("Exception while rendering ajax-response", e); } } }
From source file:org.apache.myfaces.custom.ppr.PPRPhaseListener.java
/** * Respond to an AJAX request from a {@link PPRPanelGroup}. The * triggered components are determined by reading the * TRIGGERED_COMPONENTS_PARAMETER from either the RequestParameterMap or * the Request Map. Those componenets are encoded into an XML response. * The lifecycle is quit afterwards.//from ww w. j a va 2s. c o m * * @param context the current {@link FacesContext} * @param externalContext the current {@link ExternalContext} * @param requestMap Map containing the request attributes */ private void processPartialPageRequest(FacesContext context, final ExternalContext externalContext, Map requestMap) { ServletResponse response = (ServletResponse) externalContext.getResponse(); ServletRequest request = (ServletRequest) externalContext.getRequest(); UIViewRoot viewRoot = context.getViewRoot(); // Set Character encoding, contentType and locale for the response final String characterEncoding = request.getCharacterEncoding(); String contentType = getContentType("text/xml", characterEncoding); response.setContentType(contentType); response.setLocale(viewRoot.getLocale()); // Fetch the comma-separated list of triggered components String triggeredComponents = getTriggeredComponents(context); try { PrintWriter out = response.getWriter(); context.setResponseWriter(new HtmlResponseWriterImpl(out, contentType, characterEncoding)); out.print(XML_HEADER); out.print("<response>\n"); encodeTriggeredComponents(out, triggeredComponents, viewRoot, context); out.print("</response>"); out.flush(); } catch (IOException e) { throw new FacesException(e); } context.responseComplete(); }