01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.integration.app1.services;
16:
17: import static org.apache.tapestry.ioc.internal.util.CollectionFactory.newList;
18: import static org.apache.tapestry.ioc.internal.util.CollectionFactory.newMap;
19:
20: import java.util.Collections;
21: import java.util.Comparator;
22: import java.util.List;
23: import java.util.Map;
24:
25: import org.apache.tapestry.integration.app1.data.ToDoItem;
26: import org.apache.tapestry.integration.app1.data.Urgency;
27:
28: /**
29: * We clone everything that comes in or goes out. This does a reasonable job of simulating an
30: * external database. We just use cloned copies of objects to represent data that's been marshalled
31: * into tables and columns.
32: */
33: public class ToDoDatabaseImpl implements ToDoDatabase {
34: private long _nextId = 1000;
35:
36: private final Map<Long, ToDoItem> _items = newMap();
37:
38: public ToDoDatabaseImpl() {
39: // A couple of items to get us started:
40:
41: reset();
42: }
43:
44: public void reset() {
45: _items.clear();
46:
47: add("End World Hunger", Urgency.MEDIUM, 1);
48: add("Develop Faster-Than-Light Travel", Urgency.HIGH, 2);
49: add("Cure Common Cold", Urgency.LOW, 3);
50: }
51:
52: private void add(String title, Urgency urgency, int order) {
53: ToDoItem item = new ToDoItem();
54:
55: item.setTitle(title);
56: item.setUrgency(urgency);
57: item.setOrder(order);
58:
59: add(item);
60: }
61:
62: public void add(ToDoItem item) {
63: long id = _nextId++;
64:
65: item.setId(id);
66:
67: _items.put(id, item.clone());
68: }
69:
70: public List<ToDoItem> findAll() {
71: List<ToDoItem> result = newList();
72:
73: for (ToDoItem item : _items.values())
74: result.add(item.clone());
75:
76: Comparator<ToDoItem> comparator = new Comparator<ToDoItem>() {
77: public int compare(ToDoItem o1, ToDoItem o2) {
78: return o1.getOrder() - o2.getOrder();
79: }
80: };
81:
82: Collections.sort(result, comparator);
83:
84: return result;
85: }
86:
87: public void update(ToDoItem item) {
88: long id = item.getId();
89:
90: if (!_items.containsKey(id))
91: throw new RuntimeException(String.format(
92: "ToDoItem #%d not found.", id));
93:
94: _items.put(id, item.clone());
95: }
96:
97: }
|