Javascript classes and DWR - java

I've been playing with DWR and converters for a while and I really wanted to map my Java classes to JavaScript classes. Using DWR converters, I have the option to point out what is the name of my JS constructor given a Java class. So far so good... The problem arises when my JS constructor is within a JS package-like name (just like YUI's package system, eg my.beautiful.package.MyClass). DWR's current implementation doesn't allow me to use this kind of construct, giving me a SyntaxError when I try to use it. Is there an elegant way arround this limitation?

As far as I know the this isn't possible directly. I have in my current work project experimented with enhancing each returned object on the client side with methods from a Javascript class, which gets the result that I think you are interested in.
DwrService.getThings({
callback:function(things){
for(thing in things){
YAHOO.augmentProto(thing, my.beautiful.package.MyClass);
}
// do your stuff here
}
});
I'll have to check at work on monday (now is sunday) that augmentProto is correct one to use, but I think it is. There may even be a better hook into DWR that'll allow you to do this on the fly automagically.

Related

What is a good way to implement Sockets?

dear stackoverflow community.
Currently, I am working on a project. This project shall have a server and clients connecting to it. Because of their simplicity, I'd like to use Java's integrated ServerSockets and Sockets.
In my project, data shall be sent from the client to the server and opposite.
My initial idea is to just send JSON and then parse it as receiver and get the data from that.
I'm a little unsure about that though, since JSON isn't something that's integrated into Java, but comes from Java script. Also, I'm currently using a Multithreaded-Socket-Server, so I have a ClientHandler Thread class. In that class, the messages were received, parsed and the "action" parameter was read out of the JSON and then I did a switch statement with multiple actions and their functions. I don't think that's a good way of doing that either.
So, my question is:
How can I do that better, and maybe do I have to use something else?
Thanks in advance.
It is true that JSON grew out of JavaScript, but it is a reasonable definition language on its own and I don't see any reason you shouldn't use it. There are libraries for parsing it so you don't have to.
Assuming your JSON structures are different for different purposes, and complex enough to need different classes to represent them, I like the idea of the JSON having a parameter that identifies the class to which it belongs, after which you can hand off parsing to a class that understands the designated output. Then a class can read the JSON, get the type, and some the specific parsing routine can go from there to an object created for the purpose.
I don't see anything wrong with an action string, either; it's served well enough for Swing and some other UIs, after all. Instead of branching out to a function, depending on complexity again, you could have action classes that all implemented an interface, and the action 'verb' could tell you which one (out of a map, say?) to get and execute the 'performAction()' method on or whatever you want to call it.
I don't know how clear this is from a quick description; would be willing to chat about it in an SO chat room if you care about it.

Fetch JSON data from a third-party and getting around the SOP

The Same Origin Policy is preventing me from fetching the JSON data I need from another web site (with permission). I saw one person who was working around this with JsonpRequestBuilder, but I'm not sure if that's going to be the best solution for me. The only other option that comes to my mind would be to have an intermediary servlet on my server.
What's my best bet here? I have concerns with both methods. With an intermediary servlet, I worry about the delay that would introduce. With the JsonpRequestBuilder, it looks like I have to create a complete JavascriptObject for each method I'll call from the other site, even though I only need to pull out a single value from some of those methods.
I don't use Java, but JSONP is what I usually implement when I need cross-domain chatter, and I'm sure someone will have made a Java library that unwraps it. It requires a change on the third-part's site, but it is a very simple change.
EDIT: Sounds like that is what that library does, sorry... but still... it's the way to go :)
Check out the CORS Specification. We are using this to successfully circumvent the SOP using our own server with GWT's devmode Jetty.
You don't have to "create a complete JavaScriptObject", a JavaScriptObject is actually just a mean to call to JavaScript from the Java world, so you only need the one getter for the value you need, and it can even return a "nested" value:
public native String getFoo() /*-{
return this.nested[0].obj.foo;
}-*/;
Whether you'll use JSONP (and JsonpRequestBuilder) or a "proxy servlet" actually only depends by the capabilities of the "service" you need to call: JSONP is JavaScript, not JSON, so the server has to return a "JSONP response script" or you won't be able to use JsonpRequestBuilder (and similarly, you won't be able to (safely) use CORS or a proxy-servlet if the server returns a "JSONP script" rather than application/json).

User inputed formula parsing (eval)

Good day all,
I am trying to figure out how to allow users to call a method on some specified data.
I would like to provide a predefined set of functions:
Moving average, moving_ave(x,5) ..would be a 5 day moving average on x.
3*x+y....and so on...
So basically, i will provide the users with various data series (x,y,z....) and a set of functions moving_ave, + - / * ....and they should be able to write simple formulas (restricted to the functions i provide).
how can this be done?
I will be deploying this on App Engine for Java.
so for i have found out about JSR-223...but i'm not sure if its appropriate? I am thinking i can use the Eval function.
Thanks,
It sounds like what you want is an interpreter for a simple grammar. Be very wary of approaches such as that suggested by Aerosteak; allowing your user to call functions in your code directly is dangerous, and it's easy to make mistakes sandboxing it, resulting in security vulnerabilities. It'll also require you to write your own parser.
The easiest approach is probably to use an existing language - Javascript probably fits very well, and you can use Rhino, a Javascript interpreter written in Java.
You will need to use Reflection to call unknow Method. Look a Apache BeanUtil.
You can have a TextBox with the value: 1,2,3, Convert these values to Object Array.
Have another ComBo Box with all you possible Method you can call.
Then use Bean Util to call the method with the Object Array.
For Exemple:
class MyMathManager{
public void doCalculationType1(Object args...){..}
public void doCalculationType2(Object args...){..}
public void doCalculationType3(Object args...){..}
Then Look at the Java of BeanUtil to call these Method.
Good Luck.
This sounds like something that could probably be done on the client, rather than the server. You could write a few handy javascript functions that call a restful API on the server to provide the needed data to a few more handy javascript functions that do the useful calculations. It's almost always safe to allow users to eval on their own clients.. they can do it in any case.

Can Java Code tell if it is in an App Server?

Is there something I can call from a POJO to see if the code is currently in an App Server or outside of an App Server?
Something like this (In rough PseudoCode):
System.getRunningEnvironment().equals(Environment.Glassfish)
or
System.getRunningEnvironment().equals(Environment.ApplicationServer)
or
System.getRunningEnvironment().equals(Environment.JavaSE)
If you can change AppServer initialization scripts (take a look at this link):
Add -DRunningInAppServer=true at your AppServer initialization script.
Add -DRunningInAppServer=false at your application initialization script.
Then use this method:
public boolean isRunningInAppServer() {
if ("true".equals(System.getProperty("RunningAppServer"))) {
return true;
}
return false;
}
I don't believe you can do this trivially. And would you want to distinguish between an app server, a web container etc.?
What is the reason for determining this ? To allow your POJOs to behave differently in different environments ? If so then I think this points to an object/component structure that is not quite correct, or at least where the object responsibilities are not clearly defined.
The easiest way is, to check the existence of Java EE/App Server specific classes.
I never used an application server, but maybe you'll be able to achieve this with System.getProperties() / System.getProperty(...)
Consider checking for the current SecurityManager, if your application server uses one.
I don't think there's any way to determine this directly. Yes, as SourceRebel says you could set a system property. Personally I'd avoid doing this, though, as you then have some hidden coupling going on: your function is dependent on a system property that must be set correctly for it to work, but there is nothing clearly defined in the interface to reflect this. I think you'd be far better off to just pass in a parameter that says which it is, and let the caller be responsible to pass in the correct parameter. Then the existence of this parameter can be clearly seen in the function signature, and anyone using it will have a strong clue that they need to set it correctly. Having the caller set it correctly should be trivial, as presumably at some point in the call chain you are either calling from a desktop app or from a web page, and that caller knows which it is.
Some applications server set system properties, JBoss for example:
http://community.jboss.org/wiki/JBossProperties

How to deal with monstrous Struts Actions?

I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding Actions. Most of the pages have exactly one Action, and the processExecute() methods are hideous monsters (very long and tons of nested if statements based on request parameters).
Given that Actions are an implementation of the command pattern, I'm thinking to split these Actions into one Action per user gesture. This will be a large refactoring though, and I'm wondering:
Is this the right direction?
Is there an intermediate step I could take, a pattern that deals with the mess inside the monolithic actions? Maybe another command pattern inside the Action?
My way of dealing with this would be:
dont do 'everything at once'
whenever you change anything, leave it better than you found it
replacing conditionals with separate Action implementations is one step.
Better yet: Make your implementations separate from the Action classes so that you can use it when you change frameworks
Keep your new Command implementation absolutely without references to Struts, use your new Actions as Wrapper around these implementations.
You might need to provide interfaces to your Struts ActionForms in order to pass them around without copying all the data. On the other hand - you might want to pass around other objects than ActionForms that are usually a bunch of Strings (see your other question about Struts 1.2 ActionForms)
start migrating parts to newer & better technology. Struts 1.2 was great when it came out, but is definitely not what you want to support in eternity. There are some generations of better frameworks now.
There's definitely more - Sorry, I'm running out of time here...
Struts Actions, in my mind, shouldn't have very much code in them at all. They should just interact directly with the request and response - take some data from a form or a request parameter, hand that info off to the Service Layer, and then put some stuff in a Response object or maybe save some data in the user's session.
I'd recommend staying away from doing inheritance with action classes. It sounds like a good idea at first but I think sooner or later you realize that you're shoe-horning things more than you're actually making the code base robust. Struts has enough base actions as is, if you're creating new ones you've probably got code in the web layer that shouldn't be there.
That is just my personal experience.
I've dealt with this type of thing before. A good first step is to insert another base class into the inheritance chain between Action and one of the original monstrous action classes (lets call it ClassA). Especially if you don't have time to do everything at once. Then you can start pulling out pieces of functionality into smaller parallel Action classes (ClassB, ClassC). Anything that's common between the original ClassA and the new refactored classes can be pulled up into the new base class. So the hierarchy now looks like this:
Original Hierarchy: New Hierarchy:
Action Action
| |
| BaseA
(old)ClassA |
+--------+----------+
| | |
ClassB (new)ClassA ClassC
Go one method at a time
Record some test cases you can play back later. Example here (make sure to hit as many paths through the code as you can, i.e. all user gestures on the page that call this action)
refactor the method to reduce its complexity by creating smaller methods that do smaller things.
Re-run tests as you do this
At this point, you have refactored version of the big huge annoying method. Now you can actually start creating specific actions.
You can use your newly refactored class as a base class, and implement each specific action as a subclass using those refactored small methods.
Once you've done this, you should have a good picture of the logic shared between the classes and can pull-up or push-down those methods as needed.
It's not fun, but if you will be working on the codebase for a while, it will save you time and headaches.
Tough problem but typical of early web app development.
First things first you need to start thinking about which logic constitutes business behavior, which logic constitutes "flow" (i.e. what the user sees), and which logic gets the content for what he sees.
You don't have to go down the route of factories and interfaces and all that; retroactive implementation is far less useful... but consolidating business logic and data retrieval logic into delegates of some kind... and leaving the struts actions to determine page flow based on success/failure of that logic.
From there you just have to take a few weeks and grind it out
One long method is never good, unless it happens to be a single switch statement where the cases are very short (token parsing or something like that).
You could at least refactor the long method into smaller methods with descriptive names.
If at all possible you could start your method with recognizing what it is it should do by examining the form, and then if/else your way to the various options. No nested ifs though, those tend to make code unreadable. Just
enum Operation {
ADD, DELETE;
}
...
Operation operation = determineOperation(form);
if (operation == Operation.DELETE) {
doDelete(form);
} else if (operation == Operation.ADD) {
doAdd(form);
}
If you can go that far you have your logic nice and clean and you can do whatever refactoring you want.
The hard part is to get your logic clear, and you can do that in steps. Don't choose a pattern untill you understand exactly what your problem is.
If you're planning to refactor the code you should make sure to write tests for the existing code first so you can be sure you haven't altered the functionality of it once you start refactoring.

Categories