Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DUVIDA] Estou com dificuldade de fazer a integração do NFE com meu projeto quarkus #1022

Open
SouzaRodrigo61 opened this issue Feb 5, 2025 · 1 comment

Comments

@SouzaRodrigo61
Copy link

Montei a base da implementação:

package com.divinavia;

import org.eclipse.microprofile.reactive.messaging.Incoming;
import org.jboss.logging.Logger;

import com.divinavia.config.ConfigSefaz;
import com.divinavia.model.NFEModel;
import com.fincatto.documentofiscal.DFModelo;
import com.fincatto.documentofiscal.DFUnidadeFederativa;
import com.fincatto.documentofiscal.nfe400.classes.statusservico.consulta.NFStatusServicoConsultaRetorno;
import com.fincatto.documentofiscal.nfe400.webservices.WSFacade;

import io.smallrye.mutiny.Uni;
import io.smallrye.reactive.messaging.kafka.Record;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

/**
 * Um bean consumindo dados do tópico "nfe-in" do Kafka e processando as NFEs de forma assíncrona.
 */
@ApplicationScoped
public class NFEProcessor {

    // Exemplo: se houver um serviço para envio de NFE, poderá ser injetado aqui
    // @Inject
    // NFEService nfeService;


    @Inject
    Logger logger;

    @Incoming("nfe-in")
    public Uni<Void> process(Record<String, NFEModel> record) {
        // Exemplo de processamento assíncrono utilizando o Mutiny
        return Uni.createFrom().item(record)
            .onItem().invoke(rec -> {
                logger.info("Processando envio da NFE: " + rec.key());
            })
            // Realiza a chamada bloqueante em um contexto assíncrono apropriado
            .onItem().transformToUni(rec ->
                Uni.createFrom().item(() -> {
                    NFEModel nfe = rec.value();
                    // Simulação do processamento da NFE
                    nfe.status = "Enviado";

                    // Configuração e chamada do endpoint SOAP
                    ConfigSefaz config = new ConfigSefaz(DFUnidadeFederativa.SP);
                    try {
                        NFStatusServicoConsultaRetorno retorno = new WSFacade(config)
                            .consultaStatus(config.getCUF(), DFModelo.NFE);

                            
                        logger.info("Status SOAP: " + retorno.getStatus());
                        logger.info("Motivo SOAP: " + retorno.getMotivo());
                    } catch (Exception e) {
                        logger.error("Erro ao enviar NFE: " + e.getLocalizedMessage());
                    }
                    
                    return rec;
                })
                // Se necessário, execute essa operação em um executor específico para evitar bloqueios
                .runSubscriptionOn(io.smallrye.mutiny.infrastructure.Infrastructure.getDefaultWorkerPool())
            )
            .replaceWithVoid();
    }
}

porem mesmo assim nunca está funcionando na hora que vai fazer a primeira request a parte do ConfigSefaz:

package com.divinavia.config;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import com.fincatto.documentofiscal.DFUnidadeFederativa;
import com.fincatto.documentofiscal.nfe.NFeConfig;

public class ConfigSefaz extends NFeConfig {

  private static final String CERTIFICADO_SENHA = "senha";

  private KeyStore keyStoreCertificado = null;
  private KeyStore keyStoreCadeia = null;


  private final DFUnidadeFederativa cUF;

  public ConfigSefaz(DFUnidadeFederativa cUF) {
    this.cUF = cUF;
  }

  @Override
  public DFUnidadeFederativa getCUF() {
    return cUF;
  }

  @Override
  public String getCertificadoSenha() {
    return CERTIFICADO_SENHA;
  }

  @Override
  public String getCadeiaCertificadosSenha() {
    return CERTIFICADO_SENHA;
  }

  @Override
  public KeyStore getCertificadoKeyStore() throws KeyStoreException {
    if (this.keyStoreCertificado == null) {
      this.keyStoreCertificado = KeyStore.getInstance("PKCS12");
      try (InputStream certificadoStream = new FileInputStream("./temp/certificado.pfx")) {
        this.keyStoreCertificado.load(certificadoStream, this.getCertificadoSenha().toCharArray());
      } catch (CertificateException | NoSuchAlgorithmException | IOException e) {
        this.keyStoreCertificado = null;
        throw new KeyStoreException("Não foi possível montar o KeyStore com o certificado", e);
      }
    }

    System.out.println("keyStoreCertificado: " + this.keyStoreCertificado);
    return this.keyStoreCertificado;
  }

  @Override
  public KeyStore getCadeiaCertificadosKeyStore() throws KeyStoreException {
    if (this.keyStoreCadeia == null) {
      this.keyStoreCadeia = KeyStore.getInstance("JKS");
      try (InputStream cadeia = new FileInputStream("./temp/cadeia.jks")) {
        this.keyStoreCadeia.load(cadeia, this.getCadeiaCertificadosSenha().toCharArray());
      } catch (CertificateException | NoSuchAlgorithmException | IOException e) {
        this.keyStoreCadeia = null;
        throw new KeyStoreException("Não foi possível montar o KeyStore com a cadeia de certificados", e);
      }
    }

    System.out.println("keyStoreCadeia: " + this.keyStoreCadeia);
    return this.keyStoreCadeia;
  }
}

O erro do retornando:

2025-02-04 21:51:58,921 INFO  [io.sma.rea.mes.kafka] (vert.x-eventloop-thread-0) SRMSG18256: Initialize record store for topic-partition 'nfe-0' at position 25.
2025-02-04 21:51:58,951 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Processando envio da NFE: "hml-21"
2025-02-04 21:51:58,951 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Chave: 00000000000000000000000000000000000000000000
2025-02-04 21:51:58,951 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Emitente: Empresa XYZ LTDA
2025-02-04 21:51:58,952 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Destinatário: Cliente ABC
2025-02-04 21:51:58,952 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Data: 2024-02-04
2025-02-04 21:51:58,952 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Valor: 1500.00
2025-02-04 21:51:58,952 INFO  [com.div.NFEProcessor] (vert.x-eventloop-thread-0) Status: Autorizada
keyStoreCertificado: java.security.KeyStore@20906d5d
keyStoreCadeia: java.security.KeyStore@7c01fff9
2025-02-04 21:51:59,148 WARNING [org.apa.axi.uti.sta.dia.StAXDialectDetector] (executor-thread-1) Unable to determine dialect of the StAX implementation at jar:file:///Users/rodrigosouza/.m2/repository/com/fasterxml/woodstox/woodstox-core/6.6.0/woodstox-core-6.6.0.jar!/
2025-02-04 21:51:59,230 WARNING [org.apa.axi.dep.AxisConfigBuilder] (executor-thread-1) Unable to instantiate deployer org.apache.axis2.deployment.ServiceDeployer; see debug logs for more details
2025-02-04 21:51:59,493 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) I/O exception (org.apache.axis2.AxisFault) caught when processing request: Connection or outbound has closed
2025-02-04 21:51:59,494 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) Retrying request
2025-02-04 21:51:59,610 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) I/O exception (org.apache.axis2.AxisFault) caught when processing request: Connection or outbound has closed
2025-02-04 21:51:59,610 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) Retrying request
2025-02-04 21:51:59,717 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) I/O exception (org.apache.axis2.AxisFault) caught when processing request: Connection or outbound has closed
2025-02-04 21:51:59,718 INFO  [org.apa.com.htt.HttpMethodDirector] (executor-thread-1) Retrying request
2025-02-04 21:51:59,828 INFO  [org.apa.axi.tra.htt.imp.htt.HTTPSenderImpl] (executor-thread-1) Unable to sendViaPost to url[https://homologacao.nfe.fazenda.sp.gov.br/ws/nfestatusservico4.asmx]

Exception in NFEProcessor.java:57
          55                      try {
          56                          NFStatusServicoConsultaRetorno retorno = new WSFacade(config)
        → 57                              .consultaStatus(config.getCUF(), DFModelo.NFE);
          58  
          59                              



Exception in NFEProcessor.java:57
          55                      try {
          56                          NFStatusServicoConsultaRetorno retorno = new WSFacade(config)
        → 57                              .consultaStatus(config.getCUF(), DFModelo.NFE);
          58  
          59                              

: org.apache.axis2.AxisFault: Connection or outbound has closed
        at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
        at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:78)
        at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:85)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
        at org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.executeMethod(HTTPSenderImpl.java:872)
        at org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.sendViaPost(HTTPSenderImpl.java:212)
        at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:121)
        at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:403)
        at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:234)
        at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:431)
        at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:399)
        at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
        at org.apache.axis2.client.OperationClient.execute(OperationClient.java:150)
        at com.fincatto.documentofiscal.nfe400.webservices.statusservico.consulta.NfeStatusServico4Stub.nfeStatusServicoNF(NfeStatusServico4Stub.java:110)
        at com.fincatto.documentofiscal.nfe400.webservices.WSStatusConsulta.efetuaConsultaStatus(WSStatusConsulta.java:53)
        at com.fincatto.documentofiscal.nfe400.webservices.WSStatusConsulta.consultaStatus(WSStatusConsulta.java:29)
        at com.fincatto.documentofiscal.nfe400.webservices.WSFacade.consultaStatus(WSFacade.java:137)
        at com.divinavia.NFEProcessor.lambda$2(NFEProcessor.java:57)
        at io.smallrye.context.impl.wrappers.SlowContextualSupplier.get(SlowContextualSupplier.java:21)
        at io.smallrye.mutiny.operators.uni.builders.UniCreateFromItemSupplier.subscribe(UniCreateFromItemSupplier.java:28)
        at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:36)
        at io.smallrye.mutiny.operators.uni.UniRunSubscribeOn.lambda$subscribe$0(UniRunSubscribeOn.java:27)
        at io.quarkus.vertx.core.runtime.VertxCoreRecorder$15.runWith(VertxCoreRecorder.java:639)
        at org.jboss.threads.EnhancedQueueExecutor$Task.doRunWith(EnhancedQueueExecutor.java:2675)
        at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2654)
        at org.jboss.threads.EnhancedQueueExecutor.runThreadBody(EnhancedQueueExecutor.java:1627)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1594)
        at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:11)
        at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:11)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: com.ctc.wstx.exc.WstxIOException: Connection or outbound has closed
        at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:262)
        at org.apache.axiom.om.impl.MTOMXMLStreamWriter.flush(MTOMXMLStreamWriter.java:231)
        at org.apache.axiom.om.impl.MTOMXMLStreamWriter.close(MTOMXMLStreamWriter.java:223)
        at org.apache.axiom.om.impl.common.AxiomContainerSupport.ajc$interMethod$org_apache_axiom_om_impl_common_AxiomContainerSupport$org_apache_axiom_om_impl_intf_AxiomContainer$serializeAndConsume(AxiomContainerSupport.aj:324)
        at org.apache.axiom.om.impl.llom.OMElementImpl.serializeAndConsume(OMElementImpl.java:1)
        at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:74)
        ... 34 more


2025-02-04 21:51:59,844 ERROR [com.div.NFEProcessor] (executor-thread-1) Erro ao enviar NFE: Connection or outbound has closed
@SouzaRodrigo61 SouzaRodrigo61 changed the title [DUVIDA] Estou com muita dificuildade de fazer a integração do NFE com meu projeto quarkus [DUVIDA] Estou com dificuldade de fazer a integração do NFE com meu projeto quarkus Feb 5, 2025
@LouizFC
Copy link

LouizFC commented Feb 18, 2025

Eu estava com o mesmo problema, forçar uma versão mais nova do axis2 (que é usado internamente pelo projeto) corrigiu:

  <dependency>
      <groupId>org.apache.axis2</groupId>
      <artifactId>axis2-kernel</artifactId>
      <version>1.8.2</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.axis2</groupId>
      <artifactId>axis2-adb</artifactId>
      <version>1.8.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.axis2</groupId>
      <artifactId>axis2-transport-local</artifactId>
      <version>1.8.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.axis2</groupId>
      <artifactId>axis2-transport-http</artifactId>
      <version>1.8.2</version>
      <scope>compile</scope>
    </dependency>

Edit: E também adicionar o client http da apache

    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants