1 package org.opendaylight.yangtools.yang.model.util.repo;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStreamWriter;
10 import java.io.StringBufferInputStream;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
16 public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
18 private final File storageDirectory;
19 private final Function<I, String> transformationFunction;
21 public FilesystemSchemaCachingProvider(SchemaSourceProvider<I> delegate, File directory,
22 Function<I, String> transformationFunction) {
24 this.storageDirectory = directory;
25 this.transformationFunction = transformationFunction;
29 protected synchronized Optional<InputStream> cacheSchemaSource(SourceIdentifier identifier, Optional<I> source) {
30 File schemaFile = toFile(identifier);
32 if(source.isPresent() && schemaFile.createNewFile()) {
34 FileOutputStream outStream = new FileOutputStream(schemaFile);
35 OutputStreamWriter writer = new OutputStreamWriter(outStream);
37 writer.write(transformToString(source.get()));
39 } catch (IOException e) {
43 } catch (IOException e){
46 return transformToStream(source);
49 @SuppressWarnings("deprecation")
50 private Optional<InputStream> transformToStream(Optional<I> source) {
51 if(source.isPresent()) {
52 return Optional.<InputStream>of(new StringBufferInputStream(transformToString(source.get())));
54 return Optional.absent();
57 private String transformToString(I input) {
58 return transformationFunction.apply(input);
62 protected Optional<InputStream> getCachedSchemaSource(SourceIdentifier identifier) {
63 File inputFile = toFile(identifier);
65 if (inputFile.exists() && inputFile.canRead()) {
66 InputStream stream = new FileInputStream(inputFile);
67 return Optional.of(stream);
69 } catch (FileNotFoundException e) {
70 return Optional.absent();
72 return Optional.absent();
75 private File toFile(SourceIdentifier identifier) {
76 return new File(storageDirectory, identifier.toYangFilename());
81 private static final Function<String, String> NOOP_TRANSFORMATION = new Function<String, String>() {
83 public String apply(String input) {
88 public static FilesystemSchemaCachingProvider<String> createFromStringSourceProvider(
89 SchemaSourceProvider<String> liveProvider, File directory) {
90 Preconditions.checkNotNull(liveProvider);
91 Preconditions.checkNotNull(directory);
93 return new FilesystemSchemaCachingProvider<String>(liveProvider, directory,NOOP_TRANSFORMATION);