Handling exceptions in CXF JAX-RS client - exception

I want to convert HTTP status codes to Java Exceptions in my CXF rest client. According to the official documentation I need to use ResponseExceptionMapper, but there is no example to make it work. My understanding is that I need to register it as a provider, but how can I do that with a proxy type of client? I tried the following code
//create a proxy client
locationService = JAXRSClientFactory.create(applicationURI + "/rest/", LocationService.class);
//registering my ResponseExceptionMapper
ProviderFactory.getSharedInstance().registerUserProvider(LocationResponseExceptionMapper.getInstance());
but it is not working, because ProviderFactory.getSharedInstance() returns a different ProviderFactory instance then the instance used by my client.

Supply exception mapper to proxy factory using this signature:
//create a proxy client with specified exception mapping provider
List<Object> providers = new ArrayList<Object>();
providers.add(LocationResponseExceptionMapper.getInstance());
locationService = JAXRSClientFactory.create(applicationURI + "/rest/", LocationService.class, providers);

Related

NiFi: How to develop a JUnit test of NiFi controller service?

I am developing a NiFi controller service, and this controller service has a property of another controller service which is dbcpservice.
Accoding to the source code in github.com/apache/nifi, controller service test depends on processor test too, that means define a TestProcessor which has a property of self-defined controller service, and then operate the the controller service through this processor.
But in my case, my controller service's property is another controller service(dbcpservice), I do not know how to write a junit test to set the controller service.
You can create a simple processor via anonymous inner classes (or named classes) in your test in order to exercise the behavior of your controller service. For example, DBCPServiceTest does this by defining TestProcessor alongside the test class. All that test processor needs is a property descriptor which accepts a controller service of the same type as the system under test (SUT) -- in this case, your custom controller service.
If you're asking how to configure your custom service (CustomService from here on), you pass parameters to the TestRunner instance, like so:
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final CustomService service = new CustomService();
service.setNestedService(new NestedService());
final Map<String, String> properties = new HashMap<String, String>();
runner.addControllerService("custom-service-id", service, properties);
In addition to Andy's answer - you could also create a test processor with Mockito:
AbstractProcessor processor = new Mockito().spy(AbstractProcessor.class);
TestRunner testRunner = TestRunners.newTestRunner(processor);

ConnectionFactory exception Camel testing JMS

I'm doing my first steps with Camel and currently working on writing a simple junit test using jms as a transport.
Here is a code I wrote:
public class FirstMockTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("jms:topic:quote")
.to("mock:quote");
}
};
}
#Test
public void testMessageCount() throws InterruptedException {
MockEndpoint mockEndpoint = getMockEndpoint("mock:quote");
mockEndpoint.setExpectedMessageCount(1);
template.sendBody("jms:topic:quote", "Camel rocks");
mockEndpoint.assertIsSatisfied();
}
}
Because of missing connectionFactory I got the following exception:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1: Route(route1)[[From[jms:topic:quote]] -> [To[mock:quote]]] because of connectionFactory must be specified
I'm able to fix it adding the following lines to my route:
ConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("vm://localhost?roker.persistent=false");
context.addComponent("jms", JmsComponent.jmsComponent(connectionFactory));
But I don't like I'm adding some components to my context inside the route. Also, If i want to have another route I will need to do it again.
Obviously, there should be another way to tell my test about connection factory.
Thank you in advance!
It's a good idea to define the JMS connection factory outside of your Camel context and, if possible, reuse it. How to do that depends on your component model / execution environment.
If you're using a Java SE version that supports CDI, that would be an obvious choice. You'd define your JMS connection factory as a named component once and inject it everywhere you need it. Have a look at http://camel.apache.org/cdi.html and for testing support at http://camel.apache.org/cdi-testing.html
If you're using Spring, define your connection factory as a spring bean and inject it wherever you need it.
If you're using Java EE on an application server, you'd usually define the JMS connection factory using the mechanisms of that app server. You'd then look up the JMS connection factory using JNDI.
If you're running in an OSGi container, you should define the JMS connection factory in its own bundle and export it as an OSGi service. In the bundle of your Camel context, import that OSGi servide and inject it into the Camel context.
In all above cases you should consider using a pooled JMS connection factory.
For CDI, Spring and OSGi, have a look at: http://activemq.apache.org/maven/5.14.5/apidocs/org/apache/activemq/jms/pool/PooledConnectionFactory.html
For Java EE the way how to set pooling parameters depends on your app server.
Note of caution: for Java SE CDI and Spring there should be only one Camel context per application (you can have many routes, though). So if the JMS connection factory is only used in that one Camel context, there is not much reuse. Despite that I still think it's preferable to define the JMS connection outside of the Camel context in a separate component. It's, well, cleaner.
Since you are writing a junit you can avoid creating a ConnectionFactory if you stub the jms endpoint. You can name the endpoint as stub:jms:topic:quote. Have a look at sample example at link https://github.com/camelinaction/camelinaction2/blob/master/chapter9/mock/src/test/java/camelinaction/FirstMockTest.java

How to check ActiveMQ queues in unit test using JUnit Rule with EmbeddedActiveMQBroker

I created an Integration test (based on apache camel and blueprint) that sends some messages to an ActiveMQ service on my machine.
Via the admin-web interface i can check if my messages arrived. To decouple from a locally running ActiveMQ i am now using the EmbeddedActiveMQBroker with JUnit Rule (followed instructions from here):
#Rule
public EmbeddedActiveMQBroker broker = new EmbeddedActiveMQBroker() {
#Override
protected void configure() {
try {
this.getBrokerService().addConnector("tcp://localhost:61616");
} catch (Exception e) {
// noop test should fail
}
}
};
The test works fine as before.
But: Is there a way to check the number of (queued)messeages for a given queue? The test sends messages to the queue "q".
Your EmbeddedActiveMQBroker instance wraps around an ActiveMQ BrokerService object that is the real embedded ActiveMQ broker. Because you have access to that through the EmbeddedActiveMQBroker instance you have access to all the stats maintained by the broker via the AdminView (broker.getBrokerService().getAdminView())
From there you can get all sorts of useful info like number of subscriptions, number of Queues etc. All this data is kept in the broker's JMX management context tree so standard JMX applies. One easy way to get info on number of messages in a Queue then is to lookup the Queue in the Broker's management context using code similar to the following:
// For this example the broker name is assumed to be "localhost"
protected QueueViewMBean getProxyToQueue(String name) throws MalformedObjectNameException, JMSException {
ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName="+name);
QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext()
.newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
return proxy;
}
From there you can use the QueueViewMBean to see what's in the Queue:
QueueViewMBean queueView = getProxyToQueue("myQueue");
LOG.info("Number of messages in my Queue:{}", queueView.getQueueSize());
It looks as though the current implementation disables JMX by default which is unfortunate but can be worked around. You have to give the embedded broker instance a configuration URI which is either a string containing the connector to add or an xbean configuration file.
One option would be to do something along these lines (note the useJmx=true):
#Rule
public EmbeddedActiveMQBroker broker = new EmbeddedActiveMQBroker("broker:(tcp://0.0.0.0:0)/localhost?useJmx=true&persistent=false");

Mule: JUnit test case to call a service which is in middle of the Mule flow

I'm newbie for JUnit test case. Please help me on this issue. I have 2 mule flows- first flow having MQ as inbound and it has datamapper to transformer the xml. With the first flow input, i'm calling second flow where we are calling the existing service ( SOAP/HTTP) call. Please find my JUnit below. I'm able to get the success response. But my requirement
1. I need to see the transformer response coming out from the Transformer.( Like how we see via logger component in our flow)
2.Need to override the url (HTTP) through JUnit ( in order to test the error scenario)
public class Request_SuccessPath extends FunctionalTestCase {
#Test
public void BulkRequest () throws Exception {
MuleClient client = muleContext.getClient();
System.out.println("test");
String payload = " <root> <messageName>str1234</messageName><messageId>12345</messageId><DS>123</DS><</root>";
MuleMessage reply = client.send ("vm://test",payload ,null);}
#Override
protected String getConfigResources() {
// TODO Auto-generated method stub
return "src/main/app/project.xml";}
i thought the following snippet will override the url.But it is not
DefaultHttpClient client1 = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:7800/service);
assertNotNull(response);
3. How to take the control of the flow and see any response inbetween the flow.
Instead of WMQ, i have replaced VM as inbound end point for testing purposes.
4. Is there any chance like without replacing VM can we call directly with WMQ through JUnit TestCase. Kindly help me on this.
I'm using 3.4 version, not using maven as of now. Please help me. Thanks in advance.
1) What do you mean by "see". Would it work logging it? inspecting it while debugging?
2) You should parametrize your endpoint with a variable, something like
and configure a property placeholder as explained here: http://www.mulesoft.org/documentation/display/current/Using+Parameters+in+Your+Configuration+Files
Adding http.port, http.host and http.path variables to mule-app.properties
taking into account that you must set system-properties-mode="OVERRIDE" and then start your Mule server using bin/mule -M-Dhttp.host=your-host -M-Dhttp.port=your-port -M-Dhttp.path=your-path
3) Yes, WMQ has a Java API you can use to interact with it: http://publib.boulder.ibm.com/infocenter/wmqv6/v6r0/index.jsp?topic=%2Fcom.ibm.mq.csqzaw.doc%2Fuj41013_.htm , you will probably found hundreds of examples by googling about it.
Regards.

Enterprise library exception handling problems with WCF services

my application consists of 3 layers and is very straightforward.
class library with all the business logic
WCF service that exposes the class library
asp.net web UI.
At the class library layer, I have an enterprise library exception handling policy defined so that it logs all exceptions to the database. In the underlying code, exceptions are thrown, and they coalesce up to the facade. In the facade, I trigger the EL policy to log the errors, and then I toggle a sucessStatus boolean in the response and have a method to convert all my exceptions to a friendly list so that the ultimate consumer can dig through this to get any idea of whats going on.
My facade in my class library sort of looks like this:
public SomeResponse DoSomething(SomeRequest request)
{
SomeResponse response = new SomeResponse();
try
{
response.data = SomeOperationThatWillThrowAnException;
}
catch (InvalidOperationException ex)
{
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
exceptionManager.HandleException(ex, "StandardPolicy");
response.Errors.Add(Utility.ExceptionToError(ex));
response.SuccessStatus = false;
}
return response;
}
If I build a simple winform client and have it talk to my class library, this works.
However when I use the full stack, I get "fault exception was unhandled by user code". I can't seem to configure EL at the WCF layer in any way to keep this from happening.
My WCF service is just a simple wrapper for my class library facade.
public SomeResponse DoSomething(SomeRequest request)
{
return new MyFacade.DoSomething(request);
}
What I want is to have the class library handle the error silently, and not trigger any exceptions at the WCF or UI level. I want the consumer (in this case the ASP.NET webform UI) to have to check the response message contents to get a clue of what happened instead of having an exception stop execution dead in its tracks.
You likely have an error in your configuration file resulting in GetInstance() or HandleException() throwing an exception. Have you tried debugging the WCF service?