issue with SAX parser in java - java

When web service is called by using SOAP request it will give following parse error.
I have check about the prolog of request its right there is no whitespace or dash. Even though it will cause following error
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Un
known Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispat
ch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Un
known Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Sour
ce)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:198)
at requestModel.SimpleCheckMail.checkMail(SimpleCheckMail.java:162)
at model.InboxDataBean.prepareList(InboxDataBean.java:97)
at model.InboxDataBean.getemailList(InboxDataBean.java:207)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELR
esolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELRe
solver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:1
89)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpress
ion.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.
java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.
java:182)
at javax.faces.component.UIData.getValue(UIData.java:731)
at javax.faces.component.UIData.getDataModel(UIData.java:1798)
at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIDa
ta.java:484)
at javax.faces.component.UIData.setRowIndex(UIData.java:473)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRen
derer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.jav
a:820)
at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.
java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView
(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewH
andler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePha
se.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
torBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:
927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
AbstractProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoin
t.java:1805)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:907)
at java.lang.Thread.run(Thread.java:619)
Please let me know whats the problem......of this error....thanx in advance
Ya....all of you are right ....But what i am getting is that it is an SOAP request and i have already see the request carefully there is no bad character.....But the problem is that when i am invoking the web service through soap request it gives null as a respone so i am getting the error.....
As soon as Webservice work properly ......this works fine now....thanks all of you

It means that there is something in xml before <?xml ... look carefully in it. Also check that there is no invisible character (you can do it in any HEX editor). Sometimes windows notepad adds his marker in the file beginning.

The parser sees character data before the actual XML itself is started. Either make sure your XML does not contain any stuff before the XML starts, or let your SAX parser ignore this...

Try to display the data you're actually parsing. Maybe some bad characters are inserted before the beginning of your xml, or maybe you're not reading the right file.

This may be a because of a BOM, if your XML file is stored as UTF-8 (which it probably is).
Here, you have an example of an InputStream, that gets rid of the BOM.

Related

GWT Maps Icon.NewInstance intermittently throwing exception

I'm creating a custom icon to use as a marker on a map, and intermittently, but quite often this function:
private Icon createIcon(String Url) {
Icon icon = Icon.newInstance(Url); //<-- This line throws exception
icon.setIconSize(Size.newInstance(30, 30));
icon.setIconAnchor(Point.newInstance(6, 20));
icon.setInfoWindowAnchor(Point.newInstance(14, 4));
return icon;
}
throws this exception:
11:05:55.076 [ERROR] [simplemap] Uncaught exception escaped
com.google.gwt.core.client.JavaScriptException: (TypeError) #com.google.gwt.core.client.impl.Impl::apply(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)([JavaScript object(311), JavaScript object(310), JavaScript object(333)]): undefined is not a function
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
Does anybody have any insight as to why this happens and what I can do to fix this behavior?
This ended up being a concurrency issue where the map was not finished loading when the icons were trying to be generated. When I moved some code around so it only ran after the Maps asynchronous load was finished this issue went away.

SilkTest base state unrecognized after consecutive tests run

In my testing environment, we have classes that perform certain actions, some of them using SilkTest stuff. The test procedures are defined by XML files that we parse, turn into ActionImpl classes, and perform stuff with. For example, the following will login to our app, switch users, and then restart the server:
<Script refBean="validateState" retry="false">
<DataGroups>
<Step action="log" mod="5.10.13 - Step 1" />
<Step action="switchUsers" target="mlane" />
<Step action="restartServer" />
</DataGroups>
</Script>
In the case of the restartServer action, the code eventually calls the following method, which creates a BaseState using the currently running eclipse.exe that the test is running in.
private PassFail restartServerInEclipse() {
Desktop desktop = new Desktop();
BaseState eclipseBaseState = new BaseState("*eclipse.exe", "/Shell[#caption='Java EE*']", TechDomain.SWT, TechDomain.XBROWSER, TechDomain.WIN32);
desktop.executeBaseState(eclipseBaseState);
// Do some stuff, like finding CTabItem objects, clicking them, etc.
return passFail;
}
Let's say I'm running the first test of the day. I just got to work, and decided to run a test. If the code gets to a restartServer action, and calls restartServerInEclipse(), it'll recognize the currently running eclipse.exe, and successfully perform any Silk methods on any Silk objects that I tell it to.
However, without exiting Eclipse or Open Agent, after a test has finished, if I run the same test again, as in, entirely new objects, entirely new test thread, the test ran and stopped, and I clicked the green run button in Eclipse again, I get the following error when it gets to the BaseState eclipseBaseState = new BaseState(...) code:
com.borland.silktest.jtf.common.LaunchApplicationFailedException: Failed to start application '*eclipse.exe' in working directory 'null'. The system cannot find the file specified.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.borland.silktest.jtf.agent.ExceptionTranslatorUtil.createException(ExceptionTranslatorUtil.java:60)
at com.borland.silktest.jtf.agent.ExceptionTranslatorUtil.translate(ExceptionTranslatorUtil.java:37)
at com.borland.silktest.jtf.agent.JtfModule.executeBaseState_aroundBody39$advice(JtfModule.java:121)
at com.borland.silktest.jtf.agent.JtfModule.executeBaseState(JtfModule.java:1)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:77)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy24.executeBaseState(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78)
at org.springframework.remoting.rmi.RmiBasedExporter.invoke(RmiBasedExporter.java:72)
at org.springframework.remoting.rmi.RmiInvocationWrapper.invoke(RmiInvocationWrapper.java:72)
at sun.reflect.GeneratedMethodAccessor12.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at org.springframework.remoting.support.RemoteInvocationUtils.fillInClientStackTraceIfPossible(RemoteInvocationUtils.java:47)
at org.springframework.remoting.rmi.RmiClientInterceptor.doInvoke(RmiClientInterceptor.java:351)
at org.springframework.remoting.rmi.RmiClientInterceptor.invoke(RmiClientInterceptor.java:258)
at com.borland.silktest.startservice.RmiConnectionUtil$1.invoke(RmiConnectionUtil.java:134)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy0.executeBaseState(Unknown Source)
at com.borland.silktest.jtf.Agent.executeBaseState(Agent.java:452)
at com.borland.silktest.jtf.BaseState.execute(BaseState.java:298)
at com.borland.silktest.jtf.Desktop.executeBaseState(Desktop.java:69)
at scripts.misc.validation.action.RestartServerActionImpl.restartServerInEclipse(RestartServerActionImpl.java:62)
at scripts.misc.validation.action.RestartServerActionImpl.evaluate(RestartServerActionImpl.java:25)
at scripts.misc.validation.ValidateState.evaluateStep(ValidateState.java:108)
at scripts.misc.validation.ValidateState.script(ValidateState.java:131)
at scripts.base.BaseScript.runWithRetries(BaseScript.java:204)
at scripts.base.BaseScript.runIt(BaseScript.java:312)
at suite.MainThread.script(MainThread.java:667)
at suite.MainThread.run(MainThread.java:281)
The base state that worked completely fine two seconds previous is now incorrect. As if something about Eclipse changes once the base state is initially set, so it can't re-recognize it.
The only way to get around this is to restart Eclipse and Open Agent, but even that doesn't work sometimes, and I run into some license server issues with OA occasionally, which requires a computer reboot.
From the log file you posted, I can see that you are switching between testing eclipse.exe and iexplore.exe. The way your script is currently built it is either one or the other. This means that as soon as you switch to Internet Explorer, Silk Test is detaching from Eclipse and will no longer recognize the window.
Since you are starting your applications through other mechanisms anyway, I suggest the attach method, which is cumulative and will add the pattern instead of replacing it, so you'll avoid switching between the applications.
Desktop desktop = new Desktop();
desktop.attach("*\\eclipse.exe", TechDomain.SWT, TechDomain.XBROWSER, TechDomain.WIN32);
desktop.attach("*\\iexplore.exe", TechDomain.SWT, TechDomain.XBROWSER, TechDomain.WIN32);
Shell eclipse = desktop.find("/Shell[#caption='Java EE*']");
BrowserApplication browserApp = desktop.find("/BrowserApplication");

Accessing Magento API with Java : Procedure ххх not present

I need to build Special Java Api to wrap Magento Api. After struggling with several Magento bugs, I am finally able to login and get session id; but any method I call leads me to an error. The error is:
Procedure '*procedure name*' not present
I generated Java code from wsdl using Eclipse build in plugin and wsdl located at my local server: http://localhost/magento/index.php/api/v2_soap?wsdl=1.
The example of java code I use:
Mage_Api_Model_Server_V2_HandlerPortTypeProxy proxy = new Mage_Api_Model_Server_V2_HandlerPortTypeProxy(
"http://localhost/magento/index.php/api/");
String sessionId = proxy.login("magentobot", "123456");
System.out.println("Session: " + sessionId);
CatalogProductEntity[] products = proxy.catalogProductList(sessionId, new Filters(), "");
And here is the exception I got:
Session: 12abdaf054fb7100b6c5d84ab8cb8311
Exception in thread "main" AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server
faultSubcode:
faultString: Procedure 'catalogProductList' not present
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:Procedure 'catalogProductList' not present
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:796)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
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 Magento.Mage_Api_Model_Server_V2_HandlerBindingStub.catalogProductList(Mage_Api_Model_Server_V2_HandlerBindingStub.java:3104)
at Magento.Mage_Api_Model_Server_V2_HandlerPortTypeProxy.catalogProductList(Mage_Api_Model_Server_V2_HandlerPortTypeProxy.java:260)
at Main2.main(Main2.java:14)
{http://xml.apache.org/axis/}hostname:Dacer
Here is the link to the official documentation: Magento product API
It says that the method is called catalog_product.list
The php code for the API works fine:
<?php
$proxy = new SoapClient('http://localhost/magento/index.php/api/?wsdl');
$sessionId = $proxy->login('magentobot', '123456');
$filters = array();
$products = $proxy->call($sessionId, 'product.list', array($filters));
var_dump($products);
?>
I will be glad to any help.
I've never used the API from java before, but looking over your code example, you said you generated code using the v2 WSDL (which is supposed to have better Java/.NET SOAP support), but in your code sample you're pointing at the v1 URL
http://localhost/magento/index.php/api/
I would assume you want your code sample pointing at
http://magento1point4.dev/index.php/api/v2_soap
but again, not a big Java (or SOAP, for that matter) guy, so appologies if there's something obvious I'm missing here.

Java XML Unmarshalling fails on ampersand (&) using JAXB

I have the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<details>
...
<address1>Test&Address</address1>
...
</details>
When I try to unmarshal it using JAXB, it throws the following exception:
Caused by: org.xml.sax.SAXParseException: The reference to entity "Address" must end with the ';' delimiter.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEntityReference(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:194)
But when I changed the & in the XML to &apos;, it works. Looks like the problem is only with ampersand & and I cannot understand why.
The code to unmarshal is:
JAXBContext context = JAXBContext.newInstance("some.package.name", this.getClass().getClassLoader());
Unmarshaller unmarshaller = context.createUnmarshaller();
obj = unmarshaller.unmarshal(new StringReader(xml));
Anyone have some insight?
EDIT: I tried the solution suggested by #abhin4v below (ie, add a space after &), but it doesn't seem to work too. Here's the stacktrace:
Caused by: org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEntityReference(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:194)
I've run into this too. First pass I simply replaced the &amp to a token string (AMPERSAND_TOKEN), sent it through JAXB, then re-replaced the ampersand. Not ideal, but it was a quick fix.
Second pass I made a lot of significant changes, so I'm not sure what exactly solved the problem. I suspect that providing JAXB access to the html dtds made it much happier, but that's only a guess and could be specific to my project.
HTH
Xerces converts & to & and then tries to resolve &Address which fails because it does not end with ;. Put a space between & and Address and it should work. Putting a space will not work as Xerces will now try to resolve & and throw the second error given in OP. You can wrap the test in a CDATA section and Xerces will not try to resolve the entities.
It turns out that the problem is because of the framework I'm using (Mentawai framework). The said XML comes from the POST body of an HTTP request.
Apparently, the framework converts the character entities in the XML body, therefore, & becomes & and the unmarshaller fails to unmarshal the XML.

Is there ANY way to save a graph object containing nodes and edges?

I've tried using the standard serializing type things, stuff like:
FileOutputStream f_out;
try {
f_out = new FileOutputStream("MAOS.data");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject(s);
obj_out.flush();
obj_out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} ;
But the problem seems to be that if my object s contains any recursion at ALL I get a stack overflow. If s is a graph that contains nodes and edges (with nodes knowing about edges for purposes of spreading activation, and edges knowing about nodes for the same reason) then it stack overflows. If I take edges out entirely, and just have nodes that know about which nodes they're supposed to spread activation too, the same thing happens! I can even just try to save the ArrayList of nodes that the graph knows about, and the stack overflows again!
I'm so frustrated!
Graphs aren't exactly strange and mysterious, surely SOMEONE has wanted to save one before me. I'm seeing something about saving them as XML files here...but if my problem is the recursiveness, wouldn't I still be having the same problems even if I saved it differently? I just can't think of how you could make a graph without there being connections!
Am I just doing things wrong, or is this object serialization less powerful than I thought? Or do I need to just abandon the idea of saving a graph?
-Jenny
Edit, part of the HUGE stack trace:
Exception in thread "main" java.lang.StackOverflowError
at java.io.ObjectStreamClass.getPrimFieldValues(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
These sort of structures are best saved like this:
collection of nodes, each node has a unique ID
collection of edges, each edge has two node IDs (or however many nodes an edge connects to)
without using any recursion. On reading the nodes, create a dictionary of nodes indexed by their ID. Then use the dictionary to fix up the edges when they're read. The IDs do not need to be part of the objects' run time structure, they only need to be unique within the data stream when the stream is written/read.
You could use the JGraphT library which supports serializing graphs into a text file with the ML format. GraphMLExporter Javadoc.
Java serialisation can cope with arbitrary graphs (although not necessarily very efficiently). Probably the problem lies with a custom implementation of writeObject. Perhaps a section of stack trace might help.
A useful serialization format you should consider is JSON, where dictionaries (as suggested by #Skizz) are easily represented:
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
Java serialization is capable of handling cyclic references (I assume this is what you mean by recursion), but there is a known problem with large graphs that is described here.
Don't let the date of the article throw you off, just follow chain of comments after it.
It seems you will have to use another serialization technique to accomplish this. Several have been mentioned, and some performance metrics give JSON high marks.
Hmmm. One solution would be to make it into a java bean and use XMLEncoder/XMLDecoder. This is a solution I've used in the past to save and load classes.

Categories

Resources