Reading json to Object failed when using add Mixin annotations - json

package com.dh.inheritance;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class Client6{
public static void main(String[] args){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping();
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT);
objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true);
objectMapper.registerModule(new MyModule());
try {
String test = null;
test.length();
} catch (Exception e) {
try {
String jsonString = objectMapper.writeValueAsString(e);
System.out.println(jsonString);
**objectMapper.readValue(jsonString, e.getClass());**
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
}
}
}
package com.dh.inheritance;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public abstract class MixIn {
#JsonIdentityInfo(generator=ObjectIdGenerators.StringIdGenerator.class, property="$id")
private Throwable cause;
}
package com.dh.inheritance;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class MyModule extends SimpleModule{
public MyModule() {
super("test", new Version(2, 7, 2, null));
}
#Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(Throwable.class, MixIn.class);
}
}
{"java.lang.NullPointerException":{"detailMessage":null,"cause":{"java.lang.NullPointerException":{"$id":"912da540-bf85-4e5d-869c-acfaebe85bdf","detailMessage":null,"cause":"912da540-bf85-4e5d-869c-acfaebe85bdf","stackTrace":null}},"stackTrace":null}}
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "$id" (class java.lang.NullPointerException), not
marked as ignorable (3 known properties: "cause", "stackTrace",
"detailMessage"]) at [Source:
{"java.lang.NullPointerException":{"detailMessage":null,"cause":{"java.lang.NullPointerException":{"$id":"912da540-bf85-4e5d-869c-acfaebe85bdf","detailMessage":null,"cause":"912da540-bf85-4e5d-869c-acfaebe85bdf","stackTrace":null}},"stackTrace":null}}; line: 1, column: 107] (through reference chain:
java.lang.NullPointerException["$id"]) at
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
at
com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:855)
at
com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1083)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1389)
at
com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer.deserializeFromObject(ThrowableDeserializer.java:135)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer._deserialize(AsWrapperTypeDeserializer.java:115)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer.deserializeTypedFromObject(AsWrapperTypeDeserializer.java:49)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1017)
at
com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:488)
at
com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer.deserializeFromObject(ThrowableDeserializer.java:104)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer._deserialize(AsWrapperTypeDeserializer.java:115)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer.deserializeTypedFromObject(AsWrapperTypeDeserializer.java:49)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1017)
at
com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42)
at
com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
at
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2779)
at com.dh.inheritance.Client6.main(Client6.java:38)
Above exception thrown, when converting json to Object.

Related

java.lang.NullPointerException Cannot invoke "org.openqa.selenium.WebElement" because this.webelement = null;

I am trying to sendKeys() on google field, and able to do so with normal xpath like :-
driver.findElement(By.name("q")).sendKeys("Gmail");
but getting nullpointerexception while doing with #FindBy method :-
#FindBy(how = How.XPATH, using = "//input[#name='q']")
public WebElement googlesearchfield;
googlesearchfield.sendKeys("Gmail");
package BasicTestCases;
import org.testng.annotations.Test;
import pages.*;
import Utility.TestConfiguration;
import bsh.This;
public class TC02_Login extends TestConfiguration{
// private GooglePage google;
#Test
public void Login()
{
try
{
driver.get(prop.getProperty("Google"));
GooglePage googlePage = new GooglePage();
googlePage.gmaillogin();
waitforpageload();
System.out.println("end of login tc02");
}
catch (Exception e) {
// TODO: handle exception
}
}
}
package pages;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import Utility.TestConfiguration;
public class GooglePage extends TestConfiguration{
#FindBy(how = How.XPATH, using = "//input[#name='q']")
public WebElement googlesearchfield;
#FindBy(how = How.XPATH, using = "//a[text()='Gmail']")
public WebElement gmailclick;
#FindBy(how = How.XPATH, using = "//a[text()='Gmail']")
public WebElement tryf;
public void gmaillogin()
{
try {
googlesearchfield.sendKeys("Gmail");
System.out.println("entered");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I am not able to solve this null pointer exception why it is coming.

Running Junit on command-Line

initializationError(org.junit.runner.JUnitCommandLineParseResult) error is coming when jUnit code is run on windows command prompt:
Z:\lib\com\example\tests>java -cp Z:\lib\junit-4.12.jar;Z:\lib\hamcrest-core-1.3.jar org.junit.runner.JUnitCore TripPlannerJunit
JUnit version 4.12.E
Time: 0
There was 1 failure:
1) initializationError(org.junit.runner.JUnitCommandLineParseResult)
java.lang.IllegalArgumentException: Could not find class [TripPlannerJunit]at org.junit.runner.JUnitCommandLineParseResult.parseParameters(JUnitCommandLineParseResult.java:102)at org.junit.runner.JUnitCommandLineParseResult.parseArgs(JUnitCommandLineParseResult.java:50)at org.junit.runner.JUnitCommandLineParseResult.parse(JUnitCommandLineParseResult.java:44)at org.junit.runner.JUnitCore.runMain(JUnitCore.java:72)at org.junit.runner.JUnitCore.main(JUnitCore.java:36)
Caused by: java.lang.ClassNotFoundException: TripPlannerJunitat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)at java.base/java.lang.Class.forName(Class.java:398)at org.junit.internal.Classes.getClass(Classes.java:16)at org.junit.runner.JUnitCommandLineParseResult.parseParameters(JUnitCommandLineParseResult.java:100)... 4 more
FAILURES!!!
Tests run: 1, Failures: 1
Edited - . The structure is as follows:
All the jars are in "Z:\TripPlanner\lib".
The class and java files are in - "Z:\TripPlanner\lib\com\example\tests"
The package declared is com.example.tests
package com.example.tests;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.ChromeDriverManager;
public class TripPlannerJUnit {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
ChromeDriverManager.getInstance().setup();
driver = new ChromeDriver();
baseUrl = "https://www.google.com.au/.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUntitledTestCase() throws Exception {
driver.get("https://transportnsw.info/trip#/");
driver.findElement(By.id("search-input-From")).click();
driver.findElement(By.id("search-input-From")).clear();
driver.findElement(By.id("search-input-From")).sendKeys("North");
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='North Sydney Station'])[1]/following::li[1]")).click();
driver.findElement(By.id("search-input-To")).click();
driver.findElement(By.id("search-input-To")).clear();
driver.findElement(By.id("search-input-To")).sendKeys("Town");
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Town Hall Station'])[1]/following::ul[1]")).click();
driver.findElement(By.id("search-button")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
Please, specify the path where your TripPlannerJunit is located.
If this is the current folder of a project:
java -cp .;Z:\lib\junit-4.12.jar;...
or
java -cp %CD%;Z:\lib\junit-4.12.jar;...
UPDATE based on clarification in comments.
Assumed you have this structure:
Z:\TripPlanner\lib\
| hamcrest-core-1.3.jar
| junit-4.12.jar
|
+---com
| \---example
| \---tests
| TripPlannerJunit.java
| TripPlannerJunit.class
Run the test from Z:\TripPlanner\lib folder:
Z:\TripPlanner\lib>java -cp .;junit-4.12.jar;hamcrest-core-1.3.jar org.junit.runner.JUnitCore "com.example.tests.TripPlannerJunit"

Spring REST docs: How to migrate Rule to JUnit 5

I migrated my Spring tests to JUnit 5, and they work fine. However, I don't know how to migrate #Rule public JUnitRestDocumentation restDocumentation = ....
Any hint is appreciated.
Spring RestDocs 2 introduces a new class : RestDocumentationExtension for JUnit 5. You can use it instead of Rule
#ExtendWith(RestDocumentationExtension.class)
public class JUnit5ExampleTests {
A complete example is available on https://github.com/spring-projects/spring-restdocs/blob/v2.0.0.RELEASE/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java
The extension is documented on https://github.com/spring-projects/spring-restdocs/blob/master/docs/src/docs/asciidoc/getting-started.adoc#setting-up-your-junit-5-tests
Spring RestDocs 2 requires Spring 5 and JDK 8
Until the issue is officially resolved, I was able to get it working with a JUnit 5 extension (below).
Using that extension, I modified my test class thusly:
#ExtendWith(RestDocsExtension.class)
and
#BeforeEach
void setUp(WebApplicationContext wac, ManualRestDocumentation restDocumentation) throws Exception {
Here is the Extension.
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ContainerExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestExtensionContext;
import org.springframework.restdocs.ManualRestDocumentation;
import java.lang.reflect.Method;
import java.util.Optional;
public class RestDocsExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final String REST_DOC_STORE_KEY = "restDocumentation";
private ManualRestDocumentation restDocumentation;
#Override
public void beforeAll(ContainerExtensionContext context) throws Exception {
if (restDocumentation == null) {
restDocumentation = new ManualRestDocumentation("target/generated-snippets");
getStore(context).put(REST_DOC_STORE_KEY, restDocumentation);
}
}
#Override
public void beforeEach(TestExtensionContext context) throws Exception {
Optional<Class<?>> testClass = context.getTestClass();
Optional<Method> methodNameOpt = context.getTestMethod();
if (testClass.isPresent() && methodNameOpt.isPresent()) {
getDoc(context).beforeTest(testClass.get().getClass(), methodNameOpt.get().getName());
} else {
throw new Exception("TestExtensionContext with no class or method. wat");
}
}
#Override
public void afterEach(TestExtensionContext context) throws Exception {
getDoc(context).afterTest();
}
#Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType() == ManualRestDocumentation.class;
}
#Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return getDoc(extensionContext);
}
private ManualRestDocumentation getDoc(ExtensionContext context) {
return (ManualRestDocumentation) getStore(context).get(REST_DOC_STORE_KEY);
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.DEFAULT);
}
}

How to connect Android with HTTPsURLConnection

I've been trying to figure the code out for quite a while now, however have had no success. Everytime the App crashes by throwing some random exception.
I learnt this code off a tutorial on youtube and despite that, the code doesn't work for me.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Button b1;
TextView t1;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.bthhit);
t1=(TextView)findViewById(R.id.tvJSONitem);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpsURLConnection connection = null;
BufferedReader reader = null;
#Override
protected String doInBackground(String... params) {
try {
URL url=new URL(params[0]);
connection= (HttpsURLConnection)url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuffer buffer= new StringBuffer();
while((line=reader.readLine())!=null){
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection!=null) {
connection.disconnect();
}
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
t1.setText(result);
}
}
}
Logcat shows this:
01-05 00:46:09.018 5573-5580/? E/art: Failed sending reply to debugger: Broken pipe
01-05 00:46:17.852 5573-5706/com.example.test.jsonparser E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.test.jsonparser, PID: 5573
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:58)
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
01-05 00:46:19.104 5573-5587/com.example.test.jsonparser E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab792110
Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.
If some specific methods like .getResponseCode() or,... are not needed in your app, then you can use the generic URLConnection class as well, which will refrain from introducing this kind of exceptions, since it is the parent class for both HttpURLConnection and Https... classes somehow.

Openejb rest integration tests with exception mappers

I'm writing some integration tests towards my jax-rs service where I have a set of exception mappers. So, when performing a given request I expect a certain response code based on the exception mapper. The problem is that I cannot get the exception mappers to be invoked when running in this environment.
My service which should throw a logicalexception in my test:
#Stateless
#Path("/baseCustomer")
public class BaseCustomerService {
#EJB //this one gets mocked in the unittest
private BaseCustomerManagerBean customerManager;
#POST
#Path("crud")
#Consumes({MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public Hkunde createCustomer(Hkunde newCustomer) throws LogicalException {
//throws exception according to mocking
return customerManager.createCustomer(newCustomer);
}
And the exception mapper:
#Provider
public class LogicalExceptionMapper implements ExceptionMapper<LogicalException> {
#Override
public Response toResponse(LogicalException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
I set up my tests like this:
#Mock
private BaseCustomerManagerBean baseCustomerManager;
private HttpClient httpClient;
private BaseCustomerServiceClient client;
#Configuration
public Properties config() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, LogicalExceptionMapper.class.getName());
properties.setProperty("openejb.jaxrs.providers.auto", "true");
properties.setProperty("openejb.servicemanager.enabled", "true");
return properties;
}
#MockInjector
public Class<?> mockitoInjector() {
return MockitoInjector.class;
}
#Module
public EjbModule createModule() throws Exception {
final StatelessBean bean = (StatelessBean) new StatelessBean(BaseCustomerService.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
#Module
public Class[] exceptionMappers() {
return new Class[]{LogicalExceptionMapper.class};
}
#Before
public void setup() {
ServiceHost serviceHost = new ServiceHost("http://localhost:4204/BaseCustomerServiceTest");
httpClient = new HttpClient(serviceHost);
client = new BaseCustomerServiceClient(httpClient);
}
#Test
public void createCustomer_givenLogicalException_expectsLogicalException() throws LogicalException {
Hkunde expected = new Hkunde(true);
when(baseCustomerManager.createCustomer(expected)).thenThrow(new LogicalException("mock"));
try {
client.createCustomer(expected);
fail("Expected LogicalException");
} catch (LogicalException ex) {
}
verify(baseCustomerManager).createCustomer(expected);
}
So when I execute the test, my client will read the response code from the response and throw an exception based on this code.
The problem is that the exception mapper is never invoked, and I always receive a 500 internal server error, instead of the "forbidden" response. I'm guessing I need to add some more info when setting up the ejbjar or something like that.
Thanks!
This example http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/rest-applicationcomposer/src/test/java/org/superbiz/composed/rest/GreetingServiceTest.java (via http://rmannibucau.wordpress.com/2012/09/13/use-mockito-with-openejb/ ;-)) shows exactly what you want.
Add the following after openejbJar.addEjbDeployment(... and it should work.
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", LogicalExceptionMapper.class.getName());
Here is a minimal working example (using openejb-cxf-rs 4.5.0 and openejb-core 4.5.0):
import java.util.Properties;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.OpenEjbContainer;
import org.apache.openejb.config.EjbModule;
import org.apache.openejb.jee.EjbJar;
import org.apache.openejb.jee.StatelessBean;
import org.apache.openejb.jee.oejb3.EjbDeployment;
import org.apache.openejb.jee.oejb3.OpenejbJar;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.junit.Configuration;
import org.apache.openejb.junit.Module;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(ApplicationComposer.class)
public class RestWithExceptionMapper {
#Configuration
public Properties configuration() {
return new Properties() {
{
setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
}
};
}
#Module
public EjbModule app() {
final StatelessBean bean = (StatelessBean) new StatelessBean(MyResource.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", MyExceptionMapper.class.getName());
final EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
public static class FooException extends RuntimeException {
}
public static class MyExceptionMapper implements ExceptionMapper<FooException> {
#Override
public Response toResponse(final FooException t) {
return Response.ok("Objection!").build();
}
}
#Path(value = "/test")
public static class MyResource {
#GET
#Path(value = "/throw")
public String throwException() {
throw new FooException();
}
}
#Test
public void checkServiceWasDeployed() {
assertEquals("Objection!", WebClient.create("http://localhost:4204/RestWithExceptionMapper").path("/test/throw").get(String.class));
}
}