GWT - Hibernate: How to display results from MySQL into GWT client - mysql

I am very starter to GWT and Hibernate. I made a simple GWT RPC application that adds a user to MySQL using Hibernate. I declared a single method in service interface i.e. addUser that adds a user(i.e. firstName & LastName) to MySQL calling Hibernate method. Its is working fine. Now added a 2nd method to retrieve users from DB & display.
Here are service interfaces
service interfaces
package rpctest.client;
import java.util.ArrayList;
import hibDomain.User;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("testService")
public interface RpctestService extends RemoteService {
public String addUser(String firstName,String lastName) throws
llegalArgumentException;
public ArrayList<User> getUser();
}
-------------------------------------
package rpctest.client;
import java.util.ArrayList;
import hibDomain.User;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RpctestServiceAsync {
void addUser(String firstName, String lastName,
AsyncCallback<String> callback);
void getUser(AsyncCallback<ArrayList<User>> asyncCallback);
}
Here is entry point class
package rpctest.client;
import java.util.ArrayList;
import hibDomain.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync calNumbers = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "User ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
calNumbers.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 1, result);
}
});
calNumbers.getUser(new AsyncCallback< ArrayList<User>>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess( ArrayList<User> result) {
// TODO Auto-generated method stub
}
});
}
}
Here is service implementation
package rpctest.server;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
//import com.hib.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
import rpctest.client.RpctestService;
public class RpctestServiceImpl extends RemoteServiceServlet implements RpctestService {
public String addUser(String name1, String name2)
throws IllegalArgumentException {
Transaction trns = null;
Session session =
HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
User user = new User();
user.setFirstName(name1);
user.setLastName(name2);
session.save(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
return name1+name2; // to test flextable entris only
}
#Override
public ArrayList<User> getUser()
{
List<User> getUser = null;
Transaction trns = null;
Session session =
HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
getUser = session.createQuery("from User").list();
/* for (Iterator<User> iter = users.iterator(); iter.hasNext();)
{
User user = iter.next();
User[] arrOfObjects = new User[]{user};
} */
trns.commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
return (ArrayList<User>) getUser;
}
}
The getUser method in service implementation class is showing an error, highlighting method return type i.e. ArrayList But eclipse is giving no suggestion.

Ok. Now, on the client page, create an async call to the service you have created. This link would help you:
http://examples.roughian.com/index.htm#Tutorials~RPC_To_Java
EDIT:
My apologies.
I assume you have serialized the "user" class. If not, you have to serialize it:
class user implements java.io.serializable;
If you want the resultset to convert to the array, do a check if list is null and if result list is not null, convert it to array and assign to user[] like:
try{
....
.... .list();
if(!users.isEmpty(){
getUser = users.toArray();
}
}
and then you can return getUser to the client side.

Related

Reading Events from CSV file into ESPER with POJO

Reading Events from CSV file into ESPER with POJO, the code below seams to scan through the file (larger files take longer), however no output is generated by events reaching listener.
the CSV file content is:
Geotimestamp,closeoutBid,closeoutAsk,tradable
"20170301 000000643",1.236550,1.236680,0
"20170301 000001893",1.236540,1.236680,0
"20170301 000002893",1.236550,1.236680,0
"20170301 000004410",1.236560,1.236700,0
"20170301 000006160",1.236540,1.236680,0
"20170301 000006393",1.236540,1.236670,0
The code is based on article here
import com.espertech.esper.client.*;
import com.espertech.esperio.csv.AdapterInputSource;
import com.espertech.esperio.csv.CSVInputAdapter;
import com.espertech.esperio.csv.CSVInputAdapterSpec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import java.io.File;
import java.time.Instant;
public class hAppY implements Runnable {
private static final Log log = LogFactory.getLog(AppMod.class);
public static void main(String[] args) {
SimpleLayout layout = new SimpleLayout();
ConsoleAppender appender = new ConsoleAppender(new SimpleLayout());
Logger.getRootLogger().addAppender(appender);
Logger.getRootLogger().setLevel((Level) Level.WARN);
new AppMod().run();
}
public hAppY() {
}
public void run() {
//The Configuration is meant only as an initialization-time object.
Configuration configuration = new Configuration();
// We register Ticks as objects the engine will have to handle
configuration.addEventType("HistData", HistDataEventClass.class);//.getName()
EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(configuration);
File file = new File("./data/DAT_ASCII_GBPUSD_T_201703.csv");
AdapterInputSource ais = new AdapterInputSource(file);
CSVInputAdapterSpec spec = new CSVInputAdapterSpec(ais, "HistDataEventClass");
spec.setUsingExternalTimer(true); //will not pause for time between ticks when true
EPAdministrator epAdmin = epService.getEPAdministrator();
String vel1 = "select count(*) from HistData()";//()from HistData().win:time(3 sec)";
EPStatement cepStatement1 = epAdmin.createEPL(vel1);
//attach 1st statement listener to cep statement obj
cepStatement1.addListener(new CEPListener());
(new CSVInputAdapter(epService, ais,"HistDataEventClass")).start();
}
public class HistDataEventClass {
private java.lang.String /*Instant*/ Geotimestamp;
private java.lang.String receivedTS;
private double closeoutBid;
private double closeoutAsk;
private byte tradable; //ignore
//c'tor
public HistDataEventClass(java.lang.String timestamp, java.lang.Double closeoutBid, java.lang.Double closeoutAsk, byte tradable) {
try {
this.receivedTS = Instant.now().toString(); //received time stamp at time of instantiation of event object (this)
this.Geotimestamp = timestamp;
// NEED TO PROPERLY PARSE THE TS
this.closeoutBid = Double.parseDouble(java.lang.String.valueOf(closeoutBid));
this.closeoutAsk = Double.parseDouble(java.lang.String.valueOf(closeoutAsk));
this.tradable = tradable;
}
catch (Exception e) {
e.printStackTrace();
}
}
// getters/setters
//timestamp
public java.lang.String getTimestamp() {
return this.Geotimestamp;
}
public void setGeoTimestamp(String ts) {this.Geotimestamp = ts;}
// receivedTS
public java.lang.String getReceivedTS() {return this.receivedTS;}
public void setReceivedTS(String rts) {this.receivedTS = rts;}
//CloseoutBid()
public double getCloseoutBid() {return this.closeoutBid;}
public void setCloseoutBid(double bid){this.closeoutBid=bid;}
//CloseoutAsk()
public double getCloseoutAsk() {return this.closeoutAsk;}
public void setCloseoutAsk(double ask){this.closeoutAsk=ask;}
//tradable()
public byte getTradable() {return this.tradable;}
public void setTradable(byte t){this.tradable=t;}
}
public class CEPListener implements UpdateListener { //removed static to satisfy compiler
public void update(EventBean[] newData, EventBean[] oldData) {
System.out.println("my print statement: " + newData[0].getUnderlying());
}
}//CEPListener
}

Google map API v2 J2ME

Hi everybody im a beginner in J2ME developpement and i created a little j2me application that supposed to allow me to locate places based on an address that i have to enter in a enter in a TextField so i made this piece of code based on a tutorial a from jappit.com but when i launch the application the screen is blocked on loading and i get this error in the console:
"Uncaught exception java/lang/NumberFormatException: Sorry... body { font-family: verdana."
and this is the code :
import com.jappit.midmaps.googlemaps.GoogleMaps;
import com.jappit.midmaps.googlemaps.GoogleMapsCoordinates;
import com.jappit.midmaps.googlemaps.GoogleMapsGeocoder;
import com.jappit.midmaps.googlemaps.GoogleMapsGeocoderHandler;
import com.jappit.midmaps.googlemaps.GoogleMapsMarker;
import com.jappit.midmaps.googlemaps.GoogleStaticMap;
import com.jappit.midmaps.googlemaps.GoogleStaticMapHandler;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MapMidlet extends MIDlet implements CommandListener{
TextField searchbox = new TextField("Address","Enter your address here",100,TextField.ANY);
Form menu = new Form("Search Menu");
List type = new List("Type",List.EXCLUSIVE);
Command search = new Command("Search",Command.OK,0);
Command Exit = new Command("exit",Command.EXIT,1);
Display display = Display.getDisplay(this);
Ticker ti = new Ticker("Find me If you can !");
Alert alert = new Alert("Please enter an address","address is missing", null, AlertType.ERROR);
String adress;
public MapMidlet() {
}
protected void destroyApp(boolean unconditional)
{
}
protected void pauseApp() {
}
protected void startApp() {
adress=searchbox.getString();
menu.setCommandListener(this);
menu.append(searchbox);
menu.addCommand(search);
menu.addCommand(Exit);
display.setCurrent(menu);
//display.setCurrent(new MapCanvas(this));
}
public void commandAction(Command c, Displayable d) {
if(c==search)
{
display.setCurrent(new MapCanvas(this));}
else
{notifyDestroyed();}
}
public class MapCanvas extends Canvas implements GoogleStaticMapHandler, GoogleMapsGeocoderHandler
{
GoogleMaps gMaps = null;
GoogleStaticMap map = null;
String API_KEY = "AIzaSyBe1yXRcCXWQB_6ReSGbf0lH8XVwTvNpSQ";
MapMidlet mid;
public MapCanvas(MapMidlet mid)
{
this.mid=mid;
gMaps = new GoogleMaps(API_KEY);
map = gMaps.createMap(getWidth(), getHeight(), GoogleStaticMap.FORMAT_PNG);
//map.setHandler(this);
//map.setCenter(new GoogleMapsCoordinates(36.8189700,10.1657900));
//map.setZoom(15);
//map.update();
GoogleMapsGeocoder geocoder = gMaps.createGeocoder();
geocoder.setHandler(this);
geocoder.geocodeAddress(adress);
}
protected void paint(Graphics g)
{
map.draw(g, 0, 0, Graphics.TOP | Graphics.LEFT);
}
public void GoogleMapsGeocodeError(String address, int errorCode, String errorDescription)
{
System.out.println("Geocode error: " + errorCode + ", " + errorDescription);
}
public void GoogleMapsGeocodeSuccess(String address, GoogleMapsCoordinates coordinates, int accuracy)
{
map.setCenter(coordinates);
map.addMarker(new GoogleMapsMarker(coordinates));
map.setZoom(accuracy);
map.update();
}
public void GoogleStaticMapUpdateError(GoogleStaticMap map, int errorCode, String errorMessage)
{
System.out.println("map error: " + errorCode + ", " + errorMessage);
}
public void GoogleStaticMapUpdated(GoogleStaticMap map)
{
System.out.println("map loaded");
repaint();
}
}
}
Thanks.

Openejb rest integration tests with exception mappers

I'm writing some integration tests towards my jax-rs service where I have a set of exception mappers. So, when performing a given request I expect a certain response code based on the exception mapper. The problem is that I cannot get the exception mappers to be invoked when running in this environment.
My service which should throw a logicalexception in my test:
#Stateless
#Path("/baseCustomer")
public class BaseCustomerService {
#EJB //this one gets mocked in the unittest
private BaseCustomerManagerBean customerManager;
#POST
#Path("crud")
#Consumes({MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public Hkunde createCustomer(Hkunde newCustomer) throws LogicalException {
//throws exception according to mocking
return customerManager.createCustomer(newCustomer);
}
And the exception mapper:
#Provider
public class LogicalExceptionMapper implements ExceptionMapper<LogicalException> {
#Override
public Response toResponse(LogicalException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
I set up my tests like this:
#Mock
private BaseCustomerManagerBean baseCustomerManager;
private HttpClient httpClient;
private BaseCustomerServiceClient client;
#Configuration
public Properties config() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, LogicalExceptionMapper.class.getName());
properties.setProperty("openejb.jaxrs.providers.auto", "true");
properties.setProperty("openejb.servicemanager.enabled", "true");
return properties;
}
#MockInjector
public Class<?> mockitoInjector() {
return MockitoInjector.class;
}
#Module
public EjbModule createModule() throws Exception {
final StatelessBean bean = (StatelessBean) new StatelessBean(BaseCustomerService.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
#Module
public Class[] exceptionMappers() {
return new Class[]{LogicalExceptionMapper.class};
}
#Before
public void setup() {
ServiceHost serviceHost = new ServiceHost("http://localhost:4204/BaseCustomerServiceTest");
httpClient = new HttpClient(serviceHost);
client = new BaseCustomerServiceClient(httpClient);
}
#Test
public void createCustomer_givenLogicalException_expectsLogicalException() throws LogicalException {
Hkunde expected = new Hkunde(true);
when(baseCustomerManager.createCustomer(expected)).thenThrow(new LogicalException("mock"));
try {
client.createCustomer(expected);
fail("Expected LogicalException");
} catch (LogicalException ex) {
}
verify(baseCustomerManager).createCustomer(expected);
}
So when I execute the test, my client will read the response code from the response and throw an exception based on this code.
The problem is that the exception mapper is never invoked, and I always receive a 500 internal server error, instead of the "forbidden" response. I'm guessing I need to add some more info when setting up the ejbjar or something like that.
Thanks!
This example http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/rest-applicationcomposer/src/test/java/org/superbiz/composed/rest/GreetingServiceTest.java (via http://rmannibucau.wordpress.com/2012/09/13/use-mockito-with-openejb/ ;-)) shows exactly what you want.
Add the following after openejbJar.addEjbDeployment(... and it should work.
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", LogicalExceptionMapper.class.getName());
Here is a minimal working example (using openejb-cxf-rs 4.5.0 and openejb-core 4.5.0):
import java.util.Properties;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.OpenEjbContainer;
import org.apache.openejb.config.EjbModule;
import org.apache.openejb.jee.EjbJar;
import org.apache.openejb.jee.StatelessBean;
import org.apache.openejb.jee.oejb3.EjbDeployment;
import org.apache.openejb.jee.oejb3.OpenejbJar;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.junit.Configuration;
import org.apache.openejb.junit.Module;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(ApplicationComposer.class)
public class RestWithExceptionMapper {
#Configuration
public Properties configuration() {
return new Properties() {
{
setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
}
};
}
#Module
public EjbModule app() {
final StatelessBean bean = (StatelessBean) new StatelessBean(MyResource.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", MyExceptionMapper.class.getName());
final EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
public static class FooException extends RuntimeException {
}
public static class MyExceptionMapper implements ExceptionMapper<FooException> {
#Override
public Response toResponse(final FooException t) {
return Response.ok("Objection!").build();
}
}
#Path(value = "/test")
public static class MyResource {
#GET
#Path(value = "/throw")
public String throwException() {
throw new FooException();
}
}
#Test
public void checkServiceWasDeployed() {
assertEquals("Objection!", WebClient.create("http://localhost:4204/RestWithExceptionMapper").path("/test/throw").get(String.class));
}
}

Null pointer exception in the JSON program

I'm getting a Null pointer exception in two lines with three stars as shown in the code. Please see to it. I'm a beginnner in android. Thanks in advance. I tried instantiating tiles JSONarray but even that won't work.
package pack.assignment; ***
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import android.widget.ImageView;
import java.net.MalformedURLException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.ProgressDialog;
public class Landing extends Activity {
// url to make request
private static String url = "http://playup-jo.s3.amazonaws.com/dev/config.json";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// tiles JSONArray
JSONArray tiles=null;
ImageView img;
// JSON Node names
private static final String TAG_TILES = "tiles";
private static final String TAG_IMAGE = "image";
private static final String TAG_URL = "url";
private static final String TAG_MDPI = "mdpi";
private static final String TAG_NAME = "name";
// Intent go = new Intent(this, Google.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Loading JSON in Background Thread
new LoadJSON().execute();
img = (ImageView)findViewById(R.id.image);
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
}
/**
* Background Async Task to Load all INBOX messages by making HTTP Request
* */
class LoadJSON extends AsyncTask<String, String, Bitmap> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Landing.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting JSON
* */
protected Bitmap doInBackground(String... args) {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Bitmap bitmap=null;
// Check your log cat for JSON reponse
// Log.d("JSONNN: ", json.toString());
try {
// Getting Array of Tiles
tiles= new JSONArray();
tiles = json.getJSONArray(TAG_TILES); ***
// looping through All Tiles
for(int i = 0; i < 1; i++){
JSONObject c = tiles.getJSONObject(i);
// Storing json item in variable
String name = c.getString(TAG_NAME);
// mdpi is again JSONObject
JSONObject mdpi= c.getJSONObject(TAG_MDPI);
String image=mdpi.getString(TAG_IMAGE);
String url=mdpi.getString(TAG_URL);
// Using the variable to get the bitmap
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(image).getContent());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(final Bitmap result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data
* */
img.setImageBitmap(result); // Rule:2 Always access UI toolkit for UI thread not worker thread
MyEventHandler myEvHandler = new MyEventHandler();
// making the downloaded image clickable
img.setOnClickListener(myEvHandler);
}
});
}
}
class MyEventHandler implements OnClickListener
{
public void onClick(View v)
{
if (v instanceof ImageView)
{
// startActivity(go);
}
}
}
}
The error was in JSONParser class, I was using httpPost and getting a status code of 405 and not 200. I used httpGet and it got resolved.

Swing GUI Client Listeners not responding to update of Remote RMI Property

I am having some trouble with getting a JTree to redraw when an explicit call is made to its model (a call which I make once I have added some new nodes to it).
The code, which initially worked fine, fails now that the application is exported to RMI.
I store the DefaultTreeModel object in the Controller class, which is a Remote Object.
I add the DefaultTreeModel object to the JTree in my Client, using tree.addModel(controller.getModel());
I use an ActionListener subscribed to a button on the Client GUI to call a method in the Controller which performs the "Add new node" action.
I use a TreeModelListener to print a message to screen to prove that the Model Listener has fired.
Do Client side Swing listeners not work over RMI?
I have managed to reproduce the problem. I include the code for completeness but anticipate that someone will be able to reel off the answer based on experience.
Server Driver Class:
package server;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import client.controller.TestTreeControllerService;
import server.controller.TestTreeControllerImpl;
public class TestTreeServerStart {
/**
* #param args
*/
public static void main(String[] args) {
new TestTreeServerStart();
}
public TestTreeServerStart() {
try {
LocateRegistry.createRegistry(1099);
TestTreeControllerService c = new TestTreeControllerImpl();
Registry registry = LocateRegistry.getRegistry();
registry.rebind("TestTreeControllerService", c);
System.out.println("Started the RMI Server");
}
catch (RemoteException e) {
System.out.println(e.getMessage());
}
}
}
Server Controller Implementation Class:
package server.controller;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.controller.TestTreeControllerService;
#SuppressWarnings("serial")
public class TestTreeControllerImpl extends UnicastRemoteObject implements TestTreeControllerService {
/**
*
*/
//private static final long serialVersionUID = -8137864611400855504L;
private DefaultTreeModel m ;
public DefaultTreeModel getModel() {
return m;
}
public TestTreeControllerImpl() throws RemoteException {
super();
m = new DefaultTreeModel(new DefaultMutableTreeNode("Root"));
}
public void addNodeAction() throws RemoteException {
DefaultTreeModel m = (DefaultTreeModel) getModel();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
DefaultMutableTreeNode root = (DefaultMutableTreeNode) m.getRoot();
root.add(newNode);
//m.insertNodeInto(newNode, (DefaultMutableTreeNode) m.getRoot(), m.getChildCount(m.getRoot()));
m.nodeStructureChanged(root);
}
}
Client Driver Class:
package client;
import java.rmi.Naming;
import java.rmi.RemoteException;
import client.controller.TestTreeControllerService;
import client.view.TreeTestClient;
public class TreeTestClientStart {
/**
* #param args
*/
public static void main(String[] args) {
try {
TestTreeControllerService c = (TestTreeControllerService) Naming.lookup("rmi://localhost:1099/TestTreeControllerService");
new TreeTestClient(c);
}
catch(RemoteException e) {
System.out.println("Remote service not found: " + e.getLocalizedMessage());
}
catch (Exception e) {
System.out.println("Splat");
}
}
}
Client Controller Interface:
package client.controller;
import javax.swing.tree.DefaultTreeModel;
public interface TestTreeControllerService extends java.rmi.Remote {
public DefaultTreeModel getModel() throws java.rmi.RemoteException;
public void addNodeAction() throws java.rmi.RemoteException;
}
Client UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
*Client "Add Node" Action Listener (invokes Add Action in Controller) *
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import client.view.TreeTestClient;
public class AddNodeAction implements ActionListener {
private TreeTestClient treeTest;
public AddNodeAction(TreeTestClient treeTestIn) {
treeTest=treeTestIn;
}
#Override
public void actionPerformed(ActionEvent arg0) {
try {
treeTest.getController().addNodeAction();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client "Refresh Action" Tree Listener (Prints to Screen to prove that Listener fired)
package client.view.action;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import client.view.TreeTestClient;
public class RefreshTreeAction implements PropertyChangeListener, TreeModelListener {
private TreeTestClient treeTest;
public RefreshTreeAction(TreeTestClient treeTestIn) {
treeTest = treeTestIn;
}
private void refreshTree() {
System.out.println("Refresh tree fired");
}
#Override
public void treeNodesChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesInserted(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeNodesRemoved(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void treeStructureChanged(TreeModelEvent arg0) {
refreshTree();
}
#Override
public void propertyChange(PropertyChangeEvent arg0) {
refreshTree();
}
}
The TreeModel exported by the server is serialized to the client as the client's own copy. The server doesn't know anything about what happens to the client's copy, and the client doesn't know anything about what happens to the server's copy. They are not the same object.
By adding the following code to an ActionListener subscribed to a new button on the GUI, I have been able to examine the contents of the Model at the click of a button:
//Loop contents of model attached to Client Tree
for (int i=0; i<t.getModel().getChildCount(t.getModel().getRoot()); i++) {
System.out.println("From Tree: Row #" + i + ": " + t.getModel().getChild(t.getModel().getRoot(), i));
}
//Loop contents of model object stored in Controller
try {
for (int i=0; i<c.getModel().getChildCount(c.getModel().getRoot()); i++) {
System.out.println("From Controller: Row #" + i + ": " + c.getModel().getChild(c.getModel().getRoot(), i));
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I found that the reference to the Client's Model was a different version to the state being maintained in the Controller's model object. There was no output in the Client loop, but the Controller's loop gave the correct state.
I have subsequently added a Swing Timer to the GUI to refresh the tree's model to match that of the Constructor. An updated GUI Class and GUI Refresh Action follow, which work:
Updated UI:
package client.view;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.Timer;
import client.controller.TestTreeControllerService;
import client.view.action.AddNodeAction;
import client.view.action.GUIRefreshAction;
import client.view.action.RefreshTreeAction;
public class TreeTestClient {
private JTree t;
private TestTreeControllerService c;
public JTree getTree() {
return t;
}
public TestTreeControllerService getController() {
return c;
}
public void setTree(JTree tIn) {
t = tIn;
}
public TreeTestClient(TestTreeControllerService cIn) {
//Add controller
try {
c = cIn;
//Draw Frame & Panel - set dimensions
JFrame f = new JFrame();
f.setSize(new Dimension(800,600));
JPanel p = new JPanel();
p.setSize(new Dimension(800,600));
//Create a tree and add the Model from the Controller to it
t = new JTree();
t.setModel(c.getModel());
//Try a listener that doesn't use the Remote object
t.addTreeSelectionListener(new RefreshTreeAction(this));
//Try a property change listener on the TreeModel
t.addPropertyChangeListener("treeModel", new RefreshTreeAction(this));
//Try a Tree Model Listener
t.getModel().addTreeModelListener(new RefreshTreeAction(this));
//Add listener to a button which adds nodes to the tree when clicked
JButton addNode = new JButton("Add node");
addNode.addActionListener(new AddNodeAction(this));
JScrollPane s = new JScrollPane(t);
//Add a GUI redraw timer
Timer timer = new Timer(1000, new GUIRefreshAction(this));
timer.setInitialDelay(1);
timer.start();
p.add(s);
p.add(addNode);
p.setVisible(true);
f.add(p);
f.setVisible(true);
}
catch(Exception e) {
System.out.println("Splat");
}
}
}
GUI Refresh Listener Class
package client.view.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import client.view.TreeTestClient;
public class GUIRefreshAction implements ActionListener {
private TreeTestClient client;
public GUIRefreshAction(TreeTestClient clientIn) {
client = clientIn;
}
#Override
public void actionPerformed(ActionEvent e) {
//Update the Tree's Model to match latest on Server
try {
client.getTree().setModel(client.getController().getModel());
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
}
I hope this helps someone who has the same requirements for a RMI Client Swing GUI to update in reaction to changes on the Server.