1 16 17 package org.springframework.scripting.support; 18 19 import java.io.File ; 20 import java.io.FileNotFoundException ; 21 import java.io.FileReader ; 22 import java.io.IOException ; 23 import java.io.InputStreamReader ; 24 import java.io.Reader ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 import org.springframework.core.io.Resource; 30 import org.springframework.scripting.ScriptSource; 31 import org.springframework.util.Assert; 32 import org.springframework.util.FileCopyUtils; 33 34 49 public class ResourceScriptSource implements ScriptSource { 50 51 52 protected final Log logger = LogFactory.getLog(getClass()); 53 54 private final Resource resource; 55 56 private long lastModified = -1; 57 58 private final Object lastModifiedMonitor = new Object (); 59 60 61 65 public ResourceScriptSource(Resource resource) { 66 Assert.notNull(resource, "Resource must not be null"); 67 this.resource = resource; 68 } 69 70 74 public final Resource getResource() { 75 return this.resource; 76 } 77 78 79 public String getScriptAsString() throws IOException { 80 File file = null; 81 try { 82 file = getResource().getFile(); 83 } 84 catch (IOException ex) { 85 if (logger.isDebugEnabled()) { 86 logger.debug(getResource() + " could not be resolved in the file system - " + 87 "cannot store last-modified timestamp for obtained script", ex); 88 } 89 } 90 synchronized (this.lastModifiedMonitor) { 91 this.lastModified = (file != null ? file.lastModified() : 0); 92 } 93 Reader reader = null; 94 if (file != null) { 95 try { 96 reader = new FileReader (file); 98 } 99 catch (FileNotFoundException ex) { 100 if (logger.isDebugEnabled()) { 101 logger.debug("Could not open FileReader for " + this.resource + 102 " - falling back to InputStreamReader", ex); 103 } 104 } 105 } 106 if (reader == null) { 107 reader = new InputStreamReader (this.resource.getInputStream()); 108 } 109 return FileCopyUtils.copyToString(reader); 110 } 111 112 public boolean isModified() { 113 synchronized (this.lastModifiedMonitor) { 114 return (this.lastModified < 0 || retrieveLastModifiedTime() > this.lastModified); 115 } 116 } 117 118 122 protected long retrieveLastModifiedTime() { 123 try { 124 return getResource().getFile().lastModified(); 125 } 126 catch (IOException ex) { 127 if (logger.isDebugEnabled()) { 128 logger.debug(getResource() + " could not be resolved in the file system - " + 129 "current timestamp not available for script modification check", ex); 130 } 131 return 0; 132 } 133 } 134 135 136 public String toString() { 137 return this.resource.toString(); 138 } 139 140 } 141 | Popular Tags |