Using JDK's JAXB without ns2 prefix - jaxb

After having read all posts about this on Oracle forums, Stackoverflow, java.net I'm finally posting here.
I'm using JAXB to create XML files but the problem is that it adds the famous ns2 prefix before my elements, I have tried all the solutions no one worked for me.
java -version gives "1.6.0_37"
Solution 1 : Using package-info.java
I created the file in my package containing my #Xml* annotated classes with the following content :
#XmlSchema(
namespace = "http://mynamespace",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
#XmlNs(namespaceURI = "http://mynamespace", prefix = "")
}
)
package com.mypackage;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
Solution 2 : NamespacePrefixMapper
I created the following class and set the mapper to the marshaller :
// Change mapper to avoid ns2 prefix on generated XML
class PreferredMapper extends NamespacePrefixMapper {
#Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
return "";
}
}
NamespacePrefixMapper mapper = new PreferredMapper();
try {
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
}
catch (PropertyException e) {
logger.info("No property for com.sun.xml.bind.namespacePrefixMapper found : " + e.getMessage());
}
With com.sun.xml.bind.namespacePrefixMapper nothing happens, with com.sun.xml.internal.bind.namespacePrefixMapper, it throws the exception.
I've also addded the maven dependency in my pom, but it seems that JRE version has a higher priority :
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.4</version>
</dependency>
Can you help me on this ?
PS : I can't include directly the jar in my classpath for build reasons.
PS2 : I can't use JDK7.
Thanks in advance.

Without the implementation of MOXy is not possible. JAXB if the preferred prefix is "", it generates a new one.
I had the same problem in the past, and I configured each prefix for each package-info.java.
NamespacePrefixMapper says in JAVADOC
null if there's no prefered prefix for the namespace URI.
In this case, the system will generate a prefix for you.
Otherwise the system will try to use the returned prefix,
but generally there's no guarantee if the prefix will be
actually used or not.
return "" to map this namespace URI to the default namespace.
Again, there's no guarantee that this preference will be
honored.
If this method returns "" when requirePrefix=true, the return
value will be ignored and the system will generate one"
else if use package-info
we know we can't bind to "", but we don't have any possible name at hand.
generate it here to avoid this namespace to be bound to "".
I hope I've given you all the answers about your question.

I had the same problem today. The production machine has Java 6 and when I deployed my application, I was getting the ns2 prefix. This is how I resolved it. Production server has only Java 1.6 patch 21
I made sure that I have a package-info.java file in my package where all the classes were generated using Jaxb. I checked it and the #XmlSchema was all auto generated, so I didn't mess with any of that. Don't use namespacemapper, that just confused me.
In my pom.xml file, I added jaxb-impl dependency:
com.sun.xml.bind
jaxb-impl
2.2.5-b04
and specified source and target as 1.6. Did a maven clean install and package and deployed into production, everything looks good.
Next step is to make sure that production machine is upgraded to Java 7. Hope this helps :)

Related

Is additional context configuration required when upgrading cucumber-jvm from version 4 to version 6?

I am using cucumber-jvm to perform some functional tests in Kotlin.
I have the standard empty runner class:
#RunWith(Cucumber::class)
#CucumberOptions(features=[foo],
glue=[bar],
plugin=[baz],
strict=true,
monochrome=true)
class Whatever
The actual steps are defined in another class with the #ContextConfiguration springframework annotation.
This class also uses other spring features like #Autowire or #Qualifier
#ContextConfiguration(locations=["x/y/z/config.xml"])
class MyClass {
...
#Before
...
#Given("some feature file stuff")
...
// etc
}
This all work fine in cucumber version 4.2.0, however upgrading to version 6.3.0 breaks things. After updating the imports to match the new cucumber project layout the tests now fail with this error:
io.cucumber.core.backend.CucumberBackendException: Please annotate a glue class with some context configuration.
It provides examples of what it means...
For example:
#CucumberContextConfiguration
#SpringBootTest(classes = TestConfig.class)
public class CucumberSpringConfiguration {}
Or:
#CucumberContextConfiguration
#ContextConfiguration( ... )
public class CucumberSpringConfiguration {}
It looks like it's telling me I can just add #CucumberContextConfiguration to MyClass.
But why?
I get the point of #CucumberContextConfiguration, it's explained well here but why do I need it now with version 6 when version 4 got on fine without it? I can't see any feature that was deprecated and replaced by this.
Any help would be appreciated :)
Since the error matches exactly with the error I was getting in running Cucumber tests with Spring Boot, so I am sharing my fix.
One of the probable reason is: Cucumber can't find the CucumberSpringConfiguration
class in the glue path.
Solution 1:
Move the CucumberSpringConfiguration class inside the glue path (which in my case was inside the steps package).
Solution 2:
Add the CucumberSpringConfiguration package path in the glue path.
The below screenshot depicts my project structure.
As you can see that my CucumberSpringConfig class was under configurations package so it was throwing me the error when I tried to run feature file from command prompt (mvn clean test):
"Please annotate a glue class with some context configuration."
So I applied solution 2, i.e added the configurations package in the glue path in my runner class annotation.
And this is the screenshot of the contents of CucumberSpringConfiguration class:
Just an extra info:
To run tests from command prompt we need to include the below plugin in pom.xml
https://github.com/cucumber/cucumber-jvm/pull/1959 removed the context configuration auto-discovery. The author concluded that it hid user errors and removing it would provide more clarity and reduce complexity. It also listed the scenarios where the context configuration auto-discovery used to apply.
Note that it was introduced after https://github.com/cucumber/cucumber-jvm/pull/1911, which you had mentioned.
Had the same error but while running Cucumber tests from Jar with Gradle.
The solution was to add a rule to the jar task to merge all the files with the name "META-INF/services/io.cucumber.core.backend.BackendProviderService" (there could be multiple of them in different Cucumber libs - cucumber-java, cucumber-spring).
For Gradle it is:
shadowJar {
....
transform(AppendingTransformer) {
resource = 'META-INF/services/io.cucumber.core.backend.BackendProviderService'
}
}
For Maven something like this:
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/io.cucumber.core.backend.BackendProviderService</resource>
</transformer>
</transformers>
A bit more explanation could be found in this answer

Jaxb package-info ignored when using Java 10

I'm struggling with this, and any information would be greatly appreciated. I have a project that has been using JAXB for some time to construct a Java Model from an XML Schema and uses that model. This has been working in Java 8 for some tie now.
However, I've upgraded to Open JDK 10 and I get this error when I attempt to Unmarshall an XML file into the Java objects....
java.lang.IllegalArgumentException: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.minestar.cat.com/namespace/units",
local:"units"). Expected elements are <{}units>
at minestar.units.schema.parser.UnitsXmlParser.readXml(UnitsXmlParser.java:31)
at minestar.units.javagenerator.JavaGeneratorPlugin.execute(JavaGeneratorPlugin.java:41)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:956)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.minestar.cat.com/namespace/units", local:"units"). Expected
elements are <{}units>
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:741)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:262)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:257)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:124)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1149)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:574)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:556)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:168)
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScanner
Impl.java:613)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScan
nerImpl.java:3058)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:821)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:5
32)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:635)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:258)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:229)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:170)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:209)
at minestar.units.schema.parser.UnitsXmlParser.readXml(UnitsXmlParser.java:29)
... 23 more
I am using the maven-jaxb2-plugin to generate the sources, and they look fine. I have upgraded to the latest version of this plugin (at the time of this writing, 0.14.0). The classes are generated fine, and there is a package-info.java class generated and compiled into the resulting jar. The class in question looks like this at the top
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"dimensions",
"quantityTypes"
})
#XmlRootElement(name = "units")
public class Units {
#XmlElement(name = "dimension")
protected List<Dimension> dimensions;
#XmlElement(name = "quantityType")
protected List<QuantityType> quantityTypes;
And the package-info.java looks like this
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.minestar.cat.com/namespace/units", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package minestar.units.schema;
Because this is Java 10, I have added direct dependency entries to javax.xml.bind:jaxb-api:2.3.0, com.sun.xml.bind:jaxb-core:2.3.0 and com.sun.xml.bind:jaxb-impl:2.3.0.
I have tried changing JAXB implementation from the RI to Eclipse MOXy, but that made no difference.
As a test, I edited the generated Units.java class file above, adding the namespace attribute to the #XmlRootElement annotation...
#XmlRootElement(namespace = "http://www.minestar.cat.com/namespace/units", name = "units")
public class Units {
When this java file is compiled and used downstream, the XML file can be parsed. I do not receive the UnmarshalException. However, this source file is generated so I cannot rely on these changes staying put. Additionally, from everything that I have read from much more-informed people than myself, the package-info.class file (which is in the JAR file) should make the namespace value in the annotation unnecessary.
If there is something I have not set up correctly, I would be grateful for any assistance in getting this working in Java 10.
Thanks for any help,
Ed
I have a similar problem with namespaces, unmarshalling with JAXB in a home-made plugin.
I am using Java 11.
I resolved my problem upgrading maven to 3.6.2 (the problem occured with maven 3.5.2). Not sure to be able to explain why it works, but if it helps someone...
I'm actually currently facing the same problem on Java 9.
Adding com.sun.xml.bind.backupWithParentNamespace system property makes it work, but I feel this is working around the problem.
I looked at the Java 9 source(have not looked at the Java 10 source yet), and it's inside the java.lang.Package.getPackageInfo() method that it tries to load the package-info class using:
...
String cn = packageName() + ".package-info";
Module module = module();
...
c = loader.loadClass(module, cn);
...
If I substitute it with
...
c = loader.loadClass(cn);
...
it manages to load it fine and all is well.
To me it looks like a JDK bug.
The latest maven-jaxb2-plugin does have the following option to turn off package-level annotations:
<packageLevelAnnotations>false</packageLevelAnnotations>
This resolved my problem.
Other XJC plugins seems to use "-npa" argument to turn off package-level annotations
It's a Maven bug, Mojos are unable to load package annotations on Java >= 9, fixed in 3.6.2
I have found the following solution for the same issue in my project with JDK 9:
JAXBContext ctx = JAXBContext.newInstance(YOUR_CLASS.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false); // This line is important!
XMLReader reader = sax.newSAXParser().getXMLReader();
Source source = new SAXSource(reader, new InputSource(new StringReader(xml)));
return (YOUR_CLASS) unmarshaller.unmarshal(source);

Rome 0.9 does not work correctly when module classloader order : parent last

Project description:
WebSphere Application Server 7.Maven project which uses Rome0.9.
<dependency>
<groupId>rome</groupId>
<artifactId>rome</artifactId>
<version>0.9</version>
</dependency>
I was solving the problem with log4j not logging. The problem was that log4j.properties were already set in parent project.
That's why I changed module's classloader order to Parent Last.
It fixed the problem with log4j, but application now throws following exception:
ParsingFeedException: Invalid XML
I've checked parent loaded libraries and they include the same version of Rome - 0.9.
It seems that I'm missing some dependencies in my project. I wonder if there is some way to find out which libraries are missing?
Maybe you could suggest any other solution?
I don't have a solution for searching missing loaded library.
However this workaround worked for me:
I reconfigured log4j in static block of main servlet class.
static Logger logger = LoggerFactory.getLogger(FeedAggregatorServlet.class);
static {
Properties p = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
p.load(classLoader.getResourceAsStream("/FeedAggregatorlog4j.properties"));
} catch (IOException e) {
e.printStackTrace();
}
PropertyConfigurator.configure(p);
}

ServiceStack - generate ASP.NET webservice -reference issue

I am using the very excellent servicestack libaries and trying to generate a ASP.NET web-service reference (old style not WCF) from within VS2010 across my servicestack WSDL - Soap11. To nicely wrap the service WSDL.
The DTO's are in a seperate assembly/namespace (My.WS.DTO) from the AppHost/services and are following the request/response naming convention.. when I try to generate the reference through visual studio I get the following error in VS.
Custom tool error: Unable to import WebService/Schema. Unable to import binding 'BasicHttpBinding_ISyncReply' from namespace 'http://schemas.servicestack.net/types'. Unable to import operation 'GetMyDetails'. The element 'http://schemas.servicestack.net/types:GetMyDetails' is missing.
NOTE: GetMyDetails is just the first service that appears in the list - so I dont believe this is the problem.
I have tried adding the assembly namespace in the AppHost file using
EndpointHostConfig.Instance.WsdlServiceNamespace = "My.WS.DTO"; and this just causes the same generation error (as above) but with 'My.WS.DTO' instead of 'http://schemas.servicestack.net/types'.
I assume it is perhaps some sort of referencing problem but any guidance as to what I might be doing wrong would be great.
cheers
I don't know if this is still an issue for you but I had a similar problem and found that I had not decorated one of my DTOs with [DataContract] and [DataMember] attributes, as described on the SOAP Support wiki page. Once you have added these to your DTO it will be declared in the type section of the WSDL.
Have a look at using [DataContract (Namespace = "YOUR NAMESPACE")] on top of your DTO's. This is how my objects are referenced.
[DataContract(Namespace = "My.WS.DTO")]
public class Account{
}
I also use this in my service model. [System.ServiceModel.ServiceContract()] and [System.ServiceModel.OperationContract()]
[System.ServiceModel.ServiceContract()]
public class SendGetAccountResponseService : IService<SendGetAccountNotification>
{
#region IService implementation
[System.ServiceModel.OperationContract()]
public object Execute (SendGetAccountNotification request)
{
Console.WriteLine ("Reached");
return null;
}
#endregion
}
Hope this helps / solves your problem.
I know this is an old question, but I had to add SOAP support for a 3rd party that refused to support REST very recently to my ServiceStack implementation so it could still be relevant to other people still having this issue.
I had the same issue you were having:
Unable to import binding 'BasicHttpBinding_ISyncReply'...
And like mickfold previously answered I needed to add [DataContract] and [DataMember] to my class definitions and their properties.
But I also had to add the following to my AssemblyInfo.cs file before the error went away for me:
[assembly: ContractNamespace("http://schemas.servicestack.net/types", ClrNamespace = "My Type Namespace")]
I assume that you will need one of these lines for every single namespace where you have a type declared, which based upon the original question above would be My.WS.DTO.

JAXB Unable To Handle Attribute with Colon (:) in name?

I am attempting to use JAXB to unmarshall an XML files whose schema is defined by a DTD (ugh!).
The external provider of the DTD has specified one of the element attributes as xml:lang:
<!ATTLIST langSet
id ID #IMPLIED
xml:lang CDATA #REQUIRED
>
This comes into the xjc-generated class (standard generation; no *.xjb magic) as:
#XmlAttribute(name = "xml:lang", required = true)
#XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlLang;
However, when unmarshalling valid XML files with JAXB, the xmlLang attribute is always null.
When I edited the XML file, replacing xml:lang with lang and changed the #XmlAttribute to match, unmarshalling was successful (i.e. attributes were non-null).
I did find this http://old.nabble.com/unmarshalling-ignores-element-attribute-%27xml%27-td22558466.html. But, the resolution there was to convert to XML Schema, etc. My strong preference is to go straight from an un-altered DTD (since it is externally provided and defined by an ISO standard).
Is this a JAXB bug? Am I missing something about "namespaces" in attribute names?
FWIW, java -version = "build 1.6.0_20-b02" and xjc -version = "xjc version "JAXB 2.1.10 in JDK 6""
Solved the issue by changing replacing xml: with a namespace declaration in the JAXB-generated class:
#XmlAttribute(name = "lang", namespace="http://www.w3.org/XML/1998/namespace", required = true)
Which makes sense, in a way.
Without this kind of guidance, how would JAXB know how to interpret the otherwise-undefined namespace xml:? Unless, of course, it implemented some special-case internal handling to xml: as done in http://java.sun.com/javase/6/docs/api/javax/xml/stream/XMLStreamReader.html#getNamespaceURI%28java.lang.String%29 (see the first NOTE:)
Whether it's a bug in xjc's generation of the annotated objects or a bug in the unmarhaller, or simply requires a mapping somewhere in the xjc process is still an open question in my mind.
For now, it's working and all it requires is a little xjc magic, so I'm reasonably happy.
Disclaimer: Although 8 years late, I am adding this answer for lost souls such as myself trying to understand auto generation of java files from a DTD.
You can set project wide namespaces for the unmarshaller to work with directly in the project-info.java file via the #XmlSchema option.
This file should be automatically generated by xjc when generating classes from a schema, however it appears xjc does not automatically generate the package-info.java file when generating from a DTD!
However, you can manually make this file, and add it to the same package as the files generated by xjc.
The file would look like the following:
package-info.java :
#XmlSchema(
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns = {
#XmlNs(prefix="xlink", namespaceURI="http://www.w3c.org/1999/xlink"),
#XmlNs(prefix="namespace2", namespaceURI="http://www.w3c.org/1999/namespace2")
})
package your.generated.package.hierarchy;
import javax.xml.bind.annotation.*;
You can add as many namespaces as required, simply add a new line in the form:
#XmlNs(prefix="namespace", namespaceURI="http://www.uri.to.namespace.com")
The benefit of doing it this way, rather than compared to editing the generated #XmlAttribute is that you do not need to change each generated XmlAttribute, and you do not need to manually remove the namespaces from the XmlAttribute name variable.

Resources