Enable checkstyle in yang-model-util
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / repo / util / FilesystemSchemaSourceCache.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.model.repo.util;
9
10 import com.google.common.base.MoreObjects.ToStringHelper;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Lists;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.Futures;
17 import java.io.File;
18 import java.io.FilenameFilter;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.nio.file.FileVisitResult;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.SimpleFileVisitor;
25 import java.nio.file.StandardCopyOption;
26 import java.nio.file.attribute.BasicFileAttributes;
27 import java.text.DateFormat;
28 import java.text.ParseException;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
37 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
38 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
41 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
43 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
44 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Cache implementation that stores schemas in form of files under provided folder.
50  */
51 public final class FilesystemSchemaSourceCache<T extends SchemaSourceRepresentation>
52         extends AbstractSchemaSourceCache<T> {
53
54     private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaSourceCache.class);
55
56     // Init storage adapters
57     private static final Map<Class<? extends SchemaSourceRepresentation>,
58             StorageAdapter<? extends SchemaSourceRepresentation>> STORAGE_ADAPTERS = Collections.singletonMap(
59                     YangTextSchemaSource.class, new YangTextSchemaStorageAdapter());
60
61     private static final Pattern CACHED_FILE_PATTERN =
62             Pattern.compile("(?<moduleName>[^@]+)" + "(@(?<revision>" + SourceIdentifier.REVISION_PATTERN + "))?");
63
64     private final Class<T> representation;
65     private final File storageDirectory;
66
67     public FilesystemSchemaSourceCache(
68             final SchemaSourceRegistry consumer, final Class<T> representation, final File storageDirectory) {
69         super(consumer, representation, Costs.LOCAL_IO);
70         this.representation = representation;
71         this.storageDirectory = Preconditions.checkNotNull(storageDirectory);
72
73         checkSupportedRepresentation(representation);
74
75         if (!storageDirectory.exists()) {
76             Preconditions.checkArgument(storageDirectory.mkdirs(), "Unable to create cache directory at %s",
77                     storageDirectory);
78         }
79         Preconditions.checkArgument(storageDirectory.exists());
80         Preconditions.checkArgument(storageDirectory.isDirectory());
81         Preconditions.checkArgument(storageDirectory.canWrite());
82         Preconditions.checkArgument(storageDirectory.canRead());
83
84         init();
85     }
86
87     private static void checkSupportedRepresentation(final Class<? extends SchemaSourceRepresentation> representation) {
88         for (final Class<? extends SchemaSourceRepresentation> supportedRepresentation : STORAGE_ADAPTERS.keySet()) {
89             if (supportedRepresentation.isAssignableFrom(representation)) {
90                 return;
91             }
92         }
93
94         throw new IllegalArgumentException(String.format(
95                    "This cache does not support representation: %s, supported representations are: %s",
96                    representation, STORAGE_ADAPTERS.keySet()));
97     }
98
99     /**
100      * Restore cache state.
101      */
102     private void init() {
103
104         final CachedModulesFileVisitor fileVisitor = new CachedModulesFileVisitor();
105         try {
106             Files.walkFileTree(storageDirectory.toPath(), fileVisitor);
107         } catch (final IOException e) {
108             LOG.warn("Unable to restore cache from {}. Starting with empty cache", storageDirectory);
109             return;
110         }
111
112         for (final SourceIdentifier cachedSchema : fileVisitor.getCachedSchemas()) {
113             register(cachedSchema);
114         }
115     }
116
117     @Override
118     public synchronized CheckedFuture<? extends T, SchemaSourceException> getSource(
119             final SourceIdentifier sourceIdentifier) {
120         final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
121         if (file.exists() && file.canRead()) {
122             LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
123             final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
124                     file);
125             return Futures.immediateCheckedFuture(representation.cast(restored));
126         }
127
128         LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
129         return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found",
130                     sourceIdentifier));
131     }
132
133     @Override
134     protected synchronized void offer(final T source) {
135         LOG.trace("Source {} offered to cache", source.getIdentifier());
136         final File file = sourceIdToFile(source);
137         if (file.exists()) {
138             LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
139             return;
140         }
141
142         storeSource(file, source);
143         register(source.getIdentifier());
144         LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
145     }
146
147     private File sourceIdToFile(final T source) {
148         return sourceIdToFile(source.getIdentifier(), storageDirectory);
149     }
150
151     static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
152         final String rev = identifier.getRevision();
153         final File file;
154         if (Strings.isNullOrEmpty(rev)) {
155             file = findFileWithNewestRev(identifier, storageDirectory);
156         } else {
157             file = new File(storageDirectory, identifier.toYangFilename());
158         }
159         return file;
160     }
161
162     private static File findFileWithNewestRev(final SourceIdentifier identifier, final File storageDirectory) {
163         File[] files = storageDirectory.listFiles(new FilenameFilter() {
164             final Pattern pat = Pattern.compile(Pattern.quote(identifier.getName())
165                     + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)");
166
167             @Override
168             public boolean accept(final File dir, final String name) {
169                 return pat.matcher(name).matches();
170             }
171         });
172
173         if (files.length == 0) {
174             return new File(storageDirectory, identifier.toYangFilename());
175         }
176         if (files.length == 1) {
177             return files[0];
178         }
179
180         File file = null;
181         TreeMap<Date, File> map = new TreeMap<>();
182         for (File sorted : files) {
183             String fileName = sorted.getName();
184             Matcher match = SourceIdentifier.REVISION_PATTERN.matcher(fileName);
185             if (match.find()) {
186                 String revStr = match.group();
187                 /*
188                  * FIXME: Consider using string for comparison.
189                  * String is comparable, pattern check tested format
190                  * so comparing as ASCII string should be sufficient
191                  */
192                 DateFormat df = SimpleDateFormatUtil.getRevisionFormat();
193                 try {
194                     Date date = df.parse(revStr);
195                     map.put(date, sorted);
196                 } catch (final ParseException e) {
197                     LOG.info("Unable to parse date from yang file name {}", fileName);
198                     map.put(new Date(0L), sorted);
199                 }
200
201             } else {
202                 map.put(new Date(0L), sorted);
203             }
204         }
205         file = map.lastEntry().getValue();
206
207         return file;
208     }
209
210     private void storeSource(final File file, final T schemaRepresentation) {
211         STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
212     }
213
214     private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
215
216         private final Class<T> supportedType;
217
218         protected StorageAdapter(final Class<T> supportedType) {
219             this.supportedType = supportedType;
220         }
221
222         void store(final File file, final SchemaSourceRepresentation schemaSourceRepresentation) {
223             Preconditions.checkArgument(supportedType.isAssignableFrom(schemaSourceRepresentation.getClass()),
224                     "Cannot store schema source %s, this adapter only supports %s", schemaSourceRepresentation,
225                     supportedType);
226
227             storeAsType(file, supportedType.cast(schemaSourceRepresentation));
228         }
229
230         protected abstract void storeAsType(final File file, final T cast);
231
232         public T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
233             Preconditions.checkArgument(cachedSource.isFile());
234             Preconditions.checkArgument(cachedSource.exists());
235             Preconditions.checkArgument(cachedSource.canRead());
236             return restoreAsType(sourceIdentifier, cachedSource);
237         }
238
239         protected abstract T restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource);
240     }
241
242     private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
243
244         protected YangTextSchemaStorageAdapter() {
245             super(YangTextSchemaSource.class);
246         }
247
248         @Override
249         protected void storeAsType(final File file, final YangTextSchemaSource cast) {
250             try (final InputStream castStream = cast.openStream()) {
251                 Files.copy(castStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
252             } catch (final IOException e) {
253                 throw new IllegalStateException("Cannot store schema source " + cast.getIdentifier() + " to " + file,
254                         e);
255             }
256         }
257
258         @Override
259         public YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
260             return new YangTextSchemaSource(sourceIdentifier) {
261
262                 @Override
263                 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
264                     return toStringHelper;
265                 }
266
267                 @Override
268                 public InputStream openStream() throws IOException {
269                     return Files.newInputStream(cachedSource.toPath());
270                 }
271             };
272         }
273     }
274
275     private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
276         private final List<SourceIdentifier> cachedSchemas = Lists.newArrayList();
277
278         @Override
279         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
280             final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
281             String fileName = file.toFile().getName();
282             fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
283
284             final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
285             if (si.isPresent()) {
286                 LOG.trace("Restoring cached file {} as {}", file, si.get());
287                 cachedSchemas.add(si.get());
288             } else {
289                 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
290                         + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
291             }
292             return fileVisitResult;
293         }
294
295         private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
296             final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
297             if (matcher.matches()) {
298                 final String moduleName = matcher.group("moduleName");
299                 final String revision = matcher.group("revision");
300                 return Optional.of(RevisionSourceIdentifier.create(moduleName, Optional.fromNullable(revision)));
301             }
302             return Optional.absent();
303         }
304
305         @Override
306         public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
307             LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
308             return FileVisitResult.CONTINUE;
309         }
310
311         public List<SourceIdentifier> getCachedSchemas() {
312             return cachedSchemas;
313         }
314     }
315 }