Mule upgrade 3.6 compiler error - java

I was working on mule 3.5.1, when I upgrade to mule 3.6 version, getting compile time error for following class:
import org.mule.module.jersey.MuleResponseWriter;
import com.sun.jersey.spi.container.ContainerResponse;
public class GLExportTransformer extends AbstractMessageTransformer {
public List<GLExport> methodType(#Payload MuleResponseWriter content){
List<GLExport> glExportList = (List<GLExport>) content;
System.out.println("Java payload is -->"+glExportList.getClass());
return glExportList ;
}
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)throws TransformerException {
ContainerResponse cr = (ContainerResponse) message.getInvocationProperty("jersey_response");
List<GLExport> res = (List<GLExport>)cr.getResponse().getEntity();
System.out.println("Response from QB is -->"+res);
return res;
}
}
<custom-transformer name="StringToNameString" class="com.trinet.qb.utils.GLExportTransformer" doc:name="GL Export Transformer"/>
Compile time error:
The type org.mule.module.jersey.MuleResponseWriter is not visible
The import com.sun.jersey cannot be resolved
How do I resolve this?
In my Anypoint Studio shows Mule3.6 uses all jersey related jar uses 2.11 version of jar files. Using Java 1.7 version.
EDIT:
Here is my rest component(GLExportService):
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public List<GLExport> postOperation(#Payload String content) throws ParseException {
System.out.println("Content from Reporting page-->\n\n"+content+"\n\n");
JSONParser jsonParser = new JSONParser();
Object jsonObjectInstance =null;
try {
jsonObjectInstance = jsonParser.parse(new StringReader(content));
} catch (ParseException e) {
System.out.println(e.getLocalizedMessage());
}
// parse json and assign to dto as glExportList
return glExportList;
Here is my mule flows:
<http:inbound-endpoint exchange-pattern="request-response" host="${hostname}" port="${glport}" path="QBJournalExport/QBGLRest" doc:name="HTTP"/>
<jersey:resources doc:name="REST">
<component class="com.qb.rest.GLExportService"/>
</jersey:resources>
<set-session-variable variableName="accessToken" value="#[payload.get(0).get('ACCESS_TOKEN')]" doc:name="Access token"/>
<set-session-variable variableName="accessTokenSecret" value="#[payload.get(0).get('ACCESS_TOKEN_SECRET')]" doc:name="Access Secret"/>
<set-session-variable variableName="realmId" value="#[payload.get(0).get('ACCT_SYSTEM_COMPANY_ID')]" doc:name="Company ID"/>
<set-session-variable variableName="quickbooksClient" value="#[com.qb.utils.QuickbooksUtils.getQuickbooksClient(sessionVars['accessToken'],sessionVars['accessTokenSecret'],'${consumerKey}','${consumerSecret}','${appToken}',sessionVars['realmId'])]" doc:name="QB Client"/>
<custom-transformer name="StringToNameString" class="com.qb.utils.GLExportTransformer" doc:name="GL Export Transformer"/>
<set-payload value="#[com.qb.utils.CreateJournalEntry.createJournalEntry(payload,sessionVars['accessToken'],sessionVars['accessTokenSecret'],'${consumerKey}','${consumerSecret}','${appToken}', sessionVars['realmId'])]" doc:name="Create Journal Entry"/>

import org.glassfish.jersey.server.ContainerResponse;
public class GLExportTransformer extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)throws TransformerException {
ContainerResponse cr = (ContainerResponse) message.getInvocationProperty("jersey_response");
List<GLExport> res = (List<GLExport>)cr.getEntity();
return res;
}
}
method called methodType was a dummy code.

Try making the parameter type java.util.Object, and removing the import. You are immediately casting it to List<GLExport> anyway, so you don't appear to need that type.

We indeed made MuleResponseWriter package only, but that's not the root of your problem. In Mule 3.6 we upgraded from Jersey 1.6 to 2.11. Jersey 2 is quite different, it even includes a package rename from com.sun.jersey to org.glassfish.jersey. You can find more information about the upgrade in this post, including a link to Jersey's migration guide: http://blogs.mulesoft.org/mule-3-6-api/
What I don't understand anyway, is why you need to access the ContainerResponse in your transformer instead of having your jersey resource set the message payload to the List directly.
Regards

It seems they made the class org.mule.module.jersey.MuleResponseWriter package only.
This could be because the class was never part of the public Mule API or just minor typo.
Anyways, as it is right now there is no much you can do.
The only hack is to place the transformer and any class that references org.mule.module.jersey.MuleResponseWriter inside a package named:
org.mule.module.jersey
BUT THIS IS A HACK, and I wouldn't advise it.
I'll try to find out if was made on purpose and let you know ;)

Related

How to install or register a Saxon HE 10.3 Configuration? Configuration is not being used

I'm trying to use a custom Configuration for saxon HE 10.3.
The Configuration is not being used. Presumably the config needs to be registered or installed? But how?
Here's my code:
final Configuration config = new net.sf.saxon.Configuration();
/**/ config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
net.sf.saxon.Transform.main(new String[] {
"-s:source.xml",
"-xsl:stylesheet.xslt",
"-o:result.txt"
});
You really don't want to be running net.sf.saxon.Transform.main from a Java application: use either the s9api or JAXP transformation APIs. The net.sf.saxon.Transform.main interface is designed for use from the command line, and it can therefore only modify the configuration through command line switches. It also has drawbacks like shutting down the Java VM if the transformation fails.
There is a workaround, which is to use the -init option on the command line to trigger user-supplied initialisation code (which has access to the Configuration object), but that's only really digging yourself deeper into your hole. I'd recommend switching to the s9api API.
Documentation: https://saxonica.com/documentation/index.html#!using-xsl/embedding
If you want to change the configuration when running Saxon from the command line, as Michael said, there is the -init option to pass in the name of a class implementing the Initializer interface https://saxonica.com/documentation/index.html#!javadoc/net.sf.saxon.lib/Initializer so you would use roughly e.g.
package com.example;
import net.sf.saxon.option.local.Numberer_de;
import net.sf.saxon.lib.Initializer;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.LocalizerFactory;
import net.sf.saxon.lib.Numberer;
import javax.xml.transform.TransformerException;
public class MyInitializer implements Initializer {
public override void initialize(Configuration config) throws TransformerException {
config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
}
}
compile that, put it on the classpath and then run e.g. java -cp saxon-he-10.3.jar;com/example/MyInitializer;net/sf/saxon/option/local/Numberer_de net.sf.saxon.Transform -init:com.example.MyInitializer -s:source.xml -xsl:stylesheet.xslt -o:result.txt.
Or you can subclass net.sf.saxon.Transform.
On the other hand, if you don't want to run Saxon from the command line but from the JAXP API then I think one approach is to create the Configuration e.g.
Configuration config = new Configuration();
config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
TransformerFactory transformerFactory = new TransformerFactoryImpl(config);
Templates templates = transformerFactory.newTemplates(xsltSource);
What was missing, was how to inject the Config. This worked for me:
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.lib.Feature;
final TransformerFactoryImpl factory = (TransformerFactoryImpl) TransformerFactory.newInstance();
factory.getProcessor().setConfigurationProperty(Feature.CONFIGURATION, config);

Handle multiple versions of XSD generated classes

I'm writing an application that will integrate towards an API that has endpoints that return XML backed by XSDs. My application will have to initially target two different versions of this (perhaps more in future releases), and this does not have to be dynamic. When you start the application, the user will have to tell the application which API major version to support. The XSDs are not under my control, I do not want to edit them.
The XSDs generate classes of the same name, and I've run into problems there already. I can't load both of the ObjectFactory classes generated by XJC into a JAXBContext. My solution to this is right now a map of JAXBContexts:
private static Map<Integer, Pair<Class<?>, JAXBContext>> contexts = new HashMap<>();
static {
try {
contexts.put(4, Pair.of(com.api.v4_2_0.ObjectFactory.class, JAXBContext.newInstance(com.api.v4_2_0.ObjectFactory.class)));
contexts.put(3, Pair.of(com.api.v3_9_4.ObjectFactory.class, JAXBContext.newInstance(com.api.v3_9_4.ObjectFactory.class)));
} catch (JAXBException e) {
LOGGER.error("Failed to initialize JAXBContext", e);
}
}
The pair is used to know which class the JAXBContext is based on, since I can't recover that in runtime. Then, to serialize an object I use a lot of magic reflection which works but doesn't feel right:
public static String objectToString(final Object object, final Integer majorVersion) {
try {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
getMarshallerForMajorVersion(majorVersion).marshal(createJaxbElementFromObject(object, getObjectFactoryForMajorVersion(majorVersion)), os);
return os.toString(UTF_8);
} catch (JAXBException e) {
throw SesameException.from("Failed to serialize object", e);
}
}
private static Marshaller getMarshallerForMajorVersion(final Integer majorVersion) throws JAXBException {
return getContextForMajorVersion(majorVersion).getRight().createMarshaller();
}
private static Class<?> getObjectFactoryForMajorVersion(final Integer majorVersion) {
return getContextForMajorVersion(majorVersion).getLeft();
}
private static Pair<Class<?>, JAXBContext> getContextForMajorVersion(final Integer majorVersion) {
if (contexts.containsKey(majorVersion)) {
return contexts.get(majorVersion);
}
throw illegalArgument("No JAXBContext for API with major version %d", majorVersion);
}
private static JAXBElement<?> createJaxbElementFromObject(final Object object, final Class<?> objectFactory) {
try {
LOGGER.info("Attempting to find a JAXBElement producer for class {}", object.getClass());
final Method method = findElementMethodInObjectFactory(object, objectFactory);
return (JAXBElement<?>) method.invoke(objectFactory.getConstructor().newInstance(), object);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException e) {
throw illegalArgument("Failed to construct JAXBElement for class %s", object.getClass().getName());
}
}
private static Method findElementMethodInObjectFactory(final Object object, final Class<?> left) {
return Arrays.stream(left.getMethods())
.filter(m -> m.getReturnType().equals(JAXBElement.class))
.filter(m -> m.getName().endsWith(object.getClass().getSimpleName()))
.findFirst()
.orElseThrow(() -> illegalArgument("Failed to find JAXBElement constructor for class %s", object.getClass().getName()));
}
This works fine but feels fragile.
The problem
Where it gets worse is having to deserialize XML into an object using generics:
public static <T> T stringToObject(final String xml, final Class<T> toClass, final Integer majorVersion) {
try {
final Unmarshaller unmarshaller = getUnmarshallerForVersion(majorVersion);
final JAXBElement<T> unmarshalledElement = (JAXBElement<T>) unmarshaller.unmarshal(new StringReader(xml));
return toClass.cast(unmarshalledElement.getValue());
} catch (JAXBException e) {
throw SesameException.from(format("Failed to deserialize XML into %s", toClass.getCanonicalName()), e);
}
}
// And calling this from another class
private com.api.v4_2_0.SomeClass.class toSomeClass(final HttpResponse<String> response) {
return XmlUtil.stringToObject(response.body(), com.api.v4_2_0.SomeClass.class, apiMajorVersion); // <--- I can't beforehand use this package since major version might be 3.
}
Now there is (from my knowledge) no way for me to use generics and map this to the correct class in the correct package based on what major version of the API is used.
I've also tried using an abstract base class and just giving it a single ObjectFactory for each version, but that still gives me the issue describe here in the problem section. I don't know how to return the correct version of the class:
private com.api.v4_2_0.SomeClass.class toSomeClass(final HttpResponse<String> response) {
return version4XmlUtil.stringToObject(response.body(), com.api.v4_2_0.SomeClass.class); // <--- I can't beforehand use this package since major version might be 3.
}
How do I structure my code to solve this problem? What patterns are useful? Am I going down the wrong path entirely?
EclipseLink JAXB (MOXy)'s #XmlPath and external binding file extensions can help.
The blog I cite below maps a single object model to two different XML schemas. It does this by mapping the first API by using a combination of standard JAXB and MOXy extension annotations.
package blog.weather;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name="xml_api_reply")
#XmlType(propOrder={"location", "currentCondition", "currentTemperature", "forecast"})
#XmlAccessorType(XmlAccessType.FIELD)
public class WeatherReport {
#XmlPath("weather/forecast_information/city/#data")
private String location;
#XmlPath("weather/current_conditions/temp_f/#data")
private int currentTemperature;
#XmlPath("weather/current_conditions/condition/#data")
private String currentCondition;
#XmlPath("weather/forecast_conditions")
private List<Forecast> forecast;
}
And then...
package blog.weather;
import org.eclipse.persistence.oxm.annotations.XmlPath;
public class Forecast {
#XmlPath("day_of_week/#data")
private String dayOfTheWeek;
#XmlPath("low/#data")
private int low;
#XmlPath("high/#data")
private int high;
#XmlPath("condition/#data")
private String condition;
}
You can't create a secondary set of mappings to an object model by annotations, so additional ones can utilize MOXy's XML metadata, thus covering the second API.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="blog.weather"
xml-mapping-metadata-complete="true">
<xml-schema element-form-default="QUALIFIED">
<xml-ns prefix="yweather" namespace-uri="http://xml.weather.yahoo.com/ns/rss/1.0"/>
</xml-schema>
<java-types>
<java-type name="WeatherReport" xml-accessor-type="FIELD">
<xml-root-element name="rss"/>
<xml-type prop-order="location currentTemperature currentCondition forecast"/>
<java-attributes>
<xml-attribute java-attribute="location" xml-path="channel/yweather:location/#city"/>
<xml-attribute java-attribute="currentTemperature" name="channel/item/yweather:condition/#temp"/>
<xml-attribute java-attribute="currentCondition" name="channel/item/yweather:condition/#text"/>
<xml-element java-attribute="forecast" name="channel/item/yweather:forecast"/>
</java-attributes>
</java-type>
<java-type name="Forecast" xml-accessor-type="FIELD">
<java-attributes>
<xml-attribute java-attribute="dayOfTheWeek" name="day"/>
<xml-attribute java-attribute="low"/>
<xml-attribute java-attribute="high"/>
<xml-attribute java-attribute="condition" name="text"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Default behavior is that MOXy's mapping document is used to augment any annotations specified on the model. Depending on how you set the xml-mapping-metadata-complete flag, however, the XML metadata can either completely replace, or simply augment (default), the metadata provided by annotations.
Try it on for size, and let me know what you think:
Mapping Objects to Multiple XML Schemas Using EclipseLink MOXy
http://blog.bdoughan.com/2011/09/mapping-objects-to-multiple-xml-schemas.html

JSON Parsing Error - Unable to update core database values

I am using JAX-RS over AngularJS, but I have hit a stumbling block due to json parsing errors.
Using jsonlint I can see the issues, but as I cannot update the underlying database values which are causing the issue to correct the characters (corporate data warehouse)...I am now in trouble as I can't return any data at all into the application because just a small handful of records have non compliant characters in them.
What is the general approach for dealing with these kind of issues? Is it to search and replace for non ascii- characters at the java end in the setter?
Update:
Error from Chrome:
SyntaxError: Unexpected token
at Object.parse (native)
at ub (http://localhost:8080/misf-web/lib/angular/angular.min.js:13:122)
at e.defaults.transformResponse (http://localhost:8080/misf-web/lib/angular/angular.min.js:98:83)
at http://localhost:8080/misf-web/lib/angular/angular.min.js:97:347
at Array.forEach (native)
at n (http://localhost:8080/misf-web/lib/angular/angular.min.js:6:470)
at Yb (http://localhost:8080/misf-web/lib/angular/angular.min.js:97:329)
at c (http://localhost:8080/misf-web/lib/angular/angular.min.js:99:14)
at i (http://localhost:8080/misf-web/lib/angular/angular.min.js:79:437)
at http://localhost:8080/misf-web/lib/angular/angular.min.js:80:485 angular.min.js:63
(anonymous function)
Sample JSON output - just one example which is causing me issues...it is not always "umlauts"...
{
"approvedPriority": "Approved",
"disease": "primary Sj�grens Syndrome",
"diseaseArea": "Inflammation",
"projectType": "NME",
"therapyArea": "RI"
}
In the database this disease appears as "primary Sjögren’s Syndrome"
jsonlint reports:
Parse error on line 3: ...ed", "disease": "primary Sj�grens S
----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
It is not always "umlauts" causing me issues, sometimes it is a non printable charachter it seems, and one odd error I hunted down due to what appears to be a slightly wider hyphen than normal.
Update:
As far as I am aware I am requesting UTF-8 via JAX-RS.
#GET
#Path("/projects")
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public List<Project> getAllProjects() {
logger.debug("GET: list all projects");
return projectService.getAllProjects();
}
I am developing on Tomcat 7 on Windows using Eclipse.
Seems #PRODUCES and adding charset=utf-8 doesn't work.
In the end I created a filter which added charset=utf=8 to the response header before it was sent and registered it as a provider to jersey through the application config class.
Now it works and data is being returned perfectly.
Why #PRODUCES doesn't work is a mystery.
package com.mycompany.misf.filters;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
public class HeaderResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
MediaType type = response.getMediaType();
if (type != null) {
String contentType = type.toString();
if (!contentType.contains("charset")) {
contentType = contentType + ";charset=utf-8";
response.getHeaders().putSingle("Content-Type", contentType);
}
}
}
}
Register the filter as a provider.
#ApplicationPath("resources")
public class RestApplication extends ResourceConfig {
public RestApplication() {
HashSet<Class<?>> c = new HashSet<Class<?>>();
c.add(PersonsRestService.class);
c.add(ProjectsRestService.class);
//add this
c.add(HeaderResponseFilter.class);
Set<Class<?>> classes = Collections.unmodifiableSet(c);
registerClasses(classes);
property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
}

HTTPClient Example - Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE

I am using HttpClient components from Apache for the following simple program and I see the below exception:
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:52)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:56)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:46)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:72)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:84)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:59)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$InternalConnectionFactory.(PoolingHttpClientConnectionManager.java:487)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:147)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:136)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:112)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:726)
at com.starwood.rms.controller.property.HttpExample.main(HttpExample.java:14)
public class HttpExample {
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.google.com/?q=java");
try {
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using
Httpclient-4.3.3.jar
Httpcore-4.3.2.jar
Any ideas?
I had this problem with Hadoop. It used an old version of httpclient-4.2.5.jar and httpcore-4.2.5.jar in their shared lib.
I solved this by shading parts via the maven-shade-plugin
<relocations>
<relocation>
<pattern>org.apache.http</pattern>
<shadedPattern>shaded.org.apache.http</shadedPattern>
</relocation>
</relocations>
Looking at the source code of DefaultHttpRequestWriterFactory
package org.apache.http.impl.io;
import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable;
import org.apache.http.io.HttpMessageWriter;
import org.apache.http.io.HttpMessageWriterFactory;
import org.apache.http.io.SessionOutputBuffer;
import org.apache.http.message.BasicLineFormatter;
import org.apache.http.message.LineFormatter;
#Immutable
public class [More ...] DefaultHttpRequestWriterFactory implements HttpMessageWriterFactory<HttpRequest> {
public static final DefaultHttpRequestWriterFactory INSTANCE = new DefaultHttpRequestWriterFactory();
private final LineFormatter lineFormatter;
public [More ...] DefaultHttpRequestWriterFactory(final LineFormatter lineFormatter) {
super();
this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatter.INSTANCE;
}
public [More ...] DefaultHttpRequestWriterFactory() {
this(null);
}
public HttpMessageWriter<HttpRequest> [More ...] create(final SessionOutputBuffer buffer) {
return new DefaultHttpRequestWriter(buffer, lineFormatter);
}
}
Are you sure you are using HttpCore 4.3.2? DefaultHttpRequestWriterFactory try to resolve
BasicLineFormatter.INSTANCE
field but can not find it.
Check your classpath for libraries which could contains another BasicLineFormatter class, maybe you have a HttpCore from an old version in conflict with the 4.3.2 version.
Caused by: java.lang.NoSuchFieldError: INSTANCE
one of the solution of java.lang.NoSuchFieldError: INSTANCE : This happens if we have two diff version of same class in our classpath…. […], So we first find that class(one version of class) , click that class, select "build path", then we click "remove from build path" . by 333ccc333
I had this problem. It looks like there is a problem while initializing HttpClient with HttpClientBuilder.create().build(). If you want more immediate solution just use new DefaultHttpClient() to initialize HttpClient.
HttpClient client = new DefaultHttpClient();
This code works...without any error.. check the packages if you are using similar import .
package com.jai.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpExample {
/**
* #param args
*/
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.google.com/?q=java");
try {
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
For those using Webpshere, make sure your class loading policy is set to "Parent Last", otherwise it will not work since WAS is using its own version of commons http which can be conflicting.
I had this problem too, i realized it was when we upgraded to java 1.8, i just downgraded to 1.7 and works as expected.
Not sure why the version became an issue.
I also was frustrated by this and Eclipse until I realized that similar to Pat B's Webpshere tip, it does cause issues for Eclipse if you have the dependencies in the wrong order.
Properties -> Java Build Path -> Order and Export
Play a bit around here with the order of core and client.
I have this error too, in my class path
I have httpclient-4.4.1.jar, and httpcore-4.4.1.jar
However, for some reason,the classloader loaded the class org.apache.http.message.BasicLineFormatter
from httpcore-4.0.jar in a unexpected location and caused this error
you can use below code to check which jar it is using
try{
Class cls=Class.forName('org.apache.http.message.BasicLineFormatter');
println cls.getProtectionDomain().getCodeSource().getLocation();
}catch (Error ex){
println ex
}
Hope this help~

Local part cannot be "null" when creating a QName

We are trying to track down a bug. We get the above error in the logs.
Can anyone explain what this message means? Are there any typical reasons for getting this message?
The stacktrace is:
org.apache.axiom.om.OMException: java.lang.IllegalArgumentException: local part cannot be "null" when creating a QName
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:206)
at org.apache.axiom.om.impl.llom.OMNodeImpl.build(OMNodeImpl.java:318)
at org.apache.axiom.om.impl.llom.OMElementImpl.build(OMElementImpl.java:618)
at org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.toOM(SAAJConverterImpl.java:147)
at org.apache.axis2.jaxws.message.impl.XMLPartImpl._convertSE2OM(XMLPartImpl.java:77)
at org.apache.axis2.jaxws.message.impl.XMLPartBase.getContentAsOMElement(XMLPartBase.java:203)
at org.apache.axis2.jaxws.message.impl.XMLPartBase.getAsOMElement(XMLPartBase.java:255)
at org.apache.axis2.jaxws.message.impl.MessageImpl.getAsOMElement(MessageImpl.java:464)
at org.apache.axis2.jaxws.message.util.MessageUtils.putMessageOnMessageContext(MessageUtils.java:202)
at org.apache.axis2.jaxws.core.controller.AxisInvocationController.prepareRequest(AxisInvocationController.java:370)
at org.apache.axis2.jaxws.core.controller.InvocationController.invoke(InvocationController.java:120)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:317)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invoke(JAXWSProxyHandler.java:148)
I got the same error message (local part cannot be "null" when creating a QName) while trying to construct a org.w3c.dom.Document from String. The problem went away after calling setNamespaceAware(true) on DocumentBuilderFactory. Working code snippet is given below.
private static Document getDocumentFromString(final String xmlContent)
throws Exception
{
DocumentBuilderFactory documentBuilderFactory =
DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
try
{
return documentBuilderFactory
.newDocumentBuilder()
.parse(new InputSource(new StringReader(xmlContent)));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
It means you are creating a DOM element or attribute using one of the namespace methods like createElementNS thus
document.createElementNS(namespace, null)
or createElementNS or setAttrbuteNS
and the second argument, the qname is null, or includes a prefix but no local part as in "foo:".
EDIT:
I would try to run the XML it's parsing through a validator. It's likely there's some tag or attribute name like foo: or foo:bar:baz that is a valid XML identifier but invalid according to the additional restrictions introduced by XML namespaces.
After whole hours in searching, I just wanted to share the Answer in this thread helped me with a Talend code migration - involving SOAP messages - from java8 to java11.
// Used libraries
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.SOAPBody;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
...
// This is the node I want to replace: "<DataArea><Contact/></DataArea>"
// <SOAP-ENV:Body> > SOAP Action (e.g. <ns:GetContact>) > <GetContactRequest> > <DataArea>
SOAPBody soapBodyRequest = objSOAPMessage.getSOAPPart().getEnvelope().getBody();
Node nodeDataArea = soapBodyRequest.getFirstChild().getFirstChild().getFirstChild();
// Build a valid Node object starting from a string e.g. "<Contact> etc etc nested-etc </Contact>"
DocumentBuilderFactory objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
// As per java11, this is essential. It forces the Factory to consider the ':' as a namespace separator rather than part of a tag.
objDocumentBuilderFactory.setNamespaceAware(true);
// Create the node to replace "<DataArea><Contact/></DataArea>" with "<DataArea><Contact>content and nested tags</Contact></DataArea>"
Node nodeParsedFromString = objDocumentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(strDataArea.getBytes())).getDocumentElement();
// Import the newly parsed Node object in the request envelop being built and replace the existing node.
nodeDataArea.replaceChild(
/*newChild*/nodeDataArea.getOwnerDocument().importNode(nodeParsedFromString, true),
/*oldChild*/nodeDataArea.getFirstChild()
);
This throws the Local part cannot be "null" when creating a QName exception if you don't put the .setNamespaceAware(true) instruction
Although this is an old thread, I hope this answer would help some one else searching this error.
I have faced the same error when I was trying to build a web app using maven-enunciate-cxf-plugin:1.28.
For me this was caused after I added a checked exception to my web service signature:
#WebMethod(operationName = "enquirySth")
public IBANResponse enquirySth(String input) throws I
InvalidInputException { ...
I have used JAX-WS Spec for exception throwing but no success. At the end I have found this issue in Enunciate issue tracker system which indicates this issue is resolved in current version, but I think it still exist.
Finally I have done following workaround to fix my problem:
adding #XmlRootElement to my FaultBean.
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "FaultBean",propOrder = {"errorDescription", "errorCode"})
public class FaultBean implements Serializable {
#XmlElement(required = true, nillable = true)
protected String errorDescription;
#XmlElement(required = true, nillable = true)
protected String errorCode;
public FaultBean() {
}
public String getErrorDescription() {
return this.errorDescription;
}
public void setErrorDescription(String var1) {
this.errorDescription = var1;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String var1) {
this.errorCode = var1;
}
}
That's it. Hope it helps.

Categories

Resources