Jackson returning LinkedHashMap from API generated with openapi-codegen - class

I have a Java Backend that serves an openapi.json specification. Its purpose is that is it possible to create an API Client through openapi-generator. This is what I did. The Client comes out just fine, every class is perfect, they all have the properties they should be having and so on. One example is this class:
public final data class Project public constructor(
name: kotlin.String,
title: kotlin.String,
previewUrl: kotlin.String,
connections: kotlin.collections.List<kotlin.String>? /* = compiled code */,
mapWindows: kotlin.collections.List<kotlin.String>? /* = compiled code */,
ribbons: kotlin.collections.List<kotlin.String>? /* = compiled code */
) {
#field:com.fasterxml.jackson.annotation.JsonProperty public final val connections: kotlin.collections.List<kotlin.String>? /* compiled code */
#field:com.fasterxml.jackson.annotation.JsonProperty public final val mapWindows: kotlin.collections.List<kotlin.String>? /* compiled code */
#field:com.fasterxml.jackson.annotation.JsonProperty public final val name: kotlin.String /* compiled code */
#field:com.fasterxml.jackson.annotation.JsonProperty public final val previewUrl: kotlin.String /* compiled code */
#field:com.fasterxml.jackson.annotation.JsonProperty public final val ribbons: kotlin.collections.List<kotlin.String>? /* compiled code */
#field:com.fasterxml.jackson.annotation.JsonProperty public final val title: kotlin.String /* compiled code */
}
As you see, this class looks just fine.
Then I have a service containing functions as the following:
public final fun getProjects():
kotlin.collections.List<bla.bla.bla.Project> {
/* compiled code */
}
So, what do I expect when executing this class? As it returns a List of Projects I also expect to get a List of Projects. But instead I get a List of LinkedHashMaps.
As soon as I worked with these Lists the App will get an exception. It is not possible to cast these LinkedHashMaps over to Project. As soon as I get this List it means 'Game Over'.
Actually, I have no clue what to do now. I also tried to use moshi or gson when creating the api client but sadly we have really deeply nested classes that did not work out with these.
Did anyone ever experience something similar?

Well, apparently that was an easy fix. Somehow Jackson does not like kotlin.collection.List, but it does like Arrays. So I added this line to config.json:
"collectionType": "array"
And that's it. Now it returns Arrays with the proper type.

Related

Load a ListBox content dynamically on page load

I'm currently working on a simple GWT project. One of the things I'd like to do is that when the page loads I can dynamically populate the contents of a ListBox based on certain criteria. I actually don't see any handlers for a ListBox to handle the initial render event but I see change handlers.
How does one populate a ListBox contents with data from the server side on pageload with GWT?
Right now I have a class that implements EntryPoint that has a
final ListBox fooList = new ListBox();
I also have a set of beans but I also have a class implementing RemoteService. Since I can't seem to get direct calls to my user defined packages directly in the EntryPoint (which makes sense) how do I populate that ListBox with server side content on initial page load? Right now I'm using a List but I figure if I cant get that to work I can get a DB call to work...
I've tried things in the EntryPoint like:
for (String name : FOOS) {
fooList.addItem(name, name);
}
However FOOS would derive from a server side data and the EntryPoint is supposed to be largerly limited to what can compile to JS! I can't get user defined classes to be recognized on that side as that string is the result of a set of user defined classes.
I also tried creating a method in the class implementing RemoteService that returns a ListBox. This also didn't compile when I tried to call this method. Perhaps I don't fully understand how to call methods in a RemoteService service implementing class.
I've searched a lot and I can't find anything that clearly explains the fundamentals on this. My background is much more ASP.NET and JSPs so perhaps I'm missing something.
I'm using GWT 2.6 is that is relevant.
The usual procedure is the following:
Create a bean class for the data you want to transmit between client and server. Let's call it MyBean.
Place MyBean in the shared package of your project.
This class has to implement either Serializable or IsSerializable, otherwise GWT will complain that it doesn't know how to transmit it.
Create your RemoteService that contains the method you want to use to transmit MyBean from/to the server.
Once you get your data on the client using an AsyncCallback and your RemoteService, fill the ListBox using your beans, e.g. by calling MyBean#getName() or MyBean#toString().
Success!
I based my example on the GWT sample project ( I named it example), just replace the classes and it should work :
public class Example implements EntryPoint {
/**
* Create a remote service proxy to talk to the server-side Greeting
* service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final ListBox listBox = new ListBox();
RootPanel.get("sendButtonContainer").add(listBox);
greetingService.getSomeEntries(new AsyncCallback<String[]>() {
#Override
public void onSuccess(String[] result) {
for (int i = 0; i < result.length; i++) {
listBox.addItem(result[i]);
}
}
#Override
public void onFailure(Throwable caught) {
}
});
}
}
This is our EntryPoint, it creates a listbox and calls the server with a AsyncCallback to get some dynamic data. If the call is successfull (onSuccess), the data is written into the listbox.
The GreetingService interface define the synchronous methods, it is implemented in the GreetingServiceImpl class :
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String[] getSomeEntries() ;
}
The asynchronous counterpart is the GreetingServiceAsync interface, we used it before to call the server :
public interface GreetingServiceAsync {
void getSomeEntries(AsyncCallback<String[]> callback) ;
}
The GreetingServiceImpl class is located on the server. Here you could call for example a database:
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
#Override
public String[] getSomeEntries() {
String[] entries = { "Entry 1","Entry 2","Entry 3" };
return entries;
}
}
Now if you want to use some Bean/Pojo between the server and client, replace the String[] in each class/interface with the object name, put the class in the shared package and consider that it implements Serializable/IsSerializable.

How to wrap every Callback in one place to improve error handling

Throughout my GWT app there are many different async calls to the server, using many different services. In order to do better error handling I want to wrap all my callbacks so that I can handle exceptions like InvocationExceptions in one place. A super class implementing AsyncCallback isn't really an option because that would mean that I would have to modify every async call.
RpcServiceProxy#doCreateRequestCallback() looks like the method to override. Simple enough. I just can't see how to make GWT use my new class.
Another way to state the question would be
How do I make GWT use my own subclass of RpcServiceProxy?
In order to wrap every AsynCallback<T> that is passed to any RemoteService you need to override RemoteServiceProxy#doCreateRequestCallback() because every AsynCallback<T> is handed in here before an RPC call happens.
Here are the steps to do so:
As #ChrisLercher alluded, you need to define your own Proxy Generator to step in every time a RemoteService proxy gets generated. Start by extending ServiceInterfaceProxyGenerator and overriding #createProxyCreator().
/**
* This Generator extends the default GWT {#link ServiceInterfaceProxyGenerator} and replaces it in the
* co.company.MyModule GWT module for all types that are assignable to
* {#link com.google.gwt.user.client.rpc.RemoteService}. Instead of the default GWT {#link ProxyCreator} it provides the
* {#link MyProxyCreator}.
*/
public class MyServiceInterfaceProxyGenerator extends ServiceInterfaceProxyGenerator {
#Override
protected ProxyCreator createProxyCreator(JClassType remoteService) {
return new MyProxyCreator(remoteService);
}
}
In your MyModule.gwt.xml make use of deferred binding to instruct GWT to compile using your Proxy Generator whenever it generates something of the type RemoteService:
<generate-with
class="com.company.ourapp.rebind.rpc.MyServiceInterfaceProxyGenerator">
<when-type-assignable class="com.google.gwt.user.client.rpc.RemoteService"/>
</generate-with>
Extend ProxyCreator and override #getProxySupertype(). Use it in MyServiceInterfaceProxyGenerator#createProxyCreator() so that you can define the base class for all the generated RemoteServiceProxies.
/**
* This proxy creator extends the default GWT {#link ProxyCreator} and replaces {#link RemoteServiceProxy} as base class
* of proxies with {#link MyRemoteServiceProxy}.
*/
public class MyProxyCreator extends ProxyCreator {
public MyProxyCreator(JClassType serviceIntf) {
super(serviceIntf);
}
#Override
protected Class<? extends RemoteServiceProxy> getProxySupertype() {
return MyRemoteServiceProxy.class;
}
}
Make sure both your MyProxyCreator and your MyServiceInterfaceProxyGenerator are located in a package that will not get cross-compiled by GWT into javascript. Otherwise you will see an error like this:
[ERROR] Line XX: No source code is available for type com.google.gwt.user.rebind.rpc.ProxyCreator; did you forget to inherit a required module?
You are now ready to extend RemoteServiceProxy and override #doCreateRequestCallback()! Here you can do anything you like and apply it to every callback that goes to your server. Make sure that you add this class, and any other class you use here, in my case AsyncCallbackProxy, to your client package to be cross-compiled.
/**
* The remote service proxy extends default GWT {#link RemoteServiceProxy} and proxies the {#link AsyncCallback} with
* the {#link AsyncCallbackProxy}.
*/
public class MyRemoteServiceProxy extends RemoteServiceProxy {
public MyRemoteServiceProxy(String moduleBaseURL, String remoteServiceRelativePath, String serializationPolicyName,
Serializer serializer) {
super(moduleBaseURL, remoteServiceRelativePath, serializationPolicyName, serializer);
}
#Override
protected <T> RequestCallback doCreateRequestCallback(RequestCallbackAdapter.ResponseReader responseReader,
String methodName, RpcStatsContext statsContext,
AsyncCallback<T> callback) {
return super.doCreateRequestCallback(responseReader, methodName, statsContext, new AsyncCallbackProxy<T>(callback));
}
}
References:
DevGuideCodingBasicsDeferred.html
An example applied to performance tracking
The type you're looking for is probably RemoteServiceProxy (not RpcServiceProxy), and I assume, that you should start with overriding the default binding in /com/google/gwt/user/RemoteService.gwt.xml (just copy the lines to your own .gwt.xml file and adjust):
<generate-with
class="com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator">
<when-type-assignable class="com.google.gwt.user.client.rpc.RemoteService"/>
</generate-with>
There you'll find protected Class<? extends RemoteServiceProxy> getProxySupertype(), which you can override to return your own RemoteServiceProxyclass.
Haven't tried it yet, so this may need a few additional steps...
Normally the way in GWT to handle exceptions happening in async processes is via UncaughtExceptionHandlers.
I would use my own handler to manage those exceptions:
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
if (e instanceof WhateverException) {
// handle the exception here
}
}
});
Using this you dont need to subclass anything.
If by "one place" you mean "I want to handle all errors in one method", then I would suggest either catching and throwing stuff until they're in one place OR creating an EventBus that you basically just send every error to. Then you can just have a single handler attached to this bus that can handle everything.

CQ5(CRX) bookstore application error

I checked out source code fromhttp://dev.day.com/docs/en/crx/current/getting_started/first_steps_with_crx.html#Step%20Two:%20Check%20out%20CRX%20Bookstore%20Example
When I tried to invoke http://:4502/products.html
Actual result should list the products page from bookstore app
I got "Cannot serve request to /products.html in /apps/bookstore/components/ranking/ranking.jsp: What version of the product are you using? On what operating system?
I am using CQ5.5 (CRX 2.3) on windows 7
http://code.google.com/p/crxzon/issues/detail?id=4&thanks=4&ts=1362987616
From what I see, you get NullPointerException in RankingServiceImpl:277, because the repository field is null. And the only way I can explain that is that SCR annotations didn't fire during the build.
Said that, I'm actually surprised your bundle started on CQ 5.5, as the dependencies seem to be to earlier versions (5.4 I guess) -- I suggest double checking that under /system/console/bundles (search for CRX - Sample Bookstore Demo). If you're missing imports there, try playing with /src/impl/com.day.crx.sample.bookshop.bnd to update versions as in CQ 5.5, or running it on CQ 5.4.
The annotations in RankingServiceImpl seem to be for an earlier version of CQ and CRX. Here are the changes that I made to get this to work:
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
/**
* Default implementation of the ranking service.
* The ranking is updated through observation (based on OSGi events).
* The service can be used by clients to get the highest ranked products.
*/
#Component(immediate = true)
#Service(value = RankingService.class)
#Property(name = org.osgi.service.event.EventConstants.EVENT_TOPIC, value = SlingConstants.TOPIC_RESOURCE_ADDED)
public class RankingServiceImpl
implements RankingService, EventHandler, Runnable {
private Logger logger = LoggerFactory.getLogger(this.getClass());
// private Logger logger = LoggerFactory.getLogger("RankingServiceImpl");
private static final String PROPERTY_PREV_RANKING = "lowerRankingRef";
private static final String PROPERTY_NEXT_RANKING = "higherRankingRef";
private static final int SHOW_HIGHEST_RANKING = 3;
/** Flag for stopping the background service. */
private volatile boolean running = false;
/** A local queue for handling new orders. */
protected final BlockingQueue<String> orders = new LinkedBlockingQueue<String>();
#Reference
private SlingRepository repository;
#Reference
private ResourceResolverFactory resourceResolverFactory;

how to dig into this memory leak with eclipse MAT further

I have an issue where a ScheduledThreadPoolExecutor ends up with 3 million future tasks. I am trying to see what type of task so I can go to where that task is scheduled, but I am not sure how to get any info from this screen(I have tried right clicking those future tasks and selecting various choices in the menu). It seems like there is something missing in the gui like the links to the actual runnables or something...
any ideas on how to drill into further?
Some General Stuff
You need to know, that if you have a portable heap dump (phd, see types here), then it does not contain actual data (primitives), so then you can make your findings only based on reference map (which types hold a reference to which other types).
You can give a try to OQL. This is an SQL like language, with which you can query your objects.
One example:
select * from java.lang.String s where s.#retainedHeapSize>10000
This gives back all strings, that are bigger than ~10k.
You can make also some functions (like this aggregating here).
You could give a try to it.
As for the current problem
If you check the FutureTask source (here is JDK6 below):
public class FutureTask<V> implements RunnableFuture<V> {
/** Synchronization control for FutureTask */
private final Sync sync;
...
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
sync = new Sync(callable);
}
...
public FutureTask(Runnable runnable, V result) {
sync = new Sync(Executors.callable(runnable, result));
}
The actual Runnable is referred by the Sync object:
private final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -7828117401763700385L;
/** State value representing that task is running */
private static final int RUNNING = 1;
/** State value representing that task ran */
private static final int RAN = 2;
/** State value representing that task was cancelled */
private static final int CANCELLED = 4;
/** The underlying callable */
private final Callable<V> callable;
/** The result to return from get() */
private V result;
/** The exception to throw from get() */
private Throwable exception;
/**
* The thread running task. When nulled after set/cancel, this
* indicates that the results are accessible. Must be
* volatile, to ensure visibility upon completion.
*/
private volatile Thread runner;
Sync(Callable<V> callable) {
this.callable = callable;
}
So in the GUI open the Sync object (not open in your picture), and then you can check the Runnables.
I dont know if you can change the code or not, but in general it is better always limit the size of the queue used by an executor, since this way you can avoid leaks. Or you can use some persisted queue. If you apply a limit you can define the rejection policy like for example reject, run in caller and so on. See http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html for details.

NetBeans PHPUnit test generation ignoring #assert annotation

I have an abstract class where source code looks like this:
/*
* #assert (0) == NULL
*/
public static function factory($num) {
if ($num==0)
return NULL;
//do some other stuff
}
If I delete the previously generated test file and use the "Create PHPUnit tests", it creates a new unit test file that doesn't seem to have taken the assert into account at all:
/**
* #covers {className}::{origMethodName}
* #todo Implement testFactory().
*/
public function testFactory() {
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
I must be doing something silly, but I can't figure out what. Is the failure to expand the class name and method name in the generated #covers annotation perhaps a clue?
I'm running NetBeans 7.0.1 on a Mac with PHP 5.3.6 and PHPUnit 3.6.2.
All annotations must appear in DocBlock comments which start with /** and not /*. You're missing an asterisk.
/**
* #assert (0) == NULL
*/
public static function factory($num) {