DummyCart.java
01 /*
02  * Copyright 2004 The Apache Software Foundation
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package demo.cart;
17 
18 import java.util.Vector;
19 
20 import javax.servlet.http.HttpServletRequest;
21 
22 public class DummyCart implements java.io.Serializable {
23    private static final long serialVersionUID = -6839762562623352329L;
24    Vector<String> v = new Vector<String>();
25    String submit = null;
26    String item = null;
27 
28    private void addItem(String name) {
29       v.addElement(name);
30    }
31 
32    private void removeItem(String name) {
33       v.removeElement(name);
34    }
35 
36    public void setItem(String name) {
37       item = name;
38    }
39 
40    public void setSubmit(String s) {
41       submit = s;
42    }
43 
44    public String[] getItems() {
45       String[] s = new String[v.size()];
46       v.copyInto(s);
47       return s;
48    }
49 
50    public void processRequest(HttpServletRequest request) {
51       // null value for submit - user hit enter instead of clicking on
52       // "add" or "remove"
53       if (submit != null && item != null) {
54          if (submit.equals("add")) {
55             addItem(item);
56          else if (submit.equals("remove")) {
57             removeItem(item);
58          }
59       }
60 
61       // reset at the end of the request
62       reset();
63    }
64 
65    // reset
66    private void reset() {
67       submit = null;
68       item = null;
69    }
70 
71    @Override
72    public String toString() {
73       StringBuilder sb = new StringBuilder();
74       boolean startedSeps = false;
75       for (String item : getItems()) {
76          if (startedSeps) {
77             sb.append(", ");
78          else {
79             startedSeps = true;
80          }
81          sb.append(item);
82       }
83       return sb.toString();
84    }
85 }