aboutsummaryrefslogtreecommitdiffstats
path: root/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationFile.java
blob: 160b8a3d43b8af523dbe615fdbf6d7bdfdc70e3a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.application.provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.config.application.api.ApplicationFile;
import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.util.ConfigUtils;
import com.yahoo.yolean.Exceptions;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Ulf Lilleengen
 * @author Vegard Havdal
 */
public class FilesApplicationFile extends ApplicationFile {

    private static final Logger log = Logger.getLogger("FilesApplicationFile");
    private final File file;
    private final ObjectMapper mapper = new ObjectMapper();

    public FilesApplicationFile(Path path, File file) {
        super(path);
        this.file = file;
    }

    @Override
    public boolean isDirectory() {
        return file.isDirectory();
    }

    @Override
    public boolean exists() {
        return file.exists();
    }

    @Override
    public ApplicationFile delete() {
        log.log(Level.FINE, () -> "Delete " + file);
        if (file.isDirectory() && !listFiles().isEmpty()) {
            throw new RuntimeException("files. Can't delete, directory not empty: " + this  + "(" + listFiles() + ")." + listFiles().size());
        }
        if (file.isDirectory() && file.listFiles() != null && file.listFiles().length > 0) {
            for (File f : file.listFiles()) {
                deleteFile(f);
            }
        }
        if (!file.delete()) {
            throw new IllegalStateException("Unable to delete: "+this);
        }
        try {
            writeMetaFile("", ApplicationFile.ContentStatusDeleted);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return this;
    }


    public static boolean deleteFile(File path) {
        if( path.exists() ) {
            if (path.isDirectory()) {
                File[] files = path.listFiles();
                for(int i=0; i<files.length; i++) {
                    if(files[i].isDirectory()) {
                        deleteFile(files[i]);
                    } else {
                        files[i].delete();
                    }
                }
            }
        }
        return(path.delete());
    }

    @Override
    public Reader createReader() throws FileNotFoundException {
        return new FileReader(file);
    }

    @Override
    public InputStream createInputStream() throws FileNotFoundException {
        return new FileInputStream(file);
    }

    @Override
    public ApplicationFile createDirectory() {
        if (file.isDirectory()) return this;
        if (file.exists()) {
            throw new IllegalArgumentException("Unable to create directory, file exists: "+file);
        }
        if (!file.mkdirs()) {
            throw new IllegalArgumentException("Unable to create directory: "+file);
        }
        try {
            writeMetaFile("", ApplicationFile.ContentStatusNew);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return this;
    }

    @Override
    public ApplicationFile writeFile(Reader input) {
        if (file.getParentFile() != null) {
            file.getParentFile().mkdirs();
        }
        try {
            String status = file.exists() ? ApplicationFile.ContentStatusChanged : ApplicationFile.ContentStatusNew;
            String data = com.yahoo.io.IOUtils.readAll(input);
            IOUtils.writeFile(file, data, false);
            writeMetaFile(data, status);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return this;
    }

    @Override
    public ApplicationFile appendFile(String value) {
        if (file.getParentFile() != null) {
            file.getParentFile().mkdirs();
        }
        try {
            String status = file.exists() ? ApplicationFile.ContentStatusChanged : ApplicationFile.ContentStatusNew;
            IOUtils.writeFile(file, value, true);
            writeMetaFile(value, status);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return this;
    }

    @Override
    public List<ApplicationFile> listFiles(final PathFilter filter) {
        List<ApplicationFile> files = new ArrayList<>();
        if (!file.isDirectory()) {
            return files;
        }
        FileFilter fileFilter = pathname -> filter.accept(path.append(pathname.getName()));
        for (File child : file.listFiles(fileFilter)) {
            // Ignore dot-files.
            if (!child.getName().startsWith(".")) {
                files.add(new FilesApplicationFile(path.append(child.getName()), child));
            }
        }
        return files;
    }

    private void writeMetaFile(String data, String status) throws IOException {
        File metaDir = createMetaDir();
        log.log(Level.FINE, () -> "meta dir=" + metaDir);
        File metaFile = new File(metaDir + "/" + getPath().getName());
        if (status == null) {
            status = ApplicationFile.ContentStatusNew;
            if (metaFile.exists()) {
                status = ApplicationFile.ContentStatusChanged;
            }
        }
        String hash;
        if (file.isDirectory() || status.equals(ApplicationFile.ContentStatusDeleted)) {
            hash = "";
        } else {
            hash = ConfigUtils.getMd5(data);
        }
        mapper.writeValue(metaFile, new MetaData(status, hash));
    }

    private File createMetaDir() {
        File metaDir = getMetaDir();
        if (!metaDir.exists()) {
            log.log(Level.FINE, () -> "Creating meta dir " + metaDir);
            metaDir.mkdirs();
        }
        return metaDir;
    }

    private File getMetaDir() {
        String substring = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1);
        return new File(substring + Path.fromString(".meta/"));
    }

    public MetaData getMetaData() {
        File metaDir = getMetaDir();
        File metaFile = new File(metaDir + "/" + getPath().getName());
        log.log(Level.FINE, () -> "Getting metadata for " + metaFile);
        if (metaFile.exists()) {
            try {
                return mapper.readValue(metaFile, MetaData.class);
            } catch (IOException e) {
                System.out.println("whot:" + Exceptions.toMessageString(e));
                // return below
            }
        }
        try {
            if (file.isDirectory()) {
                return new MetaData(ApplicationFile.ContentStatusNew, "");
            } else {
                return new MetaData(ApplicationFile.ContentStatusNew, ConfigUtils.getMd5(IOUtils.readAll(createReader())));
            }
        } catch (IOException | IllegalArgumentException e) {
            return null;
        }
    }

    @Override public long getSize() { return file.length(); }

    @Override
    public int compareTo(ApplicationFile other) {
        if (other == this) return 0;
        return this.getPath().getName().compareTo((other).getPath().getName());
    }

}