Search in sources :

Example 1 with ContentInfo

use of com.j256.simplemagic.ContentInfo in project balcaovirtual by trf2-jus-br.

the class DownloadJwtFilenameGet method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    Map<String, Object> map = verify(req.jwt);
    String username = (String) map.get("username");
    String origin = (String) map.get("origin");
    String password;
    if (username != null && !"pub".equals(origin))
        password = AutenticarPost.Usuario.getSenha(username);
    else {
        username = BalcaojusServlet.INSTANCE.getProperty("public.username");
        password = BalcaojusServlet.INSTANCE.getProperty("public.password");
    }
    String name = (String) map.get("name");
    String file = (String) map.get("file");
    String numProc = (String) map.get("proc");
    String numDoc = (String) map.get("doc");
    String orgao = (String) map.get("orgao");
    String type = (String) map.get("typ");
    String text = (String) map.get("text");
    String cargo = (String) map.get("cargo");
    String empresa = (String) map.get("empresa");
    String unidade = (String) map.get("unidade");
    String uuid = (String) map.get("uuid");
    String disposition = "attachment".equals(req.disposition) ? "attachment" : "inline";
    if (!"download".equals(type))
        throw new Exception("Tipo de token JWT inválido");
    if (text != null) {
        byte[] pdf = ProcessoNumeroCotaPrevisaoPdfPost.criarPDF(name, numProc, text, cargo, empresa, unidade);
        resp.contentdisposition = "inline";
        resp.contentlength = (long) pdf.length;
        resp.contenttype = "application/pdf";
        resp.inputstream = new ByteArrayInputStream(pdf);
    } else if (file != null && file.equals("avisos-pendentes.xml")) {
    // TODO: IMPLEMENTAR
    // // Processo completo
    // Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>>
    // future = SwaggerCall
    // .callAsync("obter XML de avisos", "Bearer " + req.jwt, "GET",
    // Utils.getWsProcessualUrl() + "/usuario-web/" +
    // map.get("username")
    // + "/aviso-pendente/exportar",
    // null, UsuarioWebUsernameAvisoPendenteExportarGetResponse.class);
    // SwaggerAsyncResponse<UsuarioWebUsernameAvisoPendenteExportarGetResponse>
    // sar = future.get();
    // if (sar.getException() != null)
    // throw sar.getException();
    // UsuarioWebUsernameAvisoPendenteExportarGetResponse r =
    // (UsuarioWebUsernameAvisoPendenteExportarGetResponse) sar
    // .getResp();
    // resp.contentdisposition = "attachment;filename=" +
    // map.get("username") + "-avisos-pendentes.xml";
    // resp.contentlength = r.contentlength;
    // resp.contenttype = r.contenttype;
    // resp.inputstream = r.inputstream;
    } else if (file != null && file.equals("avisos-confirmados.xml")) {
    // TODO: IMPLEMENTAR
    // Future<SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>>
    // future = SwaggerCall
    // .callAsync("obter XML de avisos confirmados", "Bearer " +
    // req.jwt, "GET",
    // Utils.getWsProcessualUrl() + "/usuario-web/" +
    // map.get("username")
    // + "/aviso-confirmado/exportar",
    // null,
    // UsuarioWebUsernameAvisoConfirmadoExportarGetResponse.class);
    // SwaggerAsyncResponse<UsuarioWebUsernameAvisoConfirmadoExportarGetResponse>
    // sar = future.get();
    // if (sar.getException() != null)
    // throw sar.getException();
    // UsuarioWebUsernameAvisoConfirmadoExportarGetResponse r =
    // (UsuarioWebUsernameAvisoConfirmadoExportarGetResponse) sar
    // .getResp();
    // resp.contentdisposition = "attachment;filename=" +
    // map.get("username") + "-avisos-confirmados.xml";
    // resp.contentlength = r.contentlength;
    // resp.contenttype = r.contenttype;
    // resp.inputstream = r.inputstream;
    } else {
        ContentInfoUtil contentInfoUtil = new ContentInfoUtil();
        if (numDoc != null) {
            byte[] ab = null;
            // Peça Processual
            username = Utils.preprocessarId(username, password, orgao, origin);
            password = Utils.preprocessarSenha(username, password, orgao, origin);
            ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, numDoc);
            ContentInfo info = contentInfoUtil.findMatch(ab);
            resp.contenttype = info.getMimeType();
            if (info.getMimeType().startsWith("application/xml")) {
                final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
                String fileEncoding = xmlStreamReader.getEncoding();
                boolean fHtml = false;
                while (xmlStreamReader.hasNext()) {
                    int eventType = xmlStreamReader.next();
                    if (eventType == XMLStreamConstants.START_ELEMENT) {
                        if (xmlStreamReader.getLocalName().equals("html"))
                            fHtml = true;
                        break;
                    }
                }
                xmlStreamReader.close();
                if (fHtml) {
                    info = contentInfoUtil.findMimeTypeMatch("text/html");
                    resp.contenttype = info.getMimeType() + "; charset=" + fileEncoding;
                }
            }
            resp.contentdisposition = disposition + ";filename=" + numProc + "-peca-" + numDoc + "." + info.getFileExtensions()[0];
            resp.contentlength = (long) ab.length;
            resp.inputstream = new ByteArrayInputStream(ab);
        } else if (uuid != null) {
            String dirTemp = Utils.getDirTemp();
            String bufName = dirTemp + "/" + numProc + "-completo-" + uuid + ".pdf";
            resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
            resp.contentlength = (long) new File(bufName).length();
            resp.contenttype = "application/pdf";
            resp.inputstream = new FileInputStream(bufName);
        } else {
            // Processo completo
            // Consulta o processo para saber quais são os documentos a serem
            // concatenados
            String json = SoapMNI.consultarProcesso(username, password, orgao, numProc, false, false, true);
            JSONObject proc = new JSONObject(json).getJSONObject("value");
            JSONArray docs = proc.getJSONArray("documento");
            // Cria um documento em diretório temporário para agregar os
            // diversos PDFs
            String dirTemp = Utils.getDirTemp();
            String bufName = dirTemp + "/" + numProc + "-completo-" + UUID.randomUUID().toString() + ".pdf";
            FileOutputStream buf = new FileOutputStream(bufName);
            Document document = new Document();
            PdfCopy copy = new PdfSmartCopy(document, buf);
            document.open();
            PdfReader reader;
            for (int i = 0; i < docs.length(); i++) {
                String idDocumento = docs.getJSONObject(i).getString("idDocumento");
                byte[] ab = SoapMNI.obterPecaProcessual(username, password, orgao, numProc, idDocumento);
                ContentInfo info = contentInfoUtil.findMatch(ab);
                if (info.getMimeType().startsWith("application/xml")) {
                    final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
                    String fileEncoding = xmlStreamReader.getEncoding();
                    boolean fHtml = false;
                    while (xmlStreamReader.hasNext()) {
                        int eventType = xmlStreamReader.next();
                        if (eventType == XMLStreamConstants.START_ELEMENT) {
                            if (xmlStreamReader.getLocalName().equals("html"))
                                fHtml = true;
                            break;
                        }
                    }
                    xmlStreamReader.close();
                    if (fHtml) {
                        String html = new String(ab, fileEncoding);
                        // System.out.println(html);
                        ab = new Html2Pdf().converter(html, false);
                        info = contentInfoUtil.findMimeTypeMatch("application/pdf");
                    }
                }
                if (info.getMimeType().startsWith("text/html")) {
                    String html = new String(ab, StandardCharsets.UTF_8);
                    if (html.toLowerCase().contains("charset=windows-1252") || html.toLowerCase().contains("iso-8859-1"))
                        html = new String(ab, StandardCharsets.ISO_8859_1);
                    // System.out.println(html);
                    ab = new Html2Pdf().converter(html, false);
                    info = contentInfoUtil.findMimeTypeMatch("application/pdf");
                }
                if (!"application/pdf".equals(info.getMimeType()))
                    throw new PresentableException("Não foi possível obter um PDF. (" + info.getMimeType() + ")");
                reader = new PdfReader(ab);
                copy.addDocument(reader);
                reader.close();
            }
            document.close();
            resp.contentdisposition = disposition + ";filename=" + numProc + "-completo.pdf";
            resp.contentlength = (long) new File(bufName).length();
            resp.contenttype = "application/pdf";
            resp.inputstream = new FileInputStream(bufName);
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) JSONArray(org.json.JSONArray) PdfReader(com.itextpdf.text.pdf.PdfReader) Document(com.itextpdf.text.Document) ContentInfoUtil(com.j256.simplemagic.ContentInfoUtil) JWTVerifyException(com.auth0.jwt.JWTVerifyException) PresentableException(com.crivano.swaggerservlet.PresentableException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) FileInputStream(java.io.FileInputStream) PdfCopy(com.itextpdf.text.pdf.PdfCopy) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(com.j256.simplemagic.ContentInfo) FileOutputStream(java.io.FileOutputStream) PdfSmartCopy(com.itextpdf.text.pdf.PdfSmartCopy) JSONObject(org.json.JSONObject) PresentableException(com.crivano.swaggerservlet.PresentableException) File(java.io.File)

Example 2 with ContentInfo

use of com.j256.simplemagic.ContentInfo in project dataio by DBCDK.

the class BinaryFileFsImpl method getCompression.

private Compression getCompression() {
    try {
        final ContentInfoUtil infoFinder = new ContentInfoUtil();
        final ContentInfo info = infoFinder.findMatch(path.toAbsolutePath().toString());
        if (info == null) {
            return Compression.RAW;
        }
        switch(info.getContentType()) {
            case BZIP2:
                return Compression.BZIP2;
            case GZIP:
                return Compression.GZIP;
            default:
                return Compression.RAW;
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ContentInfo(com.j256.simplemagic.ContentInfo) IOException(java.io.IOException) ContentInfoUtil(com.j256.simplemagic.ContentInfoUtil)

Example 3 with ContentInfo

use of com.j256.simplemagic.ContentInfo in project balcaovirtual by trf2-jus-br.

the class ProcessoCompleto method call.

@Override
public String call() throws Exception {
    ContentInfoUtil contentInfoUtil = new ContentInfoUtil();
    String bufName = null;
    try {
        this.status = Status.update(this.uuid, "Obtendo a lista de documentos", 0, 100, 0L);
        boolean fEproc = sistema.contains(".eproc");
        // Consulta o processo para saber quais são os documentos a serem
        // concatenados
        String json = SoapMNI.consultarProcesso(username, password, sistema, numProc, false, fEproc, true);
        JSONObject proc = new JSONObject(json).getJSONObject("value");
        JSONArray docs = proc.getJSONArray("documento");
        // Cria um mapa de movimentos para facilitar a criação das páginas de separação
        Map<String, JSONObject> movs = new HashMap<>();
        if (fEproc) {
            JSONArray movimentos = proc.getJSONArray("movimento");
            for (int i = 0; i < movimentos.length(); i++) {
                JSONObject mov = movimentos.getJSONObject(i);
                movs.put(mov.getString("identificadorMovimento"), mov);
            }
        }
        // Cria um documento em diretório temporário para agregar os
        // diversos PDFs
        String dirTemp = Utils.getDirTemp();
        bufName = dirTemp + "/" + numProc + "-completo-" + uuid + ".pdf";
        FileOutputStream buf = new FileOutputStream(bufName);
        Document document = new Document();
        PdfCopy copy = new PdfSmartCopy(document, buf);
        copy.setPageSize(PageSize.A4);
        document.open();
        long bytes = 0;
        for (int i = 0; i < docs.length(); i++) {
            String idDocumento = null;
            JSONObject doc;
            if (fEproc) {
                doc = docs.getJSONObject(docs.length() - i - 1);
                String movimento = doc.getString("movimento");
                String dataHora = Utils.formatarDataHoraMinutoSegundo(Utils.parsearApoloDataHoraMinuto(doc.getString("dataHora")));
                String usuario = null;
                String descricao = null;
                if (movs.containsKey(movimento)) {
                    JSONObject mov = movs.get(movimento);
                    if (mov != null) {
                        JSONArray complementos = mov.getJSONArray("complemento");
                        if (complementos != null) {
                            for (int j = 0; j < complementos.length(); j++) {
                                String complemento = complementos.getString(j);
                                if (complemento != null && complemento.startsWith("Movimentado por: ")) {
                                    usuario = complemento.replace("Movimentado por: ", "");
                                }
                            }
                        }
                        if (mov.getJSONObject("movimentoLocal") != null)
                            descricao = mov.getJSONObject("movimentoLocal").getString("descricao");
                    }
                }
                // String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style type=\"text/css\">@media print {} @page {size: a4 portrait; margin-left: 2cm; margin-right: 2cm; margin-top: 2cm; margin-bottom: 2cm;background-color: lightyellow;}</style></head><body style=\"background-color: lightyellow;\">";
                String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style type=\"text/css\">@media print {} @page {margin-left: 2cm; margin-right: 2cm; margin-top: 2cm; margin-bottom: 2cm;background-color: lightyellow;}</style></head><body style=\"background-color: lightyellow;\">";
                // String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style
                // type=\"text/css\">@media print {background-color: lightyellow; @page{size: a4
                // portrait; margin-left:0cm; padding-right: 3cm; margin-top: 3cm;
                // margin-bottom: 3cm;}}</style></head><body style=\"background-color:
                // lightyellow;\">";
                html += "<p align=\"center\"><b>";
                html += i == 0 ? "CAPA DO PROCESSO" : "PÁGINA DE SEPARAÇÃO";
                html += "</b><br/><i>(Gerada automaticamente pelo Balcãojus.)</i><br/><br/><br/><br/><br/></p>";
                if (i == 0)
                    html += "<h1 style=\"text-align: center;\">Processo N&ordm; " + Utils.formatarNumeroProcesso(numProc) + "</h1>";
                html += "<br/><br/><br/><h2 style=\"text-align: center;\">Evento " + movimento;
                html += "</h2><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>";
                html += "<p>Data: " + dataHora + "</p>";
                html += "<p>Número do Processo: " + Utils.formatarNumeroProcesso(numProc) + "</p>";
                if (movimento != null)
                    html += "<p>Número do Evento: " + movimento + "</p>";
                if (usuario != null)
                    html += "<p>Usuário: " + usuario + "</p>";
                if (descricao != null)
                    html += "<p>Descrição do Evento: " + descricao + "</p>";
                html += "</body></html>";
                byte[] abSep = new Html2Pdf().converter(html, false);
                bytes += abSep.length;
                PdfReader reader = new PdfReader(abSep);
                copy.addDocument(reader);
                reader.close();
            } else
                doc = docs.getJSONObject(i);
            idDocumento = doc.getString("idDocumento");
            this.status = Status.update(this.uuid, "Agregando documento " + (i + 1) + "/" + docs.length(), i * 2 + 1, docs.length() * 2 + 1, bytes);
            byte[] ab = SoapMNI.obterPecaProcessual(username, password, sistema, numProc, idDocumento);
            if (ab == null)
                continue;
            ContentInfo info = contentInfoUtil.findMatch(ab);
            if (info.getMimeType().startsWith("application/xml")) {
                // System.out.println("xml");
                this.status = Status.update(this.uuid, "Convertendo documento " + (i + 1) + "/" + docs.length() + " de XHTML para PDF", i * 2 + 2, docs.length() * 2 + 1, bytes);
                final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(ab));
                String fileEncoding = xmlStreamReader.getEncoding();
                boolean fHtml = false;
                while (xmlStreamReader.hasNext()) {
                    int eventType = xmlStreamReader.next();
                    if (eventType == XMLStreamConstants.START_ELEMENT) {
                        if (xmlStreamReader.getLocalName().equals("html"))
                            fHtml = true;
                        break;
                    }
                }
                xmlStreamReader.close();
                if (fHtml) {
                    String html = new String(ab, fileEncoding);
                    // System.out.println(html);
                    ab = new Html2Pdf().converter(html, false);
                    info = contentInfoUtil.findMimeTypeMatch("application/pdf");
                }
            } else if (info.getMimeType().startsWith("text/html")) {
                // System.out.println("html");
                this.status = Status.update(this.uuid, "Convertendo " + (i + 1) + "/" + docs.length() + " de HTML para PDF", i * 2 + 2, docs.length() * 2 + 1, bytes);
                String html = new String(ab, StandardCharsets.UTF_8);
                if (html.toLowerCase().contains("charset=windows-1252") || html.toLowerCase().contains("iso-8859-1"))
                    html = new String(ab, StandardCharsets.ISO_8859_1);
                // Removendo comentários no tag <style> do html que estavam desativados usando
                // <!-- -->, o que inclusive não está correto. Isso ocasionava um erro que
                // produzia uma página em branco no PDF completo.
                html = html.replaceAll("(?s)\\<!--.*?--\\>", "");
                // System.out.println(html);
                ab = new Html2Pdf().converter(html, false);
                info = contentInfoUtil.findMimeTypeMatch("application/pdf");
            } else if ("application/pdf".equals(info.getMimeType())) {
            // System.out.println("pdf");
            } else
                throw new PresentableException("Não foi possível obter um PDF. (" + info.getMimeType() + ")");
            bytes += ab.length;
            PdfReader reader = new PdfReader(ab);
            copy.addDocument(reader);
            reader.close();
        }
        document.close();
        this.status = Status.update(this.uuid, "PDF completo gerado", docs.length() * 2 + 1, docs.length() * 2 + 1, bytes);
    } catch (Exception ex) {
        this.status.ex = ex;
        Status.update(this.uuid, this.status);
    }
    return bufName;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) PdfReader(com.itextpdf.text.pdf.PdfReader) Document(com.itextpdf.text.Document) ContentInfoUtil(com.j256.simplemagic.ContentInfoUtil) PresentableException(com.crivano.swaggerservlet.PresentableException) PdfCopy(com.itextpdf.text.pdf.PdfCopy) JSONObject(org.json.JSONObject) ContentInfo(com.j256.simplemagic.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) PdfSmartCopy(com.itextpdf.text.pdf.PdfSmartCopy) PresentableException(com.crivano.swaggerservlet.PresentableException)

Aggregations

ContentInfo (com.j256.simplemagic.ContentInfo)3 ContentInfoUtil (com.j256.simplemagic.ContentInfoUtil)3 PresentableException (com.crivano.swaggerservlet.PresentableException)2 Document (com.itextpdf.text.Document)2 PdfCopy (com.itextpdf.text.pdf.PdfCopy)2 PdfReader (com.itextpdf.text.pdf.PdfReader)2 PdfSmartCopy (com.itextpdf.text.pdf.PdfSmartCopy)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileOutputStream (java.io.FileOutputStream)2 IOException (java.io.IOException)2 XMLStreamReader (javax.xml.stream.XMLStreamReader)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 JWTVerifyException (com.auth0.jwt.JWTVerifyException)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InvalidKeyException (java.security.InvalidKeyException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SignatureException (java.security.SignatureException)1 HashMap (java.util.HashMap)1