JAXB XML Object Marshalling without namespace prefixes - namespaces

Im working on a java project where i need to read some objects from an XML file, do some processing which will alter the object´s atributes and then write the Object to another XML file. For that purpose, i am using JAXB with its marshalling and unmarshalling capabilities, each of them in a method, like this:
private MyObject unmarshallXMLFile(String file) {
MyObject t=null;
try {
jc = JAXBContext.newInstance("foo.bar");
Unmarshaller unmarshaller = jc.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
unmarshaller.setSchema(sf.newSchema(new File("MySchema.xsd")));
t = (Task) unmarshaller.unmarshal(new File(file));
} catch (JAXBException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return t;
}
private void marshallXMLFile(String file) {
task.setReplay(Boolean.TRUE);
Marshaller marshaller;
try {
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
marshaller.marshal(task, new FileOutputStream(file));
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The problem is that automatically-generated namespace prefixes such as ns2 or ns3 keep appearing in the output file, and then when i want to reuse this files with the unmarshallXMLFile method (i will be using the output files as input again later) it wont get validated against the schema, and throws a org.xml.sax.SAXParseException. Here are the files i wrote:
XML Schema: MySchema.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/MySchema"
xmlns:spm="http://www.example.org/MySchema"
elementFormDefault="qualified"
attributeFormDefault="qualified">
<element name="task" >
<complexType>
<sequence>
<element name="replay" type="boolean" default="false"/>
<element name="threads" type="spm:spThread" maxOccurs="unbounded" minOccurs="1" />
</sequence>
</complexType>
</element>
<complexType name="spThread">
<sequence>
<element name="SPThreadID" type="int" />
<element name="durtime" minOccurs="0" default="0">
<simpleType>
<restriction base="int">
<minInclusive value="0" />
</restriction>
</simpleType>
</element>
<element name="minexecutions" minOccurs="0" default="0">
<simpleType>
<restriction base="int">
<minInclusive value="0" />
</restriction>
</simpleType>
</element>
<element name="numThreads" type="int" />
<element name="procedures" type="spm:procedure" minOccurs="1"
maxOccurs="unbounded" />
</sequence>
</complexType>
<complexType name="procedure">
<sequence>
<element name="id" type="int" minOccurs="1" />
<element name="name" type="string" minOccurs="1" />
<element name="weight" minOccurs="1">
<simpleType>
<restriction base="int">
<minInclusive value="0" />
<maxInclusive value="100" />
</restriction>
</simpleType>
</element>
<element name="parameterPool" type="spm:parameter" nillable="true"
minOccurs="0" maxOccurs="unbounded" />
</sequence>
</complexType>
<complexType name="parameter">
<sequence>
<element name="name" type="string" minOccurs="1" />
<element name="dataType" type="spm:parameterDataType" default="integer"/>
<element name="parmType" type="spm:parameterType" default="in"
minOccurs="0" />
<element name="minValue" type="string"/>
<element name="maxValue" type="string"/>
<element name="value" type="string"/>
</sequence>
</complexType>
<simpleType name="parameterDataType">
<restriction base="string">
<enumeration value="integer" />
<enumeration value="varchar" />
<enumeration value="char" />
</restriction>
</simpleType>
<simpleType name="parameterType">
<restriction base="string">
<enumeration value="in" />
<enumeration value="out" />
<enumeration value="in_out" />
</restriction>
</simpleType>
</schema>
input file:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<task xmlns="http://www.example.org/MySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/MySchema MySchema.xsd ">
<replay>true</replay>
<threads>
<SPThreadID>0</SPThreadID>
<durtime>10</durtime>
<minexecutions>2</minexecutions>
<numThreads>3</numThreads>
<procedures>
<id>1</id>
<name>run</name>
<weight>15</weight>
<parameterPool>
<name>energy</name>
<dataType>integer</dataType>
<parmType>in</parmType>
<minValue>10</minValue>
<maxValue>50</maxValue>
<value>11</value>
</parameterPool>
<parameterPool>
<name>speed</name>
<dataType>integer</dataType>
<parmType>in</parmType>
<minValue>12</minValue>
<maxValue>80</maxValue>
<value>13</value>
</parameterPool>
</procedures>
</threads>
</task>
output file (without any processing whatsoever: just unmarshalling and marshalling back with the methods mentioned earlier)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:task xmlns="http://www.example.org/MySchema" xmlns:ns2="http://www.example.org/MySchema.xsd">
<replay>true</replay>
<threads>
<SPThreadID>0</SPThreadID>
<durtime>10</durtime>
<minexecutions>2</minexecutions>
<numThreads>3</numThreads>
<procedures>
<id>1</id>
<name>run</name>
<weight>15</weight>
<parameterPool>
<name>energy</name>
<dataType>integer</dataType>
<parmType>in</parmType>
<minValue>10</minValue>
<maxValue>50</maxValue>
<value>11</value>
</parameterPool>
<parameterPool>
<name>speed</name>
<dataType>integer</dataType>
<parmType>in</parmType>
<minValue>12</minValue>
<maxValue>80</maxValue>
<value>13</value>
</parameterPool>
</procedures>
</threads>
</ns2:task>
exception (when using the ouput file again as an input):
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException: cvc-elt.1: The declaration of the element'ns3:task' could not be found.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:326)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:500)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:206)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:175)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:148)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:153)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:180)
at Test.main(Test.java:48)
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: The declaration of the element'ns3:task' could not be found.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(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.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at org.apache.xerces.jaxp.validation.XMLSchemaValidatorHandler.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:85)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:113)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(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 com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:202)
... 6 more
I´ve been reading about the subject and tried loads of related answers, but none of them seems to remove the prefixes. I went trough this guide but the version of jaxb i am using does not support NamespacePrefixMapper. I tried using annotations as described here to configure the prefixes but that wouldnt work.
Maybe there is a way of getting rid of this namespace prefixes: all the forums, answers and discussions i´ve found talk about customizing this prefixes, i just want to get rid of them. But somehow it makes me think that i´m missing something in both my input file and schema. Are they well written? I would say that right there is the problem, because it is the first time i work with xml and xsd at this depth, and what i´ve done is only based on what i´ve found online. Any tips on improving the xml and xsd designs would be highly appreciated
should i be using some kind of prefixes in the input file or in the schema so the JAXB framework wont generate random prefixes at time of marshalling?
thanks in advance, i hope you guys can help me.
--
Thank you very much for the answer. In that way i can use the NamespacePrefixMapper. However, when i use it, my code keeps throwing exceptions when i run it:
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name javax.xml.bind.Messages, locale de_DE
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:863)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:832)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:576)
at javax.xml.bind.Messages.format(Messages.java:47)
at javax.xml.bind.Messages.format(Messages.java:36)
at javax.xml.bind.PropertyException.<init>(PropertyException.java:99)
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:349)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527)
at Test.main(Test.java:95)
I found that it has to do something with a .properties file: i am not using anything like it, i havent changed anything.

Instead of specifying the #XmlElement's namespace attribute in every element, it's simpler to annotate at package level.
You do that by creating a file package-info.java just underneath the package you want to annotate.
For example, if you want to annotate the package org.example, then a file named package-info.java must be placed within the directory org/example with the following content:
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/StoredProceduresSchema", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.example;
It's important to note that you must annotate every package that contains classes that your plan to marshal or are referenced by those.
Hope this helps :)

Try using a NamespacePrefixMapper:
NamespacePrefixMapper mapper = new NamespacePrefixMapper() {
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
return "";
}
};
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);

Well, after some research, i tried using the #XMLElement tag on every attribute of the classes i am trying to serialize, specifying clearly what my namespace was, and using the same one on every attribute:
#XmlElement(required = true, name="myObjectPool", namespace="http://www.example.org/StoredProceduresSchema")
protected List<MyObject> myObjectPool;
It worked flawlessly: no more weird namespaces in the marshalled file.
I wanna thank for his answer: i tried that as well, but i got a weird language bundle related exception. Im glad this simpler approach solved the issue.

Then you might be using a different JAXB implementation then the reference. Read this article and try again: http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html (or if you are lazy: replace com.sun.xml.bind.namespacePrefixMapper with com.sun.xml.internal.bind.namespacePrefixMapper)

Java 7/8 solution
This problem is related to the default implementation JAXB Provider. I have found a solution using a different implementation: EclipseLink MOXy.
1. add the dependency in pom.xml
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>2.5.0</version>
</dependency>`
2. create a file jaxb.properties containing the following line
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
move the file into the package model
3. create package-file.java into the model package
#XmlSchema(xmlns = { #XmlNs(prefix = "video", namespaceURI = "http://www.google.com/schemas/sitemap-video/1.1"),
#XmlNs(prefix = "", namespaceURI = "http://www.sitemaps.org/schemas/sitemap/0.9")})
package it.my.sitemap.model;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;

Related

Camel DataFormat Jackson using blueprint XML DSL throws context exception

No matter where I place the dataformats in XML DSL blueprint, I get this error just starting at different places. if I remove it, it works but of course I can't convert JSON to POJO. ??? any help or tell me what I'm doing wrong, what i'm missing. thanks!
Error
Unable to start blueprint container for bundle passthrumt1.core/1.0.1.SNAPSHOT
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'endpoint'. One of '{"http://camel.apache.org/schema/blueprint":redeliveryPolicyProfile, "http://camel.apache.org/schema/blueprint":onException, "http://camel.apache.org/schema/blueprint":onCompletion, "http://camel.apache.org/schema/blueprint":intercept, "http://camel.apache.org/schema/blueprint":interceptFrom, "http://camel.apache.org/schema/blueprint":interceptSendToEndpoint, "http://camel.apache.org/schema/blueprint":restConfiguration, "http://camel.apache.org/schema/blueprint":rest, "http://camel.apache.org/schema/blueprint":route}' is expected.
XML DSL
<camelContext
id="com.passthru.coreCamelContext"
trace="true"
xmlns="http://camel.apache.org/schema/blueprint"
allowUseOriginalMessage="false"
streamCache="true"
errorHandlerRef="deadLetterErrorHandler" >
<properties>
<property key="http.proxyHost" value="PITC-Zscaler-Americas.proxy.corporate.com"/>
<property key="http.proxyPort" value="80"/>
</properties>
<streamCaching id="CacheConfig"
spoolUsedHeapMemoryThreshold="70"
anySpoolRules="true"/>
<!-- -->
<dataFormats>
<json id="Json2Pojo" library="Jackson" unmarshalTypeName="com.passthru.core.entities.TokenEntities">
</json>
</dataFormats>
<endpoint id="predixConsumer" uri="direct:preConsumer" />
<endpoint id="predixProducer" uri="direct:preProducer" />
<endpoint id="getToken" uri="direct:getToken" />
<onException>
<exception>com.passthru.dataservice.PDXDataServiceInvalidDataException</exception>
<redeliveryPolicy maximumRedeliveries="3" />
<handled>
<constant>true</constant>
</handled>
<log
message="Invalid Data From Data Service"
loggingLevel="ERROR" />
<setBody>
<simple>${body.toString}</simple>
</setBody>
<to uri="file:{{errorArchive}}" />
</onException>
If I place the dataformats above properties, it complains, I have to remove properties and streamcache statements in order for it to work. but I need the proxy properties. any suggestions??? thanks again
If the
<camelContext
id="com.ge.digital.passthru.coreCamelContext"
trace="true"
xmlns="http://camel.apache.org/schema/blueprint"
allowUseOriginalMessage="false"
streamCache="true"
errorHandlerRef="deadLetterErrorHandler" >
<dataFormats>
<json id="Json2Pojo" library="Jackson" unmarshalTypeName="com.passthru.core.entities.TokenEntities"/>
</dataFormats>
<properties>
<property key="http.proxyHost" value="PITC-Zscaler-Americas-Cincinnati3PR.proxy.corporate.com"/>
<property key="http.proxyPort" value="80"/>
</properties>
i get this
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'properties'. One of '{"http://camel.apache.org/schema/blueprint":redeliveryPolicyProfile, "http://camel.apache.org/schema/blueprint":onException, "http://camel.apache.org/schema/blueprint":onCompletion, "http://camel.apache.org/schema/blueprint":intercept, "http://camel.apache.org/schema/blueprint":interceptFrom, "http://camel.apache.org/schema/blueprint":interceptSendToEndpoint, "http://camel.apache.org/schema/blueprint":restConfiguration, "http://camel.apache.org/schema/blueprint":rest, "http://camel.apache.org/schema/blueprint":route}' is expected.
what am I missing?
Camel blueprint XML is validated against camel-blueprint.xsd.
You are interested in complex type with name camelContextFactoryBean which contains sequence of available elements with fixed order.
Correct order of camelContext elements defined in this sequence is:
properties
globalOptions
propertyPlaceholder
package
packageScan
contextScan
jmxAgent
streamCaching
export
defaultServiceCallConfiguration
serviceCallConfiguration
defaultHystrixConfiguration
hystrixConfiguration
routeBuilder
routeContextRef
restContextRef
threadPoolProfile
threadPool
endpoint
dataFormats
transformers
validators
redeliveryPolicyProfile
onException
onCompletion
intercept
interceptFrom
interceptSendToEndpoint
restConfiguration
rest
route
To solve your problem move all endpoint declarations right above dataFormats.

SOAP parameters passed to Nav 2013 R2 cause error as if they are null

I`m trying to call a Nav 2013 R2 web service codeunit with a custom SOAP command and I get a response indicating that the parameters being passed are null, which they are not.
Does anyone have an answer as to why this is happening or could point me in a direction that could help solve this? Thanks!
Here is the SOAP request:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><TransferOrderCreate xmlns="urn:microsoft-dynamics-schemas/Codeunit/WebTestCodeunit"><ptext>this is some text</ptext><pint>999</pint></TransferOrderCreate></soap:Body></soap:Envelope>
Here is the SOAP response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="urn:microsoft-dynamics-schemas/error">a:Microsoft.Dynamics.Nav.Service.WebMetadata.ServiceBrokerException</faultcode><faultstring xml:lang="en-CA">Parameter ptext in method TransferOrderCreate in service WebTestCodeunit is null! </faultstring><detail><string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Parameter ptext in method TransferOrderCreate in service WebTestCodeunit is null! </string></detail></s:Fault></s:Body></s:Envelope>
Here is the service as exposed by Nav:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="urn:microsoft-dynamics-schemas/codeunit/WebTestCodeunit" targetNamespace="urn:microsoft-dynamics-schemas/codeunit/WebTestCodeunit" debug="true">
<script id="FirebugLite" firebugIgnore="true" extension="Chrome"/>
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:microsoft-dynamics-schemas/codeunit/WebTestCodeunit">
<element name="TransferOrderCreate">
<complexType>
<sequence>
<element minOccurs="1" maxOccurs="1" name="ptext" type="string"/>
<element minOccurs="1" maxOccurs="1" name="pint" type="int"/>
</sequence>
</complexType>
</element>
<element name="TransferOrderCreate_Result">
<complexType>
<sequence>
<element minOccurs="1" maxOccurs="1" name="return_value" type="string"/>
</sequence>
</complexType>
</element>
</schema>
</types>
<message name="TransferOrderCreate">
<part name="parameters" element="tns:TransferOrderCreate"/>
</message>
<message name="TransferOrderCreate_Result">
<part name="parameters" element="tns:TransferOrderCreate_Result"/>
</message>
<portType name="WebTestCodeunit_Port">
<operation name="TransferOrderCreate">
<input name="TransferOrderCreate" message="tns:TransferOrderCreate"/>
<output name="TransferOrderCreate_Result" message="tns:TransferOrderCreate_Result"/>
</operation>
</portType>
<binding name="WebTestCodeunit_Binding" type="tns:WebTestCodeunit_Port">
<binding xmlns="http://schemas.xmlsoap.org/wsdl/soap/" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="TransferOrderCreate">
<operation xmlns="http://schemas.xmlsoap.org/wsdl/soap/" soapAction="urn:microsoft-dynamics-schemas/codeunit/WebTestCodeunit:TransferOrderCreate" style="document"/>
<input name="TransferOrderCreate">
<body xmlns="http://schemas.xmlsoap.org/wsdl/soap/" use="literal"/>
</input>
<output name="TransferOrderCreate_Result">
<body xmlns="http://schemas.xmlsoap.org/wsdl/soap/" use="literal"/>
</output>
</operation>
</binding>
<service name="WebTestCodeunit">
<port name="WebTestCodeunit_Port" binding="tns:WebTestCodeunit_Binding">
<address xmlns="http://schemas.xmlsoap.org/wsdl/soap/" location="http://lt0619.xx.xxxxxxxxx.xx:11047/Trunk/WS/7002/Codeunit/WebTestCodeunit"/>
</port>
</service>
</definitions>
Check namespaces in wsdl definition and your request. Namespaces are case sensitive.
wsdl:
urn:microsoft-dynamics-schemas/codeunit/WebTestCodeunit
reqest:
urn:microsoft-dynamics-schemas/Codeunit/WebTestCodeunit
This could throw the exception you see.

Parent package is not defined : jfreechart-default [Unknown Location]

I am trying use Struts2 jfreechart plugin - using a Maven project.
In Maven dependencies I am able to see the jfree-chart jar file.
DO I need to use a separate package?
Getting following error:
SEVERE: Dispatcher initialization failed
Unable to load configuration. - [unknown location]
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
at org.apache.struts2.dispatcher.Dispatcher.getContainer(Dispatcher.java:967)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:435)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:479)
at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:57)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4828)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5508)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: Parent package is not defined: jfreechart-default - [unknown location]
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.buildPackageContext(XmlConfigurationProvider.java:674)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:523)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:295)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:264)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
My struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="basicstruts2" extends="struts-default, jfreechart-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="getchart" class="com.struts.charts.actions.ChartAction"
method="execute">
<result name="success" type="chart">
<param name="width">400</param>
<param name="height">300</param>
</result>
</action>
</package>
</struts>
In the struts.xml you have used the code that requires struts2-jfreechart-plugin-x.x.x.jar to be on classpath. This plugin has struts-plugin.xml where the jfreechart-default package is defined. You need this if your package extends jfreechart-default.
<package name="basicstruts2" extends="struts-default, jfreechart-default">

using Nlog and writing to file as json

I think I'm missing something as I can't seem to figure out how to have it write to a log file in json format using NLog setup in configuration file. The straight rolling file works fine, but not the json. The json target only outputs the message (not in json).
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target xsi:type="File" name="rollingFile" fileName="${basedir}/logs/${shortdate}.log" archiveFileName="${basedir}/logs/{shortdate}_Archive{###}.log" archiveAboveSize="1000000" archiveNumbering="Sequence" layout="${longdate} ${uppercase:${level}} ${callsite} ${message}" />
<target xsi:type="File"
name="rollingFileJson"
fileName="${basedir}/logs/${shortdate}.json"
archiveFileName="${basedir}/logs/{shortdate}_Archive{###}.json"
archiveAboveSize="1000000"
archiveNumbering="Sequence"
layout="${json-encode} ${message}">
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="rollingFile" />
<logger name="*" minlevel="Trace" writeTo="rollingFileJson" />
</rules>
</nlog>
As of the release of NLog 4.0.0 it is possible to use a layout that renders events as structured JSON documents.
Example taken from NLog project site:
<target name="jsonFile" xsi:type="File" fileName="${logFileNamePrefix}.json">
<layout xsi:type="JsonLayout">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level:upperCase=true}"/>
<attribute name="message" layout="${message}" />
</layout>
</target>
Edit:
You can also create it in code.
Here is the link to the specific part of documentation.
And here the copied example:
var jsonLayout = new JsonLayout
{
Attributes =
{
new JsonAttribute("type", "${exception:format=Type}"),
new JsonAttribute("message", "${exception:format=Message}"),
new JsonAttribute("innerException", new JsonLayout
{
Attributes =
{
new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
}
},
//don't escape layout
false)
}
};
For more info read the docs.
As per NLog documentation: json-encode will only escape output of another layout using JSON rules. It will not "convert" the output to JSON. You'll have to do that yourself.
'{ "date":"${longdate}","level":"${level}","message":${message}}'
Take a look at this question for more details.

JAXB validation returning non-required fields

I am validating a Java object using the Validator API. THis works as far as telling me that the object is not valid according to the schema, but it gives a very vague error message that one of the elements from a list of all the element's properties are missing.
Schema (truncated for clarity):
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://predictivesolutions.com/schema/v1_1" xmlns:snt="http://predictivesolutions.com/schema/v1_1"
elementFormDefault="qualified">
<xs:element name="contactInsert">
<xs:complexType>
<xs:all>
<xs:element name="suffix" type="snt:stringType255"
minOccurs="0" maxOccurs="1" />
<xs:element name="firstName" type="snt:stringType255"
minOccurs="1" maxOccurs="1" />
<xs:element name="lastName" type="snt:stringType255"
minOccurs="1" maxOccurs="1" />
<xs:element name="companyID" type="snt:idType" minOccurs="1"
maxOccurs="1" />
<xs:element name="companyLocationID" type="snt:idType"
minOccurs="1" maxOccurs="1" />
<xs:element name="workPhone" type="snt:phoneType"
minOccurs="0" maxOccurs="1" />
<xs:element name="cellPhone" type="snt:phoneType"
minOccurs="0" maxOccurs="1" />
<xs:element name="homePhone" type="snt:phoneType"
minOccurs="0" maxOccurs="1" />
<xs:element name="otherPhone" type="snt:phoneType"
minOccurs="0" maxOccurs="1" />
I am basically deserializing a JSON object to the JAXB generated class from the schema above. Again this works:
ValidationErrorHandler errorHandler = null;
try {
JAXBContext jc = JAXBContext.newInstance(ContactInsert.class);
JAXBSource source = new JAXBSource(jc, contactInsert);
SchemaFactory sf = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(ContactInsert.class
.getResource("/xsd/v1_1/contact.xsd"));
Validator validator = schema.newValidator();
errorHandler = new ValidationErrorHandler();
validator.setErrorHandler(errorHandler);
validator.validate(source);
My JSON object gets converted to the ContactInsert instance:
{ "companyID":666, "lastName":"dsadasd", "companyLocationID":23950, "otherComments":null }
I would expect the validation error to be that "firstName" is expected, however it lists every element from the schema, even though these are not required (minOccurs=0 and not annotated with #Required in the generated Java class:
"cvc-complex-type.2.4.b: The content of element 'contactInsert' is not
complete. One of
'{"http://predictivesolutions.com/schema/v1_1":suffix,
"http://predictivesolutions.com/schema/v1_1":firstName,
"http://predictivesolutions.com/schema/v1_1":workPhone,
"http://predictivesolutions.com/schema/v1_1":cellPhone,
"http://predictivesolutions.com/schema/v1_1":homePhone,
"http://predictivesolutions.com/schema/v1_1":otherPhone,
"http://predictivesolutions.com/schema/v1_1":faxPhone,
"http://predictivesolutions.com/schema/v1_1":email,
"http://predictivesolutions.com/schema/v1_1":isDesignate,
"http://predictivesolutions.com/schema/v1_1":isActive,
"http://predictivesolutions.com/schema/v1_1":mainSponsorID,
"http://predictivesolutions.com/schema/v1_1":hidePercentSafeFlag,
"http://predictivesolutions.com/schema/v1_1":externalContactID,
"http://predictivesolutions.com/schema/v1_1":useAsARef,
"http://predictivesolutions.com/schema/v1_1":positionTitle,
"http://predictivesolutions.com/schema/v1_1":otherComments,
"http://predictivesolutions.com/schema/v1_1":formerCompanyID,
"http://predictivesolutions.com/schema/v1_1":industryStartDate,
"http://predictivesolutions.com/schema/v1_1":employmentStartDate}' is
expected."
Is it possible to configure the validator to only report the required field ("firstName"). I am relatively new to JAXB, but it seems like that error message is not accurate, and that JAXB is simply taking the easy way out by saying one of the elements is missing, but I will not tell you which.
Where is the Error Coming From
The error message being returned is from the javax.xml.validation.Validator and not JAXB. In this use case JAXB is simply the XML source. If you swapped in a StAXSource the StAX parser wouldn't become responsible for the schema validation.
Is it a Good Error?
OK...but why does validator report all those fields in the error
message?
Here is the error you are getting:
"cvc-complex-type.2.4.b: The content of element 'contactInsert' is not
complete. One of
'{"http://predictivesolutions.com/schema/v1_1":suffix,
"http://predictivesolutions.com/schema/v1_1":firstName,
"http://predictivesolutions.com/schema/v1_1":workPhone,
"http://predictivesolutions.com/schema/v1_1":cellPhone,
"http://predictivesolutions.com/schema/v1_1":homePhone,
"http://predictivesolutions.com/schema/v1_1":otherPhone,
"http://predictivesolutions.com/schema/v1_1":faxPhone,
"http://predictivesolutions.com/schema/v1_1":email,
"http://predictivesolutions.com/schema/v1_1":isDesignate,
"http://predictivesolutions.com/schema/v1_1":isActive,
"http://predictivesolutions.com/schema/v1_1":mainSponsorID,
"http://predictivesolutions.com/schema/v1_1":hidePercentSafeFlag,
"http://predictivesolutions.com/schema/v1_1":externalContactID,
"http://predictivesolutions.com/schema/v1_1":useAsARef,
"http://predictivesolutions.com/schema/v1_1":positionTitle,
"http://predictivesolutions.com/schema/v1_1":otherComments,
"http://predictivesolutions.com/schema/v1_1":formerCompanyID,
"http://predictivesolutions.com/schema/v1_1":industryStartDate,
"http://predictivesolutions.com/schema/v1_1":employmentStartDate}' is
expected."
This implementation has chosen to list all of the possible elements that may occur here. If only the required elements where listed someone could have opened a question similar to this one as to why the optional elements were omitted.