Java-NFe Library Documentation

repository·master·Indexed 20 days ago

https://github.com/samuel-oliveira/java_nfe

A Java library for consuming NFe (Electronic Invoice) and NFCe (Electronic Consumer Invoice) WebServices, handling XML generation, signing, and communication with SEFAZ. The documentation covers installation via Maven and Gradle, JAXB class regeneration using JDK 8 and PowerShell Core, and detailed migration guides for transitioning from version 4.00.x to 4.1.1.

Tokens
21.6K
Snippets
43
Records
60
Agent score
72%

What's inside Java-NFe

  1. How JAXB regeneration works: Sequential Passes

    master

    The project uses a sequential pass strategy to handle complex XSD dependencies and avoid collisions.

    Package schemas (5 passes)

    Compiles into the same output directory. The order is critical:

    1. consSitNFe (renames specific types)
    2. consCad (generates minimal TEndereco)
    3. distDFeInt (redefines basic types)
    4. resNFe (generates TResNFe)
    5. NFe (LAST): Must be the final pass. It generates the comprehensive ObjectFactory and the complete TEndereco (including UF, cPais, etc.), overwriting previous versions.

    Package schemas_eventos (14 passes)

    Each pass handles a specific event group (e.g., cancelamento, epec, manifestacao) using .xjb binding files to rename classes and prevent name collisions between different event types that share identical XSD element names.

    Individual Events (Passes 15+)

    For specific events (like Tax Reform/Reforma Tributária), the script runs xjc in a temporary package, extracts DetEvento.java, renames it to DetEvento<code_id>.java (e.g., DetEvento110001.java), and moves it to schemas_eventos. This ensures the @XmlRootElement annotation is preserved, which is required for successful runtime marshalling.

  2. Handle NFe vs NFCe method calls (v3.10.5 legacy)

    master
    In older versions (v3.10.5), several core methods (e.g., statusServico, consultaXml, inutilizacao, enviarNfe, cancelarNfe, cce) were updated to require an additional parameter specifying the document type. You must pass either ConstantesUtil.NFE or ConstantesUtil.NFCE.
  3. Manual Review Checklist for v4.1.1 Migration

    master

    The migration scripts use regex and text replacement. You must manually review the following areas to ensure correctness:

    1. Wildcard Imports: If you use import br.com.swconsultoria.nfe.schema_4.*;, the script replaces the prefix but keeps the *. If this causes ambiguity between the new consolidated packages, resolve them by using explicit imports.
    2. TUf Ambiguity: Both schemas and schemas_eventos packages contain a TUf class. If your code uses TUf for events, ensure the import points to br.com.swconsultoria.nfe.schemas_eventos.TUf.
    3. Reflection: Update any code that uses Class.forName(...), getClass().getName(), or compares Fully Qualified Names (FQNs) as strings.
    4. API Type Changes: Check for method signatures that changed types (e.g., the getDhRecbto() change mentioned in the breaking changes section).
  4. Important constraints for JAXB regeneration

    master

    To maintain the integrity of the generated schemas, adhere to these rules:

    • DO NOT edit .java files inside schemas/ or schemas_eventos/ manually; they are overwritten during the next regeneration.
    • DO NOT change the order of passes in scripts/regenerate-jaxb.ps1 without understanding the impact. The NFe pass MUST be the last pass in the schemas group.
    • DO NOT add extra <execution> blocks to the exec-maven-plugin. Use the canonical table defined in scripts/regenerate-jaxb.ps1.
    • DO NOT use xjc from JDK 11+ or standalone jaxb-impl (which generates jakarta.* annotations, incompatible with Java 8 + javax.*).
    • DO NOT delete orphan Suframa packages; they remain on disk without regeneration.
  5. Add a new event or document to the JAXB schemas

    master

    When SEFAZ publishes a new event or document, follow these steps to integrate it into the project's JAXB generation process:

    1. Copy XSDs: Place the new .xsd files into the schemas/ directory.
    2. Create Binding: Create a binding file in scripts/bindings/ (e.g., meu-evento.xjb) to resolve class name conflicts (e.g., renaming TEvento to TMeuEvento).
    3. Update Regeneration Script: Edit scripts/regenerate-jaxb.ps1 to add a new Invoke-XjcPass call.
      • For Events: Use the schemas_eventos package.
      • For Non-Event Documents (e.g., queries, inutilizations): Use the schemas package and ensure the pass is inserted BEFORE the NFe pass (the NFe pass must always be the last in the schemas group).
    4. Run Regeneration: Execute mvn exec:exec@regenerate-jaxb.
    5. Verify: Ensure DetEvento.java remains unchanged. If it was modified, restore it via Git.
    6. Commit: Include the new XSDs, the .xjb file, the script changes, and the generated .java files.
    # For an event (schemas_eventos):
    Invoke-XjcPass `
        -Label "schemas_eventos pass-15: meu-evento" `
        -Package "$BasePkg.schemas_eventos" `
        -XsdFiles @('leiauteMeuEvento_v1.00.xsd', 'envMeuEvento_v1.00.xsd', 'retEnvMeuEvento_v1.00.xsd') `
        -BindingFiles @((Join-Path $BindingsDir 'meu-evento.xjb'))
    
    # For a non-event document (schemas), insert BEFORE the NFe pass:
    Invoke-XjcPass `
        -Label "schemas pass-X: meu-documento" `
        -Package "$BasePkg.schemas" `
        -XsdFiles @('meuDocumento_v1.00.xsd')
  6. Prerequisites for JAXB regeneration

    master

    To run the JAXB regeneration script, you need the following tools installed:

    ToolPurposeNote
    JDK 8Required for the native xjc compiler (removed in Java 9+)Use [Adoptium Temurin 8]
    PowerShell Core (pwsh) 7+Required to run the cross-platform scriptwinget install Microsoft.PowerShell (Win), brew install powershell (macOS)
    Maven 3.6+Required for the project buildAny version 3.6 or higher

    Locating JDK 8: The script searches for JDK 8 in this order:

    1. The -Jdk8Path <path> command-line parameter.
    2. The JAVA_HOME_8 environment variable.
    3. Standard OS paths (e.g., C:\Program Files\Java\jdk1.8.0 on Windows or /usr/lib/jvm/java-8-openjdk-amd64 on Linux).
  7. Install Java-NFe via Maven

    master

    To add Java-NFe to your project using Maven, include the following dependency in your pom.xml file. Note that the version used in this example is 4.00.25.

    <dependency>
        <groupId>br.com.swconsultoria</groupId>
        <artifactId>java-nfe</artifactId>
        <version>4.00.25</version>
    </dependency>
  8. Send NFC-e (Synchronous/Asynchronous) with QR Code

    master

    Sending an NFC-e (Consumer Electronic Invoice) follows a similar pattern to NF-e but requires additional steps for QR Code generation:

    1. Construct the Model: Populate InfNFe as per the NF-e process.
    2. Generate QR Code: Use NFCeUtil.getCodeQRCode to generate the QR code string. This requires the idToken and csc (Consumer Security Code).
    3. Attach Supplementary Info: Create a TNFe.InfNFeSupl object, set the qrCode and the consultation URL (retrieved via WebServiceUtil.getUrl(config, DocumentoEnum.NFCE, ServicosEnum.URL_CONSULTANFCE)), and attach it to the infNFe.
    4. Transmit: Call Nfe.enviarNfe(config, enviNFe, DocumentoEnum.NFCE).
    5. Handle Response: Use RetornoUtil to handle asynchronous polling or synchronous validation as described in the NF-e guide.
    // ... (Setup similar to NF-e)
    
    // Generate QR Code
    String qrCode = NFCeUtil.getCodeQRCode(
        enviNFe.getNFe().get(0).getInfNFe().getId().substring(3),
        config.getAmbiente().getCodigo(),
        idToken,
        csc,
        WebServiceUtil.getUrl(config, DocumentoEnum.NFCE, ServicosEnum.URL_QRCODE)
    );
    
    // Attach Supplementary Info
    TNFe.InfNFeSupl infNFeSupl = new TNFe.InfNFeSupl();
    infNFeSupl.setQrCode(qrCode);
    infNFeSupl.setUrlChave(WebServiceUtil.getUrl(config, DocumentoEnum.NFCE, ServicosEnum.URL_CONSULTANFCE));
    enviNFe.getNFe().get(0).setInfNFeSupl(infNFeSupl);
    
    // Send
    TRetEnviNFe retorno = Nfe.enviarNfe(config, enviNFe, DocumentoEnum.NFCE);
  9. Install Java-NFe via Gradle

    master

    To add Java-NFe to your project using Gradle, ensure you have the Sonatype snapshots repository configured in your repositories block, then add the dependency to your dependencies block.

    repositories {
        maven {
            url = "https://oss.sonatype.org/content/repositories/snapshots"
        }
    }
    dependencies {
        implementation "br.com.swconsultoria:java-nfe:4.00.25"
    }
  10. Configure Proxy settings

    master

    If your network requires a proxy to communicate with external services, you can configure it on the ConfiguracoesIniciaisNfe object using the setProxy method. This method accepts the IP address, port, username, and password.

    public static ConfiguracoesIniciaisNfe iniciaConfigurações() throws NfeException {
        // Certificado Arquivo, Parametros: -Caminho Certificado, - Senha
        Certificado certificado = CertificadoService.certificadoPfx("c:/certificado/certificado.pfx", "123456");
    
        ConfiguracoesIniciaisNfe config = ConfiguracoesIniciaisNfe.iniciaConfiguracoes(Estados.GO , ConstantesUtil.AMBIENTE.HOMOLOGACAO,certificado, "C:\\SRA\\Nfe\\Schemas");
    
        String ip = "192.168.0.1";
        String porta = "3128";
        String usuario = "";
        String senha = "";
    
        config.setProxy(ip, porta, usuario , senha);
    
        return config;
    }
  11. Migrate a consumer project from v4.00.* to v4.1.1

    master

    To upgrade a project that consumes this library from version 4.00.* to 4.1.1, use the provided migration scripts. It is highly recommended to use the PowerShell version for full compatibility.

    Windows / Linux / macOS (PowerShell - Recommended):

    • Run the migration: pwsh scripts/migrate.ps1 -ProjectRoot . -BumpPom
    • Run a simulation (dry run) without changing files: pwsh scripts/migrate.ps1 -ProjectRoot . -DryRun

    Linux/macOS (Bash - Limited):

    • Run the migration: bash scripts/migrate.sh src/main/java
    # Windows / Linux / macOS (PowerShell — completo, recomendado):
    pwsh scripts/migrate.ps1 -ProjectRoot . -BumpPom
    
    # Simulacao (sem alterar arquivos):
    pwsh scripts/migrate.ps1 -ProjectRoot . -DryRun
    
    # Linux/macOS (bash — limitado):
    bash scripts/migrate.sh src/main/java