Add generalized FileGenerator interface
[yangtools.git] / plugin / plugin-generator-api / src / main / java / org / opendaylight / yangtools / plugin / generator / api / AbstractGeneratedTextFile.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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/epl-v10.html
7  */
8 package org.opendaylight.yangtools.plugin.generator.api;
9
10 import com.google.common.annotations.Beta;
11 import java.io.BufferedWriter;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.io.OutputStreamWriter;
15 import java.io.Writer;
16 import java.nio.charset.StandardCharsets;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * The contents of a generated file and its {@link GeneratedFileLifecycle}. This class is suitable for text files,
21  * for binary files see {@link AbstractGeneratedFile}. Text files are encoded in {@link StandardCharsets#UTF_8}.
22  *
23  * @author Robert Varga
24  */
25 @Beta
26 @NonNullByDefault
27 public abstract class AbstractGeneratedTextFile extends AbstractGeneratedFile {
28     protected AbstractGeneratedTextFile(final GeneratedFileLifecycle lifecycle) {
29         super(lifecycle);
30     }
31
32     @Override
33     public final void writeBody(final OutputStream output) throws IOException {
34         try (Writer writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
35             try (BufferedWriter buffered = new BufferedWriter(writer)) {
36                 writeBody(buffered);
37             }
38         }
39     }
40
41     /**
42      * Write the body of this file into specified {@link Writer}.
43      *
44      * @param output writer where to write the output
45      * @throws IOException when the stream reports an IOException
46      */
47     protected abstract void writeBody(Writer output) throws IOException;
48 }