/**
 *                                  Apache License
 *                            Version 2.0, January 2004
 *                         http://www.apache.org/licenses/
 *
 *    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 *
 *    1. Definitions.
 *
 *       "License" shall mean the terms and conditions for use, reproduction,
 *       and distribution as defined by Sections 1 through 9 of this document.
 *
 *       "Licensor" shall mean the copyright owner or entity authorized by
 *       the copyright owner that is granting the License.
 *
 *       "Legal Entity" shall mean the union of the acting entity and all
 *       other entities that control, are controlled by, or are under common
 *       control with that entity. For the purposes of this definition,
 *       "control" means (i) the power, direct or indirect, to cause the
 *       direction or management of such entity, whether by contract or
 *       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 *       outstanding shares, or (iii) beneficial ownership of such entity.
 *
 *       "You" (or "Your") shall mean an individual or Legal Entity
 *       exercising permissions granted by this License.
 *
 *       "Source" form shall mean the preferred form for making modifications,
 *       including but not limited to software source code, documentation
 *       source, and configuration files.
 *
 *       "Object" form shall mean any form resulting from mechanical
 *       transformation or translation of a Source form, including but
 *       not limited to compiled object code, generated documentation,
 *       and conversions to other media types.
 *
 *       "Work" shall mean the work of authorship, whether in Source or
 *       Object form, made available under the License, as indicated by a
 *       copyright notice that is included in or attached to the work
 *       (an example is provided in the Appendix below).
 *
 *       "Derivative Works" shall mean any work, whether in Source or Object
 *       form, that is based on (or derived from) the Work and for which the
 *       editorial revisions, annotations, elaborations, or other modifications
 *       represent, as a whole, an original work of authorship. For the purposes
 *       of this License, Derivative Works shall not include works that remain
 *       separable from, or merely link (or bind by name) to the interfaces of,
 *       the Work and Derivative Works thereof.
 *
 *       "Contribution" shall mean any work of authorship, including
 *       the original version of the Work and any modifications or additions
 *       to that Work or Derivative Works thereof, that is intentionally
 *       submitted to Licensor for inclusion in the Work by the copyright owner
 *       or by an individual or Legal Entity authorized to submit on behalf of
 *       the copyright owner. For the purposes of this definition, "submitted"
 *       means any form of electronic, verbal, or written communication sent
 *       to the Licensor or its representatives, including but not limited to
 *       communication on electronic mailing lists, source code control systems,
 *       and issue tracking systems that are managed by, or on behalf of, the
 *       Licensor for the purpose of discussing and improving the Work, but
 *       excluding communication that is conspicuously marked or otherwise
 *       designated in writing by the copyright owner as "Not a Contribution."
 *
 *       "Contributor" shall mean Licensor and any individual or Legal Entity
 *       on behalf of whom a Contribution has been received by Licensor and
 *       subsequently incorporated within the Work.
 *
 *    2. Grant of Copyright License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       copyright license to reproduce, prepare Derivative Works of,
 *       publicly display, publicly perform, sublicense, and distribute the
 *       Work and such Derivative Works in Source or Object form.
 *
 *    3. Grant of Patent License. Subject to the terms and conditions of
 *       this License, each Contributor hereby grants to You a perpetual,
 *       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 *       (except as stated in this section) patent license to make, have made,
 *       use, offer to sell, sell, import, and otherwise transfer the Work,
 *       where such license applies only to those patent claims licensable
 *       by such Contributor that are necessarily infringed by their
 *       Contribution(s) alone or by combination of their Contribution(s)
 *       with the Work to which such Contribution(s) was submitted. If You
 *       institute patent litigation against any entity (including a
 *       cross-claim or counterclaim in a lawsuit) alleging that the Work
 *       or a Contribution incorporated within the Work constitutes direct
 *       or contributory patent infringement, then any patent licenses
 *       granted to You under this License for that Work shall terminate
 *       as of the date such litigation is filed.
 *
 *    4. Redistribution. You may reproduce and distribute copies of the
 *       Work or Derivative Works thereof in any medium, with or without
 *       modifications, and in Source or Object form, provided that You
 *       meet the following conditions:
 *
 *       (a) You must give any other recipients of the Work or
 *           Derivative Works a copy of this License; and
 *
 *       (b) You must cause any modified files to carry prominent notices
 *           stating that You changed the files; and
 *
 *       (c) You must retain, in the Source form of any Derivative Works
 *           that You distribute, all copyright, patent, trademark, and
 *           attribution notices from the Source form of the Work,
 *           excluding those notices that do not pertain to any part of
 *           the Derivative Works; and
 *
 *       (d) If the Work includes a "NOTICE" text file as part of its
 *           distribution, then any Derivative Works that You distribute must
 *           include a readable copy of the attribution notices contained
 *           within such NOTICE file, excluding those notices that do not
 *           pertain to any part of the Derivative Works, in at least one
 *           of the following places: within a NOTICE text file distributed
 *           as part of the Derivative Works; within the Source form or
 *           documentation, if provided along with the Derivative Works; or,
 *           within a display generated by the Derivative Works, if and
 *           wherever such third-party notices normally appear. The contents
 *           of the NOTICE file are for informational purposes only and
 *           do not modify the License. You may add Your own attribution
 *           notices within Derivative Works that You distribute, alongside
 *           or as an addendum to the NOTICE text from the Work, provided
 *           that such additional attribution notices cannot be construed
 *           as modifying the License.
 *
 *       You may add Your own copyright statement to Your modifications and
 *       may provide additional or different license terms and conditions
 *       for use, reproduction, or distribution of Your modifications, or
 *       for any such Derivative Works as a whole, provided Your use,
 *       reproduction, and distribution of the Work otherwise complies with
 *       the conditions stated in this License.
 *
 *    5. Submission of Contributions. Unless You explicitly state otherwise,
 *       any Contribution intentionally submitted for inclusion in the Work
 *       by You to the Licensor shall be under the terms and conditions of
 *       this License, without any additional terms or conditions.
 *       Notwithstanding the above, nothing herein shall supersede or modify
 *       the terms of any separate license agreement you may have executed
 *       with Licensor regarding such Contributions.
 *
 *    6. Trademarks. This License does not grant permission to use the trade
 *       names, trademarks, service marks, or product names of the Licensor,
 *       except as required for reasonable and customary use in describing the
 *       origin of the Work and reproducing the content of the NOTICE file.
 *
 *    7. Disclaimer of Warranty. Unless required by applicable law or
 *       agreed to in writing, Licensor provides the Work (and each
 *       Contributor provides its Contributions) on an "AS IS" BASIS,
 *       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *       implied, including, without limitation, any warranties or conditions
 *       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
 *       PARTICULAR PURPOSE. You are solely responsible for determining the
 *       appropriateness of using or redistributing the Work and assume any
 *       risks associated with Your exercise of permissions under this License.
 *
 *    8. Limitation of Liability. In no event and under no legal theory,
 *       whether in tort (including negligence), contract, or otherwise,
 *       unless required by applicable law (such as deliberate and grossly
 *       negligent acts) or agreed to in writing, shall any Contributor be
 *       liable to You for damages, including any direct, indirect, special,
 *       incidental, or consequential damages of any character arising as a
 *       result of this License or out of the use or inability to use the
 *       Work (including but not limited to damages for loss of goodwill,
 *       work stoppage, computer failure or malfunction, or any and all
 *       other commercial damages or losses), even if such Contributor
 *       has been advised of the possibility of such damages.
 *
 *    9. Accepting Warranty or Additional Liability. While redistributing
 *       the Work or Derivative Works thereof, You may choose to offer,
 *       and charge a fee for, acceptance of support, warranty, indemnity,
 *       or other liability obligations and/or rights consistent with this
 *       License. However, in accepting such obligations, You may act only
 *       on Your own behalf and on Your sole responsibility, not on behalf
 *       of any other Contributor, and only if You agree to indemnify,
 *       defend, and hold each Contributor harmless for any liability
 *       incurred by, or claims asserted against, such Contributor by reason
 *       of your accepting any such warranty or additional liability.
 *
 *    END OF TERMS AND CONDITIONS
 *
 *    APPENDIX: How to apply the Apache License to your work.
 *
 *       To apply the Apache License to your work, attach the following
 *       boilerplate notice, with the fields enclosed by brackets "{}"
 *       replaced with your own identifying information. (Don't include
 *       the brackets!)  The text should be enclosed in the appropriate
 *       comment syntax for the file format. We also recommend that a
 *       file or class name and description of purpose be included on the
 *       same "printed page" as the copyright notice for easier
 *       identification within third-party archives.
 *
 *    Copyright 2014 Edgar Espina
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.jooby.assets;

import org.jooby.MediaType;

import com.google.common.base.CaseFormat;
import com.typesafe.config.Config;

/**
 *
asset processor

 *

 * Checks, validate and/or modify asset contents. An {@link AssetProcessor} is usually provided as a
 * separated dependency.
 *

 *
 *
how to use it?

 *

 * First thing to do is to add the dependency:
 *

 *

 *   <dependency>
 *     <groupId>org.jooby</groupId>
 *     <artifactId>jooby-assets-my-processor</artifactId>
 *     <scope>provided</scope>
 *   </dependency>
 *

 *
 *

 * Did you see the provided scope? We just need the processor for development,
 * because assets are processed on the fly. For prod, assets are processed at
 * built-time via Maven/Gradle plugin, at runtime we don't need this. This also, helps to keep our
 * dependencies and the jar size small.
 *

 *
 *

 * Now we have the dependency all we have to do is to add it to our pipeline:
 *

 *
 *

 * assets {
 *   pipeline: {
 *     dev: [my-processor]
 *   }
 * }
 *

 *
 *
configuration

 *

 * It is possible to configure or set options too:
 *

 *
 *

 * assets {
 *   pipeline: {
 *     dev: [my-processor]
 *     dist: [my-processor]
 *   }
 *
 *   my-processor {
 *     foo: bar
 *   }
 * }
 *

 *
 *

 * Previous example, set a foo property to bar! Options can be set
 * per environment too:
 *

 *
 *

 * assets {
 *   pipeline: {
 *     dev: [my-processor]
 *     dist: [my-processor]
 *   }
 *
 *   my-processor {
 *     dev {
 *       bar: bar
 *     }
 *     dist {
 *       foo: bar
 *     }
 *     foo: foo
 *   }
 * }
 *

 *
 *

 * Here, in dev processor has two properties: foo:foo and
 * bar:bar, while in dist the processor only has foo:bar
 *

 *
 *
binding

 *

 * The my-processor will be resolved it to: org.jooby.assets.MyProcessor
 * class. The processor name is converted to MyProcessor, it converts the hyphenated
 * name to upper camel and by default processors are defined in the org.jooby.assets
 * package.
 *

 *

 * A custom binding is provided via the class property:
 *

 *

 * assets {
 *   pipeline: {
 *     dev: [my-processor]
 *     dist: [my-processor]
 *   }
 *
 *   my-processor {
 *     class: whatever.i.Want
 *   }
 * }
 *

 *
 * @author edgar
 * @since 0.11.0
 */
public abstract class AssetProcessor extends AssetOptions {

  protected EngineFactory engineFactory;

  public String name() {
    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName());
  }

  @Override
  public AssetProcessor set(final String name, final Object value) {
    super.set(name, value);
    return this;
  }

  @Override
  public AssetProcessor set(final Config options) {
    super.set(options);
    return this;
  }

  public abstract boolean matches(final MediaType type);

  /**
   * Method that processes the provided source and returns the processed contents.
   *
   * @param filename name of the file
   * @param source   contents of the file
   * @param conf     application configuration
   * @return the processed file contents
   * @throws Exception if any error occurred
   */
  public String process(String filename, String source, Config conf) throws Exception {
    return process(filename, source, conf, getClass().getClassLoader());
  }

  /**
   * Method that processes the provided source and returns the processed contents, with access to the ClassLoader.
   *
   * @param filename name of the file
   * @param source   contents of the file
   * @param conf     application configuration
   * @param loader   loader to use if any additional files need to be loaded from disk
   * @return the processed file contents
   * @throws Exception if any error occurred
   */
  public abstract String process(String filename, String source, Config conf, ClassLoader loader) throws Exception;

  /**
   * This method is executed by the {@link AssetCompiler} at processor creation time.
   *
   * @param factory Factory or null.
   * @return Asset processor.
   */
  public AssetProcessor set(EngineFactory factory) {
    this.engineFactory = factory;
    return this;
  }

  protected <T extends Engine> T engine(Class<T> type) {
    return engine(type, null);
  }

  protected <T extends Engine> T engine(Class<T> type, String scope) {
    if (engineFactory == null) {
      throw new IllegalStateException("No JavaScript engine available");
    }
    return type.cast(engineFactory.get(getClass().getSimpleName(), scope));
  }

  @Override
  public String toString() {
    return name();
  }
}


package com.fincatto.documentofiscal.cte300.webservices.recepcaoOS;

    /**
     *  CteRecepcaoOSCallbackHandler Callback class, Users can extend this class and implement
     *  their own receiveResult and receiveError methods.
     */
    public abstract class CteRecepcaoOSCallbackHandler{

        protected final Object clientData;

    /**
    * User can pass in any object that needs to be accessed once the NonBlocking
    * Web service call is finished and appropriate method of this CallBack is called.
    * @param clientData Object mechanism by which the user can pass in user data
    * that will be avilable at the time this callback is called.
    */
    public CteRecepcaoOSCallbackHandler(Object clientData){
        this.clientData = clientData;
    }

    /**
    * Please use this constructor if you don't want to set any clientData
    */
    public CteRecepcaoOSCallbackHandler(){
        this.clientData = null;
    }

    /**
     * Get the client data
     */

     public Object getClientData() {
        return clientData;
     }

           /**
            * auto generated Axis2 call back method for cteRecepcaoOS method
            * override this method for handling normal response from cteRecepcaoOS operation
            */
           public void receiveResultcteRecepcaoOS(
                    com.fincatto.documentofiscal.cte300.webservices.recepcaoOS.CteRecepcaoOSStub.CteRecepcaoOSResult result
                        ) {
           }

          /**
           * auto generated Axis2 Error handler
           * override this method for handling error response from cteRecepcaoOS operation
           */
            public void receiveErrorcteRecepcaoOS(java.lang.Exception e) {
            }

    }


/*
  MDFeRecepcaoCallbackHandler.java
  <p>
  This file was auto-generated from WSDL
  by the Apache Axis2 version: 1.6.2  Built on : Apr 17, 2012 (05:33:49 IST)
 */

package com.fincatto.documentofiscal.mdfe3.webservices.recepcao;

/**
 *  MDFeRecepcaoCallbackHandler Callback class, Users can extend this class and implement
 *  their own receiveResult and receiveError methods.
 */
public abstract class MDFeRecepcaoCallbackHandler {

    protected final Object clientData;

    /**
     * User can pass in any object that needs to be accessed once the NonBlocking
     * Web service call is finished and appropriate method of this CallBack is called.
     * @param clientData Object mechanism by which the user can pass in user data
     * that will be avilable at the time this callback is called.
     */
    public MDFeRecepcaoCallbackHandler(Object clientData) {
        this.clientData = clientData;
    }

    /**
     * Please use this constructor if you don't want to set any clientData
     */
    public MDFeRecepcaoCallbackHandler() {
        this.clientData = null;
    }

    /**
     * Get the client data
     */

    public Object getClientData() {
        return clientData;
    }

    /**
     * auto generated Axis2 call back method for mdfeRecepcaoLote method
     * override this method for handling normal response from mdfeRecepcaoLote operation
     */
    public void receiveResultmdfeRecepcaoLote(
            com.fincatto.documentofiscal.mdfe3.webservices.recepcao.MDFeRecepcaoStub.MdfeRecepcaoLoteResult result
    ) {
    }

    /**
     * auto generated Axis2 Error handler
     * override this method for handling error response from mdfeRecepcaoLote operation
     */
    public void receiveErrormdfeRecepcaoLote(java.lang.Exception e) {
    }

}


package com.fincatto.documentofiscal.mdfe3.classes.nota;

import java.util.List;

import org.simpleframework.xml.*;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.ListValidador;
import com.fincatto.documentofiscal.validadores.StringValidador;

/**
 * Created by Eldevan Nery Junior on 03/11/17. Informações do MDF-e.
 */
@Root(name = "infMDFe")
@Namespace(reference = "http://www.portalfiscal.inf.br/mdfe")
public class MDFInfo extends DFBase {
    private static final long serialVersionUID = 5215463851140624452L;

    public static final String IDENT = "MDFe";

    @Attribute(name = "Id")
    private String identificador;
    /**
     * Tipo Versão do MDF-e - 3.00.
     */
    @Attribute(name = "versao")
    private String versao = MDFe.VERSAO;

    @Element(name = "ide")
    private MDFInfoIdentificacao identificacao;

    @Element(name = "emit")
    private MDFInfoEmitente emitente;

    @Element(name = "infModal")
    private MDFInfoModal mdfInfoModal;

    /**
     * Informações dos Documentos fiscais vinculados ao manifesto.
     */
    @Element(name = "infDoc")
    private MDFInfoInformacoesDocumentos informacoesDocumentos;

    @ElementList(name = "seg", inline = true, required = false)
    private List<MDFInfoSeguro> seguro;

    @Element(name = "tot")
    private MDFInfoTotal infoTotal;

    @ElementList(entry = "lacres", inline = true, required = false)
    private List<MDFInfoLacre1A60> lacres;

    @ElementList(name = "autXML", inline = true, required = false)
    private List<MDFInfoAutorizacaoDownload> autorizacaoDownload;

    @Element(name = "infAdic", required = false)
    private MDFInfoInformacoesAdicionais informacoesAdicionais;

    public String getIdentificador() {
        return this.identificador;
    }

    /**
     * Identificador da tag a ser assinada

     * Informar a chave de acesso do MDF-e e precedida do literal "MDFe"
     */
    public void setIdentificador(final String identificador) {
        StringValidador.exatamente44N(identificador, "Identificador");
        this.identificador = MDFInfo.IDENT + identificador;
    }

    /**
     * Retorna a chave de acesso a partir do identificador.
     * @return Chave de acesso.
     */
    public String getChaveAcesso() {
        return this.identificador.replace(MDFInfo.IDENT, "");
    }

    public MDFInfoIdentificacao getIdentificacao() {
        return this.identificacao;
    }

    public MDFInfoEmitente getEmitente() {
        return this.emitente;
    }

    /**
     * Identificação do Emitente do MDF-e
     */
    public void setEmitente(final MDFInfoEmitente emitente) {
        this.emitente = emitente;
    }

    public List<MDFInfoAutorizacaoDownload> getAutorizacaoDownload() {
        return this.autorizacaoDownload;
    }

    /**
     * Autorizados para download do XML do DF-e

     * Informar CNPJ ou CPF. Preencher os zeros não significativos.
     */
    public void setAutorizacaoDownload(final List<MDFInfoAutorizacaoDownload> autorizacaoDownload) {
        ListValidador.tamanho10(autorizacaoDownload, "Autorizados para download do XML do DF-e");
        this.autorizacaoDownload = autorizacaoDownload;
    }

    public String getVersao() {
        return this.versao;
    }

    /**
     * Versão do leiaute
     */
    public void setVersao(final String versao) {
        StringValidador.equals(MDFe.VERSAO, versao);
        this.versao = versao;
    }

    public void setIdentificacao(final MDFInfoIdentificacao identificacao) {
        this.identificacao = identificacao;
    }

    public MDFInfoModal getMdfInfoModal() {
        return this.mdfInfoModal;
    }

    public void setMdfInfoModal(final MDFInfoModal mdfInfoModal) {
        this.mdfInfoModal = mdfInfoModal;
    }

    public MDFInfoInformacoesDocumentos getInformacoesDocumentos() {
        return this.informacoesDocumentos;
    }

    public void setInformacoesDocumentos(final MDFInfoInformacoesDocumentos informacoesDocumentos) {
        this.informacoesDocumentos = informacoesDocumentos;
    }

    public MDFInfoTotal getInfoTotal() {
        return this.infoTotal;
    }

    public void setInfoTotal(final MDFInfoTotal infoTotal) {
        this.infoTotal = infoTotal;
    }

    public List<MDFInfoLacre1A60> getLacres() {
        return this.lacres;
    }

    public void setLacres(final List<MDFInfoLacre1A60> lacres) {
        this.lacres = lacres;
    }

    public MDFInfoInformacoesAdicionais getInformacoesAdicionais() {
        return this.informacoesAdicionais;
    }

    public void setInformacoesAdicionais(final MDFInfoInformacoesAdicionais informacoesAdicionais) {
        this.informacoesAdicionais = informacoesAdicionais;
    }

    public List<MDFInfoSeguro> getSeguro() {
        return this.seguro;
    }

    public void setSeguro(final List<MDFInfoSeguro> seguro) {
        this.seguro = seguro;
    }
}


package com.fincatto.documentofiscal.cte300.webservices.inutilizacao;

    /**
     *  CteInutilizacaoCallbackHandler Callback class, Users can extend this class and implement
     *  their own receiveResult and receiveError methods.
     */
    public abstract class CteInutilizacaoCallbackHandler{

        protected final Object clientData;

    /**
    * User can pass in any object that needs to be accessed once the NonBlocking
    * Web service call is finished and appropriate method of this CallBack is called.
    * @param clientData Object mechanism by which the user can pass in user data
    * that will be avilable at the time this callback is called.
    */
    public CteInutilizacaoCallbackHandler(Object clientData){
        this.clientData = clientData;
    }

    /**
    * Please use this constructor if you don't want to set any clientData
    */
    public CteInutilizacaoCallbackHandler(){
        this.clientData = null;
    }

    /**
     * Get the client data
     */

     public Object getClientData() {
        return clientData;
     }

           /**
            * auto generated Axis2 call back method for cteInutilizacaoCT method
            * override this method for handling normal response from cteInutilizacaoCT operation
            */
           public void receiveResultcteInutilizacaoCT(
                    com.fincatto.documentofiscal.cte300.webservices.inutilizacao.CteInutilizacaoStub.CteInutilizacaoCTResult result
                        ) {
           }

          /**
           * auto generated Axis2 Error handler
           * override this method for handling error response from cteInutilizacaoCT operation
           */
            public void receiveErrorcteInutilizacaoCT(java.lang.Exception e) {
            }

    }


/*
  MDFeRecepcaoEventoCallbackHandler.java
  <p>
  This file was auto-generated from WSDL
  by the Apache Axis2 version: 1.6.2  Built on : Apr 17, 2012 (05:33:49 IST)
 */

package com.fincatto.documentofiscal.mdfe3.webservices.recepcaoevento;

/**
 *  MDFeRecepcaoEventoCallbackHandler Callback class, Users can extend this class and implement
 *  their own receiveResult and receiveError methods.
 */
public abstract class MDFeRecepcaoEventoCallbackHandler {

    protected final Object clientData;

    /**
     * User can pass in any object that needs to be accessed once the NonBlocking
     * Web service call is finished and appropriate method of this CallBack is called.
     * @param clientData Object mechanism by which the user can pass in user data
     * that will be avilable at the time this callback is called.
     */
    public MDFeRecepcaoEventoCallbackHandler(Object clientData) {
        this.clientData = clientData;
    }

    /**
     * Please use this constructor if you don't want to set any clientData
     */
    public MDFeRecepcaoEventoCallbackHandler() {
        this.clientData = null;
    }

    /**
     * Get the client data
     */

    public Object getClientData() {
        return clientData;
    }

    /**
     * auto generated Axis2 call back method for mdfeRecepcaoEvento method
     * override this method for handling normal response from mdfeRecepcaoEvento operation
     */
    public void receiveResultmdfeRecepcaoEvento(
            com.fincatto.documentofiscal.mdfe3.webservices.recepcaoevento.MDFeRecepcaoEventoStub.MdfeRecepcaoEventoResult result
    ) {
    }

    /**
     * auto generated Axis2 Error handler
     * override this method for handling error response from mdfeRecepcaoEvento operation
     */
    public void receiveErrormdfeRecepcaoEvento(java.lang.Exception e) {
    }

}


package com.fincatto.documentofiscal.cte300.classes.nota;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.StringValidador;

/**
 * @author Caio
 * @info Informações do Recebedor da Carga
 */

@Root(name = "receb")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeNotaInfoRecebedorCarga extends DFBase {
    private static final long serialVersionUID = 4807226772679103277L;

    @Element(name = "CNPJ", required = false)
    private String cnpj;

    @Element(name = "CPF", required = false)
    private String cpf;

    @Element(name = "IE", required = false)
    private String inscricaoEstadual;

    @Element(name = "xNome", required = true)
    private String razaoSocial;

    @Element(name = "fone", required = false)
    private String telefone;

    @Element(name = "enderReceb", required = true)
    private CTeNotaEndereco endereco;

    @Element(name = "email", required = false)
    private String email;

    public CTeNotaInfoRecebedorCarga() {
        this.cnpj = null;
        this.cpf = null;
        this.inscricaoEstadual = null;
        this.razaoSocial = null;
        this.telefone = null;
        this.endereco = null;
        this.email = null;
    }

    public String getCnpj() {
        return this.cnpj;
    }

    /**
     * Número do CNPJ

     * Em caso de empresa não estabelecida no Brasil, será informado o CNPJ com zeros. Informar os zeros não significativos.
     */
    public void setCnpj(final String cnpj) {
        StringValidador.cnpj(cnpj);
        this.cnpj = cnpj;
    }

    public String getCpf() {
        return this.cpf;
    }

    /**
     * Número do CPF

     * Informar os zeros não significativos.
     */
    public void setCpf(final String cpf) {
        StringValidador.cpf(cpf);
        this.cpf = cpf;
    }

    public String getInscricaoEstadual() {
        return this.inscricaoEstadual;
    }

    /**
     * Inscrição Estadual

     * Informar a IE do recebedor ou ISENTO se recebedor é contribuinte do ICMS isento de inscrição no cadastro de contribuintes do ICMS. Caso o recebedor não seja contribuinte do ICMS não informar o conteúdo.
     */
    public void setInscricaoEstadual(final String inscricaoEstadual) {
        StringValidador.inscricaoEstadual(inscricaoEstadual);
        this.inscricaoEstadual = inscricaoEstadual;
    }

    public String getRazaoSocial() {
        return this.razaoSocial;
    }

    /**
     * Razão Social ou Nome
     */
    public void setRazaoSocial(final String razaoSocial) {
        StringValidador.tamanho2ate60(razaoSocial, "Razão Social ou Nome");
        this.razaoSocial = razaoSocial;
    }

    public String getTelefone() {
        return this.telefone;
    }

    /**
     * Telefone
     */
    public void setTelefone(final String telefone) {
        StringValidador.telefone(telefone);
        this.telefone = telefone;
    }

    public CTeNotaEndereco getEndereco() {
        return this.endereco;
    }

    /**
     * Dados do endereço
     */
    public void setEndereco(final CTeNotaEndereco endereco) {
        this.endereco = endereco;
    }

    public String getEmail() {
        return this.email;
    }

    /**
     * Endereço de email
     */
    public void setEmail(final String email) {
        StringValidador.tamanho60(email, "Endereço de email");
        StringValidador.email(email);
        this.email = email;
    }
}


package com.fincatto.documentofiscal.cte.webservices.distribuicao;

import com.fincatto.documentofiscal.DFSocketFactory;
import com.fincatto.documentofiscal.cte.classes.distribuicao.CTDistribuicaoInt;
import com.fincatto.documentofiscal.cte200.classes.CTAutorizador;
import com.fincatto.documentofiscal.nfe.NFeConfig;
import com.fincatto.documentofiscal.transformers.DFRegistryMatcher;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.httpclient.protocol.Protocol;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;

import javax.xml.stream.XMLStreamException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;

public class WSDistribuicaoCTe {

    /**
     * Metodo para consultar os conhecimentos de transporte e retorna uma String

     * É importante salvar esta String para não perder nenhuma informacao

     * A receita não disponibiliza o conhecimento várias vezes para consultar, retorna rejeicao: Consumo indevido
     */
    public static String consultar(final CTDistribuicaoInt distDFeInt, final NFeConfig config) throws Exception {
        Protocol.registerProtocol("https", new Protocol("https", new DFSocketFactory(config), 443));
        try {
            final OMElement ome = AXIOMUtil.stringToOM(distDFeInt.toString());

            final CTeDistribuicaoDFeSoapStub.CteDadosMsg_type0 dadosMsgType0 = new CTeDistribuicaoDFeSoapStub.CteDadosMsg_type0();
            dadosMsgType0.setExtraElement(ome);

            final CTeDistribuicaoDFeSoapStub.CteDistDFeInteresse distDFeInteresse = new CTeDistribuicaoDFeSoapStub.CteDistDFeInteresse();
            distDFeInteresse.setCteDadosMsg(dadosMsgType0);

            final CTeDistribuicaoDFeSoapStub stub = new CTeDistribuicaoDFeSoapStub(CTAutorizador.AN.getDistribuicaoDFe(config.getAmbiente()));
            final CTeDistribuicaoDFeSoapStub.CteDistDFeInteresseResponse result = stub.cteDistDFeInteresse(distDFeInteresse);

            return result.getCteDistDFeInteresseResult().getExtraElement().toString();
        } catch (RemoteException | XMLStreamException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static String decodeGZipToXml(final String conteudoEncode) throws Exception {
        if (conteudoEncode == null || conteudoEncode.length() == 0) {
            return "";
        }
        final byte[] conteudo = Base64.getDecoder().decode(conteudoEncode);//java 8
        //final byte[] conteudo = DatatypeConverter.parseBase64Binary(conteudoEncode);//java 7
        try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(conteudo))) {
            try (BufferedReader bf = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8))) {
                StringBuilder outStr = new StringBuilder();
                String line;
                while ((line = bf.readLine()) != null) {
                    outStr.append(line);
                }
                return outStr.toString();
            }
        }
    }

    public static <T> T xmlToObject(final String xml, final Class<T> classe) throws Exception {
        return new Persister(new DFRegistryMatcher(), new Format(0)).read(classe, xml);
    }
}


package com.fincatto.documentofiscal.nfe400.parsers;

import java.io.File;

import org.simpleframework.xml.core.Persister;

import com.fincatto.documentofiscal.cte300.classes.enviolote.CTeEnvioLote;
import com.fincatto.documentofiscal.cte300.classes.nota.CTeProcessado;
import com.fincatto.documentofiscal.mdfe3.classes.lote.envio.MDFEnvioLote;
import com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento.NFEnviaEventoCancelamento;
import com.fincatto.documentofiscal.nfe400.classes.evento.cartacorrecao.NFEnviaEventoCartaCorrecao;
import com.fincatto.documentofiscal.nfe400.classes.evento.inutilizacao.NFEnviaEventoInutilizacao;
import com.fincatto.documentofiscal.nfe400.classes.lote.envio.NFLoteEnvio;
import com.fincatto.documentofiscal.nfe400.classes.nota.NFNota;
import com.fincatto.documentofiscal.nfe400.classes.nota.NFNotaInfoItem;
import com.fincatto.documentofiscal.nfe400.classes.nota.NFNotaProcessada;
import com.fincatto.documentofiscal.persister.DFPersister;

public class DFParser {

    private final Persister persister;

    public DFParser() {
        this.persister = new DFPersister();
    }

    // NFe/NFCe
    public NFNota notaParaObjeto(final File xml) {
        try {
            return this.persister.read(NFNota.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFNota notaParaObjeto(final String xml) {
        try {
            return this.persister.read(NFNota.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFLoteEnvio loteParaObjeto(final File xml) {
        try {
            return this.persister.read(NFLoteEnvio.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFLoteEnvio loteParaObjeto(final String xml) {
        try {
            return this.persister.read(NFLoteEnvio.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFNotaProcessada notaProcessadaParaObjeto(final String xml) {
        try {
            return this.persister.read(NFNotaProcessada.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFNotaProcessada notaProcessadaParaObjeto(final File xml) {
        try {
            return this.persister.read(NFNotaProcessada.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoCartaCorrecao enviaEventoCartaCorrecaoParaObjeto(final File xml) {
        try {
            return this.persister.read(NFEnviaEventoCartaCorrecao.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoCartaCorrecao enviaEventoCartaCorrecaoParaObjeto(final String xml) {
        try {
            return this.persister.read(NFEnviaEventoCartaCorrecao.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoCancelamento enviaEventoCancelamentoParaObjeto(final File xml) {
        try {
            return this.persister.read(NFEnviaEventoCancelamento.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoCancelamento enviaEventoCancelamentoParaObjeto(final String xml) {
        try {
            return this.persister.read(NFEnviaEventoCancelamento.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoInutilizacao enviaEventoInutilizacaoParaObjeto(final File xml) {
        try {
            return this.persister.read(NFEnviaEventoInutilizacao.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFEnviaEventoInutilizacao enviaEventoInutilizacaoParaObjeto(final String xml) {
        try {
            return this.persister.read(NFEnviaEventoInutilizacao.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public NFNotaInfoItem notaInfoItemParaObjeto(final String xml) {
        try {
            return this.persister.read(NFNotaInfoItem.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    // CTe
    public CTeEnvioLote cteRecepcaoParaObjeto(final String xml) {
        try {
            return this.persister.read(CTeEnvioLote.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    public CTeProcessado cteProcessadoParaObjeto(final String xml) {
        try {
            return this.persister.read(CTeProcessado.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    // MDFe
    public MDFEnvioLote mdfeRecepcaoParaObjeto(final String xml) {
        try {
            return this.persister.read(MDFEnvioLote.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml do Lote MDFe: %s", e.getMessage()));
        }
    }

}


package com.fincatto.documentofiscal.cte300.webservices.consulta;

    /**
     *  CteConsultaCallbackHandler Callback class, Users can extend this class and implement
     *  their own receiveResult and receiveError methods.
     */
    public abstract class CteConsultaCallbackHandler{

        protected final Object clientData;

    /**
    * User can pass in any object that needs to be accessed once the NonBlocking
    * Web service call is finished and appropriate method of this CallBack is called.
    * @param clientData Object mechanism by which the user can pass in user data
    * that will be avilable at the time this callback is called.
    */
    public CteConsultaCallbackHandler(Object clientData){
        this.clientData = clientData;
    }

    /**
    * Please use this constructor if you don't want to set any clientData
    */
    public CteConsultaCallbackHandler(){
        this.clientData = null;
    }

    /**
     * Get the client data
     */

     public Object getClientData() {
        return clientData;
     }

           /**
            * auto generated Axis2 call back method for cteConsultaCT method
            * override this method for handling normal response from cteConsultaCT operation
            */
           public void receiveResultcteConsultaCT(
                    com.fincatto.documentofiscal.cte300.webservices.consulta.CteConsultaStub.CteConsultaCTResult result
                        ) {
           }

          /**
           * auto generated Axis2 Error handler
           * override this method for handling error response from cteConsultaCT operation
           */
            public void receiveErrorcteConsultaCT(java.lang.Exception e) {
            }

    }


/*
  MDFeConsNaoEncCallbackHandler.java
  <p>
  This file was auto-generated from WSDL
  by the Apache Axis2 version: 1.6.2  Built on : Apr 17, 2012 (05:33:49 IST)
 */

package com.fincatto.documentofiscal.mdfe3.webservices.consultanaoencerrado;

/**
 *  MDFeConsNaoEncCallbackHandler Callback class, Users can extend this class and implement
 *  their own receiveResult and receiveError methods.
 */
public abstract class MDFeConsNaoEncCallbackHandler {

    protected final Object clientData;

    /**
     * User can pass in any object that needs to be accessed once the NonBlocking
     * Web service call is finished and appropriate method of this CallBack is called.
     * @param clientData Object mechanism by which the user can pass in user data
     * that will be avilable at the time this callback is called.
     */
    public MDFeConsNaoEncCallbackHandler(Object clientData) {
        this.clientData = clientData;
    }

    /**
     * Please use this constructor if you don't want to set any clientData
     */
    public MDFeConsNaoEncCallbackHandler() {
        this.clientData = null;
    }

    /**
     * Get the client data
     */

    public Object getClientData() {
        return clientData;
    }

    /**
     * auto generated Axis2 call back method for mdfeConsNaoEnc method
     * override this method for handling normal response from mdfeConsNaoEnc operation
     */
    public void receiveResultmdfeConsNaoEnc(
            com.fincatto.documentofiscal.mdfe3.webservices.consultanaoencerrado.MDFeConsNaoEncStub.MdfeConsNaoEncResult result
    ) {
    }

    /**
     * auto generated Axis2 Error handler
     * override this method for handling error response from mdfeConsNaoEnc operation
     */
    public void receiveErrormdfeConsNaoEnc(java.lang.Exception e) {
    }

}


package com.fincatto.documentofiscal.mdfe3.classes.parsers;

import com.fincatto.documentofiscal.mdfe3.classes.lote.envio.MDFEnvioLote;
import com.fincatto.documentofiscal.mdfe3.classes.nota.MDFProcessado;
import com.fincatto.documentofiscal.mdfe3.classes.nota.MDFe;
import com.fincatto.documentofiscal.mdfe3.classes.nota.evento.MDFeEvento;
import com.fincatto.documentofiscal.persister.DFPersister;
import java.io.File;
import org.simpleframework.xml.core.Persister;

/**
 *
 * @author Edivaldo Merlo Stens on 06/10/2018
 */
public class MDFeParser {

    private final Persister persister;

    public MDFeParser() {
        this.persister = new DFPersister();
    }

    /**
     * Transforma arquivo XML (tag: MDFe) para objeto (MDFe)
     *
     * @param xml
     * @return
     */
    public MDFe mdfeParaObjeto(final File xml) {
        try {
            return this.persister.read(MDFe.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    /**
     * Transforma string XML (tag: MDFe) para objeto (MDFe)
     *
     * @param xml
     * @return
     */
    public MDFe mdfeParaObjeto(final String xml) {
        try {
            return this.persister.read(MDFe.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    /**
     * Transforma string XML (tag: enviMDFe) para objeto (MDFEnvioLote)
     *
     * @param xml
     * @return
     */
    public MDFEnvioLote mdfeRecepcaoParaObjeto(final String xml) {
        try {
            return this.persister.read(MDFEnvioLote.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml do Lote MDFe: %s", e.getMessage()));
        }
    }

    /**
     * Transforma string XML (tag: mdfeProc) para objeto (MDFProcessado)
     *
     * @param xml
     * @return
     */
    public MDFProcessado mdfeProcessadoParaObjeto(final String xml) {
        try {
            return this.persister.read(MDFProcessado.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    /**
     * Transforma arquivo XML (tag: mdfeProc) para objeto (MDFProcessado)
     *
     * @param xml
     * @return
     */
    public MDFProcessado mdfeProcessadoParaObjeto(final File xml) {
        try {
            return this.persister.read(MDFProcessado.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    /**
     * Transforma string XML (tag: eventoMDFe) para objeto (MDFeEvento)
     *
     * @param xml
     * @return
     */
    public MDFeEvento mdfeEventoParaObjeto(final String xml) {
        try {
            return this.persister.read(MDFeEvento.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }

    /**
     * Transforma arquivo XML (tag: eventoMDFe) para objeto (MDFeEvento)
     *
     * @param xml
     * @return
     */
    public MDFeEvento mdfeEventoParaObjeto(final File xml) {
        try {
            return this.persister.read(MDFeEvento.class, xml);
        } catch (final Exception e) {
            throw new IllegalArgumentException(String.format("Nao foi possivel parsear o xml: %s", e.getMessage()));
        }
    }
}


package com.fincatto.documentofiscal.validadores;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class StringValidador {

    public static void mmaaaa(final String mmaaaa) {
        if (mmaaaa != null) {
            try {
                DateTimeFormatter.ofPattern("mm/yyyy").parse(mmaaaa);
            } catch (final Exception e) {
                throw new IllegalStateException(String.format("Formato invalido (mm/aaaa) (%s)", mmaaaa));
            }
        }
    }

    public static void aamm(final String aamm) {
        if (aamm != null) {
            try {
                DateTimeFormatter.ofPattern("yymm").parse(aamm);
            } catch (final Exception e) {
                throw new IllegalStateException(String.format("Formato invalido (aamm) (%s)", aamm));
            }
        }
    }

    public static void codigoDeBarras(final String codigoDeBarras) {
        if (codigoDeBarras != null) {
            final Matcher matcher = Pattern.compile("^([0-9]{0}|[0-9]{8}|[0-9]{12,14}|SEM GTIN)$").matcher(codigoDeBarras);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Codigo de barras com formato invalido (%s)", codigoDeBarras));
            }
        }
    }

    public static void telefone(final String telefone) {
        if (telefone != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{6,14}$").matcher(telefone);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Telefone de tamanho invalido (%s)", telefone));
            }
        }
    }

    public static String telefone(final String telefone, final String info) {
        if (telefone != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{6,14}$").matcher(telefone);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Telefone de tamanho invalido (%s) em %s", telefone, info));
            }
        }
        return telefone;
    }

    public static void email(final String email) {
        if (email != null) {
            final String regex = "^([_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{1,6}))?$";
            final Matcher matcher = Pattern.compile(regex).matcher(email);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Email invalido (%s)", email));
            }
        }
    }

    public static String email(final String email, final String info) {
        if (email != null) {
            final String regex = "^([_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{1,6}))?$";
            final Matcher matcher = Pattern.compile(regex).matcher(email);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Email invalido (%s) em %s", email, info));
            }
        }
        return email;
    }

    public static void tamanho256(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 256, info);
        }
    }

    public static void tamanho9(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 9, info);
        }
    }

    public static void tamanho60(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 60, info);
        }
    }

    public static void tamanho2ate60(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 2, 60, info);
        }
    }

    public static void tamanho2ate40(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 2, 40, info);
        }
    }

    public static void tamanho2ate255(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 2, 255, info);
        }
    }

    public static void tamanho22(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 22, info);
        }
    }

    public static void tamanho21(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 21, info);
        }
    }

    public static void tamanho20(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 20, info);
        }
    }

    public static void tamanho20N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.tamanho20(string, info);
        }
    }

    public static void tamanho2000(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 2000, info);
        }
    }

    public static void tamanho5000(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 5000, info);
        }
    }

    public static void tamanho40(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 40, info);
        }
    }

    public static void placaDeVeiculo(final String placaVeiculo) {
        if (placaVeiculo != null) {
            final Matcher matcher = Pattern.compile("^([A-Z]{2,3}[0-9]{4}|[A-Z]{3,4}[0-9]{3}|[A-Z]{3}[0-9][A-Z][0-9]{2})$").matcher(placaVeiculo);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Placa de veiculo nao esta no padrao (%s)", placaVeiculo));
            }
        }
    }

    public static void placaDeVeiculo(final String placaVeiculo, final String info) {
        if (placaVeiculo != null) {
            final Matcher matcher = Pattern.compile("^([A-Z]{2,3}[0-9]{4}|[A-Z]{3,4}[0-9]{3}|[A-Z]{3}[0-9][A-Z][0-9]{2})$").matcher(placaVeiculo);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("%s nao esta no padrao (%s)", info, placaVeiculo));
            }
        }
    }

    public static void cnpj(final String cnpj) {
        if (cnpj != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{14}$").matcher(cnpj);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Formato CNPJ Invalido (%s)", cnpj));
            }
        }
    }

    public static String cnpj(final String cnpj, final String info) {
        if (cnpj != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{14}$").matcher(cnpj);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Formato CNPJ Invalido (%s) em %s", cnpj, info));
            }
        }
        return cnpj;
    }

    public static void cpf(final String cpf) {
        if (cpf != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{11}$").matcher(cpf);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Formato CPF Invalido (%s)", cpf));
            }
        }
    }

    public static String cpf(final String cpf, final String info) {
        if (cpf != null) {
            final Matcher matcher = Pattern.compile("^[0-9]{11}$").matcher(cpf);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Formato CPF Invalido (%s) em %s", cpf, info));
            }
        }
        return cpf;
    }

    public static void inscricaoEstadual(final String inscricaoEstadual) {
        if (inscricaoEstadual != null) {
            final Matcher matcher = Pattern.compile("^(ISENTO|[0-9]{2,14}|)$").matcher(inscricaoEstadual);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Inscricao estadual invalido (%s)", inscricaoEstadual));
            }
        }
    }

    public static void inscricaoEstadualSemIsencao(final String inscricaoEstadual) {
        if (inscricaoEstadual != null) {
            final Matcher matcher = Pattern.compile("^([0-9]{2,14}|)$").matcher(inscricaoEstadual);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Inscricao estadual invalido (%s)", inscricaoEstadual));
            }
        }
    }

    public static String inscricaoEstadualSemIsencao(final String inscricaoEstadual, final String info) {
        if (inscricaoEstadual != null) {
            final Matcher matcher = Pattern.compile("^([0-9]{2,14}|)$").matcher(inscricaoEstadual);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Inscricao estadual invalido (%s) em %s", inscricaoEstadual, info));
            }
        }
        return inscricaoEstadual;
    }

    public static void exatamente3(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 3, info);
        }
    }

    public static void exatamente5(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 5, info);
        }
    }

    public static void exatamente9(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 9, info);
        }
    }

    public static void exatamente9N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoExato(string, 9, info);
        }
    }

    public static void exatamente17(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 17, info);
        }
    }

    public static void exatamente4(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 4, info);
        }
    }

    public static void exatamente6(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 6, info);
        }
    }

    public static void exatamente21(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 21, info);
        }
    }

    public static void exatamente1(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 1, info);
        }
    }

    public static void exatamente13(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 13, info);
        }
    }

    public static void tamanho15(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 15, info);
        }
    }

    public static void tamanho12(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 12, info);
        }
    }

    public static void tamanho120(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 120, info);
        }
    }

    public static void tamanho160(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 160, info);
        }
    }

    public static void tamanho10(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 10, info);
        }
    }

    public static void tamanho10N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 10, info);
        }
    }

    public static void tamanho100(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 100, info);
        }
    }

    public static void tamanho6(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 6, info);
        }
    }

    public static void tamanho6N(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 6, info);
        }
    }

    public static void tamanho500(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 500, info);
        }
    }

    public static void tamanho3(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 3, info);
        }
    }

    public static void exatamente7(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 7, info);
        }
    }

    public static void exatamente8(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 8, info);
        }
    }

    public static void exatamente8N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoExato(string, 8, info);
        }
    }

    public static void exatamente2(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 2, info);
        }
    }

    public static void exatamente2N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoExato(string, 2, info);
        }
    }

    public static void tamanho8a9(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 8, 9, info);
        }
    }

    public static void tamanho15a256(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 15, 256, info);
        }
    }

    public static void tamanho15a255(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 15, 255, info);
        }
    }

    public static void tamanho5a20(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 5, 20, info);
        }
    }

    public static void tamanho5a14(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 5, 14, info);
        }
    }

    public static void tamanho5a60(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 5, 60, info);
        }
    }

    public static void tamanho2a4(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 2, 4, info);
        }
    }

    public static void tamanho2a9N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.intervalo(string, 2, 9, info);
        }
    }

    public static void tamanho8a9N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.intervalo(string, 8, 9, info);
        }
    }

    public static void tamanho15a1000(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 15, 1000, info);
        }
    }

    public static void tamanho100a600(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 100, 600, info);
        }
    }

    public static void tamanho2a95(final String string, final String info) {
        if (string != null) {
            StringValidador.intervalo(string, 2, 95, info);
        }
    }

    public static void tamanho30(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 30, info);
        }
    }

    public static void exatamente44(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoExato(string, 44, info);
        }
    }

    public static void exatamente7N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.exatamente7(string, info);
        }
    }

    public static void exatamente44N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.exatamente44(string, info);
        }
    }

    public static void exatamente4N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.exatamente4(string, info);
        }
    }

    public static void exatamente6N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.exatamente6(string, info);
        }
    }

    public static void tamanho15N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 15, info);
        }
    }

    public static void tamanho14N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 14, info);
        }
    }

    public static void tamanho4(final String string, final String info) {
        if (string != null) {
            StringValidador.validaTamanhoMaximo(string, 4, info);
        }
    }

    public static void tamanho4N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 4, info);
        }
    }

    public static void tamanho9N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 9, info);
        }
    }

    public static void tamanho2ou3N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.intervalo(string, 2, 3, info);
        }
    }

    public static void tamanho3N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 3, info);
        }
    }

    public static void tamanho2N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoMaximo(string, 2, info);
        }
    }

    public static void exatamente20N(final String string, final String info) {
        if (string != null) {
            StringValidador.apenasNumerico(string, info);
            StringValidador.validaTamanhoExato(string, 20, info);
        }
    }

    /**
     * Método para validação de Strings.
     * @param paraValidar String a ser validada
     * @param info Informação de retorno caso haja erro.
     * @param tamanho tamanho para validação da {@code String} , pode ser {@code null} :
     * @param exatamente <pre>
     * se false {@code null} a {@code String}
     *                   não precisa ter o tamanho exato do parametro anterior.
     * </pre>
     * @param numerico se true {@code null} a {@code String} precisa ser numérica[0-9].
     * @param paraValidar}.
     * @return retorna a própria {@code String} {
     */
    public static String validador(final String paraValidar, final String info, Integer tamanho, Boolean exatamente, Boolean numerico) {
        tamanho = ObjectUtils.defaultIfNull(tamanho, 1);
        exatamente = ObjectUtils.defaultIfNull(exatamente, false);
        numerico = ObjectUtils.defaultIfNull(numerico, true);
        if (paraValidar != null) {
            if (numerico) {
                StringValidador.apenasNumerico(paraValidar, info);
            }
            if (exatamente) {
                StringValidador.validaTamanhoExato(paraValidar, tamanho, info);
            } else {
                StringValidador.validaTamanhoMaximo(paraValidar, tamanho, info);
            }
        }
        return paraValidar;
    }

    /**
     * @See #validador
     */
    public static String validador(final String paraValidar, final String info, final Integer tamanho, final Boolean exatamente) {
        return StringValidador.validador(paraValidar, info, tamanho, exatamente, null);
    }

    /**
     * @See #validador
     */
    public static String validador(final String paraValidar, final String info, final Integer tamanho) {
        return StringValidador.validador(paraValidar, info, tamanho, null, null);
    }

    public static void fci(final String numeroControleFCI) {
        if (numeroControleFCI != null) {
            final Matcher matcher = Pattern.compile("^([A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12})$").matcher(numeroControleFCI);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("FCI fora do padrao (%s)", numeroControleFCI));
            }
        }
    }

    public static void ncm(final String ncm) {
        if (ncm != null) {
            final Matcher matcher = Pattern.compile("^([0-9]{2}|[0-9]{8})$").matcher(ncm);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("NCM fora do padrao (%s)", ncm));
            }
        }
    }

    private static void apenasNumerico(final String string, final String info) {
        if (string != null && !StringUtils.isNumeric(string)) {
            throw new IllegalStateException(String.format("A string %s precisa ser numerica (%s)", info, string));
        }
    }

    private static void validaTamanhoMaximo(final String string, final int tamanho, final String info) {
        if (string != null && (string.length() < 1 || string.length() > tamanho)) {
            throw new IllegalStateException(String.format("%s \"%s\" deve possuir entre 1-%s caracteres", info, string, tamanho));
        }
    }

    private static void validaTamanhoExato(final String string, final int tamanho, final String info) {
        if (string != null && string.length() != tamanho) {
            throw new IllegalStateException(String.format("%s \"%s\" deve possuir %s caracteres", info, string, tamanho));
        }
    }

    private static void intervalo(final String string, final int inicio, final int fim, final String info) {
        if (string != null && (string.length() < inicio || string.length() > fim)) {
            throw new IllegalStateException(String.format("%s \"%s\" deve possuir entre %s-%s caracteres", info, string, inicio, fim));
        }
    }

    public static String validaIntervalo(final String string, final int inicio, final int fim, final String info) {
        return StringValidador.validaIntervalo(string, inicio, fim, info, false);
    }

    public static String validaIntervalo(final String string, final int inicio, final int fim, final String info, Boolean isNumeric) {
        if (string != null) {
            isNumeric = ObjectUtils.defaultIfNull(isNumeric, false);
            if (isNumeric) {
                StringValidador.apenasNumerico(string, info);
            }
            StringValidador.intervalo(string, inicio, fim, info);
        }
        return string;
    }

    /**
     * Valida um número com N {
     *
     * <pre>
     *  StringValidador.capacidadeNDigitos("10000", "info" , 5)   = "10000"
     *  StringValidador.capacidadeNDigitos("5", "info" , 2)   = "5"
     * </pre>
     * @param capacidade
     * @param info
     * @param digitos
     * @return
     * @throws IllegalStateException se<br>
     * {@code capacidade = "10000" } & {@code digitos = 3}, ou seja , {@code capacidade.length()-1 > digitos }
     */
    public static String capacidadeNDigitos(final String capacidade, final String info, final int digitos) {
        if (capacidade != null) {
            final Matcher matcher = Pattern.compile("^(0|[1-9]{1}[0-9]{0," + digitos + "})$").matcher(capacidade);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("%s fora do padrao (%s)", info, capacidade));
            }
        }
        return capacidade;
    }

    public static void nve(final String nve) {
        if (nve != null) {
            final Matcher matcher = Pattern.compile("^[A-Z]{2}[0-9]{4}$").matcher(nve);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("NVE fora do padrao (%s)", nve));
            }
        }
    }

    public static void itemListaServico(final String itemListaServicos) {
        if (itemListaServicos != null) {
            final Matcher matcher = Pattern.compile("^\\d{2}\\.\\d{2}$").matcher(itemListaServicos);
            if (!matcher.find()) {
                throw new IllegalStateException(String.format("Item Lista de servico fora do padrao (%s)", itemListaServicos));
            }
        }
    }

    public static void exatamente54(final String string, final String info) {
        StringValidador.validaTamanhoExato(string, 54, info);
    }

    public static void exatamente15N(final String string, final String info) {
        StringValidador.validaTamanhoExato(string, 15, info);
        StringValidador.apenasNumerico(string, info);
    }

    public static void exatamente11N(final String string, final String info) {
        StringValidador.apenasNumerico(string, info);
        StringValidador.validaTamanhoExato(string, 11, info);
    }

    public static void modeloDocumentoFiscal(final String modeloDocumentoFiscal) {
        if (!modeloDocumentoFiscal.equals("55") && !modeloDocumentoFiscal.equals("65")) {
            throw new IllegalStateException(String.format("Modelo Fiscal Invalido (%s)", modeloDocumentoFiscal));
        }
    }

    public static void identificador(final String identificador) {
        final Matcher matcher = Pattern.compile("^ID\\d{41}$").matcher(identificador);
        if (!matcher.find()) {
            throw new IllegalStateException(String.format("Identificador fora do padrao (%s)", identificador));
        }
    }

    public static void equals(final String test, final String tested) {
        if (!StringUtils.equals(test, tested)) {
            throw new IllegalStateException(String.format("Valor('%s') nao corresponde com o padrao('%s')", tested, test));
        }
    }
}


package com.fincatto.documentofiscal.cte300.classes.nota;

import com.fincatto.documentofiscal.DFPais;
import org.simpleframework.xml.Element;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.StringValidador;

/**
 * @author Caio
 * @info Dados do endereço
 */

public class CTeNotaEndereco extends DFBase {
    private static final long serialVersionUID = 1528514404620728196L;

    @Element(name = "xLgr", required = true)
    private String logradouro;

    @Element(name = "nro", required = true)
    private String numero;

    @Element(name = "xCpl", required = false)
    private String complemento;

    @Element(name = "xBairro", required = true)
    private String bairro;

    @Element(name = "cMun", required = true)
    private String codigoMunicipio;

    @Element(name = "xMun", required = true)
    private String descricaoMunicipio;

    @Element(name = "CEP", required = false)
    private String cep;

    @Element(name = "UF", required = true)
    private String siglaUF;

    @Element(name = "cPais", required = false)
    private DFPais codigoPais;

    @Element(name = "xPais", required = false)
    private String descricaoPais;

    public CTeNotaEndereco() {
        this.logradouro = null;
        this.numero = null;
        this.complemento = null;
        this.bairro = null;
        this.codigoMunicipio = null;
        this.descricaoMunicipio = null;
        this.cep = null;
        this.siglaUF = null;
        this.codigoPais = null;
        this.descricaoPais = null;
    }

    public String getLogradouro() {
        return this.logradouro;
    }

    /**
     * Logradouro
     */
    public void setLogradouro(final String logradouro) {
        StringValidador.tamanho2ate60(logradouro, "Logradouro");
        this.logradouro = logradouro;
    }

    public String getNumero() {
        return this.numero;
    }

    /**
     * Número
     */
    public void setNumero(final String numero) {
        StringValidador.tamanho60(numero, "Número");
        this.numero = numero;
    }

    public String getComplemento() {
        return this.complemento;
    }

    /**
     * Complemento
     */
    public void setComplemento(final String complemento) {
        StringValidador.tamanho60(complemento, "Complemento");
        this.complemento = complemento;
    }

    public String getBairro() {
        return this.bairro;
    }

    /**
     * Bairro
     */
    public void setBairro(final String bairro) {
        StringValidador.tamanho2ate60(bairro, "Bairro");
        this.bairro = bairro;
    }

    public String getCodigoMunicipio() {
        return this.codigoMunicipio;
    }

    /**
     * Código do município (utilizar a tabela do IBGE)

     * Informar 9999999 para operações com o exterior.
     */
    public void setCodigoMunicipio(final String codigoMunicipio) {
        StringValidador.exatamente7N(codigoMunicipio, "Código do município");
        this.codigoMunicipio = codigoMunicipio;
    }

    public String getDescricaoMunicipio() {
        return this.descricaoMunicipio;
    }

    /**
     * Nome do município

     * Informar EXTERIOR para operações com o exterior.
     */
    public void setDescricaoMunicipio(final String descricaoMunicipio) {
        StringValidador.tamanho2ate60(descricaoMunicipio, "Nome do município");
        this.descricaoMunicipio = descricaoMunicipio;
    }

    public String getCep() {
        return this.cep;
    }

    /**
     * CEP

     * Informar os zeros não significativos
     */
    public void setCep(final String cep) {
        StringValidador.exatamente8N(cep, "CEP");
        this.cep = cep;
    }

    public String getSiglaUF() {
        return this.siglaUF;
    }

    /**
     * Sigla da UF

     * Informar EX para operações com o exterior.
     */
    public void setSiglaUF(final String siglaUf) {
        StringValidador.exatamente2(siglaUf, "Sigla da UF");
        this.siglaUF = siglaUf;
    }

    public DFPais getCodigoPais() {
        return this.codigoPais;
    }

    /**
     * Código do país

     * Utilizar a tabela do BACEN
     */
    public void setCodigoPais(final String codigoPais) {
        StringValidador.tamanho4N(codigoPais, "Código do país");
        this.codigoPais = DFPais.valueOfCodigo(codigoPais);
    }

    public String getDescricaoPais() {
        return this.descricaoPais;
    }

    /**
     * Nome do país
     */
    public void setDescricaoPais(final String descricaoPais) {
        StringValidador.tamanho2ate60(descricaoPais, "Nome do país");
        this.descricaoPais = descricaoPais;
    }
}