NFe

Aproveitando,

Meu programa para enviar para o ambiente de homologação esta funcionando certinho, sem problemas.

Meu medo esta em dar algum erro inesperado quando for mudar para o ambiente de produção, afinal não tem como “testar” o ambiente de produção. Alguém aqui ja passou por essa mudança e pode dizer se foi simples? é só alterar as classes para usar os wsdl do ambiente de produção e o certificado de mesmo ambiente?

Eu tentei acessar o ambiente do produção para verificar o status do serviço fazendo só as alterações que eu disse aí em cima, mas esta me retornando um erro “unable to find valid certification path to requested target”. Estou assumindo que esse erro ocorre porque ainda não estou autorizado a usar o ambiente de produção. Alguém sabe se é por isso mesmo?

Pessoal, estou precisando de uma ajuda importantissima!

Eu entrei em modo de produção na sexta-feira. Tudo funcionou certinho, até ontem no final da tarde, quando o programa simplesmente se recusa a aceitar o keystore com os certificados do ambiente de produção!

Quando tento transmitir algo, recebo o erro:

AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException faultSubcode: faultString: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target faultActor: faultNode: faultDetail: {http://xml.apache.org/axis/}stackTrace:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186) at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191) at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404) at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at br.inf.portalfiscal.www.nfe.wsdl.NfeStatusServico.NfeStatusServicoSoapStub.nfeStatusServicoNF(NfeStatusServicoSoapStub.java:110) at main.Principal.main(Principal.java:236) Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(Unknown Source) at sun.security.validator.PKIXValidator.engineValidate(Unknown Source) at sun.security.validator.Validator.validate(Unknown Source) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source) ... 23 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source) at java.security.cert.CertPathBuilder.build(Unknown Source) ... 29 more

É como se o keystore não fosse mais valido. E isso foi do nada, pois não alterei absolutamente nada no meu código.
Ja tentei gerar o keystore novamente, inclusive por metodos diferentes do ensinado nesse topico, e nada…

Alguem pode dar uma luz??

Consegui resolver o problema q eu tinha mencionado acima… como pode ser util para mais alguem, vou postar como resolvi:

Aparentemente, o SEFAZ de SP passou a exigir mais certificados para a conexao com o webservice, alem daquele do ambiente de produção disponivel para download. O que eu fiz foi pegar todos os certificados do repositório do windows que eram da Certisign e da Autoridade certificadora brasileira (eu tinha 29 desses instalados) e importar para o keystore q eu estava usando como truststore, e deu certo.

Muito provavel que não seja necessario importar todos esses certificados, mas, na duvida coloquei tudo q eu tinha

Alguem mais ja teve esse problema ??? O q fizeram ???

Enviei uma nota fiscal pelo sistema gratuito do sefaz pelo sistema de teste e funcionou perfeitamente. Entao exportei/importei para o sistema de producao e enviei a NFe mas ela consta faz umas 2 horas ja como “em processamento”, e se tento consultar pela Chave via web o status diz q essa NFe nao consta no Sefaz.

Alguem poderia me ajudar por favor ??

Grato,
Magno
magno_jr@terra.com.br

Senhores, estou com problemas na hora de fazer a comunicacao.

com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: java.net.ConnectException: Connection timed out: connect
at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(HttpClientTransport.java:121)
at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:142)
at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:83)

Ja Baixei, os WSDL gerei as classes Java e estou usando o seguinte codigo:

         //Esse é o layout para o cabeçalho e rodapé para o Status do Serviço conforme o manual de integração explica
         String nfeCabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
             + "<cabecMsg xmlns=\"http://www.portalfiscal.inf.br/nfe\" "
             + "versao=\"1.02\">" + "<versaoDados>1.07</versaoDados>"
             + "</cabecMsg>";
         String nfeDadosMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
             + "<consStatServ " + " versao=\"1.07\""
             + " xmlns=\"http://www.portalfiscal.inf.br/nfe\">"
             + "<tpAmb>2</tpAmb>" + "<cUF>42</cUF>"
             + "<xServ>STATUS</xServ>" + "</consStatServ>";




         System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

         System.setProperty("javax.net.ssl.trustStoreType", "JKS");
         System.setProperty("javax.net.ssl.trustStore", new File("").getAbsolutePath() +
            "\\certificados\\nfe.keystore");
         System.setProperty("javax.net.ssl.trustStorePassword", "senha");

         System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
         System.setProperty("javax.net.ssl.keyStore",
            new File("").getAbsolutePath() + "\\certificados\\certificadoA1.pfx");
         System.setProperty("javax.net.ssl.keyStorePassword", "senha");

         // As classes abaixo são as classes geradas atavés do arquivo WSDL no passo 1
         NfeStatusServico_Service service = new NfeStatusServico_Service();
         NfeStatusServico nfeStatus = service.getNfeStatusServico();
         System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));// O retorno deve ser um XML com o status do serviço
         return nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg);

se alguem puder me ajudar, agradeco muito.

Lembrei que quando gerei as classes a partir do wsdl ele gerou as seguintes classes:
NfeStatusServico.java
NfeStatusServicoNF.java
NfeStatusServicoNFResponse.java
NfeStatusServico_Service.java
ObjectFactory.java
package-info.java

No exemplo que eu peguei aqui mesmo no Guj usavam as seguintes classes:
NfeStatusServico
NfeStatusServicoLocator
NfeStatusServicoSoap

         NfeStatusServico service = new NfeStatusServicoLocator();  
         try {  
             NfeStatusServicoSoap nfeStatus = service.getNfeStatusServicoSoap();  
             System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));// O retorno deve ser um XML com o status do serviço  
         } catch (Throwable e1) {  
             e1.printStackTrace();  
         }  

Como nao foram geradas as classes NfeStatusServicoSoap e NfeStatusServicoLocator eu as substitui por NfeStatusServico e NfeStatusServico_Service respectivamente, visto que contem os mesmos metodos.

Sera que pode ser este o motivo?

[quote=rafaelbtz]Bom dia farzac, é o seguinte a ordem das coisas é:
Obter o Certificado Digital (no meu caso um arquivo .pfx que o meu cliente obteve junto a receita) - Gerar o XML - Assinar o XML (com o certificado .pfx) - Validar o XML no Schema (.XSD) - Enviar o XML pro SEFAZ.

Como eu fiz aqui:
Gerei, Assinei o XML e validei no Schema, e depois pra testar eu usei o programa Emissor de NF obtido no site http://www.nfe.fazenda.gov.br/portal/default.aspx - link downloads. Assim que eu consegui importar e enviar o meu XML via esse emissor do governo eu vi que a nota estava OK (Atenção, para conseguir importar o XML neste programa é preciso colocar o valor “3” na tag procEmi e o valor “TESTE 1.1.21” na tag verProc do XML). Ai eu parti para consumir o WebService:

Web Service (esse eu sofri, hehe), (por enquanto eu só testei a comunicação através do WebService StatusServico, ainda não enviei nenhum XML pois agora estou estruturando a aplicação inteira, mas se o StatusServiço funcionou e se eu consegui enviar a NF via o emissor do governo acho que não vou ter problemas para enviar via WebService):

Passo a Passo:
Baixar os arquivos .WSDL junto a receita do seu estado (no meu caso SP que fica em http://www.fazenda.sp.gov.br/nfe/url_webservices/url_webservices.asp), baixe neste mesmo link o arquivo da chave pública do Web-Service em SP esses são 2 arquivos com extensão .p7b um para Homologação outro para produção.

Passo a Passo:

  1. Com os arquivos WSDL crie as classes .java para acesso ao WebService - Eu não sei como isso funciona no NetBeans já que eu uso eclipse, mas de uma procurado no Google por “WSDL to Java on NetBeans” que com certeza vc vai achar ele vai criar umas 6 classes para cada arquivo .WSDL (por enquanto eu só criei para o WSDL do StatusServico);

  2. Instale no seu Windows a chave publica (.p7b) baixada do site da receita estadual, depois de instalar vai no Internet Explorer -> Ferramentas -> Opções da internet -> (Aba) Conteúdo -> (botão) certificados -> (Aba) outras pessoas; a chave instalada deve estar ai, selecione ela e clique no botão Exportar; na tela da exportação marque o RadioButton X.509 codificado na base 64 (*.cer) informe o arquivo com extensão .cer;

  3. Importe esta chave pública que vc exportou no IE para um keystore do Java com a ferramenta Keytool: via DOS va até a pasta bin da sua JRE e execute o seguinte comando: keytool -import -alias nfe -keystore <caminho_para_um_keystore Ex: c:\certificados\nfe.keystore> -file <caminho_completo_para_o_cert_exportado_do_IE ( arquivo .cer)>, esse comando irá gerar um arquivo que no exemplo é c:\certificados\nfe.keystore

  4. Agora é só ir pro JAVA, vamos la ( o exemplo é para verificar o Status do Serviço, para cada WebService existe um layout de mensagem diferente você pode ver isso no manual de integração que você encontra em http://www.nfe.fazenda.gov.br/portal/default.aspx), classe Java para verificar o Status é essa aqui:

public static void main(String[] args) {
   
         //Esse é o layout para o cabeçalho e rodapé para o Status do Serviço conforme o manual de integração explica
        String nfeCabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<cabecMsg xmlns=\"http://www.portalfiscal.inf.br/nfe\" "
            + "versao=\"1.02\">" + "<versaoDados>1.07</versaoDados>"
            + "</cabecMsg>";
        String nfeDadosMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<consStatServ " + " versao=\"1.07\""
            + " xmlns=\"http://www.portalfiscal.inf.br/nfe\">"
            + "<tpAmb>2</tpAmb>" + "<cUF>42</cUF>"
            + "<xServ>STATUS</xServ>" + "</consStatServ>";

       
       
       
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
        System.setProperty("javax.net.ssl.keyStore","C:\\certificados\\cert.pfx");//Aqui vem o arquivo do certificado do seu cliente
        System.setProperty("javax.net.ssl.keyStorePassword", "SENHA DO CERTIFICADO");//Aqui a senha deste certificado

        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", "C:\\certificados\\nfe.keystore");//Aqui vem o arquivo criado através do comando keytool no passo 3

       
        // As classes abaixo são as classes geradas atavés do arquivo WSDL no passo 1
        NfeStatusServico service = new NfeStatusServicoLocator();
        try {
            NfeStatusServicoSoap nfeStatus = service.getNfeStatusServicoSoap();
            System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));// O retorno deve ser um XML com o status do serviço
        } catch (Throwable e1) {
            e1.printStackTrace();
        }
    }

É isso ai para enviar a nota deve ser mais ou menos o mesmo procedimento alterando obviamente o layout da mensagem que pode ser encontrado la no manual de integração.

É isso ai espero ter ajudado, qualquer coisa é só perguntar

Obs: acho que foi vc que me mandou um email, mas todo caso se não foi estou colocando a resposta aqui também)

[/quote]

Realmente entre todas as que vi sobre NF-e esse é o melhor post de todos.

Uma pergunta, peguei seu código só que tem um problema, eu não tenho o certificado do cliente (arquivo .pfx) mas preciso fazer o teste no ambiente de homologação.

Como fazer? Meu problema está no No.1 e no No.2 no meu código:

[code] public void statusServico() {
//Esse é o layout para o cabeçalho e rodapé para o Status do Serviço conforme o manual de integração explica
String nfeCabecMsg = “<?xml version=\"1.0\" encoding=\"UTF-8\"?>” + "<cabecMsg xmlns=“http://www.portalfiscal.inf.br/nfe” " + “versao=“1.02”>” + “1.07” + “”;
String nfeDadosMsg = “<?xml version=\"1.0\" encoding=\"UTF-8\"?>” + "<consStatServ " + " versao=“1.07"” + " xmlns="http://www.portalfiscal.inf.br/nfe">" + “2” + “42” + “STATUS” + “”;

    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");

    // No.1) Aqui vem o arquivo do certificado do seu cliente
    System.setProperty("javax.net.ssl.keyStore", "C:\\certificados\\cert.pfx");

    // No.2) Aqui a senha deste certificado
    System.setProperty("javax.net.ssl.keyStorePassword", "SENHA DO CERTIFICADO");

    // No.3) Aqui vem o arquivo criado através do comando keytool no passo 3
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");
    System.setProperty("javax.net.ssl.trustStore", "C:\\Projetos\\Desktop\\KNFe\\nfe.keystore");

    // No.4) As classes abaixo são as classes geradas atavés do arquivo WSDL no passo 1
    NfeStatusServico service = new NfeStatusServico();
    try {
        NfeStatusServicoSoap nfeStatus = service.getNfeStatusServicoSoap();
        // O retorno deve ser um XML com o status do serviço
        System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));
    } catch (Throwable e1) {
        e1.printStackTrace();
    }
}[/code]

[quote=jluizsc]Ola Pessoal

Eu usei o mesmo codigo postado aqui no grupo
e adicionei um codigo o codigo X509 no projeto (ou na pasta)

somente esses dois jah funcionou

usar: Assinador.assinar( … )

segue os dois arquivos *.java na sequencia

Assinador.java

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package assinadornfe01;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
//import sun.misc.BASE64Encoder;

import java.util.Enumeration;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.security.PrivateKey;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import javax.swing.JOptionPane;

import AssinadorNFE.X509KeySelector;

public class Assinador
{
private static final String C14N_TRANSFORM_METHOD = “http://www.w3.org/TR/2001/REC-xml-c14n-20010315”;

    private static final String PROVIDER_CLASS_NAME = "org.jcp.xml.dsig.internal.dom.XMLDSigRI";
    private static final String PROVIDER_NAME = "jsr105Provider";
    
    public void assinar(String caminhoXml, String caminhoCertificado, String senha, String caminhoXmlNovo, String tipo) throws Exception 
{
	// tipo
	// '1' - NFE
	// '2' - CANCELAMENTO
	// '3' - INUTILIZACAO
	//
	String tag = "";		
	if(tipo.equals("1"))
		tag = "infNFe";
	else if (tipo.equals("2"))
		tag = "infCanc";
	else if (tipo.equals("3"))
		tag = "infInut";
		
            
		
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(false);
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document docs = builder.parse(new File(caminhoXml));
	//Document docs = builder.parse(new File("c:/xml/430802017886010001735500000000010000030371-nfe.xml"));

	// Obtem elemento do documento a ser assinado, será criado uma
	// REFERENCE para o mesmo
	NodeList elements = docs.getElementsByTagName(tag);
	Element el = (Element) elements.item(0);
	String id = el.getAttribute("Id");
	//System.out.println(id);
	
	// Create a DOM XMLSignatureFactory that will be used to
	// generate the enveloped signature.
            String providerName = System.getProperty(PROVIDER_NAME, PROVIDER_CLASS_NAME);
            XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
	//XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
	
	// Create a Reference to the enveloped document (in this case,
	// you are signing the whole document, so a URI of "" signifies
	// that, and also specify the SHA1 digest algorithm and
	// the ENVELOPED Transform.
	ArrayList transformList = new ArrayList();
	TransformParameterSpec tps = null;
	Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,tps);
	Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps);
	transformList.add(envelopedTransform);
	transformList.add(c14NTransform);

	Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
	// Create the SignedInfo.
	SignedInfo si = fac
			.newSignedInfo(fac.newCanonicalizationMethod(
					CanonicalizationMethod.INCLUSIVE,
					(C14NMethodParameterSpec) null), fac
					.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
					Collections.singletonList(ref));
	
	// Load the KeyStore and get the signing key and certificate.
	///Provider p = new sun.security.pkcs11.SunPKCS11("c:/taliam/sclara.cer");
	//Security.addProvider(p);
	//KeyStore ks = KeyStore.getInstance("PKCS11");
	//ks.load(null, new String("safeweb").toCharArray());
	
	KeyStore ks = KeyStore.getInstance("PKCS12");
	ks.load(new FileInputStream(caminhoCertificado), senha.toCharArray());
	Enumeration aliasesEnum = ks.aliases();
	String alias = "";
	while (aliasesEnum.hasMoreElements()) {
		alias = (String) aliasesEnum.nextElement();

		if (ks.isKeyEntry(alias)) {
			//System.out.println(alias);
			break;
		}
	}
	
	// Original
	//KeyStore ks = KeyStore.getInstance("JKS");
	//ks.load(new FileInputStream("santaclara.jks"), "RAIMUNDO".toCharArray());
	
	//		
	KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(senha.toCharArray()));
    
	X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
	// Create the KeyInfo containing the X509Data.
	KeyInfoFactory kif = fac.getKeyInfoFactory();
	List x509Content = new ArrayList();
	// x509Content.add(cert.getSubjectX500Principal().getName());
	
	x509Content.add(cert);
	X509Data xd = kif.newX509Data(x509Content);
	KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
	
	// Instantiate the document to be signed.
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(caminhoXml));

	// Create a DOMSignContext and specify the RSA PrivateKey and
	// location of the resulting XMLSignature's parent element.
	DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());

	// Create the XMLSignature, but don't sign it yet.
	XMLSignature signature = fac.newXMLSignature(si, ki);

	// Marshal, generate, and sign the enveloped signature.
	signature.sign(dsc);

	// Output the resulting document.
	OutputStream os = new FileOutputStream(caminhoXmlNovo);
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer trans = tf.newTransformer();
	trans.transform(new DOMSource(doc), new StreamResult(os));

	// Find Signature element.
	NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
	
	if (nl.getLength() == 0) {
		throw new Exception("Cannot find Signature element");
	}
	// Create a DOMValidateContext and specify a KeySelector and document
	// context.
	DOMValidateContext valContext = new DOMValidateContext( new X509KeySelector(ks), nl.item(0));
	// Unmarshal the XMLSignature.
	XMLSignature signatures = fac.unmarshalXMLSignature(valContext);
	// Validate the XMLSignature.
	boolean coreValidity = signatures.validate(valContext);
	// Check core validation status.
	if (coreValidity == false) {
		System.err.println("Falha na Assinatura!");
	} else {
		System.out.println("Assinatura Correta!");
	}
}

public static void main(String[] args) throws Exception {
	
	if(args.length != 5)
	{
		//JOptionPane.showMessageDialog(null, "São esperados 5 parâmetros!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
		System.out.println("Sao esperados 5 parametros!");
                    return;
	}
	String caminhoXml = args[0];
	String caminhoCertificado = args[1];
	String senha = args[2];
	String arquivoXmlNovo = args[3];
	String tipo = args[4];
	
	File file = new File(caminhoXml);
	if(!file.exists())
	{
		//JOptionPane.showMessageDialog(null, "Arquivo " + caminhoXml + " não encontrado!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
            System.out.println("Arquivo " + caminhoXml + " não encontrado!");
		return;
	}
	file = new File(caminhoCertificado);
	if(!file.exists())
	{
		//JOptionPane.showMessageDialog(null, "Arquivo " + caminhoCertificado + " não encontrado!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
            System.out.println("Arquivo " + caminhoCertificado + " não encontrado!");
		return;
	}
	try
	{
		Assinador t = new Assinador();
		t.assinar(caminhoXml, caminhoCertificado, senha, arquivoXmlNovo, tipo);
		//JOptionPane.showMessageDialog(null, "Arquivo xml assinado com sucesso!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("Arquivo xml assinado com sucesso" + caminhoXml + "!");
	}
	catch(Exception e)
	{
		//JOptionPane.showMessageDialog(null, "Erro ao tentar assinar arquivo xml! \n\n" + e.toString(), "Atenção", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("Erro ao tentar assinar arquivo xml! \n\n" + e.toString());
	}
}

}

X509KeySelector.java

package AssinadorNFE;

import java.io.InputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertSelector;
import java.security.cert.X509Certificate;
import java.security.cert.X509CertSelector;
import java.util.Enumeration;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import javax.xml.crypto.;
import javax.xml.crypto.dsig.
;
import javax.xml.crypto.dom.;
import javax.xml.crypto.dsig.keyinfo.
;

/**

  • A KeySelector that returns {@link PublicKey}s of trusted

  • {@link X509Certificate}s stored in a {@link KeyStore}.

  • This KeySelector uses the specified KeyStore

  • to find a trusted X509Certificate that matches information

  • specified in the {@link KeyInfo} passed to the {@link #select} method.

  • The public key from the first match is returned. If no match,

  • null is returned. See the select method for more

  • information.

  • NOTE!: This X509KeySelector requires J2SE 1.4 because it uses the

  • java.security.cert.X509CertSelector & javax.security.auth.x500.X500Principal

  • classes to parse X.500 DNs and match on certificate attributes.

  • @author Sean Mullan
    */
    public class X509KeySelector extends KeySelector {

    private KeyStore ks;

    /**

    • Creates an X509KeySelector.
    • @param keyStore the keystore
    • @throws KeyStoreException if the keystore has not been initialized
    • @throws NullPointerException if keyStore is
    • null
      */
      public X509KeySelector(KeyStore keyStore) throws KeyStoreException {
      if (keyStore == null) {
      throw new NullPointerException(“keyStore is null”);
      }
      this.ks = keyStore;
      // test to see if KeyStore has been initialized
      this.ks.size();
      }

    /**

    • Finds a key from the keystore satisfying the specified constraints.
    • This method compares data contained in {@link KeyInfo} entries

    • with information stored in the KeyStore. The implementation
    • iterates over the KeyInfo types and returns the first {@link PublicKey}
    • of an X509Certificate in the keystore that is compatible with the
    • specified AlgorithmMethod according to the following rules for each
    • keyinfo type:
    • X509Data X509Certificate: if it contains a KeyUsage
    • extension that asserts the digitalSignature bit and
    • matches an X509Certificate in the KeyStore.
    • X509Data X509IssuerSerial: if the serial number and issuer DN match an
    • X509Certificate in the KeyStore.
    • X509Data X509SubjectName: if the subject DN matches an
    • X509Certificate in the KeyStore.
    • X509Data X509SKI: if the subject key identifier matches an
    • X509Certificate in the KeyStore.
    • KeyName: if the keyname matches an alias in the KeyStore.
    • RetrievalMethod: supports rawX509Certificate and X509Data types. If
    • rawX509Certificate type, it must match an X509Certificate
    • in the KeyStore.
    • @param keyInfo a KeyInfo (may be null)
    • @param purpose the key’s purpose
    • @param method the algorithm method that this key is to be used for.
    • Only keys that are compatible with the algorithm and meet the
    • constraints of the specified algorithm should be returned.
    • @param an XMLCryptoContext that may contain additional
    • useful information for finding an appropriate key
    • @return a key selector result
    • @throws KeySelectorException if an exceptional condition occurs while
    • attempting to find a key. Note that an inability to find a key is not
    • considered an exception (null should be
    • returned in that case). However, an error condition (ex: network
    • communications failure) that prevented the KeySelector
    • from finding a potential key should be considered an exception.
    • @throws ClassCastException if the data type of method
    • is not supported by this key selector
      */
      public KeySelectorResult select(KeyInfo keyInfo,
      KeySelector.Purpose purpose, AlgorithmMethod method,
      XMLCryptoContext context) throws KeySelectorException {
     SignatureMethod sm = (SignatureMethod) method;
    
     try {
         // return null if keyinfo is null or keystore is empty
         if (keyInfo == null || ks.size() == 0) {
             return new SimpleKeySelectorResult(null);
         }
    
         // Iterate through KeyInfo types
         Iterator i = keyInfo.getContent().iterator();
         while (i.hasNext()) {
             XMLStructure kiType = (XMLStructure) i.next();
     // check X509Data
             if (kiType instanceof X509Data) {
                 X509Data xd = (X509Data) kiType;
         KeySelectorResult ksr = x509DataSelect(xd, sm);
             if (ksr != null) {
             return ksr;
             }
     // check KeyName
             } else if (kiType instanceof KeyName) {
         KeyName kn = (KeyName) kiType;
         Certificate cert = ks.getCertificate(kn.getName());
         if (cert != null && algEquals(sm.getAlgorithm(),
     	cert.getPublicKey().getAlgorithm())) {
     	return new SimpleKeySelectorResult(cert.getPublicKey());
         }
     // check RetrievalMethod
             } else if (kiType instanceof RetrievalMethod) {
         RetrievalMethod rm = (RetrievalMethod) kiType;
                 try {
     	KeySelectorResult ksr = null;
             if (rm.getType().equals
     	    (X509Data.RAW_X509_CERTIFICATE_TYPE)) {
     	    OctetStreamData data = (OctetStreamData) 
     		rm.dereference(context);
     	    CertificateFactory cf = 
     	        CertificateFactory.getInstance("X.509");
     	    X509Certificate cert = (X509Certificate) 
     	        cf.generateCertificate(data.getOctetStream());
                 ksr = certSelect(cert, sm);
             } else if (rm.getType().equals(X509Data.TYPE)) {
     	    NodeSetData nd = (NodeSetData) 
     		rm.dereference(context);
     	    // convert nd to X509Data
                 // ksr = x509DataSelect(xd, sm);
             } else {
     	    // skip; keyinfo type is not supported
     	    continue;
     	}
             if (ksr != null) {
                 return ksr;
                 }
                 } catch (Exception e) {
             throw new KeySelectorException(e);
         }
     }
         }
     } catch (KeyStoreException kse) {
         // throw exception if keystore is uninitialized
         throw new KeySelectorException(kse);
     }
    
     // return null since no match could be found
     return new SimpleKeySelectorResult(null);
    

    }

    /**

    • Searches the specified keystore for a certificate that matches the
    • criteria specified in the CertSelector.
    • @return a KeySelectorResult containing the cert’s public key if there
    • is a match; otherwise null
      */
      private KeySelectorResult keyStoreSelect(CertSelector cs)
      throws KeyStoreException {
      Enumeration aliases = ks.aliases();
      while (aliases.hasMoreElements()) {
      String alias = (String) aliases.nextElement();
      Certificate cert = ks.getCertificate(alias);
      if (cert != null && cs.match(cert)) {
      return new SimpleKeySelectorResult(cert.getPublicKey());
      }
      }
      return null;
      }

    /**

    • Searches the specified keystore for a certificate that matches the
    • specified X509Certificate and contains a public key that is compatible
    • with the specified SignatureMethod.
    • @return a KeySelectorResult containing the cert’s public key if there
    • is a match; otherwise null
      */
      private KeySelectorResult certSelect(X509Certificate xcert,
      SignatureMethod sm) throws KeyStoreException {
      // skip non-signer certs
      boolean[] keyUsage = xcert.getKeyUsage();
      if (keyUsage[0] == false) {
      return null;
      }
      String alias = ks.getCertificateAlias(xcert);
      if (alias != null) {
      PublicKey pk = ks.getCertificate(alias).getPublicKey();
      // make sure algorithm is compatible with method
      if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
      return new SimpleKeySelectorResult(pk);
      }
      }
      return null;
      }

    /**

    • Returns an OID of a public-key algorithm compatible with the specified
    • signature algorithm URI.
      */
      private String getPKAlgorithmOID(String algURI) {
      if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
      return “1.2.840.10040.4.1”;
      } else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
      return “1.2.840.113549.1.1”;
      } else {
      return null;
      }
      }

    /**

    • A simple KeySelectorResult containing a public key.
      */
      private static class SimpleKeySelectorResult implements KeySelectorResult {
      private final Key key;
      SimpleKeySelectorResult(Key key) { this.key = key; }
      public Key getKey() { return key; }
      }

    /**

    • Checks if a JCA/JCE public key algorithm name is compatible with
    • the specified signature algorithm URI.
      */
      //@@@FIXME: this should also work for key types other than DSA/RSA
      private boolean algEquals(String algURI, String algName) {
      if (algName.equalsIgnoreCase(“DSA”) &&
      algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
      return true;
      } else if (algName.equalsIgnoreCase(“RSA”) &&
      algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
      return true;
      } else {
      return false;
      }
      }

    /**

    • Searches the specified keystore for a certificate that matches an
    • entry of the specified X509Data and contains a public key that is
    • compatible with the specified SignatureMethod.
    • @return a KeySelectorResult containing the cert’s public key if there
    • is a match; otherwise null
      */
      private KeySelectorResult x509DataSelect(X509Data xd, SignatureMethod sm)
      throws KeyStoreException, KeySelectorException {

    // convert signature algorithm to compatible public-key alg OID
    String algOID = getPKAlgorithmOID(sm.getAlgorithm());

    KeySelectorResult ksr = null;
    Iterator xi = xd.getContent().iterator();
    while (xi.hasNext()) {
    ksr = null;
    Object o = xi.next();
    // check X509Certificate
    if (o instanceof X509Certificate) {
    X509Certificate xcert = (X509Certificate) o;
    ksr = certSelect(xcert, sm);
    // check X509IssuerSerial
    } else if (o instanceof X509IssuerSerial) {
    X509IssuerSerial xis = (X509IssuerSerial) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSerialNumber(xis.getSerialNumber());
    xcs.setIssuer(new X500Principal
    (xis.getIssuerName()).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);
    // check X509SubjectName
    } else if (o instanceof String) {
    String sn = (String) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    xcs.setSubject(new X500Principal(sn).getName());
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    ksr = keyStoreSelect(xcs);
    // check X509SKI
    } else if (o instanceof byte[]) {
    byte[] ski = (byte[]) o;
    X509CertSelector xcs = new X509CertSelector();
    try {
    xcs.setSubjectPublicKeyAlgID(algOID);
    } catch (IOException ioe) {
    throw new KeySelectorException(ioe);
    }
    // DER-encode ski - required by X509CertSelector
    byte[] encodedSki = new byte[ski.length+2];
    encodedSki[0] = 0x04; // OCTET STRING tag value
    encodedSki[1] = (byte) ski.length; // length
    System.arraycopy(ski, 0, encodedSki, 2, ski.length);
    xcs.setSubjectKeyIdentifier(encodedSki);
    ksr = keyStoreSelect(xcs);
    // check X509CRL
    // not supported: should use CertPath API
    } else {
    // skip all other entries
    continue;
    }
    if (ksr != null) {
    return ksr;
    }
    }
    return null;
    }
    }


Joao Luiz - Linux user #159951
WEB : http://site.pop.com.br/jluizsc
my space : http://www.myspace.com/jluizsc
GRATIS eh POUCO: http://br.geocities.com/jluizsc (explicacoes orolix)
GRATIS eh POUCO 2 : http://www.crescenet.dahora.net (explicacoes crescenet)

[/quote]
Usei seu código para assinar um lote de notas fiscais mas ele assinou a tag enviNFe e não cada NFe.

Veja a imagem do XML (no NB):

O que tenho que mudar para ele assinar a tab NFe?

Cara… naum sei se é a forma correta de fazer, mas, eu assinei cada nota individualmente e depois só inseri elas no xml do lote.
Tah funcionando normal aqui.

Poderia mostrar parte do código que faz isso?

Você pega XML de notas separadas e junta no XML de lote ou você pega um XML de lote e vai lendo as notas separadas e assinando e depois grava em outro XML?

Cara eh o seguinte, gero os arquivos de todas as notas separadamente, depois leio estes aquivos e gravo o conteudo dos arquivos em uma variavel string.
Envio esta variavel como argumento do metodo abaixo.

    public static String geraXmlEnvNfe(String xmlNFe, String idLote){
        String xmlEnviNfe = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<enviNFe xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"1.10\">"
                + "<idLote>" + idLote + "</idLote>"
                + xmlNFe
                + "</enviNFe>";
        //aqui eu gravo o arquivo
        MetodosGenericos.GravaArquivoCp1252NaPastaDaAplicacao(xmlEnviNfe, "\\xml-resources\\envio\\" + idLote + "-env-lot.xml");
        //retorno o local do arquivo gerado
        return MetodosGenericos.getAplicationFolder() + "\\xml-resources\\envio\\" + idLote + "-env-lot.xml";
    }

espero ter ajudado

Pessoal,

Estou tentando consultar o status do serviço, mas ainda não obtive exito ao consumir o webservice…

Segue abaixo meu código:

    public void getStatusServico() throws Exception
    {
         //Esse é o layout para o cabeçalho e rodapé para o Status do Serviço conforme o manual de integração explica
        String nfeCabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<cabecMsg xmlns=\"http://www.portalfiscal.inf.br/nfe\" "
            + "versao=\"1.02\">" + "<versaoDados>1.07</versaoDados>"
            + "</cabecMsg>";
        String nfeDadosMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<consStatServ " + " versao=\"1.07\""
            + " xmlns=\"http://www.portalfiscal.inf.br/nfe\">"
            + "<tpAmb>2</tpAmb>" + "<cUF>42</cUF>"
            + "<xServ>STATUS</xServ>" + "</consStatServ>";




        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
        System.setProperty("javax.net.ssl.keyStore","C:\\work\\erp\\nfe\\certificado\\CD.pfx");//Aqui vem o arquivo do certificado do seu cliente
        System.setProperty("javax.net.ssl.keyStorePassword", "cd9431");//Aqui a senha deste certificado

        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", "C:\\work\\erp\\nfe\\certificado\\kpalmieri.jks");//Aqui vem o arquivo criado através do comando keytool no passo 3

        try
        {
            // As classes abaixo são as classes geradas atavés do arquivo WSDL no passo 1
            NfeStatusServico service = new NfeStatusServico();
        
            
            NfeStatusServicoSoap nfeStatus = service.getNfeStatusServicoSoap();  
            System.out.println(nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg));// O retorno deve ser um XML com o status do serviço
        } 
        catch (Exception erro)
        {
           erro.printStackTrace();
        }
    }

O Erro que eu obtenho é o seguinte:

SEVERE: A WebService annotation is not present on class: java.net.URL
SEVERE:         at com.sun.xml.ws.modeler.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:218)
SEVERE:         at com.sun.xml.ws.client.ServiceContextBuilder.processAnnotations(ServiceContextBuilder.java:169)
SEVERE:         at com.sun.xml.ws.client.ServiceContextBuilder.build(ServiceContextBuilder.java:82)
SEVERE:         at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:117)
SEVERE:         at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:50)
SEVERE:         at javax.xml.ws.Service.<init>(Service.java:57)
SEVERE:         at br.com.startsoftware.webservice.NfeStatusServico.<init>(NfeStatusServico.java:44)
SEVERE:         at br.com.startsoftware.dwr.NFeDWR.getStatusServico(NFeDWR.java:46)
SEVERE:         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
SEVERE:         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
SEVERE:         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
SEVERE:         at java.lang.reflect.Method.invoke(Method.java:597)
SEVERE:         at org.directwebremoting.impl.ExecuteAjaxFilter.doFilter(ExecuteAjaxFilter.java:34)
SEVERE:         at org.directwebremoting.impl.DefaultRemoter$1.doFilter(DefaultRemoter.java:428)
SEVERE:         at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:431)
SEVERE:         at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:283)
SEVERE:         at org.directwebremoting.servlet.PlainCallHandler.handle(PlainCallHandler.java:52)
SEVERE:         at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:101)
SEVERE:         at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:146)
SEVERE:         at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
SEVERE:         at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
SEVERE:         at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:431)
SEVERE:         at org.apache.catalina.core.StandardWrapperValve.preInvoke(StandardWrapperValve.java:462)
SEVERE:         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:139)
SEVERE:         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:186)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:719)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:657)
SEVERE:         at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:96)
SEVERE:         at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
SEVERE:         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:187)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:719)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:657)
SEVERE:         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:651)
SEVERE:         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1030)
SEVERE:         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:142)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:719)
SEVERE:         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:657)
SEVERE:         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:651)
SEVERE:         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1030)
SEVERE:         at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
SEVERE:         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:242)
SEVERE:         at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:180)
SEVERE:         at com.sun.grizzly.http.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:633)
SEVERE:         at com.sun.grizzly.http.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:570)
SEVERE:         at com.sun.grizzly.http.DefaultProcessorTask.process(DefaultProcessorTask.java:827)
SEVERE:         at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:152)
SEVERE:         at com.sun.enterprise.v3.services.impl.GlassfishProtocolChain.executeProtocolFilter(GlassfishProtocolChain.java:71)
SEVERE:         at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:103)
SEVERE:         at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:89)
SEVERE:         at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
SEVERE:         at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:67)
SEVERE:         at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:56)
SEVERE:         at com.sun.grizzly.util.WorkerThreadImpl.processTask(WorkerThreadImpl.java:325)
SEVERE:         at com.sun.grizzly.util.WorkerThreadImpl.run(WorkerThreadImpl.java:184)

O que pode ser? Alguem poderia me dar uma luz por favor? Desde já agradeço a atenção prestada… Obrigado!

Algúem já desenvolveu para NFe2 com JAX-WS ?

Consegui resolver, segue:

  1. Baixe o Apache AXIS para gerar as classes a partir do WSDl, http://ws.apache.org/axis2/download.cgi
  2. Depois de descompactar, execute dentro da pasta BIN “/wsdl2java.sh -uri NFeStatusServico2.wsdl” (Linux)
  3. Copie os fontes para a pasta do projeto, inclua as bibliotecas do Apache AXIS no projeto
        NfeStatusServico2Stub stub = new NfeStatusServico2Stub();
        NfeStatusServico2Stub.NfeDadosMsg dados = new NfeStatusServico2Stub.NfeDadosMsg();
        
        String s = "<consStatServ versao=\"2.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">"+
		    "<tpAmb>2</tpAmb>"+
                    "<cUF>43</cUF>"+
                    "<xServ>STATUS</xServ>"+
                    "</consStatServ>";

        OMElement el = AXIOMUtil.stringToOM(s);
        dados.setExtraElement(el);

        NfeStatusServico2Stub.NfeCabecMsg cab = new NfeStatusServico2Stub.NfeCabecMsg();
        cab.setVersaoDados("2.00");
        cab.setCUF("43");
        NfeStatusServico2Stub.NfeCabecMsgE cabE = new NfeStatusServico2Stub.NfeCabecMsgE();
        cabE.setNfeCabecMsg(cab);
        
        System.out.println(stub.nfeStatusServicoNF2(dados , cabE).getExtraElement());

olá pessoal descumpem atravesar …
e que estou com um problema aparentemente ridiculo

estou fazendo NFe usando jaxb na verdade terminei porem estou com um problema
Criei a classe raiz NFe em “N” em mausculo conf ex:

@XmlRootElement 
public class NFe {
    
    public NFe(){}
   
    public NFe(String xmlns,infNFe infNFe)
    {
        this.infNFe = infNFe;
        this.xmlns = xmlns;

    }
    @XmlAttribute(name ="xmlns")
    private String xmlns;
    private infNFe infNFe;

porem guando gero a NFe sai minusculo…
já fiz refiz e não acho o problema fiz uns teste e pude ver que todos os doc… xml que gero com jaxb
sai a primeita letra minusca alguem sabe o que devo fazer ?

exemplo de saida NFe.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nFe xmlns="http://www.portalfiscal.inf.br/nfe">
    <infNFe Id="NFe35100369348936000104551000000578591367169950" versao="2.00">
        <ide>

Em pessoal …
O que vcs estão usando para gerar o XML .
Encontrei várias bibliotecas : JDOM / Xerces / JAXP
Mas não sei qual é melhor para o problema em questão .

[quote=javaMyLife]olá pessoal descumpem atravesar …
e que estou com um problema aparentemente ridiculo

estou fazendo NFe usando jaxb na verdade terminei porem estou com um problema
Criei a classe raiz NFe em “N” em mausculo conf ex:

@XmlRootElement 
public class NFe {
    
    public NFe(){}
   
    public NFe(String xmlns,infNFe infNFe)
    {
        this.infNFe = infNFe;
        this.xmlns = xmlns;

    }
    @XmlAttribute(name ="xmlns")
    private String xmlns;
    private infNFe infNFe;

porem guando gero a NFe sai minusculo…
já fiz refiz e não acho o problema fiz uns teste e pude ver que todos os doc… xml que gero com jaxb
sai a primeita letra minusca alguem sabe o que devo fazer ?

exemplo de saida NFe.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nFe xmlns="http://www.portalfiscal.inf.br/nfe">
    <infNFe Id="NFe35100369348936000104551000000578591367169950" versao="2.00">
        <ide>

[/quote]

CONSEGUIIIIIIIIIIIIIIII !!!

ufa!!
a solução foi atribuir (name=“NFe”) na definição do root element
conf exp…

@XmlRootElement (name="NFe")
public class NFe {
    
    public NFe(){}
   
    public NFe(String xmlns,infNFe infNFe)
    {
        this.infNFe = infNFe;
        this.xmlns = xmlns;

    }
    @XmlAttribute(name ="xmlns")
    private String xmlns;
    private infNFe infNFe;

[quote=joaoorso]Em pessoal …
O que vcs estão usando para gerar o XML .
Encontrei várias bibliotecas : JDOM / Xerces / JAXP
Mas não sei qual é melhor para o problema em questão . [/quote]

Irmão Tiver esse mesmo problema que vc passei por quasse todas as ferramentas fiz uma aplicação toda em XStream
achei que tava bom quando foi pra salvar doc.xml o xStream não se mostrou tão bom …
JDom SAX fiz em todos …

mais eu queria JAXB …

achei esse Tutorial

http://www.devmedia.com.br/articles/viewcomp.asp?comp=11547

que salvo meu projeto minha ultima duvida consegui resolver…

Na minha Opinião Eu usaria Jaxb… “na meu caso foi o que fiz”
acho melhor para trabalhar com schema …
porem vc tem um leque de ferramentas …
faça esse tutorial do link que te passei…
antes de mais nada…
boa sorte …

Alguém ja montou a NFe do destinátario??
eu montei a nfe do destinatário , mas quando valido da um erro loco…

org.xml.sax.SAXParseException: Identity Constraint error: identity constraint "KeyRef@1d15445" has a keyref which refers to a key or unique that is out of scope.
se alguém tiver alguma dica…
alguem sabe de algum validador para o layout 2?

abraco

Validador: http://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx