Update of /cvsroot/struts/dialogs/src/net/jspcontrols/dialogs/samples/crudaction In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12963/src/net/jspcontrols/dialogs/samples/crudaction Added Files: CRUDActionSample.java CRUDFormSample.java CRUDListActionSample.java ItemListActionSample.java Log Message: --- NEW FILE: CRUDActionSample.java --- package net.jspcontrols.dialogs.samples.crudaction; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.jspcontrols.dialogs.actions.crud.CRUDAction; import net.jspcontrols.dialogs.actions.crud.ICRUDForm; import net.jspcontrols.dialogs.samples.crudaction.business.BusinessObj; import java.util.ArrayList; /** * Created by IntelliJ IDEA. * User: Mikus * Date: Jun 28, 2005 * Time: 7:58:45 AM * To change this template use Options | File Templates. */ public class CRUDActionSample extends CRUDAction { /** * Returns an <code>ActionForward</code> instance describing the View * for current dialog state, usually a forward to a JSP page. * <p> * If you want to use the default implementation, define the View * under "DIALOG-VIEW" name in <forward> element of your action * mapping. * <p> * To use different mapping name, define the view in <forward> * element of your action mapping, and override this method to return * ActionForward object for your mapping name. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception java.lang.Exception if an exception occurs * @return ActionForward instance describing the View for dialog state */ public ActionForward getDialogView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Mark response as non-cachable setNoCache(response); // Return mapping corresponding to business object state return super.getDialogView(mapping, form, request, response); } } --- NEW FILE: CRUDFormSample.java --- /* * Copyright 2004-2005 Michael Jouravlev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jspcontrols.dialogs.samples.crudaction; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import net.jspcontrols.dialogs.actions.crud.ICRUDForm; import net.jspcontrols.dialogs.actions.crud.CRUDForm; import net.jspcontrols.dialogs.samples.crudaction.business.BusinessObj; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.Iterator; /** * Example of CRUDAction an ICRUDForm usage. The data from this form bean * is stored to a simple business object with two values: stingvalue and numvalue. * * @author Michael Jouravlev */ public class CRUDFormSample extends CRUDForm implements ICRUDForm { /** * Key to store item list in the session */ public static final String CRUD_LIST_KEY = "crud-item-list"; /* * Page header: "New Item", "Edit Item" or "View Item". * Used on the JSP to reflect current UI mod. No setter for this property. */ private String itemHeader; public String getItemHeader() {return itemHeader;} /* * Item ID aka Primary Key; each business object is identified by a key. * Getter is used on JSP page, setter is used to to identify an existing * item, which must be edited. */ private String itemId; public String getItemId() {return itemId;} public void setItemId(String itemId) {this.itemId = itemId;} /************************************************************************** * Business data: every property of business object is exposed explicitly. **************************************************************************/ /* * Simple string value, must not be null. */ private String stringValue; public String getStringValue() {return stringValue;} public void setStringValue(String stringValue) {this.stringValue = stringValue;} /* * Simple integer value, must be over 150. */ private String intValue; public String getIntValue() {return intValue;} public void setIntValue(String intValue) {this.intValue = intValue;} /************************************************************************** * Data lifecycle **************************************************************************/ /** * Generates and returns ID for new item. * @return stringified ID, hopefully unique */ String createUnuqueId() { return (new Integer((new Double((Math.random() * 100000))). intValue())).toString(); } /** * Creates new item. This particular implementation generates item ID * (that is, database PK) right at the moment when item is generated. * <p> * Another approach is to generate item ID when item is actually * stored. In this case you would probably need a status field. * You would generate ID for items with "new" status. Items loaded * from database would have "existing" status. * @return non-empty ActionMessages object if could not create item. */ public ActionMessages crudCreate() { // Initialize new item itemId = createUnuqueId(); intValue = null; stringValue = null; itemHeader = "New Item"; // New item is ready to be edited changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_EDITABLE); // No errors creating new item return null; } /** * Duplicates new business data from existing object. * @return non-empty ActionMessages object if could not duplicate item. */ public ActionMessages crudDuplicate() { return initLoadedItem(true, "New Item", ICRUDForm.CRUD_UI_MODE_EDITABLE); } /** * Loads business data from persistence layer into the action form or * into nested property of action form, and switches to edit mode. * @return non-empty ActionMessages object if could not load business item. */ public ActionMessages crudLoadForUpdate() { return initLoadedItem(false, "Edit Item", ICRUDForm.CRUD_UI_MODE_EDITABLE); } /** * Load business data from persistence layer into the action form or * into nested property of action form, and switches to view mode. * @return non-empty ActionMessages object if could not load business item. */ public ActionMessages crudLoadForPreview() { return initLoadedItem(false, "View Item", ICRUDForm.CRUD_UI_MODE_READONLY); } /** * Deletes business data from underlying persistent layer * @return non-empty ActionMessages object if could not delete item. */ public ActionMessages crudDelete() { // Find and delete item if found BusinessObj item = findOrDeleteItem(this.itemId, true); if (item != null) { // Deactivate CRUDAction view changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_INACTIVE); // No errors loading an item return null; } else { ActionErrors errors = new ActionErrors(); errors.add("ERROR", new ActionMessage("crudData.itemnotfound", this.itemId)); return errors; } } /** * Cancels process of updating existing or new item. * @return always null */ public ActionMessages crudCancel() { // New item is ready to be edited changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_INACTIVE); // No errors loading an item return null; } /** * Closes preview from of existing item. * @return always null */ public ActionMessages crudClose() { // New item is ready to be edited changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_INACTIVE); // No errors loading an item return null; } /** * Stores business data in the persistence layer. * <p> * When new item is created, this particular implementation generates * item ID right away. * <p> * Another approach is to generate item ID when it is actually * stored. In this case you would need something like status field. * You would generate ID for items with "new" status. Items loaded * from database would have "existing" status. * @return non-empty ActionMessages object if could not store business data. */ public ActionMessages crudStore() { ActionErrors errors = new ActionErrors(); // Try to persist item if (ICRUDForm.CRUD_UI_MODE_EDITABLE.equals(getCrudUIMode())) { // Test business rules: fail persist if num value is too low if (Integer.parseInt(intValue) < 150) { // Keep UI mode, which is CRUD_UI_MODE_EDIT, no need to change // changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_EDIT); errors.add("ERROR", new ActionMessage("crudData.storevaluetoolow")); return errors; // Persisting } else { int tempIntValue = 0; try { tempIntValue = Integer.parseInt(intValue); } catch (NumberFormatException e) { errors.add("ERROR", new ActionMessage("crudData.numbernotint")); return errors; } BusinessObj item = findOrDeleteItem(this.itemId, false); if (item != null) { item.setStringValue(this.stringValue); item.setIntValue(tempIntValue); } else { ArrayList items = (ArrayList) session.getAttribute(CRUD_LIST_KEY); item = new BusinessObj(itemId, stringValue, tempIntValue); items.add(item); } // New item is ready to be edited changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_INACTIVE); // No errors storing item return null; } } else { errors.add("ERROR", new ActionMessage("crudData.badmode")); return errors; } } /************************************************************************** * Helpers **************************************************************************/ /** * Finds item in the "persistent storage", that is, in the list of items. * @param id id of item to look for * @return non-null item if found, or null if item not found */ private BusinessObj findOrDeleteItem(String id, boolean delete) { ArrayList items = null; if (session != null && (items = (ArrayList) session.getAttribute(CRUD_LIST_KEY)) != null) { Iterator itemIte = items.listIterator(); while(itemIte.hasNext()) { BusinessObj item = (BusinessObj) itemIte.next(); if (item.getItemId().equals(id)) { if (delete) { itemIte.remove(); // This is a lame way to signal that item was found and // deleted. Cannot return reference to deleted object. return new BusinessObj(); } else { return item; } } } } return null; } /** * Loads item from storage (in this example from the session object) * @return non-empty ActionMessages object if could not load item. */ private ActionMessages loadItem() { ActionErrors errors = new ActionErrors(); try { BusinessObj item = findOrDeleteItem(this.itemId, false); if (item != null) { intValue = Integer.toString(item.getIntValue()); stringValue = item.getStringValue(); return null; } else { errors.add("ERROR", new ActionMessage("crudData.itemnotfound", this.itemId)); return errors; } } catch (Throwable e) { errors.add("ERROR", new ActionMessage("crudData.internalstorageerror")); return errors; } } /** * Initialized loaded item for duplicate, edit and preview modes. * @param initId if true, generate new item ID * @param title page title to use, like "View item" or "Edit item" * @param successState which state to switch to if item loaded successfully * @return non-empty ActionMessages object if could not load business item. */ private ActionMessages initLoadedItem(boolean initId, String title, String successState) { // Load existing item. Use item id which is already set in the form. ActionMessages errors = loadItem(); // Loaded successfully if (errors == null || errors.isEmpty()) { if (initId) { // Create new item ID, used for duplicating itemId = createUnuqueId(); } // Set up header for view JSP page itemHeader = title; // New item is ready to be edited or viewed changeCrudUIMode(successState); // No errors loading an item return null; // Could not load } else { // Deactivate CRUDAction view changeCrudUIMode(ICRUDForm.CRUD_UI_MODE_INACTIVE); // Report errors to CRUDAction return errors; } } /************************************************************************** * Reset and Validate **************************************************************************/ /** * Session stores list of business objects in this demo */ private HttpSession session; /** * Resets action form. Clear checkboxes here. This method is called before * form fields are populated, so here you can check request type, scope * and other action form parameters. * * @param mapping The ActionMapping used to select this instance * @param request The HTTP request we are processing */ public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); // Store session to access business objects this.session = request.getSession(); } /** * Validates input data. This method should be called manually from * action class to ensure, that (1) fields are not validated during * rendering phase, and to ensure that (2) action class handlers are called * even if input data is invalid. * @param actionMapping * @param httpServletRequest * @return */ public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) { ActionErrors errors = new ActionErrors(); if (stringValue == null || stringValue.length() == 0) { errors.add("ERROR", new ActionMessage("crudData.stringisnull")); } try { Integer.parseInt(intValue); } catch (NumberFormatException e) { errors.add("ERROR", new ActionMessage("crudData.numbernotint")); } return errors; } } --- NEW FILE: CRUDListActionSample.java --- package net.jspcontrols.dialogs.samples.crudaction; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.jspcontrols.dialogs.actions.crud.CRUDAction; import net.jspcontrols.dialogs.actions.crud.ICRUDForm; import net.jspcontrols.dialogs.samples.crudaction.business.BusinessObj; import java.util.ArrayList; /** * Created by IntelliJ IDEA. * User: Mikus * Date: Jun 28, 2005 * Time: 7:58:45 AM * To change this template use Options | File Templates. */ public class CRUDListActionSample extends CRUDAction { public void prepareItemList(HttpServletRequest request) { // Verify that item list exists in session HttpSession session = request.getSession(); synchronized(session) { ArrayList items = (ArrayList) session.getAttribute(CRUDFormSample.CRUD_LIST_KEY); // Create test sample of three items if (items == null) { items = new ArrayList(); items.add(new BusinessObj()); items.add(new BusinessObj()); items.add(new BusinessObj()); session.setAttribute(CRUDFormSample.CRUD_LIST_KEY, items); } } } /** * Returns an <code>ActionForward</code> instance describing the View * for current dialog state, usually a forward to a JSP page. * <p> * If you want to use the default implementation, define the View * under "DIALOG-VIEW" name in <forward> element of your action * mapping. * <p> * To use different mapping name, define the view in <forward> * element of your action mapping, and override this method to return * ActionForward object for your mapping name. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception Exception if an exception occurs * @return ActionForward instance describing the View for dialog state */ public ActionForward getDialogView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Mark response as non-cachable setNoCache(response); // Obtain current BO mode ICRUDForm crudForm = (ICRUDForm) form; String uiMode = crudForm.getCrudUIMode(); // There are no active items, so show item list if (ICRUDForm.CRUD_UI_MODE_INACTIVE.equals(uiMode)) { prepareItemList(request); } // Display a page corresponding to current item state return mapping.findForward(uiMode); } } --- NEW FILE: ItemListActionSample.java --- /* * Copyright 2004-2005 Michael Jouravlev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jspcontrols.dialogs.samples.crudaction; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import net.jspcontrols.dialogs.samples.crudaction.business.BusinessObj; /** * This class builds list of business items. This is a helper to show * CRUDAction in work. * * @author Michael Jouravlev */ public class ItemListActionSample extends Action { /** * Prepare and show item list. Each item can be operated by CRUDAction. */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Verify that item list exists in session HttpSession session = request.getSession(); ArrayList items = (ArrayList) session.getAttribute(CRUDFormSample.CRUD_LIST_KEY); // Create default item list of three items if (items == null) { items = new ArrayList(); items.add(new BusinessObj()); items.add(new BusinessObj()); items.add(new BusinessObj()); session.setAttribute(CRUDFormSample.CRUD_LIST_KEY, items); } // Modify response header to make page non-cachable. response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); response.setDateHeader("Expires", 1); // Show item list in crudaction-list.jsp return mapping.findForward("showlist"); } } |