Verify Signature XADES throw java.lang.ArrayIndexOutOfBoundsException: 0 - java

I need to verify signature XADES in signed xml file. I use xades4j v. 1.4.0 but when call method verify throw java.lang.ArrayIndexOutOfBoundsException: 0.
With some file work , with other one no.
I have tried in debug mode and the exception throw in method checkForm -XAdESFormChecker class.
My code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputStream);
DOMHelper.useIdAsXmlId(doc.getDocumentElement());
NodeList nList = doc.getElementsByTagName("ds:Signature");
Element elem = null;
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
elem.setIdAttributeNS(null, "Id", true);
}
}
data = item.getData();
CertificateValidationProvider certValidator = new CertificateValidationProviderImpl();
XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
XadesVerifier v = p.newVerifier();
SignatureSpecificVerificationOptions opts = new SignatureSpecificVerificationOptions().useDataForAnonymousReference(data);
XAdESVerificationResult result = v.verify(elem, opts);
The signature :Xml signature
Can you help me?
What is the error?
EDIT - STACK TRACE
*java.lang.ArrayIndexOutOfBoundsException: 0
at xades4j.verification.XAdESFormChecker$XAdESFormDesc.getPrevious(XAdESFormChecker.java:109)
at xades4j.verification.XAdESFormChecker.checkForm(XAdESFormChecker.java:55)
at xades4j.verification.XadesVerifierImpl.verify(XadesVerifierImpl.java:213)
at it.yyy.kkkFramework.albo.InserimentoRichiestaController.listenerUploadDoc(InserimentoRichiestaController.java:1811)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:187)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.richfaces.event.MethodExpressionEventListener.processEvent(MethodExpressionEventListener.java:125)
at org.richfaces.view.facelets.FileUploadHandler$FileUploadListenerImpl.processFileUpload(FileUploadHandler.java:55)
...

xades4j is based in ETSI TS 101 903 (XAdES 1.4.1). You signature, however, contains SigningCertificateV2, which is a property defined in more recent XAdES specs, not yet supported by xades4j. This is causing the error, as the SigningCertificate property is not present.
The library shouldn't be throwing the "array out of bounds" exception (this will be fixed, as it is a bug), but it wouldn't be able to verify the signature. If it wasn't for the bug you'd see the much more obvious exception thrown in this line: https://github.com/luisgoncalves/xades4j/blob/master/src/main/java/xades4j/verification/XAdESFormChecker.java#L64

Related

Get "Current Node: [#document: null], type: 9" when call XMLSignature.validate and run on JBOSS 7

I have a signed xml file with content:
<?xml version="1.0" encoding="utf-8" standalone="yes"?><ObjectMessage TXDATE="" TXNUM="" TXTIME="" TLID="" MBID="" LOCAL="N" MSGTYPE="O" OBJNAME="SA.SYSVAR" ACTIONFLAG="INQUIRY" CMDINQUIRY=" SELECT MAX(NVL(ACTUALVERSION,'')) AS ACTUALVERSION, MAX(NVL(AUTOUPDATE,'')) AS AUTOUPDATE, MAX(NVL(REPORTVERSION,'')) AS REPORTVERSION FROM ( SELECT VARVALUE AS ACTUALVERSION, '' AS AUTOUPDATE, '' REPORTVERSION FROM SYSVAR WHERE VARNAME='ACTUALVERSION' UNION ALL SELECT '' AS ACTUALVERSION, VARVALUE AUTOUPDATE, '' REPORTVERSION FROM SYSVAR WHERE VARNAME='AUTOUPDATE' UNION ALL SELECT '' AS ACTUALVERSION, '' AUTOUPDATE, VARVALUE REPORTVERSION FROM SYSVAR WHERE VARNAME='REPORTVERSION')" CLAUSE="" FUNCTIONNAME="" AUTOID="" REFERENCE="" RESERVER="" IPADDRESS="192.168.22.22" CMDTYPE="T" PARENTOBJNAME="" PARENTCLAUSE="" SESSIONID="1A7FD51AB9F1989132EBEA49A3AF8F408AE906E35B84B7ED360F6CECC546EC6412674C14C693108735A9B8B0882261A9C44711AF60C343701D5BA1A6B5FCF2E40AB7858023C446E4B40CD0DFCE659032C083D3E5FA85504AF433F736BC39BD1A87D047430BF37B7B8D0EB960868A6C2C" REQUESTID="a341acd6-3540-48a0-9f92-b8e896bb1b50" CHILDTABLE=""><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116"><XPath>ancestor-or-self::Signature</XPath></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</DigestValue></Reference></SignedInfo><SignatureValue>dz/JLG9rh+o5eAe34R4WQOBR/a+YJ3LCnSe6Uijh3bbwbXM6JvfLhux4T4DUJA+jb7UZoFWQ0orh7xAyh1ecWlyvrDSNrkWA3XjNuXLyxlNLOhOZIo4ou0glpLHGQHIC7u5q7OxLfBartbnnyZHvVrueFfwJvrZI4JkNqhwUll8=</SignatureValue><KeyInfo><X509Data><X509Certificate>MIIEfDCCA2SgAwIBAgIQVAMHXnuXweJ+qlRbtOgaNTANBgkqhkiG9w0BAQUFADBJMQswCQYDVQQGEwJWTjEOMAwGA1UEBxMFSGFub2kxGTAXBgNVBAoTEEJrYXYgQ29ycG9yYXRpb24xDzANBgNVBAMTBkJrYXZDQTAeFw0xODA0MDQwNDUwNDRaFw0yMDA1MTUwMzM1NDhaMIHNMTEwLwYKCZImiZPyLGQBAQwhQ01ORDowMTAyNjg0MDA2LUNNTkQ6MDM0MDgzMDAwMDM0MRwwGgYDVQQDDBNM4bqhaSBI4buvdSBExrDGoW5nMUMwQQYDVQQKDDpDw7RuZyBUeSBD4buVIFBo4bqnbiBHaeG6o2kgUGjDoXAgUGjhuqduIE3hu4FtIFTDoGkgQ2jDrW5oMRQwEgYDVQQHDAtUaGFuaCBYdcOibjESMBAGA1UECAwJSMOgIE7hu5lpMQswCQYDVQQGEwJWTjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAnO6nPGRJo77txMVboWcG4JtM1KF+Fo0qzuw4y22cUDcRYZY0FWPMWOs0rB9cxuMz8wgtonyabnjEwsNDCrvozPwRVYZwmeLrDS1aFPx5/Q9qDeYyTPTaEYrg0roTVSMKp+vmeUTWkZB0E2YWBfU1Pg6lgPTVHe/mlH1VQmgwkvcCAwEAAaOCAV0wggFZMDEGCCsGAQUFBwEBBCUwIzAhBggrBgEFBQcwAYYVaHR0cDovL29jc3AuYmthdmNhLnZuMB0GA1UdDgQWBBRZq1U4DEA/D5DmAZcr+IRQqVgVozAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFB6wD0iX39DDZ6dGhDtYO4gNU5SGMH8GA1UdHwR4MHYwdKAjoCGGH2h0dHA6Ly9jcmwuYmthdmNhLnZuL0JrYXZDQS5jcmyiTaRLMEkxDzANBgNVBAMMBkJrYXZDQTEZMBcGA1UECgwQQmthdiBDb3Jwb3JhdGlvbjEOMAwGA1UEBwwFSGFub2kxCzAJBgNVBAYTAlZOMA4GA1UdDwEB/wQEAwIGwDAfBgNVHSUEGDAWBggrBgEFBQcDBAYKKwYBBAGCNwoDDDAkBgNVHREEHTAbgRl0aHV5Lm5ndXllbmxlQGZzc2MuY29tLnZuMA0GCSqGSIb3DQEBBQUAA4IBAQC6nSJ4Uiuca1uQ5BRihpbep8qTPakG571zmD/MchVjVAykRmvvPUMb/+osXVFiy7DdDkuvmn2oOZGUtd16uTd13MRtNyjGHZB8aOEmi8LElV9YUzSw17VWkN9MWOtmJDo76RRND0S8CaIXYEI09vAtoeUr0GGEpu1rxUnfgTv3BaR86I0gm+6RWbBBGT9YtT/HSrua6WDp6aI3sN7sWCSl4j7nIWVPyfkJYxP6VTA8XboTeTMGLl+zZBLjwbVtdRDa6hjNhUF+P2yDR+U0b1tUGfJu3HRmKEAr7+BrKHfa9ZQNzK9uvV4/+DOj5vAzGozX2fKpFriS0MZ5dQoo/0UB</X509Certificate></X509Data></KeyInfo></Signature></ObjectMessage>
I try to verify it with java code:
File fff = new File("S:\\signeData.xml");
FileInputStream fileInputStream = new FileInputStream(fff);
long byteLength = fff.length();
byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder()
.parse(new ByteArrayInputStream(filecontent));
dbf.setNamespaceAware(true);
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
String providerName = System.getProperty("jsr105Provider",
"org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
(Provider) Class.forName(providerName).newInstance());
DOMValidateContext valContext = new DOMValidateContext(
new XmlUtil.X509KeySelector(), nl.item(nl.getLength() - 1));
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
res = signature.validate(valContext);
Almost another xml files can be authenticated, except for this file. It was crash in res=signature.validate(valContext) with Current Node: [#document: null], type: 9 message. The puzzling point is, if I run this code on eclipse, everything is normal, the file is successfully validated. This error only occurs when the code is run on JBOSS 7, only with this file.

PDF document verify exception

When I try to verify signed pdf document I get RuntimeException:
Exception in thread "main" java.lang.RuntimeException: algorithm identifier 1.2.398.3.10.1.1.1.1 in key not recognised
at org.bouncycastle.jce.provider.JDKKeyFactory.createPublicKeyFromPublicKeyInfo(Unknown Source)
at org.bouncycastle.jce.provider.X509CertificateObject.getPublicKey(Unknown Source)
at com.itextpdf.text.pdf.PdfPKCS7.<init>(PdfPKCS7.java:582)
at com.itextpdf.text.pdf.PdfPKCS7.<init>(PdfPKCS7.java:421)
at com.itextpdf.text.pdf.AcroFields.verifySignature(AcroFields.java:2307)
at Main.verifyPDF(Main.java:62)
at Main.main(Main.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
my verification piece of code looks like this:
public static boolean verifyPDF(String fileToVerify, KeyStore trustedStore, CRL crl) throws IOException, GeneralSecurityException {
List<CRL> crls = null;
if (crl != null) {
crls = new ArrayList<CRL>(1);
crls.add(crl);
}
boolean result = false;
PdfReader checker = new PdfReader(fileToVerify);
AcroFields af = checker.getAcroFields();
ArrayList<String> names = af.getSignatureNames();
for (int k = 0; k < names.size(); ++k) {
String name = (String) names.get(k);
System.out.println("Signature: " + name);
com.itextpdf.text.pdf.PdfPKCS7 pk = af.verifySignature(name, "KALKAN");
result = pk.verify();
System.out.println("Signer certificate DN: " + pk.getSigningCertificate().getSubjectDN());
Calendar cal = pk.getSignDate();
X509Certificate pkc[] = (X509Certificate[]) pk.getSignCertificateChain();
System.out.println("Document modified: " + !result);
Object fails[] = PdfPKCS7.verifyCertificates(pkc, trustedStore, crls, cal);
if (fails == null)
System.out.println("Certificates verified against the KeyStore");
else
System.out.println("Certificate failed: " + fails[1]);
}
return result;
}
the exception occurs on this string:
com.itextpdf.text.pdf.PdfPKCS7 pk = af.verifySignature(name, "KALKAN");
I use patched iText library. I had to patch it because there was no algorithm like ECGOST34310 and I just added it. Signing is performed in usual way, there is no problem with it.
Please help!
Thanks.
At first glance that OID 1.2.398.3.10.1.1.1.1 seems to be defined by a Kazakh authority (cf. this page), related to GOST 34,310-2.004 represented by the parent OID, without having yet been included in the mainstream BouncyCastle distribution, cf. the BouncyCastle specifications.
Thus, just like you have extended iText to be able to sign using GOST 34,310-2.004
I use patched iText library. I had to patch it because there was no algorithm like ECGOST34310 and I just added it.
you have to extend it (or in this case more exactly the crypto library BouncyCastle used by iText) to be able to verify signatures using GOST 34,310-2.004. Maybe, though, someone else already has done that and comes forth to help?
By the way, it would be great if you shared the results as soon as they work.
That all been said I am not aware of GOST being mentioned in the context of either ISO 32000-1 or PAdES integrated PDF signatures. Using GOST for PDF signatures, therefore, will likely result in very limited interoperability.

ArrayIndexOutOfBoundsException on Document.adoptNode()

I'm getting an ArrayIndexOutOfBoundsException when I call adoptNode() from the Document.
The problem occurs on the 10th call to the method.
The error occurs on line
nodeToPutSignature.getOwnerDocument().adoptNode(signature);
All the method code:
Document tempDocument = new XmlParser().getDocument();
// Sign the temporary Document using xmldsig
sign(tempDocument, getAddress());
tempDocument = XmlTools.newDocument(XmlTools.nodeToString(tempDocument));
// Signature tag from temporary document
final Node signature = XmlTools.getNode(tempDocument, getAddress() + "//Signature");
final Node nodeToPutSignature = XmlTools.getNode(node,
XPathTools.getXPath(signature.getParentNode()));
// Put the signature tag on the document
nodeToPutSignature.getOwnerDocument().adoptNode(signature);
nodeToPutSignature.appendChild(signature);
All the stacktrace:
java.lang.ArrayIndexOutOfBoundsException: 35
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.clearChunkIndex(DeferredDocumentImpl.java:2023)
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.getLastChild(DeferredDocumentImpl.java:826)
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.getLastChild(DeferredDocumentImpl.java:811)
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.synchronizeChildren(DeferredDocumentImpl.java:1693)
at com.sun.org.apache.xerces.internal.dom.DeferredAttrImpl.synchronizeChildren(DeferredAttrImpl.java:142)
at com.sun.org.apache.xerces.internal.dom.AttrImpl.setOwnerDocument(AttrImpl.java:198)
at com.sun.org.apache.xerces.internal.dom.NamedNodeMapImpl.setOwnerDocument(NamedNodeMapImpl.java:405)
at com.sun.org.apache.xerces.internal.dom.ElementImpl.setOwnerDocument(ElementImpl.java:235)
at com.sun.org.apache.xerces.internal.dom.ParentNode.setOwnerDocument(ParentNode.java:184)
at com.sun.org.apache.xerces.internal.dom.ElementImpl.setOwnerDocument(ElementImpl.java:233)
at com.sun.org.apache.xerces.internal.dom.ParentNode.setOwnerDocument(ParentNode.java:184)
at com.sun.org.apache.xerces.internal.dom.ElementImpl.setOwnerDocument(ElementImpl.java:233)
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.adoptNode(CoreDocumentImpl.java:1874)
at br.gov.serpro.testtool.xml.testtool.tag.Sign.visit(Sign.java:67)

Out of memory Error when using scala to process some xml

I have broken wiki xml dump into many small parts of 1M and tried to clean it (after cleaning it with another program by somebody else)
I get an out of memory error which I don't know how to solve. Can anyone enlighten me?
I get the following error message:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at org.apache.lucene.index.FreqProxTermsWriterPerField$FreqProxPostingsArray.<init>(FreqProxTermsWriterPerField.java:212)
at org.apache.lucene.index.FreqProxTermsWriterPerField$FreqProxPostingsArray.newInstance(FreqProxTermsWriterPerField.java:235)
at org.apache.lucene.index.ParallelPostingsArray.grow(ParallelPostingsArray.java:48)
at org.apache.lucene.index.TermsHashPerField$PostingsBytesStartArray.grow(TermsHashPerField.java:252)
at org.apache.lucene.util.BytesRefHash.add(BytesRefHash.java:292)
at org.apache.lucene.index.TermsHashPerField.add(TermsHashPerField.java:151)
at org.apache.lucene.index.DefaultIndexingChain$PerField.invert(DefaultIndexingChain.java:645)
at org.apache.lucene.index.DefaultIndexingChain.processField(DefaultIndexingChain.java:342)
at org.apache.lucene.index.DefaultIndexingChain.processDocument(DefaultIndexingChain.java:301)
at org.apache.lucene.index.DocumentsWriterPerThread.updateDocument(DocumentsWriterPerThread.java:241)
at org.apache.lucene.index.DocumentsWriter.updateDocument(DocumentsWriter.java:454)
at org.apache.lucene.index.IndexWriter.updateDocument(IndexWriter.java:1541)
at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1256)
at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:1237)
at qa.main.ja.Indexing$$anonfun$5$$anonfun$apply$4.apply(SearchDocument.scala:234)
at qa.main.ja.Indexing$$anonfun$5$$anonfun$apply$4.apply(SearchDocument.scala:224)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.Iterator$class.foreach(Iterator.scala:750)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1202)
at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at qa.main.ja.Indexing$$anonfun$5.apply(SearchDocument.scala:224)
at qa.main.ja.Indexing$$anonfun$5.apply(SearchDocument.scala:220)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
Where line 234 is as follows:
writer.addDocument(document)
It is adding some documents to Lucene
and where line 224 is as follows:
for (doc <- target_xml \\ "doc") yield {
It is the first line of a for loop for adding various elements as fields in the index.
Is it a code problem, setting problem or hardware problem?
EDIT
Hi, this is my for loop:
for (knowledgeFile <- knowledgeFiles) yield {
System.err.println(s"processing file: ${knowledgeFile}")
val target_xml=XML.loadString(" <file>"+cleanFile(knowledgeFile).mkString+"</file>")
for (doc <- target_xml \\ "doc") yield {
val id = (doc \ "#id").text
val title = (doc \ "#title").text
val text = doc.text
val document = new Document()
document.add(new StringField("id", id, Store.YES))
document.add(new TextField("text", new StringReader(title + text)))
writer.addDocument(document)
val xml_doc = <page><title>{ title }</title><text>{ text }</text></page>
id -> xml_doc
}
}).flatten.toArray`
The inner loop just loops thru every doc element. The outer loop loops thru every file. Is the nested for the source of the problem?
Below is the cleanFile function for reference:
def cleanFile(fileName:String):Array[String] = {
val tagRe = """<\/?doc.*?>""".r
val lines = Source.fromFile(fileName).getLines.toArray
val outLines = new Array[String](lines.length)
for ((line,lineNo) <- lines.zipWithIndex) yield {
if (tagRe.findFirstIn(line)!=None)
{
outLines(lineNo) = line
}
else
{
outLines(lineNo) = StringEscapeUtils.escapeXml11(line)
}
}
outLines
}
Thanks again
Looks like you would like to try increasing the heap size by having -xmx jvm argument?

can't write dom document to xml file

I have spring mvc project in whicn I upload xml file and try to write it to the my xml by DOM, but confront with this exception. When I make attempts to do the same proccesses in usual project - all works fine. Can't understand why it happens..
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.NullPointerException
org.apache.xml.utils.TreeWalker.dispatachChars(TreeWalker.java:303)
org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:447)
org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:202)
org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:343)
com.mycompany.xmlloader.xmlHandler.DOMParser.saveToCatalog(DOMParser.java:147)
com.mycompany.xmlloader.service.XMLServiceImpl.updateCatalog(XMLServiceImpl.java:48)
com.mycompany.xmlloader.controller.XMLController.uploadToCatalog(XMLController.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
And snippet of code:
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(catalogFile.toURI().getPath());
Source source = new DOMSource(doc);
trans.transform(source, result);
The likely cause of your problem is a Text node in your Document which has its data set to null. (See here and here for discussions of the problem.)
You can check your Document to see if this diagnosis is correct using the following code:
public static void checkDoc(Node n) {
if (n instanceof Text) {
if (((Text) n).getData() == null) {
System.err.println("null data!!!!");
}
}
NodeList l = n.getChildNodes();
for (int i = 0; i < l.getLength(); ++i) {
checkDoc(l.item(i));
}
}
Call checkDoc on your Document:
checkDoc(doc);
If you see any output, then you now know the immediate cause for your NPE. The solution to your problem is then: Do not build a Document containing Text nodes with null data.

Categories