OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
174 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils.sync;
15
 
16
import org.openconcerto.utils.CollectionUtils;
17
import org.openconcerto.utils.MessageDigestUtils;
18
import org.openconcerto.utils.StreamUtils;
19
 
20
import java.io.BufferedOutputStream;
21
import java.io.File;
22
import java.io.IOException;
23
import java.io.InputStream;
24
import java.io.OutputStream;
25
import java.io.UnsupportedEncodingException;
26
import java.net.MalformedURLException;
27
import java.net.ProtocolException;
28
import java.net.URL;
29
import java.nio.charset.StandardCharsets;
30
import java.nio.file.Files;
31
import java.nio.file.Path;
32
import java.nio.file.StandardCopyOption;
33
import java.nio.file.attribute.FileTime;
34
import java.security.DigestOutputStream;
35
import java.security.MessageDigest;
36
import java.time.Instant;
37
import java.util.ArrayList;
38
import java.util.Base64;
39
import java.util.Collections;
40
import java.util.List;
41
import java.util.Set;
42
import java.util.concurrent.atomic.AtomicBoolean;
43
import java.util.function.BiFunction;
44
import java.util.function.Predicate;
45
import java.util.zip.GZIPInputStream;
46
import java.util.zip.GZIPOutputStream;
47
 
48
import javax.net.ssl.HttpsURLConnection;
49
import javax.net.ssl.SSLSocketFactory;
50
 
51
import net.minidev.json.JSONArray;
52
import net.minidev.json.JSONObject;
53
import net.minidev.json.parser.JSONParser;
54
 
55
public final class SimpleSyncClient {
56
 
57
    private static final int MIN_GZIP_SIZE = 64;
58
 
59
    static protected final long getLong(final Object o) {
60
        return ((Number) o).longValue();
61
    }
62
 
63
    static protected final Instant getInstant(final Object o) {
64
        return Instant.ofEpochMilli(getLong(o));
65
    }
66
 
67
    static public class ServerException extends RuntimeException {
68
        private final int responseCode;
69
        private final boolean authenticateError;
70
 
71
        protected ServerException(int responseCode, boolean authenticateError) {
72
            super("Response code was " + responseCode);
73
            this.responseCode = responseCode;
74
            this.authenticateError = authenticateError;
75
        }
76
 
77
        public final int getResponseCode() {
78
            return this.responseCode;
79
        }
80
 
81
        public final boolean isAuthenticateError() {
82
            return this.authenticateError;
83
        }
84
    }
85
 
86
    static public final class Response {
87
 
88
        protected final static Response create(HttpsURLConnection con, final Set<Integer> okCodes) throws IOException {
89
            final boolean success = okCodes == null ? con.getResponseCode() == 200 : okCodes.contains(con.getResponseCode());
90
            return new Response(success, con.getResponseCode(), con.getResponseMessage(), con.getContentEncoding(), con.getContentType());
91
        }
92
 
93
        private final boolean success;
94
        private final int code;
95
        private final String message;
96
        private final String contentEncoding, contentType;
97
 
98
        protected Response(boolean success, int code, String message, String contentEncoding, String contentType) {
99
            super();
100
            this.success = success;
101
            this.code = code;
102
            this.message = message;
103
            this.contentEncoding = contentEncoding;
104
            this.contentType = contentType;
105
        }
106
 
107
        public final int getCode() {
108
            return this.code;
109
        }
110
 
111
        public final boolean isSuccess() {
112
            return this.success;
113
        }
114
 
115
        public final String getMessage() {
116
            return this.message;
117
        }
118
 
119
        public final String getContentEncoding() {
120
            return this.contentEncoding;
121
        }
122
 
123
        public final String getContentType() {
124
            return this.contentType;
125
        }
126
    }
127
 
128
    static protected abstract class BaseAttrs {
129
        private final String path;
130
        private final String name;
131
        private final Instant lastModified;
132
 
133
        protected BaseAttrs(final String path, final String name, final Instant lastModified) {
134
            super();
135
            this.path = path;
136
            this.name = name;
137
            this.lastModified = lastModified;
138
        }
139
 
140
        public final String getPath() {
141
            return this.path;
142
        }
143
 
144
        public final String getName() {
145
            return this.name;
146
        }
147
 
148
        public final Instant getLastModified() {
149
            return this.lastModified;
150
        }
151
 
152
        @Override
153
        public String toString() {
154
            return this.getClass().getSimpleName() + " '" + this.getName() + "'";
155
        }
156
    }
157
 
158
    static public final class DirAttrs extends BaseAttrs {
159
        static protected DirAttrs fromJSON(final String path, final JSONArray array) {
160
            return new DirAttrs(path, (String) array.get(0), getInstant(array.get(1)));
161
        }
162
 
163
        protected DirAttrs(final String path, String name, Instant lastModified) {
164
            super(path, name, lastModified);
165
        }
166
    }
167
 
168
    static public final class FileAttrs extends BaseAttrs {
169
 
170
        static protected FileAttrs fromJSON(final String path, final JSONArray array) {
171
            return new FileAttrs(path, (String) array.get(0), getInstant(array.get(2)), getLong(array.get(1)), (String) array.get(3));
172
        }
173
 
174
        private final long size;
175
        private final String sha256;
176
 
177
        protected FileAttrs(final String path, String name, Instant lastModified, long size, String sha256) {
178
            super(path, name, lastModified);
179
            this.size = size;
180
            this.sha256 = sha256;
181
        }
182
 
183
        public final long getSize() {
184
            return this.size;
185
        }
186
 
187
        public final String getSHA256() {
188
            return this.sha256;
189
        }
190
 
191
        public final void saveFile(final InputStream in, final Path localFile) throws IOException {
192
            // Save to temporary file to avoid overwriting old file with a new invalid one. In
193
            // same folder for the move.
194
            final Path tmpFile = Files.createTempFile(localFile.getParent(), "partial", null);
195
            try {
196
                final MessageDigest md = this.getSHA256() == null ? null : MessageDigestUtils.getSHA256();
197
                try (final BufferedOutputStream fileStream = new BufferedOutputStream(Files.newOutputStream(tmpFile));
198
                        //
199
                        final OutputStream out = md == null ? fileStream : new DigestOutputStream(fileStream, md)) {
200
                    StreamUtils.copy(in, out);
201
                }
202
                if (this.getSize() >= 0) {
203
                    final long savedSize = Files.size(tmpFile);
204
                    if (savedSize != this.getSize())
205
                        throw new IOException("Expected " + this.getSize() + " bytes but saved " + savedSize);
206
                }
207
                if (md != null) {
208
                    final String savedHash = MessageDigestUtils.getHashString(md);
209
                    if (!savedHash.equalsIgnoreCase(this.getSHA256()))
210
                        throw new IOException("Expected hash was " + this.getSHA256() + " but saved " + savedHash);
211
                }
212
                Files.move(tmpFile, localFile, StandardCopyOption.REPLACE_EXISTING);
213
            } finally {
214
                Files.deleteIfExists(tmpFile);
215
            }
216
            if (this.getLastModified().compareTo(Instant.EPOCH) > 0)
217
                Files.setLastModifiedTime(localFile, FileTime.from(this.getLastModified()));
218
        }
219
 
220
        @Override
221
        public String toString() {
222
            return super.toString() + " of size " + getSize();
223
        }
224
    }
225
 
226
    static public final class DirContent {
227
        private final String path;
228
        private final JSONObject json;
229
 
230
        protected DirContent(final String path, JSONObject json) {
231
            super();
232
            this.path = path;
233
            this.json = json;
234
        }
235
 
236
        public final List<FileAttrs> getFiles() {
237
            return this.getFiles(null);
238
        }
239
 
240
        public final List<FileAttrs> getFiles(final Predicate<String> namePredicate) {
241
            return this.getContent("files", namePredicate, FileAttrs::fromJSON);
242
        }
243
 
244
        public final List<DirAttrs> getDirs() {
245
            return this.getDirs(null);
246
        }
247
 
248
        public final List<DirAttrs> getDirs(final Predicate<String> namePredicate) {
249
            return this.getContent("dirs", namePredicate, DirAttrs::fromJSON);
250
        }
251
 
252
        protected final <T extends BaseAttrs> List<T> getContent(final String key, final Predicate<String> namePredicate, final BiFunction<String, JSONArray, T> create) {
253
            final JSONArray files = (JSONArray) this.json.get(key);
254
            if (files == null)
255
                return Collections.emptyList();
256
            final List<T> res = new ArrayList<>();
257
            for (final Object f : files) {
258
                final JSONArray array = (JSONArray) f;
259
                if (namePredicate == null || namePredicate.test((String) array.get(0))) {
260
                    res.add(create.apply(this.path, array));
261
                }
262
            }
263
            return res;
264
        }
265
    }
266
 
267
    private final String url;
268
    private SSLSocketFactory socketFactory;
269
    private String token;
270
    private boolean throwException = true;
271
 
272
    public SimpleSyncClient(final String url) {
273
        this.url = url;
274
    }
275
 
276
    public final SSLSocketFactory getSocketFactory() {
277
        return this.socketFactory;
278
    }
279
 
280
    public final void setSocketFactory(SSLSocketFactory socketFactory) {
281
        this.socketFactory = socketFactory;
282
    }
283
 
284
    public final void setToken(String token) {
285
        this.token = token;
286
    }
287
 
288
    public final boolean hasToken() {
289
        return this.getToken() != null;
290
    }
291
 
292
    protected final String getToken() {
293
        return this.token;
294
    }
295
 
296
    public final void setThrowException(boolean throwException) {
297
        this.throwException = throwException;
298
    }
299
 
300
    public final boolean throwsException() {
301
        return this.throwException;
302
    }
303
 
304
    protected Response checkResponseCode(final HttpsURLConnection con) throws IOException {
305
        return checkResponseCode(con, null);
306
    }
307
 
308
    protected Response checkResponseCode(final HttpsURLConnection con, final Set<Integer> okCodes) throws IOException {
309
        final Response res = Response.create(con, okCodes);
310
        if (this.throwsException() && !res.isSuccess())
311
            throw new ServerException(res.getCode(), con.getHeaderField("WWW-Authenticate") != null);
312
        return res;
313
    }
314
 
315
    private final HttpsURLConnection openConnection(final String path) throws IOException {
316
        final HttpsURLConnection con = (HttpsURLConnection) new URL(this.url + path).openConnection();
317
        con.setRequestProperty("Accept-Encoding", "gzip");
318
        if (this.getSocketFactory() != null)
319
            con.setSSLSocketFactory(this.getSocketFactory());
320
        if (getToken() != null)
321
            con.setRequestProperty("Authorization", "Bearer " + Base64.getEncoder().encodeToString(getToken().getBytes(StandardCharsets.UTF_8)));
322
        return con;
323
    }
324
 
325
    private final InputStream getInputStream(final HttpsURLConnection con) throws IOException {
326
        return "gzip".equals(con.getContentEncoding()) ? new GZIPInputStream(con.getInputStream()) : con.getInputStream();
327
    }
328
 
329
    private final HttpsURLConnection send(final HttpsURLConnection con, final String params) throws IOException {
330
        return this.send(con, params.getBytes(StandardCharsets.UTF_8), false);
331
    }
332
 
333
    private final HttpsURLConnection send(final HttpsURLConnection con, final byte[] toSend, final boolean allowGzip) throws IOException {
334
        final boolean useGzip = allowGzip && toSend.length >= MIN_GZIP_SIZE;
335
        if (useGzip)
336
            con.setRequestProperty("Content-Encoding", "gzip");
337
        con.setRequestMethod("POST");
338
        con.setDoOutput(true);
339
        try (final OutputStream o = useGzip ? new GZIPOutputStream(con.getOutputStream()) : con.getOutputStream()) {
340
            o.write(toSend);
341
        }
342
        return con;
343
    }
344
 
345
    public DirContent getDir(final String path) throws Exception {
346
        final HttpsURLConnection con = openConnection("/getDir");
347
        final Response res = checkResponseCode(send(con, "rp=" + path + "&type=json"));
348
        if (!res.isSuccess())
349
            return null;
350
        final JSONParser p = new JSONParser(JSONParser.MODE_STRICTEST);
351
        try (final InputStream in = getInputStream(con)) {
352
            return new DirContent(path, (JSONObject) p.parse(in));
353
        }
354
    }
355
 
356
    @FunctionalInterface
357
    static public interface FileConsumer {
358
        public void accept(FileAttrs attrs, InputStream fileStream) throws IOException;
359
    }
360
 
361
    static private final Set<Integer> GETFILE_OK_CODES = CollectionUtils.createSet(200, 404);
362
 
363
    public Response getFile(final String path, final String fileName, final FileConsumer fileConsumer) throws IOException {
364
        final HttpsURLConnection con = openConnection("/get");
365
        send(con, "rn=" + fileName + "&rp=" + path);
366
        final Response res = checkResponseCode(con, GETFILE_OK_CODES);
367
        if (res.getCode() == 404) {
368
            fileConsumer.accept(null, null);
369
        } else if (res.getCode() == 200) {
370
            final FileAttrs fileAttrs = new FileAttrs(path, fileName, Instant.ofEpochMilli(con.getLastModified()), -1, con.getHeaderField("X-SHA256"));
371
            try (final InputStream in = getInputStream(con)) {
372
                fileConsumer.accept(fileAttrs, in);
373
            }
374
        }
375
        return res;
376
    }
377
 
378
    // ATTN contrary to other methods, the result isn't if the request was OK : it ignores
379
    // throwsException() and always throws. The return value is true if the file existed and was
380
    // saved.
381
    public boolean saveFile(final String path, final String fileName, final Path localFile) throws IOException {
382
        final AtomicBoolean missing = new AtomicBoolean(true);
383
        final Response res = this.getFile(path, fileName, (fileAttrs, in) -> {
384
            missing.set(fileAttrs == null);
385
            if (!missing.get()) {
386
                fileAttrs.saveFile(in, localFile);
387
            }
388
        });
389
        if (!res.isSuccess())
390
            throw new IOException("Couldn't retrieve file " + fileName);
391
        return !missing.get();
392
    }
393
 
394
    public Response deleteFile(final String path, final String fileName) throws MalformedURLException, IOException, ProtocolException, UnsupportedEncodingException {
395
        final HttpsURLConnection con = openConnection("/delete");
396
        return checkResponseCode(send(con, "rn=" + fileName + "&rp=" + path));
397
    }
398
 
399
    public Response sendFile(String path, File localFile) throws Exception, MalformedURLException, IOException, ProtocolException {
400
        byte[] newsha256 = HashWriter.getHash(localFile);
401
        long size = localFile.length();
402
 
403
        final HttpsURLConnection con = openConnection("/put");
404
        // We use Base64 because headers are not supporting UTF8
405
        con.setRequestProperty("X_FILENAME_B64", Base64.getEncoder().encodeToString(localFile.getName().getBytes(StandardCharsets.UTF_8)));
406
        con.setRequestProperty("X_PATH_B64", Base64.getEncoder().encodeToString(path.getBytes(StandardCharsets.UTF_8)));
407
        con.setRequestProperty("X_FILESIZE", String.valueOf(size));
408
        con.setRequestProperty("X_SHA256", HashWriter.bytesToHex(newsha256));
409
        con.setRequestProperty("X-Last-Modified-ms", String.valueOf(localFile.lastModified()));
410
 
411
        return checkResponseCode(send(con, Files.readAllBytes(localFile.toPath()), true));
412
    }
413
}