Static classes, methods, and fields in GWT client - java

A colleague who coded the client side of a GWT application has essentially made all widgets and their methods and fields static. I am trying to evaluate it's impact.
Based on my reading so far, this has the result of making the javascript objects global for each user's compiled nocache.js file. In terms of drawbacks, this is potentially inefficient in that objects are not created dynamically and freed on demand. Also, it's a major hassle to maintain this code.
Are there any other risks in coding the client this way?

You cannot use your widget in two places in your app: they will keep the last entered data in the lastly used form.
This must be time consuming at startup (page load), since all widgets of the app are created : there is no control on the instant the widget is created
The recommended way is to have a ClientFactory (http://www.gwtproject.org/doc/latest/DevGuideMvpActivitiesAndPlaces.html#ClientFactory) :
Widget lifetime is controlled through this object that decides whether to create a new instance for each widget request or use the same one

Related

How to approach JMX Client polling

recently I dove into the world of JMX, trying to instrument our applications, and expose some operations through a custom JMXClient. The work of figuring out how to instrument the classes without having to change much about our existing code is already done. I accomplished this using a DynamicMBean implementation. Specifically, I created a set of annotations, which we decorate our classes with. Then, when objects are created (or initialized if they are used as static classes), we register them with our MBeanServer through a static class, that builds a dynamicMBean for the class and registers it. This has worked out beautifully when we just use JConsole or VisualVM. We can execute operations and view the state of fields all like we should be able to. My question is more geared toward creating a semi-realtime JMXClient like JConsole.
The biggest problem I'm facing here is how to make the JMXClient report the state of fields in as close to realtime as I can reasonably get, without having to modify the instrumented libraries to push notifications (eg. in a setter method of some class, set the field, then fire off a JMX notification). We want the classes to be all but entirely unaware they are being instrumented. If you check out JConsole while inspecting an attribute, there is a refresh button at the bottom of the the screen that refreshes the attribute values. The value it displays to you is the value retrieved when that attribute was loaded into the view, and wont ever change without using the refresh button. I want this to happen on its own.
I have written a small UI which shows some data about connection states, and a few field on some instrumented classes. In order to make those values reflect the current state, I have a Thread which spins in the background. Every second or so the thread attempts to get the current values of the fields I'm interested in, then the UI gets updated as a result. I don't really like this solution very much, as its tricky to write the logic that updates the underlying models. And even trickier to update the UI in a way that doesn't cause strange bugs (using Swing).
I could also write an additional section of the JMXAgent in our application side, with a single thread that runs through the list of DynamicMBeans that have been registered, determines if the values of their attributes have change, then pushes a notification(s). This would move the notification logic out of the instrumented libraries, but still puts more load on the applications :(.
I'm just wondering if any of you have been in this position with JMX, or something else, and can guide me in the right direction for a design methodology for the JMXClient or really any other advice that could make this solution more elegant than the one I have.
Any suggestions you guys have would be appreciated.
If you don't want to change the entities then something is going to have to poll them. Either your JMXAgent or the JMX client is going to have to request the beans every so often. There is no way for you to get around this performance hit although since you are calling a bunch of gets, I don't think it's going to be very expensive. Certainly your JMXAgent would be better than the JMX client polling all of the time. But if the client is polling all of the beans anyway then the cost may be exactly the same.
You would not need to do the polling if the objects could call the agent to say that they have been changed or if they supported some sort of isDirty() method.
In our systems, we have a metrics system that the various components used. Each of the classes incremented their own metric and it was the metrics that were wired into a persister. You could request the metric values using JMX or persist them to disk or the wire. By using a Metric type, then there was separation between the entity that was doing the counting and the entities that needed access to all of the metric values.
By going to a registered Metric object type model, your GUI could then query the MetricRegistrar for all of the metrics and display them via JMX, HTML, or whatever. So your entities would just do metric.increment() or metric.set(...) and the GUI would query the metric whenever it needed the value.
Hope something here helps.
Being efficient here means staying inside the mbean server that contains the beans you're looking at. What you want is a way to convert the mbeans that don't know how to issue notifications into mbeans that do.
For watching numeric and string attributes, you can use the standard mbeans in the monitor package. Instantiate those in the mbean server that contains the beans you actually want to watch, and then set the properties appropriately. You can do this without adding code to the target because the monitor package is standard in the JVM. The monitor beans will watch the objects you select for changes and will emit change notifications only when actual changes are observed. Use setGranularityPeriod to tell the monitor beans how often to look at the target.
Once the monitor beans are in place, just register for the MonitorNotifications that will be created upon change.
not a solution per se but you can simplify your polling-event translator JMXAgent implementation using spring integration. It has something called JMX Attribute Polling Channel which seems to fulfill your need. example here

How can I share memory between two Java web services?

I got two Java web services, hosted in Tomcat on the same server.
Is there any way to share memory (objects) between them?
I can turn the sharing into some kind of web methods calls, however
this is complicated, a lot of changes are required.
this is not really sharing, objects are duplicated, although it should work for my case.
this will expose methods that should not be called by the clients.
Not that I know of. Sounds like it's fraught with peril. It's hard enough to synchronize objects in one app; you have no hope with two. What good could this possibly do?
If it's common methods you need, put them into a service that both can call. If it's common data, put it in a database.
Is there any way to share memory (objects) between them?
You can create a shared memory region that is shared by two JVMs. You can do this using native code, or (in theory) by mapping a file into the address-space of two apps.
But you can't put Java objects in that region. The JVM doesn't support this, either in Java code or in native code. (And even if you could, synchronization would be a big problem.)
So could you use shared memory to share data between two JVMs?
Maybe. But you'd need to treat the share memory segment as a kind of database, and implement a scheme for copying object state between the segment and each JVM's heap. And you'd need to implement a robust synchronization scheme, probably using semaphores.
In short, it would be a significant amount of work to implement, and it wouldn't "feel" like the JVMs were sharing objects. It would be easier to use an existing database or distributed caching solution.
Try using JCS:
http://commons.apache.org/proper/commons-jcs/
Hope it helps! ;)
On Inter process communications, Java says:
To facilitate communication between processes, most operating systems
support Inter Process Communication (IPC) resources, such as pipes and
sockets. IPC is used not just for communication between processes on
the same system, but processes on different systems.
I would rather go for pipes or sockets. This will make your life a lot easier and your web services more flexible, as they can run on two separate machines still with the ability to talk to each other as if they were setting side by side.
This is being said, back to practice. Say for example you have a set of objects {a,b,c} you want to share between your services. Create a data store class that holds {a,b,c} objects and whenever there is an update, do it in the data store dataStore.setA(A new_a). Behind the scene, and for every update, the local data store will notify the remote data store sitting in the other application and transmit all the updates that have just been made. The following DTO can be used to transmit all changes from one data store to another:
public class ObjectUpdateEvent<Source> implements Serializable {
private String fieldName;
private Object previousValue;
private Object newValue;
private Source source;
// Constructor...
}
Updating an the object "a" can be done the following way
public class DataStore{
// .....
public setA(A new_a){
ObjectUpdateEvent<DataStore> updateDto = new ObjectUpdateEvent<DataStore>();
updateDto.setPreviousValue(a);
updateDto.setNewValue(new_a);
sendUpdateDto();
a = new_a;
}
}
EDIT: This is exactly what #duffymo mentioned above.
How about using a shared library.
You can refactor your logic, move them to a separate library, and build as a separate jar.
The jar should be place in tomcat_home/lib directory.
And in your web apps the library dependency should be set as provided ( in maven )
You store create and store the objects you need to be shared in the shared memory, and access them from any web

Creating globally available map

I am working on an hospital application where i need to show blood group in every second page in drop down and getting values from them to the db tables
since blood group are not frequent changing entity so we are planning to create a map with key value pair and make available this map throughout application in order to avid creation of same map multiple time
my question is what can be the best way to achieve this.some of the quick options coming to my mind are
Create a map at application start up and place it in application context
Create a utility class which read a property file and fill map with these values or simply create map with exisitng blood type.
but i am not sure how effective these options are as site will have to handle a good amount to user hits in near future.
Thanks in advance
Create a utility class that loads these values on system startup or load values when the class loads. Creating a class this way would give few advantages:
You can test this class and its functionality by writing test cases for this class. (Check if things are loading properly etc)
This makes you less dependent on the context and how the context works. Makes your application less troublesome to move if you, for some reason, need to change application server.
Code becomes more readable (BloodGroupUtils.getAll() compared to Application.getContext().get("bloodGroups"); or something similar.)
On Performance, this may be a bit faster. Not necessarily though ( we would need to check several other system usage/parameters to come to that conclusion.)
Retrieving the values from a static class or the application context will have essentially the same performance. The static class might be trivially faster as you don't have to get the map out of the application context, but I can't imagine it'd be worth worrying about.

GUI patterns in Java/GWT - general approach

I'm helping to build a GWT application for a client and rewrote most of the stuff to work better, shorter code, faster, etc. However in all the GUI application I've worked on (not so many really) there comes a flexing point where you just have to put a lot of rules and move logic from the listeners to some common mediator. Then some times this could get an ugly mess so you whatever small think you need to do in the listener.
Let's take an example:
form with 10-20 fields
two exclusive radio control about half of the state of the other fields (enabling, validation, input limits)
three exclusive radio controls control again almost the same fields, but in a different way (affecting calculations, enabling); they are also controlled by the above
4 or so number fields are validated on the fly depending on the previous selections and some real-time data object; they can have upper/lower limits, be enabled/disabled
one drop-down box controls the next 6 or so controls - displaying/hiding them, modifying validators
some checkboxes (shown by the above combo) activate some input fields and also determine their validation algorithm
While everything is up an running, without known bugs, there are a few coding gotchas that really bother me:
code is spread among listeners and some mediator methods.
loading the form with some preset values presents its own challenges: like data objects that might be available or not, data objects that might alter their state and subsequent field behaviour
some fields are having a default value set and this should not be overwritten by automatic filling, but if the data objects are not there (yet) then they will need to be filled eventually when the later become available
form cannot be submitted if any of the fields are not validated
My approach:
identify which fields share a common afair and move code into one place
each radio group shares a single listener implementation between its radios
default form filling is deferred until the live data is available (as much as possible) and as a result it gets called multiple times
each action has a call to a common validator method
the validator runs through all the fields in the form, calls their validators (which highlight all errors) and returns a single boolean
each relevant keypress or mouse action, data change it gets deferred to be called after 250ms from the last call; this means first call just places the validator as a delayed action, subsequent calls reset the timer
Ok, it doesn't make any sense to dwelve into more details but I'm more upset about the fact that there is no clear separation between visual actions (enabling), data actions (setting form field values), field listeners, retrieving form values and live data listeners.
What would be a good approach/pattern (next time maybe) to make sure that MVC get separated and lends itself better to maintenance? I know this is not a typical question but I've read every documentation I could get my hands on and still did not find some helpful answer.
I'd move closer towards MVP than MVC. It's clearly the way Google intends to go, so adopting it will probably mean that you're able to go with the flow rather than fight the current.
How does this affect you? Well, I believe you should accept that a tidier implementation may involve more code: not the 'shorter code' you were hoping for. But, if it's logically structured, efficient code the Google compiler should be able to trim lots out in the compiler optimisation phase.
So, move as much of the logic as you can into the model layer. Test this thoroughly, and verify that the correct level of page reset/tidying happens (all of this can be done with plain JUnit, without any UI). Next, use your Presenter (Activity) to tie the View to the Model: handling the interactions, populating the fields, etc.
you can divide a Huge class in different classes bu dividing the GUI in different JPanels. All the panels are implemented in different classes extending JPanel. Guess that would help you.

How to apply static class in php

I am java and php programmer.
In java i can use static class/method so that anyone can use the same one time created class during run-time.
But for php how to do it since it is script based and only run while we refreshing the page?
My main objective is, I want to use syncronized class/method so that it wont clash while executing the PHP...
Need your help to give input.
Thanks
Update:
I am doing portal like multi level marketing(mlm)
Once register a member, we should pay bonus to the uplines
I don't want immidiately calculate the bonus because it is risky and could take some time to finish, so is is better just to register the member and show successfull.
My idea is, after registration, just invoke another class to run bonus with syncronized method so that the bonus calculation will not disturb by another registration.
Given that a php scripts runs from new every sinlge time a "static" class would not be very different from an ordinary class.
If you want to store some sort of state or preserve some data between runs of a php program then there are a number of options.
SESSION variables can be used to store data between requests from a single users as long as he keeps the session open.
COOKIES can be used to store data which persists between sessions as long as the user is using the same browser, on hte same machine and hasnt emptied the cookie jar.
memchached and similar packages can be used to store data and make it available to any php program on the server.
Databases are the most scalable solution as they will persist data between sessions, and between servers. There is some overhead involved is establishing connections and retrieving the data compared with the other solutions.
PHP is shared-nothing. Everything just lives for the Request. If you want to share information between Requests, you have to implement some additional technology layer that can do so. Or look into process control, shared memory segments and semaphores. The latter three are uncommon usage in PHP though. And all of the above will still be asynchronous.
To my knowledge, there is no way to update class Foo in one Request and have it change state immediately in a concurrent Request with PHP.

Categories