ArrayIndexOutOfBoundsException on Document.adoptNode() - java

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)

Related

Verify Signature XADES throw java.lang.ArrayIndexOutOfBoundsException: 0

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

copyURLToFile behavior in multithreading

I'm using copyURLToFile to download a file from url.
When I use it sequentially, in a loop, about 74% of the iterations sucsseds.
But when I use it in multithreading and there are 100 concurrently running Threads, it drops down to below 5%.
Interestingly enough, when i debug the program, it get back to 74% sucsses and even higher.
Every unsuccessful attempt is caused by an exception thrown:
java.net.MalformedURLException: no protocol:
My question is whether FileUtils uses some limited resource which cause a race condition, or any other reason it fails in significantly higher rate in multithreaded environment.
I have checked the documentation of copyURLToFile, but there is no refernce there to this issue.
I have also checked the source code of copyURLToFile), but couldn't spot any thing to give a hint of why those exceptions are thrown.
public void doDownload () {
try (final WebClient webClient = new WebClient()) {
// Get the page
final HtmlPage page1 = webClient.getPage(YouTubeConvertor);
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
final List<HtmlForm> form = page1.getForms();
final HtmlTextInput textField = form.get(0).getInputByName(InputName);
final HtmlSubmitInput button = form.get(0).getInputByValue(InputValue);
// Change the value of the text field
textField.setValueAttribute(this.link);
// Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
HtmlElement down = page2.getHtmlElementById(FileElement);
String name = down.getAttribute(HrefElement);
URL linkUrl = new URL(name);
File f = new File (Dir , this.saveName + Mp3Ending);
FileUtils.copyURLToFile(linkUrl, f);
} catch(Exception ex) {
System.out.println("Some form of error happened! " + ex.toString());
// timeout based on attempts and time elapsed
if (times++ < 10 && TimeUnit.SECONDS.convert
(System.nanoTime()-this.startTime, TimeUnit.NANOSECONDS) < 60) {
doDownload ();
}
}

When i tried running this code it causes " Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0" this exception

import javax.speech.*;
import java.util.*;// creates a default Systhesize
import javax.speech.synthesis.*; //code for text-speech engine
public class SpeechUtils
{
String speaktext;
public void dospeak(String speak,String voicename)
{
speaktext=speak;
String voiceName =voicename;
try
{
SynthesizerModeDesc desc = new
SynthesizerModeDesc(null,"general",Locale.US,null,null);
Synthesizer synthesizer = Central.createSynthesizer(desc);
synthesizer.allocate();
synthesizer.resume();
desc = (SynthesizerModeDesc)
synthesizer.getEngineModeDesc();
Voice[] voices = desc.getVoices();
Voice voice = null;
for (int i = 0; i < voices.length; i++)
{
if (voices[i].getName().equals(voiceName))
{
voice = voices[i];
break;
}
}
synthesizer.getSynthesizerProperties().setVoice(voice);
synthesizer.speakPlainText(speaktext, null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
synthesizer.deallocate();
}catch (Exception e)
{
String message = " missing speech.properties in " + System.getProperty("user.home") + "\n";
System.out.println(""+e);
System.out.println(message);}
}
public static void main(String[] args)
{
SpeechUtils obj=new SpeechUtils();
obj.dospeak(args[0],"life is beautiful");//getting an exception here....
}
}
How to fix this exception? i am getting an error like
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SpeechUtils.main(SpeechUtils.java:44)".
It is a Java program or text to speech conversion.i imported all the necessary libraries.But unable to fix this exception alone
You need to provide a runtime argument while running the program. As in your code your accessing the first argument:
obj.dospeak(args[0],"life is beautiful");//getting an exception here....
If you don't provide an argument then there will be no element at index 0 of args array and hence accessing it using args[0] will throw ArrayIndexOutOfBoundsException. You need to run your code like this:
java SpeechUtils argument
replace argument with the actual value you want to input to your program
You need to pass some argument when you do call to your program from commandline
java SpeechUtils "I am doing well"
please remember
java.lang.ArrayIndexOutOfBoundsException:10
means that Array which you are trying to access does not have any element assigned to it at Array[10]
i.e. 11th element is missing. Here you are getting exception at 0 which means 0th element is not there
Missing argument While execution of the program.
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Error caused due to missing argument which you need to provide, since you had used args[0] in the code obj.dospeak(args[0],"life is beautiful"); So pass argument while runtime. args[0] denote array with its first element so, only one argument is necessary to run your program.
Use the command java SpeechUtils YourArgumentYouWantToAdd

Protobuf / Protocol Buffers - IndexOutOfBoundsException

I am developing a Client-Server-application which uses Google Protocol Buffers.
Unfortunatelly when I am building the protocol buffer response on the server side using the builder pattern I get a IndexOutOfBoundsException:
This is the line where I build the protobuf file:
Builder getVGResonseBuilder = App_getVGResponse.GetVGResponse.newBuilder().getVGBuilder(0);
[some more code that uses the builder patterns]
getVGResponseBuilder.set...
getVGResponseBuilder.set...
the error occures in the first line of code.
here is the protobuf definition (ofc I have compiled it! The compiled calss is App_getVGResponse):
message GetVGResponse {
message VG {
optional string id = 1;
optional string g_id = 2;
optional int64 f_id = 3;
optional string g_name = 4;
}
repeated VG v_gp = 1;
}
Here is a excerpt of my stacktrace
Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: **Protocol message tag had invalid wire type.**
at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:78)
at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:498)
at com.google.protobuf.GeneratedMessage$Builder.parseUnknownField(GeneratedMessage.java:439)
and the debugger at runtime shows ma the variable:
e
-> cause: IndexOutOfBoundsException (id=12291)
-> detaiMessage: Index: 0, Size: 0 (id=12324)
-> stackTrace null
personally I create the "child builder" then add it to the parent builder. i.e.
App_GetVGResponse.GetVGResponse.Builder bldr = App_GetVGResponse.GetVGResponse.newBuilder();
App_GetVGResponse.GetVGResponse.VG.Builder childBldr = App_GetVGResponse.GetVGResponse.VG.newBuilder();
childBldr.setId(value);
...........
bldr.addVGp(childBldr);
I think the error is because you get the "child" builder before adding one

Play Framework 2.0: "Errorjava.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file

Xml Template:
#(product: models.Product, productComponents: List[models.ProductComponent])
<product>
<name>#product.name</name>
<tomcatLocation>#product.tomcatLocation</tomcatLocation>
<productComponents>
#for(productComponent <- productComponents) {
<component>
<name>#productComponent.name</name>
<packageName>#productComponent.packageName</packageName>
<buildPath>#productComponent.buildPath</buildPath>
<packageFormat>#productComponent.packageFormat</packageFormat>
<versionAction>#productComponent.versionAction</versionAction>
<versionFilePath>#productComponent.versionFilePath</versionFilePath>
<versionCommand>#productComponent.versionCommand</versionCommand>
</component>
}
</productComponents>
</product>
Controller Action:
public static Result upgradeProduct(String serverId, String productId) throws InterruptedException
{
models.Server server = models.Server.retrieveById(Long.parseLong(serverId));
models.Product product = models.Product.retrieveById(Long.parseLong(productId));
List<models.ProductComponent> productComponents =
models.ProductComponent.retrieveByProductId(Long.parseLong(productId));
Xml renderedXmlPage = upgradeService.render(product, productComponents);
Promise<WS.Response> upgradeStatus =
WS.url("http://" + server.hostIp + ":8085/upgradeProduct").setHeader("Content-Type", "text/xml").post(
renderedXmlPage.toString());
String testMessage = upgradeStatus.get().getBody();
return TODO;
}
Web Service:
public static Result upgradeProduct()
{
return async( WS.url(MAIN_URL).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response)
{
try
{
Document doc = response.asXml();
return ok("I WORKED");
}
catch(RuntimeException e)
{
return ok("Error" + e.getMessage()+ "\n");
}
}
})
);
}
When I run this action, The following runtime exception is thrown
"Errorjava.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.".
The this exception is being thrown at "Document doc = response.asXml();". I don't know why this is occurring? any help is much appreciated thanks!
Stack Trace:
play.libs.WS$Response.asXml(WS.java:332)
controllers.Service$1.apply(Service.java:40)
controllers.Service$1.apply(Service.java:35)
play.libs.F$Promise$2.apply(F.java:111)
play.api.libs.concurrent.STMPromise$$anonfun$map$1$$anonfun$apply$9.apply(Promise.scala:185)
scala.util.control.Exception$Catch$$anonfun$either$1.apply(Exception.scala:110)
scala.util.control.Exception$Catch$$anonfun$either$1.apply(Exception.scala:110)
scala.util.control.Exception$Catch.apply(Exception.scala:88)
scala.util.control.Exception$Catch.either(Exception.scala:110)
play.api.libs.concurrent.STMPromise.redeem(Promise.scala:166)
play.api.libs.concurrent.STMPromise$$anonfun$map$1.apply(Promise.scala:185)
play.api.libs.concurrent.STMPromise$$anonfun$map$1.apply(Promise.scala:184)
play.api.libs.concurrent.STMPromise$PromiseInvoker$$anonfun$receive$1.apply(Promise.scala:10 4)
play.api.libs.concurrent.STMPromise$PromiseInvoker$$anonfun$receive$1.apply(Promise.scala:10 3)
akka.actor.Actor$class.apply(Actor.scala:290)
play.api.libs.concurrent.STMPromise$PromiseInvoker.apply(Promise.scala:101)
akka.actor.ActorCell.invoke(ActorCell.scala:617)
akka.dispatch.Mailbox.processMailbox(Mailbox.scala:179)
akka.dispatch.Mailbox.run(Mailbox.scala:161)
akka.dispatch.ForkJoinExecutorConfigurator$MailboxExecutionTask.exec(AbstractDispatcher.scala:505)
akka.jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:259)
akka.jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:997)
akka.jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1495)
akka.jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)
Correct me if I'm wrong, but it doesn't look like you are returning your xml document from the service!? Instead you return "I WORKED", which of cause won't parse as xml, and the parser will throw an exception.
In the Service you are calling, via WS, an external URL (MAIN_URL) and using the response on line:
Document doc = response.asXml();
The error means that the service you are calling (MAIN_URL) is not returning XML.
By the way, your controller has TODO as return value, I'm not sure if that's what you want in there as it seems that you have working code in the controller.
Other than the obvious case of not having any XML input to begin with, sometimes this error also gets thrown the second time your code tries to read a javax.xml.transform.Source or a javax.xml.transform.sax.SAXSource. The first time everything runs OK, but the second time the bytes have been consumed and you get that exception. At least that how I've encountered it, in which case I simply create the Source anew - I don't know applicable this is in your particular case.

Categories