Class wrapper extending different base class - java

I have a Java project and now I also want to use this code for a GWT project so I don't have to write the same code twice. The problem is that some classes are not available in gwt, for example java.awt.geom.Rectangle2D.Double.
I was thinking of creating a wrapper class called RectangleWrapper that would extend either the standard Rectangle class or a gwt version of the same class.
In the shared code I would replace all my Rectangle2D.Double with my Rectangle and depending on a final boolean my wrapper class (compiler flags java) would either extend on or the other Rectangle class.
Is this even possible or is there a better way to do this?

I just took one of my GWT-project client-side classes and added the following lines:
if (false) {
String a = StringEscapeUtils.escapeHtml("lalala");
}
This obviously compiles just fine, but when I launch the GWT app I get this:
ERROR: Errors in 'file:/C:/gwtproject/src/main/java/package/ClientSideClass.java'
ERROR: Line 119: No source code is available for type org.apache.commons.lang.StringEscapeUtils; did you forget to inherit a required module?
So the answer would be no, you can't use a wrapper like that.
Is there any other way of achieving that? I highly doubt it.
One of the main features of GWT is replacing the old AWT/Swing desktop GUI components with a whole set of web GUI components designed for Javascript compatibility; there's no point in making the old components available or supported in any way.
If you were talking about utility libraries like Apache Commons, I could advise you to make an RPC call instead (client-side calls server-side where you can use anything you like, and return the results asynchronously), but that's not the case.

Related

Perform AsyncTask inside Class

I have a method inside of a class called
ChopraWisdom.GetQuote()
that pulls in some data from the interwebs. To use it I have to use an AsyncTask in my activity. Thats fine and all, but my Activity code now gets cluttered with the AsyncTask code.
I was hoping that I could hide the AsyncTask in my Class and then create another method called
ChopraWisdom.GetQuoteAsync()
But I'm not sure how to pass in "Actions" (I come from a .Net background) in order to handle the various UI updating that needs to take place.
In C# I would define the method signature as something like:
ChopraWisdom.GetQuoteAsync(Action preExecute, Action postExecute, Action updateProgress)
Questions:
Does java have something comparable to 'Action'?
What is the acceptable pattern for 'wrapping' Async functionality like this in Java?
I like clean code, but am I being to picky here?
Please provide examples.
EDIT - Added Example class
public class ChopraWisdom
{
public string GetQuote()
{
//...do stuff and return a string
}
}
You should really think about using Loaders instead of AsynkTask(with android support lib).
If you still want to use AsyncTask in your situation best way would be to create new interface Action(something like https://github.com/ReactiveX/RxJava/blob/1.x/src/main/java/rx/functions/Action0.java)
You could use RxJava in your project and use all they have https://github.com/ReactiveX/RxJava/tree/1.x/src/main/java/rx/functions
You could use https://github.com/evant/gradle-retrolambda in combination with (2) option to provide C# like lambdas in your java code.
Java does have something comparable to Action. It is called Function and only available in Java 8. The standard way for passing a function as parameter is to create an interface and provide it as a parameter. That way you can either pass in an instance of a class implementing that interface or create an anonymous class inline. You encounter the latter everywhere in Android (OnClickListener, etc ...)
I would highly recommend you to take a look at Android Annotations. It provides useful features like:
Dependency injection
View injection
OnClickListener via annotation
AsyncTask via annotation
...
And the best thing: everything is done at compile time through subclassing, therefore there is no performance impact and you can check what the framework is doing at any given point.
You are not too picky at all. Clean code is very important in Android development as you have to write a lot of boilerplate- / gluecode anyway.
Here are some other handy android frameworks that are definitely worth checking out:
GreenDao
Eventbus

GWT - Mark parts of shared code as "server only"

I have a GWT app which contains, besides traditional "client" and "server" packages, also a "shared" package, which contains POJO DTOs that travel back/forth through RPC. I need to create some methods in those DTOs which should exist only on server-side (i.e. they should not be compiled to JS, because they'd use code which is not compile-able to JS), especially the static() method.
Is this possible in GWT (some attribute, ifdef, ...)?
Background:
I have some generic validators which require "registration" of the class to be validated (via a static method register(Class<T>), and since I can't find any GWT init() method I'd put the registration in static constructors of the DTOs, so when (if) the class gets loaded it registers itself for validation.
A detailed discussion of this issue:
http://code.google.com/p/google-web-toolkit/issues/detail?id=3769
We had some similar issues with some DTO objects in a project recently. We ended up splitting the data away from the methods, creating a second set of classes that contained static methods for dealing with the data. As far as I can tell, there isn't any way to annotate methods in a class to prevent gwtc from trying to convert them to javascript.
It seems that Google implemented it in r11570.

Java API Question

I am trying to implement a custom Java widget using GWT.This requires me to copy a class from the GWT API and pasting it in my own new Class.(I am not sure if this is a right approach.Suggest me if its wrong to copy the API in my new class).The reason why i am doing this is i need to make modifications to the API,because the API does not provide me getter/setter's for a object.
But the problem with this is ,the API class uses many methods which have the protected access modifier.So when i paste this code in my package ,these methods are not recognized.I cannot even think of making my class a sub class (a workaround for protected access modifier) as the methods are from different classes and i cannot make my class a sub class of more than one class.
Can any one suggest me a work around for this scenario.I am trying to implement a widget whose functionality is similar to the browser's navigation widget(the place where we enter a website's url).Its similar to combining the functionality of ListBox+SuggestBox.
This is my previous question.That is what i am trying to implement.
Thanks
Derive a new widget by extending from Composite and then implement whatever functionality you need within that. e.g. If you need a ListBox to make suggestions then create one from inside your Composite and hook up whatever listeners you need to on the inner widget to drive suggestions.
A sample of a Composite widget is shown here.
There shouldn't be any reason to have to copy & paste existing source code. Indeed doing so is not going to get you far since most widgets in GWT are just wrappers HTML elements anyway with some plumbing to hook up to the event model.
It would really help if you provided some sample code, you should never have to copy and paste code from the API. What are you trying to extend and what variables within that class do you need access to and to do what? Usually there is a reason why variables are private and thats because messing with them will cause a break in functionality.

DLLs for a dynamic Java program?

I'm currently working on a Java project where I have a set of data which I wish to output in several custom formats. I have a class for each format, which takes the raw data and converts it accordingly. However, to begin with I am only implementing two or three of these formats, but wish to allow more formats to be added at a later date without having to do a massive rebuild of the application.
My idea was to create a DLL for each of the format classes, and have my application pass the data to be converted to each of these. This way, I can create a DLL later on and have my main application accessing it. (I would gladly listen to any alternative ways of doing this, as someone who has done this in C++/C# before this felt like the logical solution but it may not be applicable to Java)
My problem is that I have absolutely no idea how to do this - in C++/C# I could write this in a few lines of code but I'm not sure how it works with Java. At the risk of asking a terribly vague question, how can I do this?
Answers are greatly appreciated and cookies and tea will be offered. :)
Thanks in advance,
M
Edit: Sorry, just to add: I am also unsure how to create the DLL, which must be in Java for this project, to be read in the first place. Thanks. :)
Rather than using a DLL per se, it seems like what is wanted is a plugin architecture of some sort.
One reason why I wouldn't recommend using a DLL unless it is necessary is that linking Java code with native code will require using the Java Native Interface (JNI) which would probably require more effort than a pure Java solution.
One relatively simple way to do so is to use the reflection capabilities of Java.
From the information given, I would probably go along the lines of the following:
Define an interface for the output format.
Create a Java class implementing the interface.
Have the class available from the classpath.
Dynamically load the class using reflection. (Using the Class.newInstance method can instantiate objects from class files loaded by the ClassLoader.)
With these steps, it would be possible to implement a simplistic plugin which wouldn't require a full rebuild when support for a new format is required.
Step 1: Define the interface
Let's say we end up with an interface like the following:
public interface Outputter {
public void write(Data d);
}
Step 2: Make an implementation class
Then, we'll make an implementation class.
public class TextOutputter {
public void write(Data d) {
// ... output data to text
}
}
Then, compiling the above, we'll end up with a class file called TextOutputter.class.
Step 3: Make the class available from the classpath
When running the main application, we'll need to have the above TextOutputter.class in the classpath. Normally, one would tell the JVM a list of places to consider as the classpath, and that should include the above class file.
Once that is done, we should be able to load the above class using reflection.
Step 4: Dynamically load the class using reflection
Now, when we actually want to load the above class, we'd do something like the following:
// Note: We load the class by specifying the fully-qualified class name!
Class<?> clazz = Class.forName("TextOutputter");
// Then, we instantiate the class.
// Note that the following method will call the no-argument constructor.
Outputter outputter = clazz.newInstance();
// Now, we can give data to the TextOutputter object that we loaded dynamically.
outputter.write(...);
The Class.forName method is used to attempt to find the TextOutputter class from the default ClassLoader. Once we obtain the class as a Class representation, we can then instantiate an object of that class.
Instantiating the object can be performed by using the Class.newInstance method. If something other than the no-argument constructor should be used, the Constructor of the class would have to be obtained proceed to instantiate the object from there.
The object instantiates via reflection is then placed into a Outputter variable, so the write method can be called on the TextOutputter.
Adding more formats would entail the above process, but changing the fully-qualified class name (e.g. for String, the FQCN is java.lang.String) is all that is needed to load up a different class.
In a nutshell, that's what it will take to dynamically load class files and use it from your application.
(Just as a side note, I did not actually compile the above code, so there may be some errors here and there, but I hope I could illustrate the process it will take.)
I've made such things.
i created an open java based plugin architecture POJO based,that even did reload on the fly of updated plugin classes.
JNI is the interface for dealing with native code.
The only technical part was to rewrite a classloader that enabled DLL reloading dynamically at runtime.
But if you do only make "offline" updates, no such things are needed.
You can load a new DLL at any time with System.loadLibrary(). However you may need to load a java class for it to bind to.
You might find using an OSGi container helpful as this supports both load and unloading of modules (including shared libraries)
I would suggest using karaf with iPOJO but there are many others.
If you want write native codes (compiled to a DLL) to be used in java, you want to look at Java Native Interface (JNI).
Update you can use System.loadLibrary(String libName) (if you know the library name and the library path is set) or System.load(String filename) (library filename) to load library (DLL) in java.
I think you can ignore the JNI path. I have the impression you're using the term dll for lack of a better word, you don't really need a dll.
You could do the same thing in Java, but you'd put your filters in jar files instead of dll.
Define an interface for the file format filters to implement
Put each implementation into a jar, in a specific folder (like 'filters')
At one point in the app, iterate over the folder, generate classloader for the jars
Use reflection to find all implementations of your interface, and create a class for each
Call the methods to do their job
That's basically it.
Java SE 6 introduces the ServiceLoader class:
http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html
If you want a proper modular approach consider the NetBeans Platform (especially if it is a desktop application) or OSGi.

Where to put business logic in Eclipse RCP program

I'm writing a small application in RCP to wrap around the business logic in another (non-RCP) simulation library. I can access and use the library fine from any of my plugins, but I don't know where I should put the instance of the Simulation library so that, say, one of the command handlers can make calls to it.
From reading the docs it sounds like I should be storing 'global' information like this in the workbench - but I still don't really understand how to do that.
Help?
First, the business layer (BL) can and should reside in its' own plugin. That will provide decent decoupling between the layers.
Second, you should carefully decide what the interface should be and which classes are exposed. Ideally, you should mostly expose interfaces and data objects.
Finally, decide how the "hand shake" works. E.g., how to obtain the initial interface to the BL. Since it is a Plugin, it could have an Activator which loads it. You could add a method in the activator which returns the BL interface.
If you are looking for something more decoupled, you could create an extension point or deploy the BL as an OSGi service, but that's a bit of an overkill for you need.
If I understand you correctly, I see two ways:
Store the instance in the model plug-in itself, using ‘SimulationFactory.getInstance(String myAppId)‘. The passed String is a constant in you app that is always used, when obtaining the reference.
Define a new class e.g. GlobalAccess in you app that is initilized with an instance of your model and has some getter (whether you use a single instance again or only provide public static methods is a matter of taste).
The seocond way is similar to some classes in eclipse like platfom or platformui, where you can obtain initial references and navigate through the workbench.
edit
i just found a tutorial that might help you:
Passing Data between Plug-ins

Categories