001
014
015 package com.liferay.portal.template;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncCharArrayWriter;
018 import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
019 import com.liferay.portal.kernel.template.TemplateResource;
020
021 import java.io.IOException;
022 import java.io.ObjectInput;
023 import java.io.ObjectOutput;
024 import java.io.Reader;
025
026 import java.util.concurrent.atomic.AtomicReference;
027
028
031 public class CacheTemplateResource implements TemplateResource {
032
033
037 public CacheTemplateResource() {
038 }
039
040 public CacheTemplateResource(TemplateResource templateResource) {
041 if (templateResource == null) {
042 throw new IllegalArgumentException("Template resource is null");
043 }
044
045 _templateResource = templateResource;
046 }
047
048 @Override
049 public boolean equals(Object obj) {
050 if (this == obj) {
051 return true;
052 }
053
054 if (!(obj instanceof CacheTemplateResource)) {
055 return false;
056 }
057
058 CacheTemplateResource cacheTemplateResource =
059 (CacheTemplateResource)obj;
060
061 if (_templateResource.equals(cacheTemplateResource._templateResource)) {
062 return true;
063 }
064
065 return false;
066 }
067
068 public long getLastModified() {
069 return _lastModified;
070 }
071
072 public Reader getReader() throws IOException {
073 String templateContent = _templateContent.get();
074
075 if (templateContent != null) {
076 return new UnsyncStringReader(templateContent);
077 }
078
079 Reader reader = null;
080
081 try {
082 reader = _templateResource.getReader();
083
084 char[] buffer = new char[1024];
085
086 int result = -1;
087
088 UnsyncCharArrayWriter unsyncCharArrayWriter =
089 new UnsyncCharArrayWriter();
090
091 while ((result = reader.read(buffer)) != -1) {
092 unsyncCharArrayWriter.write(buffer, 0, result);
093 }
094
095 templateContent = unsyncCharArrayWriter.toString();
096
097 _templateContent.set(templateContent);
098 }
099 finally {
100 if (reader != null) {
101 reader.close();
102 }
103 }
104
105 return new UnsyncStringReader(templateContent);
106 }
107
108 public String getTemplateId() {
109 return _templateResource.getTemplateId();
110 }
111
112 @Override
113 public int hashCode() {
114 return _templateResource.hashCode();
115 }
116
117 public void readExternal(ObjectInput objectInput)
118 throws ClassNotFoundException, IOException {
119
120 _lastModified = objectInput.readLong();
121 _templateResource = (TemplateResource)objectInput.readObject();
122 }
123
124 public void writeExternal(ObjectOutput objectOutput) throws IOException {
125 objectOutput.writeLong(_lastModified);
126 objectOutput.writeObject(_templateResource);
127 }
128
129 private long _lastModified = System.currentTimeMillis();
130 private AtomicReference<String> _templateContent =
131 new AtomicReference<String>();
132 private TemplateResource _templateResource;
133
134 }