How to use Jackson with Jersey 2.8? - jersey-2.0

I am using Jersey 1.x Now I am migrating to Jersey 2.x
The problem right now I am facing is the use of Jackson(JSON provider) with Jersey 2.8
Tell me how can I get rid of this problem. I am going to use Jersey 2.8 so what to do for using Jackson with it.

Here I find the solution of my question.
The only thing I need to do is to register the Jackson provider and ContextResolver to ObjectMapper..
#Provider
public class UserObjectProvider implements ContextResolver {
final ObjectMapper defaultObjectMapper;
final ObjectMapper combinedObjectMapper;
public UserObjectProvider () {
defaultObjectMapper = createDefaultMapper();
combinedObjectMapper = createCombinedObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
if (type == CombinedAnnotationBean.class) {
return combinedObjectMapper;
} else {
return defaultObjectMapper;
}
}
private static ObjectMapper createDefaultMapper() {
final ObjectMapper result = new ObjectMapper();
result.configure(Feature.INDENT_OUTPUT, true);
return result;
}
// ...
}
Now register your Jackson provider.
final Application application = new ResourceConfig().register(UserObjectProvider.class)
.register(JacksonFeature.class);
Thanks

Related

JsonpRequestBuilder with typed response throws InCompatibleClassChangeError

I have an existing app that I'm adding a "Suggested Products" feature to and I'm having trouble with my JSONP response not being properly transformed to the typed JsArray. I'm hoping someone can give me an idea of what I'm doing wrong?
I have defined my type that will be returned from the server in its own class:
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName();
public final native String getImageURL();
}
I have a method that uses the JsonpRequestBuilder to fire off a request to get my JSON.
private void loadSuggestedProducts() {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
builder.requestObject(buildSuggestedProductURL(), new AsyncCallback<JsArray<SuggestedProduct>>() {
public void onFailure(Throwable caught) {
//Handle errors
}
public void onSuccess(JsArray<SuggestedProduct> data) {
if ( data == null) {
//Handle empty data
return;
}
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<h4>Suggested Products:</h4>");
for (int i=0; i < data.length(); i++) {
SuggestedProduct product = data.get(i); //<- This line throws the exception
sb.appendHtmlConstant("<div class=\"card\">");
sb.appendHtmlConstant("<img class=\"card-img-top\" src=\"" + product.getImageURL() + "\" alt=\"" + product.getFormName() + "\">");
sb.appendHtmlConstant("<div class=\"card-body\">");
sb.appendHtmlConstant("<h5 class=\"card-title\">" + product.getFormName() + "</h5>");
sb.appendHtmlConstant("<a onclick=\"javascript:addItems();\" class=\"cmd-add\">Add <i aria-hidden=\"true\" class=\"fa fa-plus-circle\"></i></a>");
sb.appendHtmlConstant("</div></div>");
}
view.getSuggestedProducts().setInnerSafeHtml(sb.toSafeHtml());
}
});
}
When I try to use a SuggestedProduct from the response, I get an error:
java.lang.IncompatibleClassChangeError: Found interface
com.google.gwt.cor.client.JsArray, but class was expected
I've been following the guide in the GWT documentation. I don't see any difference between what I'm trying and what they say will work. When I debug, it looks as though the returned data is an array of SuggestedProducts, so I'm stumped as to how to proceed. Any help would be appreciated.
After closer inspection I realized my overlay type was missing method bodies for what fields to return from the JSON object they represented. The fix was to include the proper JSNI method definitions.
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName() /*-{ return this.formname; }-*/;
public final native String getImageURL() /*-{ return this.imageurl; }-*/;
}

Jersey client with RxJava conflicts with resteasy

I have a web application deployed to JBOSS. It contains dependency to jersey-rx-client-rxjava package and one of the packages has transient dependency to resteasy-jaxrs.
I have the following code.
RxObservable.newClient()
.target(fullURL)
.request()
.header("Authorization", "Bearer " + config.getApiKey())
.rx()
.post(javax.ws.rs.client.Entity.entity(context, MediaType.APPLICATION_JSON_TYPE), AIResponse.class)
.map(new Func1<AIResponse, String>() {
#Override
public String call(AIResponse res) {
return res.getType();
}
})
.subscribe(new Action1<String>() {
#Override
public void call(final String type) {
Log.info(type);
}
}, new Action1<Throwable>() {
#Override
public void call(final Throwable throwable) {
//async.resume(throwable);
Log.error(throwable.getMessage(), throwable);
}
}, new Action0() {
#Override
public void call() {
//async.resume(throwable);
Log.info("Done");
}
});
At this line, the following exception is thrown.
final JerseyInvocation invocation = (JerseyInvocation) getBuilder().build(name, entity);
Why does the build method return org.jboss.resteasy.client.jaxrs.internal.ClientInvocation, instead of JerseyInvocation?
2017-03-20 12:18:43,678 ERROR [com.optawork.bot.CustomResource] (default task-2) org.jboss.resteasy.client.jaxrs.internal.ClientInvocation cannot be cast to org.glassfish.jersey.client.JerseyInvocation: java.lang.ClassCastException: org.jboss.resteasy.client.jaxrs.internal.ClientInvocation cannot be cast to org.glassfish.jersey.client.JerseyInvocation
at org.glassfish.jersey.client.rx.rxjava.JerseyRxObservableInvoker$2.call(JerseyRxObservableInvoker.java:89)
at org.glassfish.jersey.client.rx.rxjava.JerseyRxObservableInvoker$2.call(JerseyRxObservableInvoker.java:83)
at rx.Observable.unsafeSubscribe(Observable.java:10142)
at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
at rx.Observable.subscribe(Observable.java:10238)
at rx.Observable.subscribe(Observable.java:10205)
at rx.Observable.subscribe(Observable.java:10086)
at ai.api.AIDataService.converse(AIDataService.java:601)
Why does the build method return org.jboss.resteasy.client.jaxrs.internal.ClientInvocation, instead of JerseyInvocation
It's just how the JAX-RS Client API is designed. When we try to call ClientBuilder.newBuilder (which is done internally), the JAX-RS API does a service lookup for any implementation of the JAX-RS Client API. If there is none, it falls back to Jersey. The problem is that when the service lookup is done, RESTEasy's client is found on the classpath.
The Jersey RX API has a from(Client) method that we can user, instead of the default newClient. This will allow us to pass an explicit JerseyClient instead of using the JAX-RS API ClientBuilder.newBuilder/newClient
// actual JerseyClient which implements Client
Client client = new JerseyClientBuilder().build();
RxObservable.from(client)
JerseyClientBuilder has pretty much the same API as the JAX-RS ClientBuilder, so you can use it pretty much the same way.

getting null pointer exception when mocking the objects using mockito

I am working spring boot, spring integration, gradle project. And I am using junit and Mockito for mocking my soap service. And Basically I have these three classes for my application.
Junit Class for mocking soap service.
#Before
public void setup() {
gw=Mockito.mock(ProjectGateway.class);
pc=new ProjectController();
pc.setGateWay(gw);
}
#Test
public void testGetProject() throws Exception {
GetAuthorizedWebSendTransferProjects mockRequest=new GetAuthorizedWebSendTransferProjects();
GetAuthorizedWebSendTransferProjectsResponse mockResponse=getMockResponse();
when(gw.getResponse(mockRequest)).thenReturn(mockResponse);
List<Project> projects=pc.getProject();
assertEquals(1,projects.size());
}`
and an interface which calls soap service.
`public interface ProjectGateway {
public GetAuthorizedWebSendTransferProjectsResponse getResponse(
GetAuthorizedWebSendTransferProjects request);
}'
and the method on which I need to do unit testing.
#RequestMapping(value = "/projects", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Project> getProject() {
GetAuthorizedWebSendTransferProjects request = new GetAuthorizedWebSendTransferProjects();
GetAuthorizedWebSendTransferProjectsResponse response = gw
.getResponse(request);
JAXBElement<ArrayOfProjectContainer> arr = response
.getGetAuthorizedWebSendTransferProjectsResult();
ArrayOfProjectContainer arr1 = arr.getValue();
List<ProjectContainer> arr2 = arr1.getProjectContainer();
List<Project> projects = getPopulatedProjectList(arr2);
return projects;
}
But I am getting an nullpointerexception in "List projects=pc.getProject();" of test method. Can anybody help me out in this issue. Thank you in advance.
The issue is that the instance of request that is expected by the mock does not match the instance that is actually passed. Therefore the condition doesn't match and the mock is returning null.
Use
when(mock.getResponse(
Mockito.isA(GetAuthorizedWebSendTransferProjects.class)))
.thenReturn(...)

Eclipse RCP e4 Logging

I amtrying to add logging capabilities to my RCP e4 application. I found the following Snippet.
import org.eclipse.e4.core.di.annotations.Creatable;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.log.Logger;
#Creatable
public class LoggerWrapper extends Logger {
#Optional
#Inject
private Logger logger;
#Override
public boolean isErrorEnabled() {
if (logger != null) {
return logger.isErrorEnabled();
}
return false;
}
#Override
public void error(Throwable t, String message) {
if (logger != null && isErrorEnabled()) {
logger.error(t, withPluginInfo(message));
}
}
}
But I am not sure how to configure/initialize the Logger? Any help will be appreciated. Thanks!
If I read E4Application correctly it will always initialize the application context to contain a Logger which is implemented by org.eclipse.e4.ui.internal.workbench.WorkbenchLogger.
You could override this in the PostContextCreate method of your Life Cycle class (if you have one).
You can also inject StatusReporter which provides simple logging facilities in the Eclipse log (based on Status objects).

What is the equivalent of IVisitor.CONTINUE TRAVERSAL in wicket 1.5

I'm porting our Wicket 1.4 app to Wicket 1.5. Visitors are now very different. What I would like to know is how do I handle a CONTINUAL_TRAVERSAL in Wicket 1.5? The existing 1.4 code is below:
public class MyFormVisitor implements IVisitor<Component, Object>, Serializable {
private static final long serialVersionUID = 7271477325583441433L;
private Set<Component> visited = new HashSet<Component>();
#Override
public Object component(Component c) {
if (!visited.contains(c)) {
visited.add(c);
c.add(new MandatoryBehavior());
c.add(new ErrorHighlightBehavior());
}
return IVisitor.CONTINUE_TRAVERSAL;
}
Just convert your method to something like this and you should be fine:
#Override
public void component(final Component c, final IVisit<Void> visit) {
if (!visited.contains(c)) {
visited.add(c);
c.add(new MandatoryBehavior());
c.add(new ErrorHighlightBehavior());
}
}
As you can see in the documentation you linked, the traversal is now controlled via the IVisit passed to the method. If none of the methods to either stop or not go deeper is called, the traversal will simply continue.