persistenceexample2/PersistenceExample.java
package persistenceexample2;
import java.io.IOException;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import persistenceexample2.bean.TableViewBean;
import persistenceexample2.datafactory.ReadWriteEntities;
import com.sap.ip.me.api.logging.AbstractLogging;
import com.sap.ip.me.api.logging.AppLog;
import com.sap.ip.me.api.logging.Severities;
import com.sap.ip.me.api.runtime.jsp.AbstractMEHttpServlet;
// Uses the Peristence API to store and read data
public class PersistenceExample extends AbstractMEHttpServlet implements Constants {
public static int idCounter;
private TableViewBean tableViewBean;
private String headLine;
boolean listall;
private int filter_index;
private int sort_index;
private boolean sort_ascending;
private String buttontext;
private String buttontextQuery;
private String filter_string;
/**
* Must be overwritten - return the name of the application
*/
public String getApplicationName() {
return MI_APPLICATION_NAME;
}
/**
* doIntialize - called when the servlet is activated the first time
*/
public void doInitialize() throws ServletException {
/* No resource bundle used setResourceBundle("/NoResourceBundleUsed"); */
idCounter = 0;
// Setup and initialize the Persistence Runtime
ReadWriteEntities.setupPersistenceRuntime();
// We create initial entries with the Persistence API, so that we have not to display an emtpy table
ReadWriteEntities.writeExampleEntries();
// Set list parameter to list only main entries
setListPartial();
setFilterOff();
// Set sorting variables.
sort_index = 0;
sort_ascending = true;
// Prepare a log output - Level DEBUG - Information about classloader
ClassLoader cl = getClass().getClassLoader();
AbstractLogging aLogger = AppLog.getInstance(MI_APPLICATION_NAME);
aLogger.log(Severities.DEBUG, "MIClientInfo: Create MIClientInfoServlet.doInitialize with Classloader {0}", (cl == null ? "(null)" : cl.toString()));
}
/**
* doHandleEvent - called any subsequent time when an event on the web client occurs.
*/
public String doHandleEvent(String eventName, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the name of the JSP that has to be called when this method is finished.
// INITIAL_JSP ist defined in the interface Constants.java and refers to welcome.jsp. This JSP displays a welcome message
// and asks for your name. Welcome.jsp has a submit button which generates the event EVENT_NAME. When this event occurs,
// the tableView.jsp is called and displays system information.
// The welcome.jsp is called by default - if the servlet is called the first time or an unknown event occurs.
// Set default JSP.
String nextJSP = INITIAL_JSP;
// Set default text for headline
headLine = WELCOME_MESSAGE;
// Get bean, if there is one, in the session context, otherwise create a new instance.
getBeansFromContext(request);
//
// Events in menu.jsp
if (eventName.equals(EVENT_LIST)) {
// Toggle on listall (boolean) - if acutally true than set to false and vice versa
if (listall == true) {
setListPartial();
} else {
setListAll();
}
}
if (eventName.equals(EVENT_ADDENTRY)) {
// Event occurs when the ADD button in menu.jsp has been pressed.
// We display add.jsp as next JSP.
nextJSP = ADD_JSP;
}
if (eventName.equals(EVENT_QUERY)) {
// Event occurs when the FILTER button in menu.jsp has been pressed.
// We display query.jsp.
nextJSP = QUERY_JSP;
}
if (eventName.equals(EVENT_DELENTRY)) {
// Event occurs when the DELETE button in menu.jsp has been pressed.
nextJSP = deleteEntry(request);
}
if (eventName.equals(EVENT_SAVE)) {
// Event occurs when the SAVE button in menu.jsp has been pressed.
ReadWriteEntities.commit();
}
//
// Events from add.jsp or delete.jsp (Cancel event - is handled the same for both JSP
//
if (eventName.equals(EVENT_ADDENTRYCANCEL)) {
// Event occurs when the cancel button has been pressed on the ADD ENTRY JSP. No action. Show initial screen
nextJSP = INITIAL_JSP;
}
//
// Events in add.jsp
//
if (eventName.equals(EVENT_ADDENTRYSUBMIT)) {
// Event occurs when the submit button has been pressed on the ADD ENTRY JSP
nextJSP = addEntry(request);
}
//
// Event in delete.jsp - is the OK button to acknowledge the information text
//
if (eventName.equals(EVENT_DELETEENTRYSUBMIT)) {
nextJSP = INITIAL_JSP;
}
//
// Event in query.jsp
//
if (eventName.equals(EVENT_QUERYCANCEL)) {
// Event occurs when the cancel button has been pressed on the Cancel button. No action. Show initial screen
nextJSP = INITIAL_JSP;
}
if (eventName.equals(EVENT_QUERYSUBMIT)) {
// Event occurs when the OK button has been pressed. The Filter string is set for the Query.
nextJSP = setFilter(request);
}
// Load bean with values from persistence layer
loadBean(listall);
// Put bean in the session context.
putBeansIntoContext(request);
// Exit with name of JSP.
return nextJSP;
}
/**
* Method deleteEntry - deletes an selected entry
* @return String - next JSP to call.
*/
private String deleteEntry(HttpServletRequest request) {
String nextJSP = null;
// We loop through all entries and check
// which row has been selected. If we find a selected row we delete the entry.
// We use the request.getParameter(valueOfCheckbox) method to find out which checkbox is clicked. The valueOfCheckbox
// is stored in the first column of the databean.
// If no row is selected we display a hint to select a row first.
boolean aRowWasChecked = false;
for (int i = 1; i < tableViewBean.getTableRows(); i++) {
String check = (String) request.getParameter(tableViewBean.getTableContent(i, 0));
if (check != null) {
// Check Row has been found
aRowWasChecked = true;
String car = tableViewBean.getTableContent(i, 0);
// Delete car. License is deleted also, because we use TreeOptionType.COMPLETE in the deleteEntity method
if (car.length() > 0) {
ReadWriteEntities.deleteEntity(car);
}
}
}
nextJSP = INITIAL_JSP;
if (aRowWasChecked == false) {
// no row was checked - display an information message
nextJSP = DELETE_JSP;
}
return nextJSP;
}
/**
* Method addEntry. - Adds an Entry according to user input
* @return String - next JSP to call
*/
private String addEntry(HttpServletRequest request) {
// We take the content of the inputfield in the JSP named CAR and LICENCE and store in via the Peristence API
// As next JSP we set the INITIAL_JSP again.
String make = (String) request.getParameter("MAKE");
String model = (String) request.getParameter("MODEL");
String engine = (String) request.getParameter("ENGINE");
String cylinders = (String) request.getParameter("CYLINDERS");
String valves = (String) request.getParameter("VALVES");
String lic = (String) request.getParameter("LICENSE");
ReadWriteEntities.addEntity(make, model, engine, cylinders, valves, lic);
return INITIAL_JSP;
}
/**
* Method setFilter - according to user input a filter string will be set up.
* @param request
* @return String - next JSP to call
*/
private String setFilter(HttpServletRequest request) {
filter_string = (String) request.getParameter("MAKE");
if (filter_string.length() == 0) {
setFilterOff();
} else {
// The filter_index has to match the "AttributeDescriptor" in ExamplePackagePersistenceMaster. I_MAKE is the
// index for our output array, which has the entityKey at index 0. The "AttributeDescriptor" has no entityKey
// and starts with "make" right away - so we subtract 1 from the I_MAKE index.
setFilterOn(I_MAKE - 1, filter_string);
}
return INITIAL_JSP;
}
private void getBeansFromContext(HttpServletRequest request) {
// Get table defintion bean from session context. There is a bean, when this servlet has already been called once.
tableViewBean = (TableViewBean) request.getSession().getAttribute(CONTEXT_BEAN);
// No bean in session context - create a new instance.
if (tableViewBean == null)
tableViewBean = new TableViewBean();
}
public void loadBean(boolean all) {
// Set headline
tableViewBean.setString(headLine);
// Set button text for list button
tableViewBean.setButton(buttontext);
// Set button text for query button
tableViewBean.setButtonQuery(buttontextQuery);
// Read data from persistence layer according to filter settings.
Vector ent = new Vector();
// create header
/* The "Make" and "Model" (index 1 and 2) headline can be clicked by the user to select which column is sorted by. That the event
* of the link is passed on to this servlet and also tells us which link has been clicked, we use the ?event=
* paramenter on the "href" tag. A image indiactes which column is active for sorting. The getMime... methods
* return either a "nosort.gif" (this column is not used for sorting) or "ascending.gif" when the column is
* used for sorting
*/
Vector dataVec = new Vector();
dataVec.addElement(" ");
dataVec.addElement("Make");
dataVec.addElement("Model");
dataVec.addElement("License");
dataVec.addElement("Engine");
dataVec.addElement("C");
dataVec.addElement("V");
ent.addElement(dataVec);
ent = ReadWriteEntities.readEntity(ent, filter_index, sort_index, sort_ascending, filter_string, all);
tableViewBean.setTableContent(ent);
tableViewBean.setTableRows(ent.size());
tableViewBean.setTableColumns(7);
}
/**
* Method getMimeModelFileName. - gets the apporiate filename to indicate sorting direction for model
* @return String
*/
private String getMimeMakeFileName() {
String mime = "mimes/nosort.gif";
if (sort_index == I_MAKE - 1) {
mime = "mimes/ascending.gif";
if (sort_ascending == false)
mime = "mimes/descending.gif";
}
return mime;
}
private String getMimeModelFileName() {
String mime = "mimes/nosort.gif";
if (sort_index == I_MODEL - 1) {
mime = "mimes/ascending.gif";
if (sort_ascending == false)
mime = "mimes/descending.gif";
}
return mime;
}
private void putBeansIntoContext(HttpServletRequest request) {
// Put table definition bean in session context
if (tableViewBean == null) {
request.getSession().removeAttribute(CONTEXT_BEAN);
} else {
request.getSession().setAttribute(CONTEXT_BEAN, tableViewBean);
}
}
public void setListPartial() {
listall = false;
buttontext = " List all ";
}
public void setListAll() {
listall = true;
buttontext = "Short List";
}
/**
* Method setFilterOff - All Data without Filter are displayed.
*/
private void setFilterOff() {
filter_index = I_ALL;
buttontextQuery = BUTTON_QUERY_TEXT;
}
private void setFilterOn(int Index, String filter_string) {
buttontextQuery = "Filter: " + filter_string;
filter_index = I_MAKE - 1;
}
}