Webservices - Axis2 ClientStub policy error - axis2

Trying to invoke a webservice usign the AXIS genereated client stubs .
When i run my standalone java program am getting
Exception in thread "main" java.lang.NullPointerException
at org.apache.neethi.PolicyBuilder.processOperationElement(PolicyBuilder.java:201)
The getPolicy() method in the stub class
return org.apache.neethi.PolicyEngine.getPolicy (org.apache.axiom.om.OMXMLBuilderFactory.createOMBuilder(
new java.io.StringReader(policyString)).getDocument().getXMLStreamReader(false));
Why is that am getting NullPointerException?
I tried splitting the code like below. But still getting teh same NullPointerException
System.out.println("policy String :" + policyString);
OMXMLParserWrapper omp = org.apache.axiom.om.OMXMLBuilderFactory.createOMBuilder(
new java.io.StringReader(policyString));
System.out.println("Step 2 :" + omp);
XMLStreamReader omd = omp.getDocument().getXMLStreamReader(false);
System.out.println("Step 3 " + omd);
Policy policy = org.apache.neethi.PolicyEngine.getPolicy(omd);
System.out.println("Step 4");
return policy;
Has anyone faced this kind of error ? Any advice is highly appreciated

The issue got fixed. The stubs were generated behind a firewall and was throwing this exception. I generated the stubs outside of firewall and it works like a charm

Related

Get broken constrains in OptaPanner with non-reversible accumulator

I am trying to obtains list of broken constrains from a problem instance in OptaPlanner. I am using OptaPlanner version 7.0.0.Final and drools for rules engine (also 7.0.0.Final). The problem is solved correctly and without any error, but when I try to obtain broken constrains I get a NullPointer exception.
As far as I have researched, I found out, that this only happens, when I use drools accumulator without reverse operation (like max or min). Further I have made a custom accumulator, which is the exact copy from org.drools.core.base.accumulators.LongSumAccumulateFunction and everything works as expected, but as soon as I change the supportsReverse() function to return false, the NullPointer exception rises.
I have managed to reconstruct this problem in one of the provided examples - CloudBalancing. This is the change to CloudBalancingHelloWorld, it's only purpose is to obtain list of broken constraints as mentioned in this post.
public class CloudBalancingHelloWorld {
public static void main(String[] args) {
// Build the Solver
SolverFactory<CloudBalance> solverFactory = SolverFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml");
Solver<CloudBalance> solver = solverFactory.buildSolver();
// Load a problem with 400 computers and 1200 processes
CloudBalance unsolvedCloudBalance = new CloudBalancingGenerator().createCloudBalance(400, 1200);
// Solve the problem
CloudBalance solvedCloudBalance = solver.solve(unsolvedCloudBalance);
// Display the result
System.out.println("\nSolved cloudBalance with 400 computers and 1200 processes:\n"
+ toDisplayString(solvedCloudBalance));
//
//A Piece of code added - start
//
ScoreDirector<CloudBalance> scoreDirector = solver.getScoreDirectorFactory().buildScoreDirector();
scoreDirector.setWorkingSolution(solvedCloudBalance);
Collection<ConstraintMatchTotal> constrains = scoreDirector.getConstraintMatchTotals();
System.out.println(constrains.size());
//
//A Piece of code added - end
//
}
public static String toDisplayString(CloudBalance cloudBalance) {
StringBuilder displayString = new StringBuilder();
for (CloudProcess process : cloudBalance.getProcessList()) {
CloudComputer computer = process.getComputer();
displayString.append(" ").append(process.getLabel()).append(" -> ")
.append(computer == null ? null : computer.getLabel()).append("\n");
}
return displayString.toString();
}
}
And this is the change to requiredCpoPowerTotal rule. Please note that I have done this only to demonstrate the problem. Basicaly I have changed sum to max.
rule "requiredCpuPowerTotal"
when
$computer : CloudComputer($cpuPower : cpuPower)
accumulate(
CloudProcess(
computer == $computer,
$requiredCpuPower : requiredCpuPower);
$requiredCpuPowerTotal : max($requiredCpuPower);
(Integer) $requiredCpuPowerTotal > $cpuPower
)
then
scoreHolder.addHardConstraintMatch(kcontext, $cpuPower - (Integer) $requiredCpuPowerTotal);
end
I am really confused, because the error does not happen during planing phase, but when the scoreDirector recomputes the score to obtain broken constrains it does. I mean the same calculations must have happened during the planning phase right?
Anyway here is the stack trace
Exception in thread "main" Exception executing consequence for rule "requiredCpuPowerTotal" in org.optaplanner.examples.cloudbalancing.solver: java.lang.NullPointerException
at org.drools.core.runtime.rule.impl.DefaultConsequenceExceptionHandler.handleException(DefaultConsequenceExceptionHandler.java:39)
at org.drools.core.common.DefaultAgenda.handleException(DefaultAgenda.java:1256)
at org.drools.core.phreak.RuleExecutor.innerFireActivation(RuleExecutor.java:438)
at org.drools.core.phreak.RuleExecutor.fireActivation(RuleExecutor.java:379)
at org.drools.core.phreak.RuleExecutor.fire(RuleExecutor.java:135)
at org.drools.core.phreak.RuleExecutor.evaluateNetworkAndFire(RuleExecutor.java:88)
at org.drools.core.concurrent.AbstractRuleEvaluator.internalEvaluateAndFire(AbstractRuleEvaluator.java:34)
at org.drools.core.concurrent.SequentialRuleEvaluator.evaluateAndFire(SequentialRuleEvaluator.java:43)
at org.drools.core.common.DefaultAgenda.fireLoop(DefaultAgenda.java:1072)
at org.drools.core.common.DefaultAgenda.internalFireAllRules(DefaultAgenda.java:1019)
at org.drools.core.common.DefaultAgenda.fireAllRules(DefaultAgenda.java:1011)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.internalFireAllRules(StatefulKnowledgeSessionImpl.java:1321)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.fireAllRules(StatefulKnowledgeSessionImpl.java:1312)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.fireAllRules(StatefulKnowledgeSessionImpl.java:1296)
at org.optaplanner.core.impl.score.director.drools.DroolsScoreDirector.getConstraintMatchTotals(DroolsScoreDirector.java:134)
at org.optaplanner.examples.cloudbalancing.app.CloudBalancingHelloWorld.main(CloudBalancingHelloWorld.java:52)
Caused by: java.lang.NullPointerException
at org.drools.core.base.accumulators.JavaAccumulatorFunctionExecutor$JavaAccumulatorFunctionContext.getAccumulatedObjects(JavaAccumulatorFunctionExecutor.java:208)
at org.drools.core.reteoo.FromNodeLeftTuple.getAccumulatedObjects(FromNodeLeftTuple.java:94)
at org.drools.core.common.AgendaItem.getObjectsDeep(AgendaItem.java:78)
at org.drools.core.reteoo.RuleTerminalNodeLeftTuple.getObjectsDeep(RuleTerminalNodeLeftTuple.java:359)
at org.optaplanner.core.api.score.holder.AbstractScoreHolder.extractJustificationList(AbstractScoreHolder.java:118)
at org.optaplanner.core.api.score.holder.AbstractScoreHolder.registerConstraintMatch(AbstractScoreHolder.java:88)
at org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder.addHardConstraintMatch(HardSoftScoreHolder.java:53)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313.defaultConsequence(Rule_requiredCpuPowerTotal1284553313.java:14)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313DefaultConsequenceInvokerGenerated.evaluate(Unknown Source)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313DefaultConsequenceInvoker.evaluate(Unknown Source)
at org.drools.core.phreak.RuleExecutor.innerFireActivation(RuleExecutor.java:431)
... 13 more
Thank you for any help in advance.
That NPE sounds like a bug in Drools. The ConstraintMatch API should always just work. Very that you get it against the latest master version. If so, please create a jira for this with a minimal reproducer and we'll look into it.

Axis2 web service stub failing

We have a website written in Java that makes a web service call. Recently, we have noticed that we are recieving a null response from the web service (The endpoint is a 3rd party not maintained by us).
I've tracked down the point at which our code is failing and it's in our stub. See the code below, the code is failing between the two System.out.println lines. My problem is that no exception is thrown, so I don't know why the _operationClient.execute(true); fails. Would anyone have any idea how I can go about solving this?
public SuggestXResponseE suggestX(SuggestXE suggestX0)
throws java.rmi.RemoteException {
org.apache.axis2.context.MessageContext _messageContext = null;
try {
org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[0].getName());
_operationClient.getOptions().setAction("http://www.test.com/service/suggestX");
_operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&");
// create a message context
_messageContext = new org.apache.axis2.context.MessageContext();
// create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env = null;
env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()),
suggestX0,
optimizeContent(new javax.xml.namespace.QName("http://www.test.com/service",
"suggestX")));
//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);
// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);
System.out.println("Log message 1");
//execute the operation client
_operationClient.execute(true);
System.out.println("Log message 2");
org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext(
org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();
java.lang.Object object = fromOM(
_returnEnv.getBody().getFirstElement(),
SuggestXResponseE.class,
getEnvelopeNamespaces(_returnEnv));
return (SuggestXResponseE) object;
} catch (org.apache.axis2.AxisFault f) {
// Handle exception.
}
finally {
_messageContext.getTransportOut().getSender().cleanup(_messageContext);
}
}
System.out.println("Log message 1");
//execute the operation client
_operationClient.execute(true);
System.out.println("Log message 2");
If you're getting the first log message but not the second one, then one of two things is happening:
System.exit() is being called somewhere within _operationClient.execute(). You'd recognize this by the fact the process exits.
More likely, _operationClient.execute() is throwing something.
You say it's not throwing an exception, but it could be throwing an Error or some other kind of Throwable. It's not normally advised to catch non-Exception throwables, but you could add some code to do it temporarily:
try {
_operationClient.execute(true);
} catch (Throwable t) {
log.error(t);
throw t;
}
You might find that you're getting an OutOfMemoryError or a NoClassDefFoundError because some jar is missing from your deployment, for example.

Netty - `Future.operationComplete` never called when running in SSL mode in idle timeout handler

We have implemented the following channelIdle implementation.
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
throws Exception {
Response response = business.getResponse();
final Channel channel = e.getChannel();
ChannelFuture channelFuture
= Channels.write(
channel,
ChannelBuffers.wrappedBuffer(response.getXML().getBytes())
);
if (response.shouldDisconnect()) {// returns true and listener _is_ added.
channelFuture.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
channel.close(); // never gets called :(
}
});
}
}
When running in non-SSL mode this works as expected.
However, when running with SSL enabled the operationComplete method never gets called. We've verified this a few times on various machines. The idle timeout happens many times but the operationComplete isn't called. We don't see any exceptions being thrown.
I've tried tracing through the code to see where operationComplete should get called but it is complex and I've not quite figured it out.
There is a call to future = succeededFuture(channel); in SslHandler.wrap() but I don't know if that means anything. The future returned from wrap is never used elsewhere in the SslHandler code.
This sounds like a bug.. Would it be possible to write a simple "test-case" that shows the problem and open an issue at our github issue tracker[1].
Be sure to explain if it happens all the time or only sometimes etc..
[1] https://github.com/netty/netty/issues

AXIS Client v.s. AXIS2 Service

I must implement an AXIS 1.4 client which consume an AXIS2 1.4 method. AXIS 1.4 client is made by creating the stubs. The client send a request and get back a response from service with some attachment (MTOM). When I call the method (operation) by AXIS 1.4 port type object I got an error:
org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.
I think MTOM messed up with AXIS. So here is the question: how did I get the attachment the AXIS2 1.4 (MTOM) web service return me back? TIA.
Francesco
P.S: here is the code. There are stubs generated by WSDL. The problem is: i get the exception when I call the port's stub method. There are attachments in the message I get back.
String codistat = "CODISTAT";
OrdinanzeViabilitaLocator ovlocretreive = new OrdinanzeViabilitaLocator();
ovlocretreive.setOrdinanzeViabilitaHttpSoap11EndpointEndpointAddress(".. the service url + action..");
try {
OrdinanzeViabilitaPortType ovretreive = ovlocretreive.getOrdinanzeViabilitaHttpSoap11Endpoint();
((Stub) ovretreive)._setProperty(javax.xml.rpc.Call.USERNAME_PROPERTY, "username");
((Stub) ovretreive)._setProperty(javax.xml.rpc.Call.PASSWORD_PROPERTY, "password");
//problems began here
MessageReqOrdinanze mrq = new MessageReqOrdinanze();
mrq.setCodistat(codistat);
Calendar date_from = Calendar.getInstance();
date_from.setTimeInMillis(0);
Calendar date_to = Calendar.getInstance();
date_from.setTimeInMillis(0);
mrq.setDate_from(date_from);
mrq.setDate_to(date_to);
// the next line generate the exception
MessageOrdinanze mretreive = ovretreive.getOrdinanze(mrq);
} catch (AxisFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
The message I get back has a
<xop:include href="cid... >...< ../xop/include"/>
tag inside, it's MTOM (it cause the exception I guess).
Hope this helps.
There are two things that need to be done to make MTOM work on the client side:
Ensure that in the stubs, the xs:base64Binary type is mapped to java.activation.DataHandler instead of byte[].
Set up a (runtime) type mapping for xs:base64Binary and java.activation.DataHandler that uses JAFDataHandlerSerializer and JAFDataHandlerDeserializer (which support MTOM).
The second part is fairly easy. Simply set up a client-config.wsddfile with the following type mapping:
<typeMapping languageSpecificType="java:javax.activation.DataHandler" qname="xs:base64Binary"
deserializer="org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"
serializer="org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"
encodingStyle=""/>
The first part is more tricky because the tooling (wsdl2java) in Axis 1.4 doesn't support changing the Java type associated with a given XML type. There are several ways to work around that limitation:
Edit the generated stubs by hand and change byte[] to javax.activation.DataHandler. Depending on how you manage generated code in your project, that may or may not be an acceptable solution.
It is probably possible (although I didn't test that) to trick wsdl2java into using javax.activation.DataHandler by giving it a modified WSDL where the type {http://www.w3.org/2001/XMLSchema}base64Binary is replaced by {java}javax.activation.DataHandler.
I fixed the tooling in the current Axis trunk so that it supports this type of configuration. Note however that this is only implemented in the wsdl2java Maven plugin (but not in the Ant task or the command line tool). You could use the 1.4.1-SNAPSHOT version of that plugin; the generated code would still work with Axis 1.4. You can find some documentation here.
Above solution is great. However those who might be struggling to make above code snippet work, please use xmlns:xs="http://www.w3.org/2001/XMLSchema", then only given typeMapping snippet works.
<typeMapping qname="xs:base64Binary" languageSpecificType="java:javax.activation.DataHandler"
deserializer="org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"
serializer="org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"
xmlns:xs="http://www.w3.org/2001/XMLSchema" encodingStyle="" />

How to get details of ClientResponseFailure in RestEasy Client?

How to get http response contents when status >=400 is returned. That's my code sample :
try {
ChatService client = ProxyFactory.create(ChatService.class, apiUrl);
client.putMessage(dto);
} catch (ClientResponseFailure ex) {
System.out.println(ex.getResponse().getEntity().toString());
}
This throws :
Exception in thread "main" org.jboss.resteasy.spi.ReaderException: java.io.IOException: Stream closed
at org.jboss.resteasy.core.messagebody.ReaderUtility.doRead(ReaderUtility.java:123)
at org.jboss.resteasy.client.core.BaseClientResponse.readFrom(BaseClientResponse.java:246)
at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:210)
at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:171)
at App.main(App.java:40)
Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream.read(SelfExpandingBufferredInputStream.java:58)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at org.jboss.resteasy.client.core.SelfExpandingBufferredInputStream.read(SelfExpandingBufferredInputStream.java:68)
at org.jboss.resteasy.util.ReadFromStream.readFromStream(ReadFromStream.java:30)
at org.jboss.resteasy.plugins.providers.ByteArrayProvider.readFrom(ByteArrayProvider.java:32)
at org.jboss.resteasy.plugins.providers.ByteArrayProvider.readFrom(ByteArrayProvider.java:23)
at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:105)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.read(GZIPDecodingInterceptor.java:46)
at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108)
at org.jboss.resteasy.core.messagebody.ReaderUtility.doRead(ReaderUtility.java:111)
... 4 more
I'd like to have more details than just status code 400.
Is that the exception you meant to send?
Unfortunately the RestEASY client framework doesn't support Exception marshalling per se, and instead adapts it into the HTTP framework. Exceptions should still be thrown on the server though. I've never done it, you can use ExceptionMappers for checked Exceptions.
http://docs.jboss.org/resteasy/docs/1.2.GA/userguide/html/ExceptionHandling.html
When debugging I noticed that the details I needed were in the 'streamFactory' object as a byte stream of XML. I found this help topic in the RestEasy docs about ClientResponse. It says
getEntity(java.lang.Class<T2> type)
where getEntity can marshal the output to the desired class. In my case, I have a custom class for errors returned from services called ServiceError. So, that was the class I passed to getEntity:
try {
serviceResult = proxy.addCustomer(customerName, customerProfile);
} catch (ClientResponseFailure ex) {
ClientResponse<String> cResp = ex.getResponse();
ServiceError myEntity = cResp.getEntity(ServiceError.class);
System.out.println("myEntity errorText=" + myEntity.getErrorMessage().getErrorText());
System.out.println("myEntity errorCode=" + myEntity.getErrorMessage().getErrorCode());
}