Skip to content

Commit

Permalink
Implemented Add/save/delete in java server side example
Browse files Browse the repository at this point in the history
  • Loading branch information
Mirko Pasqualetti committed Jan 16, 2016
1 parent 8bf1f92 commit be9042f
Show file tree
Hide file tree
Showing 3 changed files with 182 additions and 22 deletions.
6 changes: 3 additions & 3 deletions server/java/WebContent/index.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ $(function () {
// defined form
$().w2form({
name : 'user_edit',
url : 'users.php',
style : 'border: 0px; background-color: transparent;',
name : 'user_edit',
url : 'users.list',
style : 'border: 0px; background-color: transparent;',
formHTML:
'<div class="w2ui-page page-0">'+
' <div class="w2ui-label">First Name:</div>'+
Expand Down
112 changes: 99 additions & 13 deletions server/java/src/com/w2ui/servlets/W2uiGridData.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,20 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
}
if ( cmd.equals("save-records") ) {
processSaveRecords(reqParams);
} else if ( cmd.equals("save-record") ) {
processSaveRecord(reqParams);
} else if ( cmd.equals("delete-records") ) {
processDeleteRecords(reqParams);
int[] ids = paramToIntVector(reqParams, "selected");
processDeleteRecords(ids);
} else if (cmd.equals("get-records")) {
JSONArray array = processGetRecords(reqParams);
jsobj.put("total", array.length());
jsobj.put("records", array);
} else if (cmd.equals("get-record")) {
JSONObject record = processGetRecord(reqParams);
jsobj.put("record", record);
} else {
throw new Exception("Unknown command ["+cmd+"]");
}
jsobj.put("status", "success");
} catch (Exception ex) {
Expand All @@ -78,7 +86,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
response.getWriter().write(jsonText);
}

protected JSONArray readArray(HttpServletRequest request, String arrayName) {
private JSONArray readArray(HttpServletRequest request, String arrayName) {
int cnt=0;
JSONArray ret = new JSONArray();
while(true) {
Expand Down Expand Up @@ -115,49 +123,127 @@ protected JSONArray readArray(HttpServletRequest request, String arrayName) {
}
return ret;
}

protected int[] paramToIntVector(JSONObject reqParams, String paramName) throws Exception{
Object selected = reqParams.get(paramName);
int[] ids;
if (selected instanceof JSONArray) {
JSONArray jsar = (JSONArray)selected;
ids = new int[jsar.length()];
for (int cnt = 0; cnt < jsar.length(); cnt++) {
ids[cnt] = jsar.getInt(cnt);
}
} else if (selected instanceof String) {
ids = new int[1];
ids[0] = Integer.parseInt((String)selected);
} else {
throw new Exception("Wrong type of parameter ["+paramName+"]");
}
return ids;
}

protected JSONObject requestToJson(HttpServletRequest request) {
private JSONObject requestToJson(HttpServletRequest request) {
JSONObject jsobj = new JSONObject();
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (name.startsWith("search") || name.startsWith("sort")) {
// these parameters are treater apart
if ( name.startsWith("search") || name.startsWith("sort")) {
// these are treated later
continue;
}
String localName = name;
if (localName.endsWith("[]")) {
// remove []
localName = name.substring(0, name.length()-2);
}
// find the value
String[] values = request.getParameterValues(name);
Object value = null;
if (values.length == 1) {
jsobj.put(localName, values[0]);
value = values[0];
} else {
JSONArray arr = new JSONArray();
for (int i=0; i < values.length; i++) {
arr.put(values[i]);
}
jsobj.put(localName, arr);
value = arr;
}
// check if localName is something like record[recid]
int pos1 = localName.indexOf('[');
if (pos1 > 0) {
int pos2 = localName.indexOf(']', pos1);
if (pos2 > 0) {
// found!
String objName = localName.substring(0, pos1);
String fieldName = localName.substring(pos1+1, pos2);
JSONObject jsobj2 = new JSONObject();
if ( jsobj.has(objName) ) {
jsobj2 = jsobj.getJSONObject(objName);
}
jsobj2.put(fieldName, value);
jsobj.put(objName, jsobj2);
continue;
}
}

jsobj.put(localName, value);
}

JSONArray search = readArray(request, "search");
jsobj.put("search", search);

JSONArray sort = readArray(request, "sort");
jsobj.put("sort", sort);
JSONArray arr = readArray(request, "sort");
jsobj.put("sort", arr);

arr = readArray(request, "search");
jsobj.put("search", arr);

return jsobj;
}

/**
* processGetRecords: retrieve records from database in case command is "get-records"
* Implement this function in child class
* @param reqParams parameters extracted from request with requestToJson
* @throws Exception
*/
protected abstract JSONArray processGetRecords(JSONObject reqParams) throws Exception;

/**
* processGetRecord: retrieve a single from database in case command is "get-record"
* If you need to get a single record implement this function in child class
* @param reqParams parameters extracted from request with requestToJson
* @throws Exception
*/
protected JSONObject processGetRecord(JSONObject reqParams) throws Exception {
throw new Exception ("Save not implemented");
}

/**
* processSaveRecords: save records on database in case command is "save-records"
* If you need to save records implement this function in child class
* @param reqParams parameters extracted from request with requestToJson
* @throws Exception
*/
protected void processSaveRecords(JSONObject reqParams) throws Exception {
throw new Exception ("Save not implemented");
}

protected void processDeleteRecords(JSONObject reqParams) throws Exception {
/**
* processSaveRecord: save record on database in case command is "save-record"
* If you need to save records implement this function in child class
* @param reqParams parameters extracted from request with requestToJson
* @throws Exception
*/
protected void processSaveRecord(JSONObject reqParams) throws Exception {
throw new Exception ("Save not implemented");
}

/**
* processSaveRecords: delete records from database in case command is "delete-records"
* If you need to delete records implement this function in child class
* @param ids record ids that must be deleted
* @throws Exception
*/
protected void processDeleteRecords(int[] ids) throws Exception {
throw new Exception ("Delete not implemented");
}

}
86 changes: 80 additions & 6 deletions server/java/src/com/w2ui/servlets/example/W2uiGridExample.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.w2ui.servlets.example;

import java.io.InputStream;
import java.util.Iterator;

import javax.servlet.Servlet;

Expand All @@ -10,16 +11,24 @@
import com.w2ui.servlets.W2uiGridData;

/**
* Servlet implementation class W2uiGridExample
* Servlet implementation of a class derived from W2uiGridData
* This class is not intended to be used in production but only to show how to implement methods
* Recorda are stored in a database but only into an array in memory; you should
* adjust (or rewrite) functions to interact with your favorite DBMS (Postgres, MySql, etc.)
*
* Code of this class is not optimized and does not wanto to be: it is intended only as example
*/
public class W2uiGridExample extends W2uiGridData implements Servlet {
private static final long serialVersionUID = 7163093252884618719L;

// this variable simulates the users database
// it is NOT thread safe ... but this is just an example
/**
* this variable simulates the users database
* it is NOT thread safe ... but this is just an example
*/
protected static JSONArray dbUsers = new JSONArray();

static {
// Load the simulated database for the first time
InputStream is = null;
try {
StringBuffer sb = new StringBuffer();
Expand Down Expand Up @@ -145,15 +154,80 @@ protected JSONArray processGetRecords(JSONObject reqParams)
}

// NOTE: sorting is not implemented here
// if you have a DBMS you should do it in the query reading the properties contained in
// field "sort"

return ret;
}

@Override
protected JSONObject processGetRecord(JSONObject reqParams) throws Exception {
int recid = reqParams.getInt("recid");
for (int i=0; i < dbUsers.length(); i++) {
JSONObject jsobj = dbUsers.getJSONObject(i);
int id = jsobj.getInt("recid");
if (id == recid) {
return jsobj;
}
}
throw new Exception("Not found");
}

protected void updateRecord(int recid, JSONObject change) throws Exception {
for (int i=0; i < dbUsers.length(); i++) {
JSONObject jsobj = dbUsers.getJSONObject(i);
int id = jsobj.getInt("recid");
if (recid == id) {
// update the record
Iterator<String> it = change.keys();
while (it.hasNext()) {
String key = it.next();
Object obj = change.get(key);
jsobj.put(key, obj);
}
// put record on DB
dbUsers.put(i, jsobj);
return;
}
}
// if we are here no update has been done: we add a new record
change.put("recid", recid);
dbUsers.put(change);
}

protected void processSaveRecords(JSONObject reqParams) throws Exception {
throw new Exception ("TO DO");
JSONArray changed = reqParams.getJSONArray("changed");
for (int cnt=0; cnt < changed.length(); cnt++) {
JSONObject change = changed.getJSONObject(cnt);
int recid = change.getInt("recid");
updateRecord(recid, change);
}
}

protected void processSaveRecord(JSONObject reqParams) throws Exception {
JSONObject change = reqParams.getJSONObject("record");
int recid = reqParams.getInt("recid");
updateRecord(recid, change);
}

protected void processDeleteRecords(JSONObject reqParams) throws Exception {
throw new Exception ("TO DO");
protected void processDeleteRecords(int[] ids) throws Exception {
JSONArray newDB = new JSONArray();
for (int i=0; i < dbUsers.length(); i++) {
JSONObject jsobj = dbUsers.getJSONObject(i);
int recid = jsobj.getInt("recid");
boolean remove = false;
for (int cnt=0; cnt < ids.length; cnt++) {
if (recid == ids[cnt]) {
// do not add in new DB the record
remove = true;
break;
}
}
if ( !remove ) {
newDB.put(jsobj);
}
}
// replace DB
dbUsers = newDB;
}
}

0 comments on commit be9042f

Please sign in to comment.