All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sourceforge.plantuml.Pipe Maven / Gradle / Ivy

There is a newer version: 1.2024.8
Show newest version
// THIS FILE HAS BEEN GENERATED BY A PREPROCESSOR.
/* +=======================================================================
 * |
 * |      PlantUML : a free UML diagram generator
 * |
 * +=======================================================================
 *
 * (C) Copyright 2009-2024, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 *
 * If you like this project or if you find it useful, you can support us at:
 *
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/liberapay (only 1€ per month!)
 * https://plantuml.com/paypal
 *
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License V2.
 *
 * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
 * LICENSE ("AGREEMENT"). [GNU General Public License V2]
 *
 * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
 * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
 *
 * You may obtain a copy of the License at
 *
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * PlantUML can occasionally display sponsored or advertising messages. Those
 * messages are usually generated on welcome or error images and never on
 * functional diagrams.
 * See https://plantuml.com/professional if you want to remove them
 *
 * Images (whatever their format : PNG, SVG, EPS...) generated by running PlantUML
 * are owned by the author of their corresponding sources code (that is, their
 * textual description in PlantUML language). Those images are not covered by
 * this GPL v2 license.
 *
 * The generated images can then be used without any reference to the GPL v2 license.
 * It is not even necessary to stipulate that they have been generated with PlantUML,
 * although this will be appreciated by the PlantUML team.
 *
 * There is an exception : if the textual description in PlantUML language is also covered
 * by any license, then the generated images are logically covered
 * by the very same license.
 *
 * This is the IGY distribution (Install GraphViz by Yourself).
 * You have to install GraphViz and to setup the GRAPHVIZ_DOT environment variable
 * (see https://plantuml.com/graphviz-dot )
 *
 * Icons provided by OpenIconic :  https://useiconic.com/open
 * Archimate sprites provided by Archi :  http://www.archimatetool.com
 * Stdlib AWS provided by https://github.com/milo-minderbinder/AWS-PlantUML
 * Stdlib Icons provided https://github.com/tupadr3/plantuml-icon-font-sprites
 * ASCIIMathML (c) Peter Jipsen http://www.chapman.edu/~jipsen
 * ASCIIMathML (c) David Lippman http://www.pierce.ctc.edu/dlippman
 * CafeUndZopfli ported by Eugene Klyuchnikov https://github.com/eustas/CafeUndZopfli
 * Brotli (c) by the Brotli Authors https://github.com/google/brotli
 * Themes (c) by Brett Schwarz https://github.com/bschwarz/puml-themes
 * Twemoji (c) by Twitter at https://twemoji.twitter.com/
 *
 */
package net.sourceforge.plantuml;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.SFile;

public class Pipe {
	// ::remove file when __CORE__
	// ::remove file when __HAXE__

	private final Option option;
	private final BufferedReader br;
	private final PrintStream ps;
	private final Stdrpt stdrpt;

	public Pipe(Option option, PrintStream ps, InputStream is, String charset) {
		this.option = option;
		try {
			this.br = new BufferedReader(
					new InputStreamReader(is, (charset != null) ? charset : Charset.defaultCharset().name()));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Invalid charset provided", e);
		}
		this.ps = ps;
		this.stdrpt = option.getStdrpt();
	}

	public void managePipe(ErrorStatus error) throws IOException {
		final boolean noStdErr = option.isPipeNoStdErr();

		for (String source = readFirstDiagram(); source != null; source = readSubsequentDiagram()) {
			final Defines defines = option.getDefaultDefines();
			final SFile newCurrentDir = option.getFileDir() == null ? null : new SFile(option.getFileDir());
			final SourceStringReader sourceStringReader = new SourceStringReader(defines, source, UTF_8,
					option.getConfig(), newCurrentDir);

			if (option.isComputeurl())
				computeUrlForDiagram(sourceStringReader);
			else if (option.isSyntax())
				syntaxCheckDiagram(sourceStringReader, error);
			else if (option.isPipeMap())
				createPipeMapForDiagram(sourceStringReader, error);
			else
				generateDiagram(sourceStringReader, error, noStdErr);

			ps.flush();
		}
	}

	private void generateDiagram(SourceStringReader sourceStringReader, ErrorStatus error, boolean noStdErr)
			throws IOException {
		final OutputStream os = noStdErr ? new ByteArrayOutputStream() : ps;
		final DiagramDescription result = sourceStringReader.outputImage(os, option.getImageIndex(),
				option.getFileFormatOption());

		printInfo(noStdErr ? ps : System.err, sourceStringReader);
		if (result != null && "(error)".equalsIgnoreCase(result.getDescription())) {
			error.goWithError();
		} else {
			error.goOk();
			if (noStdErr) {
				final ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
				baos.close();
				ps.write(baos.toByteArray());
			}
		}
		if (option.getPipeDelimitor() != null)
			ps.println(option.getPipeDelimitor());

	}

	private void createPipeMapForDiagram(SourceStringReader sourceStringReader, ErrorStatus error) throws IOException {
		final String result = sourceStringReader.getCMapData(option.getImageIndex(), option.getFileFormatOption());
		// https://forum.plantuml.net/10049/2019-pipemap-diagrams-containing-links-give-zero-exit-code
		// We don't check errors
		error.goOk();
		if (result == null) {
//			final CMapData empty = new CMapData();
//			ps.println(empty.asString("plantuml"));
			ps.println();
		} else
			ps.println(result);

	}

	private void computeUrlForDiagram(SourceStringReader sourceStringReader) throws IOException {
		for (BlockUml s : sourceStringReader.getBlocks())
			ps.println(s.getEncodedUrl());

	}

	private void syntaxCheckDiagram(SourceStringReader sourceStringReader, ErrorStatus error) {
		final Diagram system = sourceStringReader.getBlocks().get(0).getDiagram();
		if (system instanceof UmlDiagram) {
			error.goOk();
			ps.println(((UmlDiagram) system).getUmlDiagramType().name());
			ps.println(system.getDescription());
		} else if (system instanceof PSystemError) {
			error.goWithError();
			stdrpt.printInfo(ps, system);
		} else {
			error.goOk();
			ps.println("OTHER");
			ps.println(system.getDescription());
		}
	}

	private void printInfo(final PrintStream output, final SourceStringReader sourceStringReader) {
		final List blocks = sourceStringReader.getBlocks();
		if (blocks.size() == 0)
			stdrpt.printInfo(output, null);
		else
			stdrpt.printInfo(output, blocks.get(0).getDiagram());

	}

	String readFirstDiagram() throws IOException {
		return readSingleDiagram(true);
	}

	String readSubsequentDiagram() throws IOException {
		return readSingleDiagram(false);
	}

	String readSingleDiagram(boolean unmarkedAllowed) throws IOException {
		State state = State.NO_CONTENT;
		String expectedEnd = null;
		final StringBuilder sb = new StringBuilder();

		String line;
		while (state != State.COMPLETE && (line = br.readLine()) != null) {

			if (line.startsWith("@@@format ")) {
				manageFormat(line);
			} else {
				if (state == State.NO_CONTENT && line.trim().length() > 0)
					state = State.START_MARK_NOT_FOUND;

				if (state == State.START_MARK_NOT_FOUND && line.startsWith("@start")) {
					sb.setLength(0); // discard any previous input
					state = State.START_MARK_FOUND;
					final Matcher m = Pattern.compile("@start([A-Za-z]*)").matcher(line);
					if (m.matches())
						expectedEnd = "@end" + m.group(1);
					else
						expectedEnd = "@end";

				} else if (state == State.START_MARK_FOUND && line.startsWith(expectedEnd)) {
					state = State.COMPLETE;
				}

				if (state != State.NO_CONTENT)
					sb.append(line).append("\n");

			}
		}

		switch (state) {
		case NO_CONTENT:
			return null;
		case START_MARK_NOT_FOUND:
			return (unmarkedAllowed) ? "@startuml\n" + sb.toString() + "@enduml\n" : null;
		case START_MARK_FOUND:
			return sb.toString() + expectedEnd;
		case COMPLETE:
			return sb.toString();
		default:
			throw new IllegalStateException("Unexpected value: " + state);
		}
	}

	void manageFormat(String s) {
		s = s.toLowerCase();
		if (s.contains("png"))
			option.setFileFormatOption(new FileFormatOption(FileFormat.PNG));
		else if (s.contains("svg"))
			option.setFileFormatOption(new FileFormatOption(FileFormat.SVG));
		else if (s.contains("atxt"))
			option.setFileFormatOption(new FileFormatOption(FileFormat.ATXT));
		else if (s.contains("utxt"))
			option.setFileFormatOption(new FileFormatOption(FileFormat.UTXT));
	}

	enum State {
		NO_CONTENT, START_MARK_NOT_FOUND, START_MARK_FOUND, COMPLETE
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy