@Override public void doRender(Invocation inv) throws Exception { if (StringUtils.isEmpty(text)) { return; } if (logger.isDebugEnabled()) { logger.debug("trying to render text:" + text); } HttpServletResponse response = inv.getResponse(); String oldEncoding = response.getCharacterEncoding(); if (StringUtils.isBlank(oldEncoding) || oldEncoding.startsWith("ISO-")) { String encoding = inv.getRequest().getCharacterEncoding(); Assert.isTrue(encoding != null); response.setCharacterEncoding(encoding); if (logger.isDebugEnabled()) { logger.debug( "set response.characterEncoding by default:" + response.getCharacterEncoding()); } } if (response.getContentType() == null) { response.setContentType("text/html"); if (logger.isDebugEnabled()) { logger.debug("set response content-type by default: " + response.getContentType()); } } sendResponse(response, text); }
/* 避免中文乱码 */ private void setContentType(HttpServletResponse res) { String contentType = res.getContentType(); if (Strings.isNullOrEmpty(contentType)) { contentType = "text/html; charset=UTF-8"; } final String iso = "iso-8859-1"; if (!contentType.toLowerCase().contains("charset")) { String encoding = res.getCharacterEncoding(); if (Strings.isNullOrEmpty(encoding) || encoding.toLowerCase().equals(iso)) { encoding = "UTF-8"; } contentType += "; charset=" + encoding; res.setContentType(contentType); } else { int pos = contentType.toLowerCase().lastIndexOf(iso); if (pos > 0) { String mime = contentType.substring(0, pos) + "UTF-8"; int start = pos + iso.length() + 1; if (start < contentType.length()) { mime += contentType.substring(start); } res.setContentType(mime); } } }
public void marshalResult(final HttpServletResponse pResponse) throws TransformerException, IOException, XmlException { if (mResult instanceof XmlSerializable) { // By default don't use JAXB setContentType(pResponse, "text/xml"); OutputStreamWriter writer = new OutputStreamWriter(pResponse.getOutputStream(), pResponse.getCharacterEncoding()); XmlUtil.serialize((XmlSerializable) mResult, writer); writer.close(); return; } final XmlRootElement xmlRootElement = mResult == null ? null : mResult.getClass().getAnnotation(XmlRootElement.class); if (xmlRootElement != null) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(getReturnType()); final JAXBSource jaxbSource = new JAXBSource(jaxbContext, mResult); setContentType(pResponse, "text/xml"); Sources.writeToStream(jaxbSource, pResponse.getOutputStream()); } catch (final JAXBException e) { throw new MessagingException(e); } } else { serializeValue(pResponse, this.mResult); } }
/** * Return the character output stream for this response. This is either the original stream or a * buffered stream. * * @exception IllegalStateException Thrown when byte stream has been already initialized ({@link * #getOutputStream()}). */ public PrintWriter getWriter() throws IOException { if (stream != null) { throw new IllegalStateException( "Byte stream has been already initialized. Use streams consequently."); } if (writer != null) { return writer; } if (passthrough) { writer = this.origResponse.getWriter(); return writer; } /* * TODO: The character encoding should be extracted in {@link #setContentType()}, * saved somewhere locally and used here. The response's character encoding may be * different (depends on the stylesheet). */ final String charEnc = origResponse.getCharacterEncoding(); this.stream = new DeferredOutputStream(); if (charEnc != null) { writer = new PrintWriter(new OutputStreamWriter(stream, charEnc)); } else { writer = new PrintWriter(stream); } return writer; }
/** * Return the writer associated with this Response. * * @exception IllegalStateException if <code>getOutputStream</code> has already been called for * this response * @exception IOException if an input/output error occurs */ public PrintWriter getWriter() throws IOException { if (writer != null) return (writer); if (stream != null) throw new IllegalStateException( "getOutputStream() has already been called for this response"); stream = createOutputStream(); if (debug > 1) { System.out.println("stream is set to " + stream + " in getWriter"); } // String charset = getCharsetFromContentType(contentType); String charEnc = origResponse.getCharacterEncoding(); if (debug > 1) { System.out.println("character encoding is " + charEnc); } // HttpServletResponse.getCharacterEncoding() shouldn't return null // according the spec, so feel free to remove that "if" if (charEnc != null) { writer = new PrintWriter(new OutputStreamWriter(stream, charEnc)); } else { writer = new PrintWriter(stream); } return (writer); }
/** @see org.displaytag.util.RequestHelper#getParameterMap() */ public Map getParameterMap() { Map map = new HashMap(); // get the parameters names Enumeration parametersName = this.request.getParameterNames(); while (parametersName.hasMoreElements()) { // ... get the value String paramName = (String) parametersName.nextElement(); request.getParameter(paramName); // put key/value in the map String[] originalValues = (String[]) ObjectUtils.defaultIfNull(this.request.getParameterValues(paramName), new String[0]); String[] values = new String[originalValues.length]; for (int i = 0; i < values.length; i++) { try { values[i] = URLEncoder.encode( StringUtils.defaultString(originalValues[i]), StringUtils.defaultString( response.getCharacterEncoding(), "UTF8")); // $NON-NLS-1$ } catch (UnsupportedEncodingException e) { throw new UnhandledException(e); } } map.put(paramName, values); } // return the Map return map; }
public static void afterRoot( FacesContext context, HttpServletRequest req, HttpServletResponse res) { HttpSession session = ((HttpServletRequest) req).getSession(false); if (session != null) session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, res.getCharacterEncoding()); }
public PrintWriter getPrintWriter(String contentType) throws IOException { assert InternalUtils.isNonBlank(contentType); OutputStream os = getOutputStream(contentType); Writer w = new OutputStreamWriter(os, response.getCharacterEncoding()); return new PrintWriter(new BufferedWriter(w)); }
private void serializeValue(final HttpServletResponse pResponse, Object value) throws TransformerException, IOException, FactoryConfigurationError { if (value instanceof Source) { setContentType(pResponse, "application/binary"); // Unknown content type Sources.writeToStream((Source) value, pResponse.getOutputStream()); } else if (value instanceof Node) { pResponse.setContentType("text/xml"); Sources.writeToStream(new DOMSource((Node) value), pResponse.getOutputStream()); } else if (value instanceof XmlSerializable) { pResponse.setContentType("text/xml"); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE); try { XmlWriter out = XmlStreaming.newWriter( pResponse.getOutputStream(), pResponse.getCharacterEncoding(), true); try { out.startDocument(null, null, null); ((XmlSerializable) value).serialize(out); out.endDocument(); } finally { out.close(); } } catch (XmlException e) { throw new TransformerException(e); } } else if (value instanceof Collection) { final XmlElementWrapper annotation = getElementWrapper(); if (annotation != null) { setContentType(pResponse, "text/xml"); try (OutputStream outStream = pResponse.getOutputStream()) { writeCollection( outStream, getGenericReturnType(), (Collection<?>) value, getQName(annotation)); } } } else if (value instanceof CharSequence) { setContentType(pResponse, "text/plain"); pResponse.getWriter().append((CharSequence) value); } else { if (value != null) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(getReturnType()); setContentType(pResponse, "text/xml"); final JAXBSource jaxbSource = new JAXBSource(jaxbContext, value); Sources.writeToStream(jaxbSource, pResponse.getOutputStream()); } catch (final JAXBException e) { throw new MessagingException(e); } } } }
/** * Assembles a response from a cached page include. These responses are never gzipped The content * length should not be set in the response, because it is a fragment of a page. Don't write any * headers at all. */ protected void writeResponse(final HttpServletResponse response, final PageInfo pageInfo) throws IOException { byte[] cachedPage = pageInfo.getUngzippedBody(); String page = new String(cachedPage, response.getCharacterEncoding()); String implementationVendor = response.getClass().getPackage().getImplementationVendor(); if (implementationVendor != null && implementationVendor.equals("\"Evermind\"")) { response.getOutputStream().print(page); } else { response.getWriter().write(page); } }
@Override public PrintWriter getWriter() throws IOException { if (writer == null) { if (output != null) { throw new IllegalStateException("getOutputStream() has already been called!"); } writer = new PrintWriter( new OutputStreamWriter( new Base64ResponseStream(response), response.getCharacterEncoding())); } return writer; }
public PrintWriter getWriter() throws IOException { if (writer != null) { return (writer); } if (stream != null) { throw new IllegalStateException("getOutputStream() has already been called!"); } stream = createOutputStream(); // Reuse content's encoding writer = new PrintWriter(new OutputStreamWriter(stream, origResponse.getCharacterEncoding())); return (writer); }
String getBodyContent() { String charset = originResponse.getCharacterEncoding(); if (wrappingOutputStream == null || wrappingOutputStream.baos == null || wrappingOutputStream.baos.size() == 0) { return "empty body"; } String body = new String(wrappingOutputStream.baos.toByteArray(), Charset.forName(charset)); if (wrappingOutputStream.isComplete) { return body; } else { return "truncated body: " + body; } }
/** * 获取编码字符集 * * @param request * @param response * @return String */ public static String getCharacterEncoding( HttpServletRequest request, HttpServletResponse response) { if (null == request || null == response) { return "gbk"; } String enc = request.getCharacterEncoding(); if (null == enc || "".equals(enc)) { enc = response.getCharacterEncoding(); } if (null == enc || "".equals(enc)) { enc = "gbk"; } return enc; }
/** JaggeryMethod responsible of writing to the output stream */ public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException { if (!isWebSocket) { JaggeryContext jaggeryContext = CommonManager.getJaggeryContext(); // If the script itself havent set the content type we set the default content type to be // text/html HttpServletResponse servletResponse = (HttpServletResponse) jaggeryContext.getProperty(SERVLET_RESPONSE); if (servletResponse.getContentType() == null) { servletResponse.setContentType(DEFAULT_CONTENT_TYPE); } if (servletResponse.getCharacterEncoding() == null) { servletResponse.setCharacterEncoding(DEFAULT_CHAR_ENCODING); } CommonManager.print(cx, thisObj, args, funObj); } }
@RequestMapping("/manageNsx") public ModelAndView manageNsx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { NoiSanXuatDAO noiSanXuatDAO = new NoiSanXuatDAO(); request.getCharacterEncoding(); response.getCharacterEncoding(); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String action = request.getParameter("action"); if ("AddNsx".equalsIgnoreCase(action)) { String nsxMa = request.getParameter("nsxMa"); String nsxTen = request.getParameter("nsxTen"); noiSanXuatDAO.addNoiSanXuat(new NoiSanXuat(nsxMa, nsxTen)); ArrayList<NoiSanXuat> noiSanXuatList = (ArrayList<NoiSanXuat>) noiSanXuatDAO.getAllNoiSanXuat(); return new ModelAndView("danh-muc-noi-san-xuat", "noiSanXuatList", noiSanXuatList); } if ("deleteNsx".equalsIgnoreCase(action)) { String[] idList = request.getParameterValues("nsxMa"); for (String s : idList) { noiSanXuatDAO.deleteNoiSanXuat(noiSanXuatDAO.getNoiSanXuat(s)); } ArrayList<NoiSanXuat> noiSanXuatList = (ArrayList<NoiSanXuat>) noiSanXuatDAO.getAllNoiSanXuat(); return new ModelAndView("danh-muc-noi-san-xuat", "noiSanXuatList", noiSanXuatList); } if ("manageNsx".equalsIgnoreCase(action)) { ArrayList<NoiSanXuat> noiSanXuatList = (ArrayList<NoiSanXuat>) noiSanXuatDAO.getAllNoiSanXuat(); return new ModelAndView("danh-muc-noi-san-xuat", "noiSanXuatList", noiSanXuatList); } return new ModelAndView("login"); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ExtendManager.hasAction("BeforeSSIFilter")) { ExtendManager.executeAll("BeforeSSIFilter", new Object[] {request, response, chain}); } HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if ((Config.ServletMajorVersion == 2) && (Config.ServletMinorVersion == 3)) response.setContentType("text/html;charset=" + Constant.GlobalCharset); else { response.setCharacterEncoding(Constant.GlobalCharset); } request.setCharacterEncoding(Constant.GlobalCharset); req.setAttribute("org.apache.catalina.ssi.SSIServlet", "true"); ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(this.config.getServletContext(), req, res, basos); chain.doFilter(req, responseIncludeWrapper); responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); String encoding = res.getCharacterEncoding(); SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver( this.config.getServletContext(), req, res, this.isVirtualWebappRelative, this.debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, this.debug); Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); writer.flush(); bytes = ssiout.toByteArray(); if (this.expires != null) { res.setDateHeader("expires", new Date().getTime() + this.expires.longValue() * 1000L); } if (lastModified > 0L) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); res.setContentType("text/html;charset=" + Constant.GlobalCharset); try { OutputStream out = res.getOutputStream(); out.write(bytes); } catch (Throwable t) { Writer out = res.getWriter(); out.write(new String(bytes)); } }
public synchronized String getCharacterEncoding() { return actualResponse.getCharacterEncoding(); }
@Override public String getCharacterEncoding() { return response .getCharacterEncoding(); // To change body of implemented methods use File | Settings | File // Templates. }
// The tck uses only get & post requests protected void processTCKReq(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.entering(LOG_CLASS, "servlet entry"); PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request"); PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response"); PortletConfig portletConfig = (PortletConfig) request.getAttribute("javax.portlet.config"); long svtTid = Thread.currentThread().getId(); long reqTid = (Long) portletReq.getAttribute(THREADID_ATTR); PrintWriter writer = ((MimeResponse) portletResp).getWriter(); JSR286DispatcherReqRespTestCaseDetails tcd = new JSR286DispatcherReqRespTestCaseDetails(); // Create result objects for the tests /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_containsHeader */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.containsHeader must return false" */ TestResult tr0 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_CONTAINSHEADER); try { boolean ok = response.containsHeader("Accept"); tr0.setTcSuccess(ok == false); } catch (Exception e) { tr0.appendTcDetail(e.toString()); } tr0.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectURL1 */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeRedirectURL must return null" */ TestResult tr1 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL1); try { String isval = response.encodeRedirectURL("http://www.cnn.com/"); CompareUtils.stringsEqual(isval, null, tr1); } catch (Exception e) { tr1.appendTcDetail(e.toString()); } tr1.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectUrl */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeRedirectUrl must return null" */ TestResult tr2 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL); try { String isval = response.encodeRedirectUrl("http://www.cnn.com/"); CompareUtils.stringsEqual(isval, null, tr2); } catch (Exception e) { tr2.appendTcDetail(e.toString()); } tr2.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeURL1 */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeURL must provide the same */ /* functionality as ResourceResponse.encodeURL" */ TestResult tr3 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL1); try { String turl = "http://www.apache.org/"; String hval = (String) response.encodeURL(turl); String pval = (String) portletResp.encodeURL(turl); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr3); } catch (Exception e) { tr3.appendTcDetail(e.toString()); } tr3.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeUrl */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeUrl must provide the same */ /* functionality as ResourceResponse.encodeURL" */ TestResult tr4 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL); try { String turl = "http://www.apache.org/"; String hval = (String) response.encodeUrl(turl); String pval = (String) portletResp.encodeURL(turl); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr4); } catch (Exception e) { tr4.appendTcDetail(e.toString()); } tr4.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getBufferSize */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getBufferSize must provide the same */ /* functionality as ResourceResponse.getBufferSize" */ TestResult tr5 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETBUFFERSIZE); try { int hval = response.getBufferSize(); int pval = ((ResourceResponse) portletResp).getBufferSize(); String str = "Value " + hval + " from " + "HttpServletResponse" + " does not equal value " + pval + " + ResourceResponse"; if (hval != pval) { tr5.appendTcDetail(str); } tr5.setTcSuccess(hval == pval); } catch (Exception e) { tr5.appendTcDetail(e.toString()); } tr5.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getCharacterEncoding */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getCharacterEncoding must provide */ /* the same functionality as ResourceResponse.getCharacterEncoding" */ TestResult tr6 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCHARACTERENCODING); try { String hval = response.getCharacterEncoding(); String pval = ((ResourceResponse) portletResp).getCharacterEncoding(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr6); } catch (Exception e) { tr6.appendTcDetail(e.toString()); } tr6.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getContentType */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getContentType must provide the */ /* same functionality as ResourceResponse.getContentType" */ TestResult tr7 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCONTENTTYPE); try { String hval = response.getContentType(); String pval = ((ResourceResponse) portletResp).getContentType(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr7); } catch (Exception e) { tr7.appendTcDetail(e.toString()); } tr7.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getLocale */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getLocale must provide the same */ /* functionality as ResourceResponse.getLocale" */ TestResult tr8 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETLOCALE); try { Locale hl = response.getLocale(); Locale pl = ((MimeResponse) portletResp).getLocale(); String hval = hl.getDisplayName(); String pval = pl.getDisplayName(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr8); } catch (Exception e) { tr8.appendTcDetail(e.toString()); } tr8.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_isCommitted */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.isCommitted must provide the same */ /* functionality as ResourceResponse.isCommitted" */ TestResult tr9 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ISCOMMITTED); try { boolean hval = response.isCommitted(); boolean pval = ((ResourceResponse) portletResp).isCommitted(); String str = "Value " + hval + " from " + "HttpServletResponse" + " does not equal value " + pval + " + ResourceResponse"; if (hval != pval) { tr9.appendTcDetail(str); } tr9.setTcSuccess(hval == pval); } catch (Exception e) { tr9.appendTcDetail(e.toString()); } tr9.writeTo(writer); }
@Override public PrintWriter getWriter() throws IOException { pw = new PrintWriter(new OutputStreamWriter(bout, response.getCharacterEncoding())); return pw; }
public String recibo(int id_movimento) { MovimentoDB db = new MovimentoDBToplink(); Movimento movimento = db.pesquisaCodigo(id_movimento); try { Collection vetor = new ArrayList(); Juridica sindicato = (Juridica) (new SalvarAcumuladoDBToplink()).pesquisaCodigo(1, "Juridica"); PessoaEnderecoDB dbp = new PessoaEnderecoDBToplink(); // MovimentosReceberSocialDB dbs = new MovimentosReceberSocialDBToplink(); PessoaEndereco pe = dbp.pesquisaEndPorPessoaTipo(1, 2); String formas[] = new String[10]; // PESQUISA FORMA DE PAGAMENTO List<FormaPagamento> fp = db.pesquisaFormaPagamento(movimento.getBaixa().getId()); float soma_dinheiro = 0; for (int i = 0; i < fp.size(); i++) { // 4 - CHEQUE if (fp.get(i).getTipoPagamento().getId() == 4) { formas[i] = fp.get(i).getTipoPagamento().getDescricao() + ": R$ " + Moeda.converteR$Float(fp.get(i).getValor()) + " (B: " + fp.get(i).getChequeRec().getBanco() + " Ag: " + fp.get(i).getChequeRec().getAgencia() + " C: " + fp.get(i).getChequeRec().getConta() + " CH: " + fp.get(i).getChequeRec().getCheque() + ")"; // 5 - CHEQUE PRÉ } else if (fp.get(i).getTipoPagamento().getId() == 5) { formas[i] = fp.get(i).getTipoPagamento().getDescricao() + ": R$ " + Moeda.converteR$Float(fp.get(i).getValor()) + " (B: " + fp.get(i).getChequeRec().getBanco() + " Ag: " + fp.get(i).getChequeRec().getAgencia() + " C: " + fp.get(i).getChequeRec().getConta() + " CH: " + fp.get(i).getChequeRec().getCheque() + " P: " + fp.get(i).getChequeRec().getVencimento() + ")"; // QUALQUER OUTRO } else { formas[i] = fp.get(i).getTipoPagamento().getDescricao() + ": R$ " + Moeda.converteR$Float(fp.get(i).getValor()); if (fp.get(i).getTipoPagamento().getId() == 3) { soma_dinheiro = soma_dinheiro + fp.get(i).getValor(); } } } String lblVencimento = ""; String vencimento = ""; DataHoje dataHoje = new DataHoje(); List<Movimento> lista = db.listaMovimentoBaixaOrder(movimento.getBaixa().getId()); for (int i = 0; i < lista.size(); i++) { // tem casos de ter responsaveis diferentes, resultando em empresas conveniadas diferentes Guia gu = db.pesquisaGuias(lista.get(i).getLote().getId()); String conveniada = "", mensagemConvenio = ""; if (gu.getId() != -1) { if (gu.getPessoa() != null) { conveniada = gu.getPessoa().getNome(); } } if (lista.get(i).getLote().getRotina().getId() == 132) { if (lista.get(i).getServicos().isValidadeGuias() && !lista.get(i).getServicos().isValidadeGuiasVigente()) { lblVencimento = "Validade"; vencimento = dataHoje.incrementarDias( lista.get(i).getServicos().getValidade(), lista.get(i).getLote().getEmissao()); } else if (lista.get(i).getServicos().isValidadeGuias() && lista.get(i).getServicos().isValidadeGuiasVigente()) { lblVencimento = "Validade"; vencimento = DataHoje.converteData(DataHoje.lastDayOfMonth(DataHoje.dataHoje())); } else { lblVencimento = "Validade"; vencimento = ""; } // MOSTRANDO MENSAGEM APENAS SE VIER DA PAGINA EMISSÃO DE GUIAS --- by rogerinho // 17/03/2015 -- chamado 579 mensagemConvenio = lista.get(i).getLote().getHistorico(); } else { lblVencimento = "Vencimento"; vencimento = lista.get(i).getVencimento(); } vetor.add( new ParametroRecibo( ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()) .getRealPath( "/Cliente/" + ControleUsuarioBean.getCliente() + "/Imagens/LogoCliente.png"), sindicato.getPessoa().getNome(), pe.getEndereco().getDescricaoEndereco().getDescricao(), pe.getEndereco().getLogradouro().getDescricao(), pe.getNumero(), pe.getComplemento(), pe.getEndereco().getBairro().getDescricao(), pe.getEndereco().getCep().substring(0, 5) + "-" + pe.getEndereco().getCep().substring(5), pe.getEndereco().getCidade().getCidade(), pe.getEndereco().getCidade().getUf(), sindicato.getPessoa().getTelefone1(), sindicato.getPessoa().getEmail1(), sindicato.getPessoa().getSite(), sindicato.getPessoa().getDocumento(), lista.get(i).getPessoa().getNome(), // RESPONSÁVEL String.valueOf(lista.get(i).getPessoa().getId()), // ID_RESPONSAVEL String.valueOf(lista.get(i).getBaixa().getId()), // ID_BAIXA lista.get(i).getBeneficiario().getNome(), // BENEFICIÁRIO lista.get(i).getServicos().getDescricao(), // SERVICO vencimento, // VENCIMENTO new BigDecimal(lista.get(i).getValorBaixa()), // VALOR BAIXA lista.get(i).getBaixa().getUsuario().getLogin(), lista.get(i).getBaixa().getBaixa(), DataHoje.horaMinuto(), formas[0], formas[1], formas[2], formas[3], formas[4], formas[5], formas[6], formas[7], formas[8], formas[9], (conveniada.isEmpty()) ? "" : "Empresa Conveniada: " + conveniada, lblVencimento, mensagemConvenio, lista.get(i).getPessoa().getDocumento(), Moeda.converteR$Float(soma_dinheiro + lista.get(i).getBaixa().getTroco()), Moeda.converteR$Float(lista.get(i).getBaixa().getTroco()))); } File fl = new File( ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()) .getRealPath("/Relatorios/RECIBO.jasper")); JasperReport jasper = (JasperReport) JRLoader.loadObject(fl); JRBeanCollectionDataSource dtSource = new JRBeanCollectionDataSource(vetor); JasperPrint print = JasperFillManager.fillReport(jasper, null, dtSource); boolean printPdf = true; if (printPdf) { byte[] arquivo = JasperExportManager.exportReportToPdf(print); salvarRecibo(arquivo, lista.get(0).getBaixa()); HttpServletResponse res = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); res.setContentType("application/pdf"); res.setHeader("Content-disposition", "inline; filename=\"" + "recibo" + ".pdf\""); res.getOutputStream().write(arquivo); res.getCharacterEncoding(); FacesContext.getCurrentInstance().responseComplete(); } else { // CASO QUEIRA IMPRIMIR EM HTML HTMLPRINT PRINTHTML IMPRIMIRRECIBOHTML TOHTML if (lista.get(0).getBaixa().getCaixa() == null) { return null; } String caminho = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()) .getRealPath( "/Cliente/" + ControleUsuarioBean.getCliente() + "/" + "Arquivos/recibo/" + lista.get(0).getBaixa().getCaixa().getCaixa() + "/" + DataHoje.converteData(lista.get(0).getBaixa().getDtBaixa()) .replace("/", "-")); Diretorio.criar( "Arquivos/recibo/" + lista.get(0).getBaixa().getCaixa().getCaixa() + "/" + DataHoje.converteData(lista.get(0).getBaixa().getDtBaixa()).replace("/", "-")); String path_arquivo = caminho + String.valueOf(lista.get(0).getBaixa().getUsuario().getId()) + "_" + String.valueOf(lista.get(0).getBaixa().getId()) + ".html"; File file_arquivo = new File(path_arquivo); String n = String.valueOf(lista.get(0).getBaixa().getUsuario().getId()) + "_" + String.valueOf(lista.get(0).getBaixa().getId()) + ".html"; if (file_arquivo.exists()) { path_arquivo = caminho + String.valueOf(lista.get(0).getBaixa().getUsuario().getId()) + "_" + String.valueOf(lista.get(0).getBaixa().getId()) + "_(2).html"; n = String.valueOf(lista.get(0).getBaixa().getUsuario().getId()) + "_" + String.valueOf(lista.get(0).getBaixa().getId()) + "_(2).html"; } JasperExportManager.exportReportToHtmlFile(print, path_arquivo); Download download = new Download(n, caminho, "text/html", FacesContext.getCurrentInstance()); download.baixar(); // String reportPath =JasperRunManager.runReportToHtmlFile(fl.getPath(), // null, dtSource); // File reportHtmlFile = new File(reportPath); // FileInputStream fis = new FileInputStream(reportHtmlFile); // byte[] arquivo = new byte[(int)reportHtmlFile.length()]; // fis.read(arquivo); // HttpServletResponse res = (HttpServletResponse) // FacesContext.getCurrentInstance().getExternalContext().getResponse(); // res.setHeader("Content-Disposition","inline; filename=myReport.html"); // res.setContentType("text/html"); // res.setContentLength(arquivo.length); // res.getOutputStream().write(arquivo); // res.getCharacterEncoding(); // // FacesContext.getCurrentInstance().responseComplete(); // FacesContext.getCurrentInstance().responseComplete(); // HttpServletResponse response = (HttpServletResponse) // FacesContext.getCurrentInstance().getExternalContext().getResponse(); // // response.sendRedirect("http://localhost:8080/Sindical/Cliente/Sindical/Arquivos/recibo/0/16-06-2015/1_683382.html"); // FacesContext.getCurrentInstance().getExternalContext().redirect("/Sindical/baixaGeral.jsf"); } } catch (JRException | IOException ex) { ex.getMessage(); } return null; }
@Override public String getCharacterEncoding() { return wrap.getCharacterEncoding(); }
/** * This method renders the given request URI using the Sling request processing and stores the * result at the request's location relative to the cache root folder. The request is processed in * the context of the given user's session. * * @param uri The request URI including selectors and extensions * @param configCacheRoot The cache root folder * @param admin The admin session used to store the result in the cache * @param session The user's session * @return <code>true</code> if the cache was updated */ protected boolean renderResource( String uri, String configCacheRoot, Session admin, Session session) throws RepositoryException, ServletException, IOException { String cachePath = configCacheRoot + getTargetPath(uri); ResourceResolver resolver = null; try { resolver = createResolver(session.getUserID()); // render resource ByteArrayOutputStream out = new ByteArrayOutputStream(); HttpServletRequest request = createRequest(uri); HttpServletResponse response = requestResponseFactory.createResponse(out); slingServlet.processRequest(request, response, resolver); response.getWriter().flush(); // compare md5 checksum with cache String md5 = requestResponseFactory.getMD5(response); String md5Path = cachePath + "/" + JcrConstants.JCR_CONTENT + "/" + MD5_HASH_PROPERTY; if (!admin.propertyExists(md5Path) || !admin.getProperty(md5Path).getString().equals(md5)) { log.info("MD5 hash missing or not equal, updating content sync cache: {}", cachePath); JcrUtil.createPath(cachePath, "sling:Folder", "nt:file", admin, false); Node cacheContentNode = JcrUtil.createPath(cachePath + "/jcr:content", "nt:resource", admin); if (needsUtf8Encoding(response)) { cacheContentNode.setProperty( JcrConstants.JCR_DATA, admin .getValueFactory() .createBinary( IOUtils.toInputStream(out.toString(response.getCharacterEncoding())))); } else { cacheContentNode.setProperty( JcrConstants.JCR_DATA, admin.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); } cacheContentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance()); if (response.getContentType() != null) { cacheContentNode.setProperty(JcrConstants.JCR_MIMETYPE, response.getContentType()); } if (response.getCharacterEncoding() != null) { cacheContentNode.setProperty(JcrConstants.JCR_ENCODING, response.getCharacterEncoding()); } cacheContentNode.addMixin(NT_MD5_HASH); cacheContentNode.setProperty(MD5_HASH_PROPERTY, md5); admin.save(); return true; } else { log.info("Skipping update of content sync cache: {}", uri); return false; } } catch (LoginException e) { log.error("Creating resource resolver for resource rendering failed: ", e); return false; } finally { if (resolver != null) { resolver.close(); } if (admin.hasPendingChanges()) { admin.refresh(false); } } }
public String getCharacterEncoding() { return rawResponse.getCharacterEncoding(); }