Configure the Advanced I/O Function
Next, we will begin coding the to-do list application by configuring the function component.
The functions directory, functions/ToDoList contains:
- The ToDoList.java main function file
- The catalyst-config.json configuration file
- Java library files in the lib directory
- .classpath and .project dependency files
You will be adding code in the ToDoList.java file.
The three APIs in the Advanced I/O function that handle the routing between the server and the Data Store are:
- GET /todo: To obtain the to-do list items from the TodoItems table in the Data Store
- POST /todo: To create and save a new list item in the Data Store
- DELETE /todo: To delete a list item from the Data Store
Next, let’s add the code in the function file. Copy the Java code and paste it in ToDoList.java in the functions/TodoList directory of your project, and save the file. You can use any IDE of your choice to work with the application’s files.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.catalyst.advanced.CatalystAdvancedIOHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zc.component.object.ZCObject;
import com.zc.component.object.ZCRowObject;
import com.zc.component.object.ZCTable;
import com.zc.component.zcql.ZCQL;
public class ToDoList implements CatalystAdvancedIOHandler {
private static final String GET = “GET”;
private static final String POST = “POST”;
private static final String DELETE = “DELETE”;
private JSONObject responseData = new JSONObject();
private static final Logger LOGGER = Logger.getLogger(ToDoList.class.getName());
@SuppressWarnings("unchecked")
@Override
public void runner(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
String uri = request.getRequestURI();
String method = request.getMethod();
// GET method gets data from the TodoItems table in the Data Store.
if (method.equals(GET) && uri.equals("/all")) {
Integer page = Integer.parseInt(request.getParameter("page"));
Integer perPage = Integer.parseInt(request.getParameter("perPage"));
ArrayList<ZCRowObject> rowList = ZCQL.getInstance().executeQuery("SELECT COUNT(ROWID) FROM TodoItems");
Integer totalTodos = Integer.parseInt(new ObjectMapper().writeValueAsString(rowList.get(0).get("TodoItems", "COUNT(ROWID)")));
Boolean hasMore = totalTodos > page * perPage;
ArrayList<HashMap<String, String>> todoItems = new ArrayList<>();
ZCQL.getInstance().executeQuery(String.format("SELECT ROWID, Notes FROM TodoItems LIMIT %d, %d",
(page - 1) * perPage, perPage)).forEach(row -> {
HashMap<String, String> item = new HashMap<>();
item.put("id", row.get("TodoItems", "ROWID").toString());
item.put("notes", row.get("TodoItems", "Notes").toString());
todoItems.add(item);
});
response.setStatus(200);
responseData.put("status", "success");
responseData.put("data", new JSONObject() {
{
put("hasMore", hasMore);
put("todoItems", todoItems);
}
});
// POST method adds a new todo item to the TodoItems table in the Data Store.
} else if (method.equals(POST) && uri.equals("/add")) {
JSONParser jsonParser = new JSONParser();
ServletInputStream requestBody = request.getInputStream();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(requestBody, "UTF-8"));
String notes = jsonObject.get("notes").toString();
ZCRowObject row = ZCRowObject.getInstance();
row.set("Notes", notes);
ZCRowObject todoItem = ZCObject.getInstance().getTable("TodoItems").insertRow(row);
response.setStatus(200);
responseData.put("status", "success");
responseData.put("data", new JSONObject() {
{
put("todoItem", new JSONObject() {
{
put("id", todoItem.get("ROWID").toString());
put("notes", todoItem.get("Notes").toString());
}
});
}
});
// DELETE method deletes a todo item from the Data Store by its ID.
} else if (method.equals(DELETE) && uri.matches("/\\d+")) {
ZCTable table = ZCObject.getInstance().getTable("TodoItems");
table.deleteRow(Long.parseLong(uri.substring(1)));
response.setStatus(200);
responseData.put("status", "success");
responseData.put("data", new JSONObject() {
{
put("todoItem", new JSONObject() {
{
put("id", uri.substring(1));
}
});
}
});
} else {
response.setStatus(404);
responseData.put("status", "failure");
responseData.put("message", "Please check if the URL trying to access is a correct one");
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception in Main", e);
responseData.put("status", "failure");
responseData.put("message", "We're unable to process the request.");
}
response.setContentType("application/json");
response.getWriter().write(responseData.toString());
}
}
The functions directory is now configured.
Last Updated 2024-09-20 19:07:45 +0530 IST