001/*
002 * Configurate
003 * Copyright (C) zml and Configurate contributors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.spongepowered.configurate.loader;
018
019import static java.util.Objects.requireNonNull;
020import static org.spongepowered.configurate.loader.ParsingException.UNKNOWN_POS;
021
022import com.google.errorprone.annotations.ForOverride;
023import org.checkerframework.checker.nullness.qual.Nullable;
024import org.spongepowered.configurate.ConfigurateException;
025import org.spongepowered.configurate.ConfigurationNode;
026import org.spongepowered.configurate.ConfigurationOptions;
027import org.spongepowered.configurate.ScopedConfigurationNode;
028import org.spongepowered.configurate.reference.ConfigurationReference;
029import org.spongepowered.configurate.util.UnmodifiableCollections;
030
031import java.io.BufferedReader;
032import java.io.BufferedWriter;
033import java.io.File;
034import java.io.FileNotFoundException;
035import java.io.IOException;
036import java.io.InputStreamReader;
037import java.io.StringReader;
038import java.io.StringWriter;
039import java.io.Writer;
040import java.net.URL;
041import java.nio.charset.StandardCharsets;
042import java.nio.file.Files;
043import java.nio.file.NoSuchFileException;
044import java.nio.file.Path;
045import java.util.Iterator;
046import java.util.List;
047import java.util.concurrent.Callable;
048import java.util.function.UnaryOperator;
049import java.util.regex.Pattern;
050
051/**
052 * Base class for many stream-based configuration loaders. This class provides
053 * conversion from a variety of input sources to {@link BufferedReader}
054 * suppliers, providing a consistent API for loaders to read from and write to.
055 *
056 * <p>Either the source or sink may be null. If this is true, this loader may
057 * not support either loading or saving. In this case, implementing classes are
058 * expected to throw an {@link IOException} for the unsupported operation.</p>
059 *
060 * @param <N> the {@link ConfigurationNode} type produced by the loader
061 * @since 4.0.0
062 */
063public abstract class AbstractConfigurationLoader<N extends ScopedConfigurationNode<N>> implements ConfigurationLoader<N> {
064
065    /**
066     * The escape sequence used by Configurate to separate comment lines.
067     */
068    public static final String CONFIGURATE_LINE_SEPARATOR = "\n";
069
070    /**
071     * A pattern that will match line breaks in comments.
072     */
073    public static final Pattern CONFIGURATE_LINE_PATTERN = Pattern.compile(CONFIGURATE_LINE_SEPARATOR);
074
075    /**
076     * The line separator used by the system.
077     *
078     * @see System#lineSeparator()
079     */
080    protected static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator();
081
082    /**
083     * The reader source for this loader.
084     *
085     * <p>Can be null (for loaders which don't support loading!)</p>
086     */
087    protected final @Nullable Callable<BufferedReader> source;
088
089    /**
090     * The writer sink for this loader.
091     *
092     * <p>Can be null (for loaders which don't support saving!)</p>
093     */
094    protected final @Nullable Callable<BufferedWriter> sink;
095
096    /**
097     * The comment handlers defined for this loader.
098     */
099    private final List<CommentHandler> commentHandlers;
100
101    /**
102     * The mode used to read/write configuration headers.
103     */
104    private final HeaderMode headerMode;
105
106    /**
107     * The default {@link ConfigurationOptions} used by this loader.
108     */
109    private final ConfigurationOptions defaultOptions;
110
111    /**
112     * Create a loader instance from a builder.
113     *
114     * @param builder the user-configured builder
115     * @param commentHandlers supported comment formats for extracting the
116     *      configuration header
117     * @since 4.0.0
118     */
119    protected AbstractConfigurationLoader(final Builder<?, ?> builder, final CommentHandler[] commentHandlers) {
120        this.source = builder.source();
121        this.sink = builder.sink();
122        this.headerMode = builder.headerMode();
123        this.commentHandlers = UnmodifiableCollections.toList(commentHandlers);
124        this.defaultOptions = builder.defaultOptions();
125    }
126
127    /**
128     * Gets the primary {@link CommentHandler} used by this loader.
129     *
130     * @return the default comment handler
131     * @since 4.0.0
132     */
133    public CommentHandler defaultCommentHandler() {
134        return this.commentHandlers.get(0);
135    }
136
137    @Override
138    public ConfigurationReference<N> loadToReference() throws ConfigurateException {
139        return ConfigurationReference.fixed(this);
140    }
141
142    @Override
143    public N load(ConfigurationOptions options) throws ParsingException {
144        if (this.source == null) {
145            throw new ParsingException(UNKNOWN_POS, UNKNOWN_POS, "", "No source present to read from!", null);
146        }
147        try (BufferedReader reader = this.source.call()) {
148            if (this.headerMode == HeaderMode.PRESERVE || this.headerMode == HeaderMode.NONE) {
149                final @Nullable String comment = CommentHandlers.extractComment(reader, this.commentHandlers);
150                if (comment != null && comment.length() > 0) {
151                    options = options.header(comment);
152                }
153            }
154            final N node = createNode(options);
155            loadInternal(node, reader);
156            return node;
157        } catch (final ParsingException ex) {
158            throw ex;
159        } catch (final FileNotFoundException | NoSuchFileException e) {
160            // Squash -- there's nothing to read
161            return createNode(options);
162        } catch (final IOException e) {
163            throw new ParsingException(UNKNOWN_POS, UNKNOWN_POS, options.header(), null, e);
164        } catch (final Exception e) {
165            throw new ParsingException(UNKNOWN_POS, UNKNOWN_POS, options.header(), "Unknown error occurred while loading", e);
166        }
167    }
168
169    /**
170     * Using a created node, attempt to read a configuration file.
171     *
172     * <p>The header will already have been read if applicable.</p>
173     *
174     * @param node node to load into
175     * @param reader reader to load from
176     * @throws ParsingException if an error occurs at any stage of loading
177     * @since 4.0.0
178     */
179    @ForOverride
180    protected abstract void loadInternal(N node, BufferedReader reader) throws ParsingException;
181
182    @Override
183    public void save(final ConfigurationNode node) throws ConfigurateException {
184        if (this.sink == null) {
185            throw new ConfigurateException(node, "No sink present to write to!");
186        }
187        this.checkCanWrite(node);
188        try (Writer writer = this.sink.call()) {
189            writeHeaderInternal(writer);
190            if (this.headerMode != HeaderMode.NONE) {
191                final @Nullable String header = node.options().header();
192                if (header != null && !header.isEmpty()) {
193                    final Iterator<String> lines = defaultCommentHandler().toComment(CONFIGURATE_LINE_PATTERN.splitAsStream(header)).iterator();
194                    while (lines.hasNext()) {
195                        writer.write(lines.next());
196                        writer.write(SYSTEM_LINE_SEPARATOR);
197                    }
198                    writer.write(SYSTEM_LINE_SEPARATOR);
199                }
200            }
201            saveInternal(node, writer);
202        } catch (final ConfigurateException ex) {
203            throw ex;
204        } catch (final Exception ex) {
205            throw new ConfigurateException(node, ex);
206        }
207    }
208
209    /**
210     * Perform format-specific validation of a node.
211     *
212     * <p>This method will be called before a writer is opened, allowing the
213     * loader to perform any basic validation it may need to before it opens a
214     * writer replacing an existing file.</p>
215     *
216     * @param node the node to write
217     * @throws ConfigurateException if any invalid data is present
218     * @since 4.1.0
219     */
220    @ForOverride
221    protected void checkCanWrite(final ConfigurationNode node) throws ConfigurateException {}
222
223    /**
224     * Write out any implementation-specific file header.
225     *
226     * @param writer writer to output to
227     * @throws IOException if an error occurs in the implementation
228     * @since 4.0.0
229     */
230    @ForOverride
231    protected void writeHeaderInternal(final Writer writer) throws IOException {}
232
233    /**
234     * Perform a save of the node to the provided writer.
235     *
236     * @param node node to save
237     * @param writer writer to output to
238     * @throws ConfigurateException if any of the node's data is unsavable
239     * @since 4.0.0
240     */
241    @ForOverride
242    protected abstract void saveInternal(ConfigurationNode node, Writer writer) throws ConfigurateException;
243
244    @Override
245    public ConfigurationOptions defaultOptions() {
246        return this.defaultOptions;
247    }
248
249    @Override
250    public final boolean canLoad() {
251        return this.source != null;
252    }
253
254    @Override
255    public final boolean canSave() {
256        return this.sink != null;
257    }
258
259    /**
260     * An abstract builder implementation for {@link AbstractConfigurationLoader}s.
261     *
262     * @param <T> the builder's own type (for chaining using generic types)
263     * @since 4.0.0
264     */
265    public abstract static class Builder<T extends Builder<T, L>, L extends AbstractConfigurationLoader<?>> {
266        protected HeaderMode headerMode = HeaderMode.PRESERVE;
267        protected @Nullable Callable<BufferedReader> source;
268        protected @Nullable Callable<BufferedWriter> sink;
269        protected ConfigurationOptions defaultOptions = ConfigurationOptions.defaults();
270
271        /**
272         * Create a new builder.
273         *
274         * <p>This is where any custom default options can be applied.</p>
275         *
276         * @since 4.0.0
277         */
278        protected Builder() {}
279
280        @SuppressWarnings("unchecked")
281        private T self() {
282            return (T) this;
283        }
284
285        /**
286         * Sets the sink and source of the resultant loader to the given file.
287         *
288         * <p>The {@link #source() source} is defined using
289         * {@link Files#newBufferedReader(Path)} with UTF-8 encoding.</p>
290         *
291         * <p>The {@link #sink() sink} is defined using {@link AtomicFiles} with UTF-8
292         * encoding.</p>
293         *
294         * @param file the configuration file
295         * @return this builder (for chaining)
296         * @since 4.0.0
297         */
298        public T file(final File file) {
299            return path(requireNonNull(file, "file").toPath());
300        }
301
302        /**
303         * Sets the sink and source of the resultant loader to the given path.
304         *
305         * <p>The {@link #source() source} is defined using
306         * {@link Files#newBufferedReader(Path)} with UTF-8 encoding.</p>
307         *
308         * <p>The {@link #sink() sink} is defined using {@link AtomicFiles} with UTF-8
309         * encoding.</p>
310         *
311         * @param path the path of the configuration file
312         * @return this builder (for chaining)
313         * @since 4.0.0
314         */
315        public T path(final Path path) {
316            final Path absPath = requireNonNull(path, "path").toAbsolutePath();
317            this.source = () -> Files.newBufferedReader(absPath, StandardCharsets.UTF_8);
318            this.sink = AtomicFiles.atomicWriterFactory(absPath, StandardCharsets.UTF_8);
319            return self();
320        }
321
322        /**
323         * Sets the source of the resultant loader to the given URL.
324         *
325         * @param url the URL of the source
326         * @return this builder (for chaining)
327         * @since 4.0.0
328         */
329        public T url(final URL url) {
330            requireNonNull(url, "url");
331            this.source = () -> new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), StandardCharsets.UTF_8));
332            return self();
333        }
334
335        /**
336         * Sets the source of the resultant loader.
337         *
338         * <p>The "source" is used by the loader to load the configuration.</p>
339         *
340         * @param source the source
341         * @return this builder (for chaining)
342         * @since 4.0.0
343         */
344        public T source(final @Nullable Callable<BufferedReader> source) {
345            this.source = source;
346            return self();
347        }
348
349        /**
350         * Gets the source to be used by the resultant loader.
351         *
352         * @return the source
353         * @since 4.0.0
354         */
355        public @Nullable Callable<BufferedReader> source() {
356            return this.source;
357        }
358
359        /**
360         * Sets the sink of the resultant loader.
361         *
362         * <p>The "sink" is used by the loader to save the configuration.</p>
363         *
364         * @param sink the sink
365         * @return this builder (for chaining)
366         * @since 4.0.0
367         */
368        public T sink(final @Nullable Callable<BufferedWriter> sink) {
369            this.sink = sink;
370            return self();
371        }
372
373        /**
374         * Gets the sink to be used by the resultant loader.
375         *
376         * @return the sink
377         * @since 4.0.0
378         */
379        public @Nullable Callable<BufferedWriter> sink() {
380            return this.sink;
381        }
382
383        /**
384         * Sets the header mode of the resultant loader.
385         *
386         * @param mode the header mode
387         * @return this builder (for chaining)
388         * @since 4.0.0
389         */
390        public T headerMode(final HeaderMode mode) {
391            this.headerMode = requireNonNull(mode, "mode");
392            return self();
393        }
394
395        /**
396         * Gets the header mode to be used by the resultant loader.
397         *
398         * @return the header mode
399         * @since 4.0.0
400         */
401        public HeaderMode headerMode() {
402            return this.headerMode;
403        }
404
405        /**
406         * Sets the default configuration options to be used by the
407         * resultant loader.
408         *
409         * @param defaultOptions the options
410         * @return this builder (for chaining)
411         * @since 4.0.0
412         */
413        public T defaultOptions(final ConfigurationOptions defaultOptions) {
414            this.defaultOptions = requireNonNull(defaultOptions, "defaultOptions");
415            return self();
416        }
417
418        /**
419         * Sets the default configuration options to be used by the resultant
420         * loader by providing a function which takes the current default
421         * options and applies any desired changes.
422         *
423         * @param defaultOptions to transform the existing default options
424         * @return this builder (for chaining)
425         * @since 4.0.0
426         */
427        public T defaultOptions(final UnaryOperator<ConfigurationOptions> defaultOptions) {
428            this.defaultOptions = requireNonNull(defaultOptions.apply(this.defaultOptions), "defaultOptions (updated)");
429            return self();
430        }
431
432        /**
433         * Gets the default configuration options to be used by the resultant
434         * loader.
435         *
436         * @return the options
437         * @since 4.0.0
438         */
439        public ConfigurationOptions defaultOptions() {
440            return this.defaultOptions;
441        }
442
443        /**
444         * Builds the loader.
445         *
446         * @return a new loader
447         * @since 4.0.0
448         */
449        public abstract L build();
450
451        /**
452         * Configure to read from a string, build, and load in one step.
453         *
454         * @param input the input to load
455         * @return a deserialized node
456         * @since 4.1.0
457         */
458        public ConfigurationNode buildAndLoadString(final String input) throws ConfigurateException {
459            return this.source(() -> new BufferedReader(new StringReader(input)))
460                    .build()
461                    .load();
462        }
463
464        /**
465         * Configure to write to a string, build, and save in one step.
466         *
467         * @param output the node to write
468         * @return the output string
469         * @since 4.1.0
470         */
471        public String buildAndSaveString(final ConfigurationNode output) throws ConfigurateException {
472            requireNonNull(output, "output");
473            final StringWriter writer = new StringWriter();
474            this.sink(() -> new BufferedWriter(writer))
475                    .build()
476                    .save(output);
477            return writer.toString();
478        }
479
480    }
481
482}