Friday, March 25, 2011

GWT CellTable Reading Json Data.

Hi All,

I am new to the GWT looking for some help in the following code.

Basically want to iterate over some json data and display it in a cell
Table.

Here is how it looks like.

(1) JsonIntegrate.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='jsonintegrate'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>

<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.standard.Standard'/>
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->

<!-- Other module inherits -->
<inherits name="com.google.gwt.http.HTTP" />

<!-- Specify the app entry point class. -->
<entry-point class='com.symantec.mmavis.gwt.client.JsonIntegrate'/>

<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>

</module>

(2) Client.

JsonIntegrate.java

package com.symantec.mmavis.gwt.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.TextColumn;
import
com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.Range;

/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class JsonIntegrate implements EntryPoint {

// The list of data to display.

//ResultData rs1 = new ResultData();

//private static List<Contact> CONTACTS = Arrays.asList(new
Contact("John", "123 Fourth Road"), new Contact("Mary", "222 Lancer
Lane"), new Contact("Zander", "94 Road Street"));
private static final String JSON_URL = GWT.getModuleBaseURL() +
"search?q=5";

private ListDataProvider<SearchResult> dataProvider = new
ListDataProvider<SearchResult>();

private final ArrayList<SearchResult> contactList = new
ArrayList<SearchResult>();

public void onModuleLoad() {

// Create a CellTable.
final CellTable<SearchResult> table = new CellTable<SearchResult>();

// Create ordernumber column.
final TextColumn<SearchResult> orderColumn = new
TextColumn<SearchResult>() {
@Override
public String getValue(final SearchResult contact) {
return contact.getOrdernumber();
}
};

// Make the name column sortable.
orderColumn.setSortable(true);

// Create status column.
final TextColumn<SearchResult> statusColumn = new
TextColumn<SearchResult>() {
@Override
public String getValue(final SearchResult contact) {
return contact.getStatus();
}
};
statusColumn.setSortable(true);

// Create View Detail Column
TextColumn<SearchResult> viewDetailColumn = new
TextColumn<SearchResult>() {

@Override
public String getValue(SearchResult contact) {
return contact.getDetail();
}
};
viewDetailColumn.setSortable(true);

// Add the columns.
table.addColumn(orderColumn, "Order Number");
table.addColumn(statusColumn, "Status");
table.addColumn(viewDetailColumn, "View Detail");

this.getJsonData();

// Set the total row count. You might send an RPC request to
determine the
// total row count.
table.setRowCount(contactList.size(), true);

// Set the range to display. In this case, our visible range is
smaller than
// the data set.
table.setVisibleRange(0, contactList.size());

// Create a data provider.
final AsyncDataProvider<SearchResult> dataProvider = new
AsyncDataProvider<SearchResult>() {
@Override
protected void onRangeChanged(final HasData<SearchResult> display)
{
final Range range = display.getVisibleRange();

// Get the ColumnSortInfo from the table.
final ColumnSortList sortList = table.getColumnSortList();

// This timer is here to illustrate the asynchronous nature of
this data
// provider. In practice, you would use an asynchronous RPC call
to
// request data in the specified range.
new Timer() {
@Override
public void run() {
final int start = range.getStart();
final int end = start + range.getLength();
// This sorting code is here so the example works. In practice,
you
// would sort on the server.
Collections.sort(contactList, new Comparator<SearchResult>() {

@Override
public int compare(final SearchResult o1, final SearchResult
o2) {
if (o1 == o2) {
return 0;
}

// Compare the name columns.
int diff = -1;
if (o1 != null) {
diff = (o2 != null) ?
o1.getOrdernumber().compareTo(o2.getOrdernumber()) : 1;
}
return sortList.get(0).isAscending() ? diff : -diff;
}

});
final List<SearchResult> dataInRange =
contactList.subList(start, end);

// Push the data back into the list.
table.setRowData(start, dataInRange);
}
}.schedule(2000);
}
};

// Connect the list to the data provider.
dataProvider.addDataDisplay(table);

// Add a ColumnSortEvent.AsyncHandler to connect sorting to the
// AsyncDataPRrovider.
final AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);

// We know that the data is sorted alphabetically by default.
table.getColumnSortList().push(orderColumn);

// Add it to the root panel.
RootPanel.get().add(table);
}

private void getJsonData() {

String url = JSON_URL;

url = URL.encode(url);

// Send request to server and catch any errors.
final RequestBuilder builder = new
RequestBuilder(RequestBuilder.GET, url);

try {
final Request request = builder.sendRequest(null, new
RequestCallback() {
public void onError(final Request request, final Throwable
exception) {
System.out.println("error");
}

public void onResponseReceived(final Request request, final
Response response) {
if (200 == response.getStatusCode()) {
loadData(asArrayOfResultData(response.getText()));
} else {
System.out.println("error");
}
}
});
} catch (final RequestException e) {
System.out.println("error");
}

}

/**
* Update the Price and Change fields all the rows in the stock
table.
*
* @param prices Stock data for all rows.
*/
private void loadData(final JsArray<ResultData> resultData) {

for (int i = 0; i < resultData.length(); i++) {

ResultData res = resultData.get(i);

SearchResult c = new SearchResult(res.getOrdernumber(),
res.getStatus(), res.getDetail());
contactList.add(c);
}

// Display timestamp showing last refresh.
//this.lastUpdatedLabel.setText("Last update : " +
DateTimeFormat.getMediumDateTimeFormat().format(new Date()));

// Clear any errors.
//this.errorMsgLabel.setVisible(false);

}

/**
* Convert the string of JSON into JavaScript object.
*/
private final native JsArray<ResultData> asArrayOfResultData(String
json) /*-{
return eval(json);
}-*/;

}

(3) Server

package com.symantec.mmavis.gwt.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonResultData extends HttpServlet {

private static final long serialVersionUID = 1855404725167762932L;

@Override
protected void doGet(final HttpServletRequest req, final
HttpServletResponse resp) throws ServletException, IOException {

// final Random rnd = new Random();

final Result result_1 = new Result("1001", "Valid", "View Detail
1");
final Result result_2 = new Result("1002", "Pending", "View Detail
2");
final Result result_3 = new Result("1003", "Revoked", "View Detail
3");
final Result result_4 = new Result("1004", "Revoked", "View Detail
4");
final Result result_5 = new Result("1005", "Valid", "View Detail
5");
final Result result_6 = new Result("1006", "Pending", "View Detail
6");
final Result result_7 = new Result("1007", "Valid", "View Detail
7");
final Result result_8 = new Result("1008", "Valid", "View Detail
8");
final Result result_9 = new Result("1009", "Revoked", "View Detail
9");
final Result result_10 = new Result("1010", "Valid", "View Detail
10");

final Result[] arrayResult = { result_1, result_2, result_3,
result_4, result_5, result_6, result_7, result_8, result_9,
result_10 };

final PrintWriter out = resp.getWriter();
out.println('[');
final int count = Integer.valueOf(req.getParameter("q"));

for (int i = 0; i < count; i++) {

out.println(" {");
out.print(" \"ordernumber\": \"");
out.print(arrayResult[i].getOrdernumber());
out.println("\",");
out.print(" \"status\": \"");
out.print(arrayResult[i].getStatus());
out.println("\",");
out.print(" \"detail\": \"");
out.print(arrayResult[i].getDetail());
out.println("\"");
out.println("}, ");

}
out.println(']');
out.flush();
}
}

So basically server side we have some json being generated:

http://127.0.0.1:8888/jsonintegrate/search?q=8

When load this page: http://127.0.0.1:8888/JsonIntegrate.html?gwt.codesvr=127.0.0.1:9997
it only loads up the header, the data is not visible..can somebody
please help ??

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To post to this group, send email to google-web-toolkit@googlegroups.com.
To unsubscribe from this group, send email to google-web-toolkit+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

No comments:

Post a Comment