1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.scripting.support;
18
19 import java.io.IOException;
20 import java.io.Reader;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24
25 import org.springframework.core.io.Resource;
26 import org.springframework.core.io.support.EncodedResource;
27 import org.springframework.scripting.ScriptSource;
28 import org.springframework.util.Assert;
29 import org.springframework.util.FileCopyUtils;
30 import org.springframework.util.StringUtils;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public class ResourceScriptSource implements ScriptSource {
48
49
50 protected final Log logger = LogFactory.getLog(getClass());
51
52 private EncodedResource resource;
53
54 private long lastModified = -1;
55
56 private final Object lastModifiedMonitor = new Object();
57
58
59
60
61
62
63 public ResourceScriptSource(EncodedResource resource) {
64 Assert.notNull(resource, "Resource must not be null");
65 this.resource = resource;
66 }
67
68
69
70
71
72 public ResourceScriptSource(Resource resource) {
73 Assert.notNull(resource, "Resource must not be null");
74 this.resource = new EncodedResource(resource, "UTF-8");
75 }
76
77
78
79
80
81
82 public final Resource getResource() {
83 return this.resource.getResource();
84 }
85
86
87
88
89
90
91 public void setEncoding(String encoding) {
92 this.resource = new EncodedResource(this.resource.getResource(), encoding);
93 }
94
95
96 @Override
97 public String getScriptAsString() throws IOException {
98 synchronized (this.lastModifiedMonitor) {
99 this.lastModified = retrieveLastModifiedTime();
100 }
101 Reader reader = this.resource.getReader();
102 return FileCopyUtils.copyToString(reader);
103 }
104
105 @Override
106 public boolean isModified() {
107 synchronized (this.lastModifiedMonitor) {
108 return (this.lastModified < 0 || retrieveLastModifiedTime() > this.lastModified);
109 }
110 }
111
112
113
114
115
116 protected long retrieveLastModifiedTime() {
117 try {
118 return getResource().lastModified();
119 }
120 catch (IOException ex) {
121 if (logger.isDebugEnabled()) {
122 logger.debug(getResource() + " could not be resolved in the file system - " +
123 "current timestamp not available for script modification check", ex);
124 }
125 return 0;
126 }
127 }
128
129 @Override
130 public String suggestedClassName() {
131 return StringUtils.stripFilenameExtension(getResource().getFilename());
132 }
133
134 @Override
135 public String toString() {
136 return this.resource.toString();
137 }
138
139 }