Search in sources :

Example 6 with PresentableException

use of com.crivano.swaggerservlet.PresentableException in project balcaovirtual by trf2-jus-br.

the class NotificarPost method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    String auth = AutenticarPost.getAuthorizationHeader();
    String property = BalcaojusServlet.INSTANCE.getProperty("notificar.password");
    if (property == null)
        throw new PresentableException("Senha para habilitar notificações não foi configurada no parâmetro balcaojus.notificar.password");
    if (!property.equals(auth))
        throw new PresentableException("Não foram informadas credenciais confiáveis para iniciar procedimento de notificação");
    Status.update(Notificar.NOTIFICACAO_STATUS, "Aguardando na fila de tarefas", 0, 100, 0L);
    BalcaojusServlet.submitToExecutor(new Notificar());
}
Also used : PresentableException(com.crivano.swaggerservlet.PresentableException)

Example 7 with PresentableException

use of com.crivano.swaggerservlet.PresentableException in project balcaovirtual by trf2-jus-br.

the class CertidaoEmitirRequisitanteCpfcnpjPost method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    if (!CertidaoObterTokenGet.isValidToken(req.token, null, req.requisitante, req.cpfcnpj))
        throw new PresentableException("Token inválido");
    FetchResponse r = fetch(Utils.getCertApiUrl(req.sistema) + "/bv_emissao_cert.asp", Utils.getCertApiPassword(req.sistema), "POST", "Botao=Emitir&CPFReq=" + req.requisitante + "&NumDocPess=" + req.cpfcnpj);
    if (r.headerFields.containsKey(Utils.ERROR_MESSAGE))
        throw new PresentableUnloggedException(r.headerFields.get(Utils.ERROR_MESSAGE).get(0));
    if (r.headerFields.containsKey(Utils.RESULT_KIND)) {
        resp.tipo = r.headerFields.get(Utils.RESULT_KIND).get(0);
        resp.html = Utils.obterHtml(r.html, resp.tipo);
    }
    if (r.headerFields.containsKey(Utils.CERT_NUMBER))
        resp.numero = r.headerFields.get(Utils.CERT_NUMBER).get(0);
    if (r.headerFields.containsKey(Utils.NAME))
        resp.nome = r.headerFields.get(Utils.NAME).get(0);
    if (r.headerFields.containsKey(Utils.QS))
        resp.qs = r.headerFields.get(Utils.QS).get(0);
    if (r.headerFields.containsKey(Utils.POST_PARAMS))
        resp.params = r.headerFields.get(Utils.POST_PARAMS).get(0);
    if (!r.headerFields.containsKey(Utils.RESULT_KIND) && resp.html == null) {
        resp.tipo = "REQUERER";
        resp.numero = req.cpfcnpj;
        resp.nome = "Nome não disponível";
        resp.html = "Essa certidão não pôde ser emitida de forma automática.\r\n" + "Isto ocorre porque pode haver algum processo vinculado ao requerente,\r\n" + "caso de homonímia, ou outro caso que exija análise para emissão.\r\n" + "Basta clicar no botão abaixo para solicitar o processamento desse pedido\r\n" + "para impressão através de nosso site no prazo de 05 dias úteis.";
    }
}
Also used : PresentableUnloggedException(com.crivano.swaggerservlet.PresentableUnloggedException) PresentableException(com.crivano.swaggerservlet.PresentableException)

Example 8 with PresentableException

use of com.crivano.swaggerservlet.PresentableException in project balcaovirtual by trf2-jus-br.

the class CertidaoReimprimirNumeroCpfcnpjGet method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    if (!CertidaoObterTokenGet.isValidToken(req.token, req.numero, null, req.cpfcnpj))
        throw new PresentableException("Token inválido");
    FetchResponse r = CertidaoEmitirRequisitanteCpfcnpjPost.fetch(Utils.getCertApiUrl(req.sistema) + "/bv_cons_cert_lib.asp", Utils.getCertApiPassword(req.sistema), "POST", "Botao=Emitir&NumProt=" + req.numero + "&NumDocPess=" + req.cpfcnpj);
    if (r.headerFields.containsKey(Utils.ERROR_MESSAGE))
        throw new PresentableUnloggedException(r.headerFields.get(Utils.ERROR_MESSAGE).get(0));
    resp.html = r.html;
    if (r.headerFields.containsKey(Utils.RESULT_KIND)) {
        resp.tipo = r.headerFields.get(Utils.RESULT_KIND).get(0);
        resp.html = Utils.obterHtml(resp.html, resp.tipo);
    }
    if (r.headerFields.containsKey(Utils.CERT_NUMBER))
        resp.numero = r.headerFields.get(Utils.CERT_NUMBER).get(0);
}
Also used : PresentableUnloggedException(com.crivano.swaggerservlet.PresentableUnloggedException) PresentableException(com.crivano.swaggerservlet.PresentableException) FetchResponse(br.jus.trf2.balcaojus.CertidaoEmitirRequisitanteCpfcnpjPost.FetchResponse)

Example 9 with PresentableException

use of com.crivano.swaggerservlet.PresentableException 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 10 with PresentableException

use of com.crivano.swaggerservlet.PresentableException in project balcaovirtual by trf2-jus-br.

the class ImprimirFilenameGet method recuperarPdfEmCache.

public static CachedHtml recuperarPdfEmCache(String filename) throws Exception {
    byte[] data = SwaggerUtils.memCacheRetrieve(filename);
    if (data == null)
        throw new PresentableException("Conteúdo da certidão não encontrado no cache. Por favor, emita novamente.");
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    ObjectInputStream ois = new ObjectInputStream(bis);
    CachedHtml ch = (CachedHtml) ois.readObject();
    return ch;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PresentableException(com.crivano.swaggerservlet.PresentableException) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

PresentableException (com.crivano.swaggerservlet.PresentableException)15 PresentableUnloggedException (com.crivano.swaggerservlet.PresentableUnloggedException)7 Usuario (br.jus.trf2.balcaojus.AutenticarPost.Usuario)4 UsuarioDetalhe (br.jus.trf2.balcaojus.AutenticarPost.UsuarioDetalhe)3 FetchResponse (br.jus.trf2.balcaojus.CertidaoEmitirRequisitanteCpfcnpjPost.FetchResponse)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ProcessoValido (br.jus.trf2.balcaojus.IBalcaojus.ProcessoValido)2 Processo (br.jus.trf2.balcaojus.model.Processo)2 JWTVerifyException (com.auth0.jwt.JWTVerifyException)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 ContentInfo (com.j256.simplemagic.ContentInfo)2 ContentInfoUtil (com.j256.simplemagic.ContentInfoUtil)2 FileOutputStream (java.io.FileOutputStream)2 IOException (java.io.IOException)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SignatureException (java.security.SignatureException)2