Fix license header violations in yang-parser-api
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / repo / FilesystemSchemaCachingProvider.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/eplv10.html
7  */
8 package org.opendaylight.yangtools.yang.model.util.repo;
9
10 import com.google.common.base.Charsets;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import java.io.ByteArrayInputStream;
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.FileNotFoundException;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStreamWriter;
22 import java.util.regex.Pattern;
23 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Filesystem-based schema caching source provider
29  *
30  * This schema source provider caches all YANG modules loaded from backing
31  * schema source providers (registered via
32  * {@link #createInstanceFor(SchemaSourceProvider)} to supplied folder.
33  *
34  * @param <I>
35  *            Input format in which schema source is represented.
36  *
37  * @deprecated Replaced with {@link org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache}
38  *
39  */
40 @Deprecated
41 public final class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
42     private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaCachingProvider.class);
43     public static final Pattern REVISION_PATTERN = Pattern.compile("\\d\\d\\d\\d-\\d\\d-\\d\\d");
44
45     private final File storageDirectory;
46     private final SchemaSourceTransformation<I, String> transformationFunction;
47
48     /**
49      *
50      * Construct filesystem caching schema source provider.
51      *
52      *
53      * @param delegate
54      *            Default delegate to lookup for missed entries in cache.
55      * @param directory
56      *            Directory where YANG files should be cached.
57      * @param transformationFunction
58      *            Transformation function which translates from input in format
59      *            <code>I</code> to InputStream.
60      * @throws IllegalArgumentException
61      *             If supplied directory does not exists or is not directory.
62      */
63     public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
64             final SchemaSourceTransformation<I, String> transformationFunction) {
65         super(delegate);
66         Preconditions.checkNotNull(directory, "directory must not be null.");
67         Preconditions.checkArgument(directory.exists(), "directory must be directory.");
68         Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
69         this.storageDirectory = directory;
70         this.transformationFunction = Preconditions.checkNotNull(transformationFunction,
71                 "transformationFunction must not be null.");
72     }
73
74     /**
75      *
76      * Construct filesystem caching schema source provider.
77      *
78      *
79      * @param delegate
80      *            Default delegate to lookup for missed entries in cache.
81      * @param directory
82      *            Directory where YANG files should be cached.
83      * @param transformationFunction
84      *            Transformation function which translates from input in format
85      *            <code>I</code> to InputStream.
86      * @throws IllegalArgumentException
87      *             If supplied directory does not exists or is not directory.
88      * @deprecated Use
89      *             {@link #FilesystemSchemaCachingProvider(AdvancedSchemaSourceProvider, File, SchemaSourceTransformation)}
90      *             with
91      *             {@link SchemaSourceProviders#schemaSourceTransformationFrom(Function)}
92      *             instead.
93      */
94     @Deprecated
95     public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
96             final Function<I, String> transformationFunction) {
97         super(delegate);
98         Preconditions.checkNotNull(directory, "directory must not be null.");
99         Preconditions.checkArgument(directory.exists(), "directory must be directory.");
100         Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
101         this.storageDirectory = directory;
102         this.transformationFunction = SchemaSourceProviders.schemaSourceTransformationFrom(transformationFunction);
103     }
104
105     @Override
106     protected synchronized Optional<InputStream> cacheSchemaSource(final SourceIdentifier identifier,
107             final Optional<I> source) {
108         File schemaFile = toFile(identifier);
109         try {
110             if (source.isPresent() && schemaFile.createNewFile()) {
111                 try (FileOutputStream outStream = new FileOutputStream(schemaFile);
112                         OutputStreamWriter writer = new OutputStreamWriter(outStream);) {
113                     writer.write(transformToString(source.get()));
114                     writer.flush();
115                 } catch (IOException e) {
116                     LOG.warn("Could not chache source for {}. Source: ",identifier,source.get(),e);
117                 }
118             }
119         } catch (IOException e) {
120             LOG.warn("Could not create cache file for {}. File: ",identifier,schemaFile,e);
121         }
122         return transformToStream(source);
123     }
124
125     private Optional<InputStream> transformToStream(final Optional<I> source) {
126         if (source.isPresent()) {
127             return Optional.<InputStream> of(new ByteArrayInputStream(transformToString(source.get()).getBytes(
128                     Charsets.UTF_8)));
129         }
130         return Optional.absent();
131     }
132
133     private String transformToString(final I input) {
134         return transformationFunction.transform(input);
135     }
136
137     @Override
138     protected Optional<InputStream> getCachedSchemaSource(final SourceIdentifier identifier) {
139         File inputFile = toFile(identifier);
140         try {
141             if (inputFile.exists() && inputFile.canRead()) {
142                 InputStream stream = new FileInputStream(inputFile);
143                 return Optional.of(stream);
144             }
145         } catch (FileNotFoundException e) {
146             return Optional.absent();
147         }
148         return Optional.absent();
149     }
150
151     private File toFile(final SourceIdentifier identifier) {
152         return sourceIdToFile(identifier, storageDirectory);
153     }
154
155     public static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
156         org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier newIdentifier =
157                 org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier.create(identifier.getName(), Optional.fromNullable(identifier.getRevision()));
158         return FilesystemSchemaSourceCache.sourceIdToFile(newIdentifier, storageDirectory);
159     }
160
161     public static FilesystemSchemaCachingProvider<String> createFromStringSourceProvider(
162             final SchemaSourceProvider<String> liveProvider, final File directory) {
163         Preconditions.checkNotNull(liveProvider);
164         Preconditions.checkNotNull(directory);
165         directory.mkdirs();
166         return new FilesystemSchemaCachingProvider<String>(
167                 SchemaSourceProviders.toAdvancedSchemaSourceProvider(liveProvider),//
168                 directory, //
169                 SchemaSourceProviders.<String>identityTransformation());
170     }
171 }