01: /*
02: * Copyright 2003 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:
17: package velosurf.util;
18:
19: import java.io.InputStream;
20: import java.io.StringReader;
21: import java.util.Date;
22:
23: import org.apache.velocity.runtime.resource.loader.ResourceLoader;
24: import org.apache.velocity.runtime.resource.Resource;
25: import org.apache.velocity.exception.ResourceNotFoundException;
26: import org.apache.commons.collections.ExtendedProperties;
27:
28: import velosurf.context.DBReference;
29: import velosurf.context.EntityReference;
30: import velosurf.web.VelosurfTool;
31:
32: /**
33: * A database resource loader for use with Velosurf. Experimental.
34: *
35: * @author <a href=mailto:claude.brisson@gmail.com>Claude Brisson</a>
36: */
37:
38: public class DBResourceLoader extends ResourceLoader {
39:
40: protected DBReference db = null;
41: protected EntityReference table = null;
42:
43: protected String entity = null;
44: protected String dataField = null;
45: protected String timestampField = null;
46:
47: public void init(ExtendedProperties configuration) {
48: entity = configuration.getString("entity", "template");
49: dataField = configuration.getString("data", "data");
50: timestampField = configuration.getString("lastmodified",
51: "lastmodified");
52:
53: initdb();
54: }
55:
56: protected synchronized void initdb() {
57: if (db == null) {
58: db = VelosurfTool.getDefaultInstance();
59: if (db != null) {
60: table = (EntityReference) db.get(entity);
61: }
62: }
63: }
64:
65: public InputStream getResourceStream(String id)
66: throws ResourceNotFoundException {
67: if (db == null) {
68: initdb();
69: }
70: String template = (String) table.fetch(id).get(dataField);
71: return new ReaderInputStream(new StringReader(template));
72: }
73:
74: public boolean isSourceModified(Resource resource) {
75: return ((Date) table.fetch(resource.getName()).get(
76: timestampField)).getTime() > resource.getLastModified();
77: }
78:
79: public long getLastModified(Resource resource) {
80: return ((Date) table.fetch(resource.getName()).get(
81: timestampField)).getTime();
82: }
83: }
|