1
0
mirror of https://github.com/octoleo/plantuml.git synced 2024-12-22 10:59:01 +00:00

version 1.2020.11

This commit is contained in:
Arnaud Roques 2020-05-30 17:20:23 +02:00
parent 9ba7d08d52
commit 3192fa218c
181 changed files with 2584 additions and 2490 deletions

View File

@ -35,7 +35,7 @@
<groupId>net.sourceforge.plantuml</groupId> <groupId>net.sourceforge.plantuml</groupId>
<artifactId>plantuml</artifactId> <artifactId>plantuml</artifactId>
<version>1.2020.11-SNAPSHOT</version> <version>1.2020.12-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>PlantUML</name> <name>PlantUML</name>

View File

@ -3,11 +3,10 @@ package ext.plantuml.com.ctreber.acearth.gui;
import java.awt.Color; import java.awt.Color;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import javax.imageio.ImageIO; import net.sourceforge.plantuml.security.ImageIO;
import ext.plantuml.com.ctreber.acearth.renderer.RenderTarget; import ext.plantuml.com.ctreber.acearth.renderer.RenderTarget;
@ -30,17 +29,15 @@ public class PixelCanvas implements RenderTarget {
* <p> * <p>
* Construct a canvas of the specified size. * Construct a canvas of the specified size.
* *
* @param pWidth * @param pWidth Width
* Width * @param pHeight Height
* @param pHeight
* Height
*/ */
public PixelCanvas(int pWidth, int pHeight) { public PixelCanvas(int pWidth, int pHeight) {
fImageWidth = pWidth; fImageWidth = pWidth;
fImageHeight = pHeight; fImageHeight = pHeight;
fEarthImage2 = new BufferedImage(fImageWidth, fImageHeight, BufferedImage.TYPE_INT_RGB); fEarthImage2 = new BufferedImage(fImageWidth, fImageHeight, BufferedImage.TYPE_INT_RGB);
} }
public Graphics2D getGraphics2D() { public Graphics2D getGraphics2D() {
return fEarthImage2.createGraphics(); return fEarthImage2.createGraphics();
} }
@ -61,10 +58,6 @@ public class PixelCanvas implements RenderTarget {
return fImageHeight; return fImageHeight;
} }
public boolean saveToImage(String pFileName, String pFormat) throws IOException {
return ImageIO.write(fEarthImage2, pFormat, new File(pFileName));
}
public void saveToImage(OutputStream os) throws IOException { public void saveToImage(OutputStream os) throws IOException {
ImageIO.write(fEarthImage2, "png", os); ImageIO.write(fEarthImage2, "png", os);
} }

View File

@ -17,11 +17,6 @@
package ext.plantuml.com.google.zxing.client.j2se; package ext.plantuml.com.google.zxing.client.j2se;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import ext.plantuml.com.google.zxing.common.BitMatrix; import ext.plantuml.com.google.zxing.common.BitMatrix;

View File

@ -18,8 +18,6 @@
*/ */
package jcckit.util; package jcckit.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties; import java.util.Properties;
/** /**
@ -31,19 +29,6 @@ import java.util.Properties;
public class PropertiesBasedConfigData extends FlatConfigData { public class PropertiesBasedConfigData extends FlatConfigData {
private final Properties _properties; private final Properties _properties;
/**
* Creates an instance from the specified <tt>.properties</tt> file.
* @param fileName File name of the <tt>.properties</tt> file relative
* to the working directory or absolute.
* @throws IOException if the <tt>.properties</tt> does not exist or could
* not be read.
*/
public PropertiesBasedConfigData(String fileName) throws IOException {
super(null);
_properties = new Properties();
_properties.load(new FileInputStream(fileName));
}
/** /**
* Creates an instance based on the specified properties. * Creates an instance based on the specified properties.
* The path is undefined. * The path is undefined.

View File

@ -35,20 +35,21 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import net.sourceforge.plantuml.security.SFile;
public interface AFile { public interface AFile {
public InputStream open() throws IOException; public InputStream openFile();
public boolean isOk(); public boolean isOk();
public AParentFolder getParentFile(); public AParentFolder getParentFile();
public File getUnderlyingFile(); public SFile getUnderlyingFile();
public File getSystemFolder() throws IOException; public SFile getSystemFolder() throws IOException;
} }

View File

@ -35,26 +35,26 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import net.sourceforge.plantuml.security.SFile;
public class AFileRegular implements AFile { public class AFileRegular implements AFile {
private final File file; private final SFile file;
@Override @Override
public String toString() { public String toString() {
return "AFileRegular::" + file; return "AFileRegular::" + file.getAbsolutePath();
} }
public AFileRegular(File file) { public AFileRegular(SFile file) {
this.file = file; this.file = file;
} }
public InputStream open() throws IOException { public InputStream openFile() {
return new FileInputStream(file); return file.openFile();
} }
public boolean isOk() { public boolean isOk() {
@ -78,11 +78,11 @@ public class AFileRegular implements AFile {
return new AParentFolderRegular(file.getParentFile()); return new AParentFolderRegular(file.getParentFile());
} }
public File getUnderlyingFile() { public SFile getUnderlyingFile() {
return file; return file;
} }
public File getSystemFolder() throws IOException { public SFile getSystemFolder() throws IOException {
return file.getParentFile().getCanonicalFile(); return file.getParentFile().getCanonicalFile();
} }

View File

@ -35,60 +35,60 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import net.sourceforge.plantuml.security.SFile;
public class AFileZipEntry implements AFile { public class AFileZipEntry implements AFile {
private final File zipFile; private final SFile zipFile;
private final String entry; private final String entry;
public AFileZipEntry(File file, String entry) { public AFileZipEntry(SFile file, String entry) {
this.zipFile = file; this.zipFile = file;
this.entry = entry; this.entry = entry;
} }
@Override @Override
public String toString() { public String toString() {
return "AFileZipEntry::" + zipFile + " " + entry; return "AFileZipEntry::" + zipFile.getAbsolutePath() + " " + entry;
} }
public InputStream open() throws IOException { public InputStream openFile() {
final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); final InputStream tmp = zipFile.openFile();
ZipEntry ze = zis.getNextEntry(); if (tmp != null)
try {
final ZipInputStream zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry();
while (ze != null) { while (ze != null) {
final String fileName = ze.getName(); final String fileName = ze.getName();
if (ze.isDirectory()) { if (ze.isDirectory()) {
} else if (fileName.trim().equalsIgnoreCase(entry.trim())) { } else if (fileName.trim().equalsIgnoreCase(entry.trim())) {
return zis; return zis;
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (IOException e) {
e.printStackTrace();
} }
ze = zis.getNextEntry(); return null;
}
zis.closeEntry();
zis.close();
throw new IOException();
} }
public boolean isOk() { public boolean isOk() {
if (zipFile.exists() && zipFile.isDirectory() == false) { if (zipFile.exists() && zipFile.isDirectory() == false) {
InputStream is = null; final InputStream is = openFile();
try { if (is != null) {
is = open();
return true;
} catch (IOException e) {
// e.printStackTrace();
} finally {
try { try {
if (is != null) { is.close();
is.close(); return true;
} } catch (IOException e) {
} catch (IOException e1) { e.printStackTrace();
e1.printStackTrace();
} }
} }
} }
@ -113,11 +113,11 @@ public class AFileZipEntry implements AFile {
return new AParentFolderZip(zipFile, entry); return new AParentFolderZip(zipFile, entry);
} }
public File getUnderlyingFile() { public SFile getUnderlyingFile() {
return zipFile; return zipFile;
} }
public File getSystemFolder() throws IOException { public SFile getSystemFolder() throws IOException {
return zipFile.getParentFile().getCanonicalFile(); return zipFile.getParentFile().getCanonicalFile();
} }

View File

@ -35,31 +35,32 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import net.sourceforge.plantuml.security.SFile;
public class AParentFolderRegular implements AParentFolder { public class AParentFolderRegular implements AParentFolder {
private final File dir; private final SFile dir;
public AParentFolderRegular(File dir) { public AParentFolderRegular(SFile dir) {
this.dir = dir; this.dir = dir;
// Log.info("Creating AParentFolderRegular " + dir); // Log.info("Creating AParentFolderRegular " + dir);
} }
@Override @Override
public String toString() { public String toString() {
return "AParentFolderRegular::" + (dir == null ? "NULL" : dir.getAbsolutePath()); return "AParentFolderRegular::" + (dir == null ? "NULL" : dir.getPrintablePath());
} }
public AFile getAFile(String nameOrPath) throws IOException { public AFile getAFile(String nameOrPath) throws IOException {
final File filecurrent; final SFile filecurrent;
// Log.info("AParentFolderRegular::looking for " + nameOrPath); // Log.info("AParentFolderRegular::looking for " + nameOrPath);
// Log.info("AParentFolderRegular::dir = " + dir); // Log.info("AParentFolderRegular::dir = " + dir);
if (dir == null) { if (dir == null) {
filecurrent = new File(nameOrPath); filecurrent = new SFile(nameOrPath);
} else { } else {
filecurrent = new File(dir.getAbsoluteFile(), nameOrPath); filecurrent = dir.getAbsoluteFile().file(nameOrPath);
} }
// Log.info("AParentFolderRegular::Filecurrent " + filecurrent); // Log.info("AParentFolderRegular::Filecurrent " + filecurrent);
if (filecurrent.exists()) { if (filecurrent.exists()) {

View File

@ -35,12 +35,13 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import net.sourceforge.plantuml.security.SFile;
public class AParentFolderZip implements AParentFolder { public class AParentFolderZip implements AParentFolder {
private final File zipFile; private final SFile zipFile;
private final String parent; private final String parent;
@Override @Override
@ -48,7 +49,7 @@ public class AParentFolderZip implements AParentFolder {
return "AParentFolderZip::" + zipFile + " " + parent; return "AParentFolderZip::" + zipFile + " " + parent;
} }
public AParentFolderZip(File zipFile, String entry) { public AParentFolderZip(SFile zipFile, String entry) {
this.zipFile = zipFile; this.zipFile = zipFile;
final int idx = entry.lastIndexOf('/'); final int idx = entry.lastIndexOf('/');
if (idx == -1) { if (idx == -1) {

View File

@ -39,8 +39,6 @@ import java.awt.Color;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte; import java.awt.image.DataBufferByte;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@ -112,23 +110,20 @@ public class AnimatedGifEncoder {
protected int sample = 10; // default sample interval for quantizer protected int sample = 10; // default sample interval for quantizer
/** /**
* Sets the delay time between each frame, or changes it for subsequent * Sets the delay time between each frame, or changes it for subsequent frames
* frames (applies to last frame added). * (applies to last frame added).
* *
* @param ms * @param ms int delay time in milliseconds
* int delay time in milliseconds
*/ */
public void setDelay(int ms) { public void setDelay(int ms) {
delay = Math.round(ms / 10.0f); delay = Math.round(ms / 10.0f);
} }
/** /**
* Sets the GIF frame disposal code for the last added frame and any * Sets the GIF frame disposal code for the last added frame and any subsequent
* subsequent frames. Default is 0 if no transparent color has been set, * frames. Default is 0 if no transparent color has been set, otherwise 2.
* otherwise 2.
* *
* @param code * @param code int disposal code.
* int disposal code.
*/ */
public void setDispose(int code) { public void setDispose(int code) {
if (code >= 0) { if (code >= 0) {
@ -137,12 +132,11 @@ public class AnimatedGifEncoder {
} }
/** /**
* Sets the number of times the set of GIF frames should be played. Default * Sets the number of times the set of GIF frames should be played. Default is
* is 1; 0 means play indefinitely. Must be invoked before the first image * 1; 0 means play indefinitely. Must be invoked before the first image is
* is added. * added.
* *
* @param iter * @param iter int number of iterations.
* int number of iterations.
*/ */
public void setRepeat(int iter) { public void setRepeat(int iter) {
if (iter >= 0) { if (iter >= 0) {
@ -153,26 +147,24 @@ public class AnimatedGifEncoder {
/** /**
* Sets the transparent color for the last added frame and any subsequent * Sets the transparent color for the last added frame and any subsequent
* frames. Since all colors are subject to modification in the quantization * frames. Since all colors are subject to modification in the quantization
* process, the color in the final palette for each frame closest to the * process, the color in the final palette for each frame closest to the given
* given color becomes the transparent color for that frame. May be set to * color becomes the transparent color for that frame. May be set to null to
* null to indicate no transparent color. * indicate no transparent color.
* *
* @param c * @param c Color to be treated as transparent on display.
* Color to be treated as transparent on display.
*/ */
public void setTransparent(Color c) { public void setTransparent(Color c) {
transparent = c; transparent = c;
} }
/** /**
* Adds next GIF frame. The frame is not written immediately, but is * Adds next GIF frame. The frame is not written immediately, but is actually
* actually deferred until the next frame is received so that timing data * deferred until the next frame is received so that timing data can be
* can be inserted. Invoking <code>finish()</code> flushes all frames. If * inserted. Invoking <code>finish()</code> flushes all frames. If
* <code>setSize</code> was not invoked, the size of the first image is * <code>setSize</code> was not invoked, the size of the first image is used for
* used for all subsequent frames. * all subsequent frames.
* *
* @param im * @param im BufferedImage containing frame to write.
* BufferedImage containing frame to write.
* @return true if successful. * @return true if successful.
*/ */
public boolean addFrame(BufferedImage im) { public boolean addFrame(BufferedImage im) {
@ -246,8 +238,7 @@ public class AnimatedGifEncoder {
* Sets frame rate in frames per second. Equivalent to * Sets frame rate in frames per second. Equivalent to
* <code>setDelay(1000/fps)</code>. * <code>setDelay(1000/fps)</code>.
* *
* @param fps * @param fps float frame rate (frames per second)
* float frame rate (frames per second)
*/ */
public void setFrameRate(float fps) { public void setFrameRate(float fps) {
if (fps != 0f) { if (fps != 0f) {
@ -256,14 +247,13 @@ public class AnimatedGifEncoder {
} }
/** /**
* Sets quality of color quantization (conversion of images to the maximum * Sets quality of color quantization (conversion of images to the maximum 256
* 256 colors allowed by the GIF specification). Lower values (minimum = 1) * colors allowed by the GIF specification). Lower values (minimum = 1) produce
* produce better colors, but slow processing significantly. 10 is the * better colors, but slow processing significantly. 10 is the default, and
* default, and produces good color mapping at reasonable speeds. Values * produces good color mapping at reasonable speeds. Values greater than 20 do
* greater than 20 do not yield significant improvements in speed. * not yield significant improvements in speed.
* *
* @param quality * @param quality int greater than 0.
* int greater than 0.
*/ */
public void setQuality(int quality) { public void setQuality(int quality) {
if (quality < 1) if (quality < 1)
@ -275,10 +265,8 @@ public class AnimatedGifEncoder {
* Sets the GIF frame size. The default size is the size of the first frame * Sets the GIF frame size. The default size is the size of the first frame
* added if this method is not invoked. * added if this method is not invoked.
* *
* @param w * @param w int frame width.
* int frame width. * @param h int frame width.
* @param h
* int frame width.
*/ */
public void setSize(int w, int h) { public void setSize(int w, int h) {
if (started && !firstFrame) if (started && !firstFrame)
@ -296,8 +284,7 @@ public class AnimatedGifEncoder {
* Initiates GIF file creation on the given stream. The stream is not closed * Initiates GIF file creation on the given stream. The stream is not closed
* automatically. * automatically.
* *
* @param os * @param os OutputStream on which GIF images are written.
* OutputStream on which GIF images are written.
* @return false if initial write failed. * @return false if initial write failed.
*/ */
public boolean start(OutputStream os) { public boolean start(OutputStream os) {
@ -314,24 +301,23 @@ public class AnimatedGifEncoder {
return started = ok; return started = ok;
} }
/** // /**
* Initiates writing of a GIF file with the specified name. // * Initiates writing of a GIF file with the specified name.
* // *
* @param file // * @param file String containing output file name.
* String containing output file name. // * @return false if open or initial write failed.
* @return false if open or initial write failed. // */
*/ // public boolean start(String file) {
public boolean start(String file) { // boolean ok = true;
boolean ok = true; // try {
try { // out = SecurityUtils.createBufferedOutputStream(file);
out = new BufferedOutputStream(new FileOutputStream(file)); // ok = start(out);
ok = start(out); // closeStream = true;
closeStream = true; // } catch (IOException e) {
} catch (IOException e) { // ok = false;
ok = false; // }
} // return started = ok;
return started = ok; // }
}
/** /**
* Analyzes image colors and creates color map. * Analyzes image colors and creates color map.
@ -576,9 +562,9 @@ class NeuQuant {
/* /*
* Program Skeleton ---------------- [select samplefac in range 1..30] [read * Program Skeleton ---------------- [select samplefac in range 1..30] [read
* image from input file] pic = (unsigned char*) malloc(3*width*height); * image from input file] pic = (unsigned char*) malloc(3*width*height);
* initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write * initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output
* output image header, using writecolourmap(f)] inxbuild(); write output * image header, using writecolourmap(f)] inxbuild(); write output image using
* image using inxsearch(b,g,r) * inxsearch(b,g,r)
*/ */
/* /*
@ -608,8 +594,7 @@ class NeuQuant {
/* defs for decreasing radius factor */ /* defs for decreasing radius factor */
protected static final int initrad = (netsize >> 3); /* protected static final int initrad = (netsize >> 3); /*
* for 256 cols, * for 256 cols, radius starts
* radius starts
*/ */
protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */ protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */
@ -617,9 +602,7 @@ class NeuQuant {
protected static final int radiusbias = (((int) 1) << radiusbiasshift); protected static final int radiusbias = (((int) 1) << radiusbiasshift);
protected static final int initradius = (initrad * radiusbias); /* protected static final int initradius = (initrad * radiusbias); /*
* and * and decreases by a
* decreases
* by a
*/ */
protected static final int radiusdec = 30; /* factor of 1/30 each cycle */ protected static final int radiusdec = 30; /* factor of 1/30 each cycle */
@ -707,7 +690,8 @@ class NeuQuant {
/* /*
* Insertion sort of network and building of netindex[0..255] (to do after * Insertion sort of network and building of netindex[0..255] (to do after
* unbias) * unbias)
* ------------------------------------------------------------------------------- * -----------------------------------------------------------------------------
* --
*/ */
public void inxbuild() { public void inxbuild() {
@ -837,8 +821,7 @@ class NeuQuant {
} }
/* /*
* Search for BGR values 0..255 (after net is unbiased) and return colour * Search for BGR values 0..255 (after net is unbiased) and return colour index
* index
* ---------------------------------------------------------------------------- * ----------------------------------------------------------------------------
*/ */
public int map(int b, int g, int r) { public int map(int b, int g, int r) {
@ -915,9 +898,10 @@ class NeuQuant {
} }
/* /*
* Unbias network to give byte values 0..255 and record position i to * Unbias network to give byte values 0..255 and record position i to prepare
* prepare for sort * for sort
* ----------------------------------------------------------------------------------- * -----------------------------------------------------------------------------
* ------
*/ */
public void unbiasnet() { public void unbiasnet() {
@ -934,7 +918,8 @@ class NeuQuant {
/* /*
* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in
* radpower[|i-j|] * radpower[|i-j|]
* --------------------------------------------------------------------------------- * -----------------------------------------------------------------------------
* ----
*/ */
protected void alterneigh(int rad, int i, int b, int g, int r) { protected void alterneigh(int rad, int i, int b, int g, int r) {
@ -995,8 +980,7 @@ class NeuQuant {
/* finds closest neuron (min dist) and updates freq */ /* finds closest neuron (min dist) and updates freq */
/* finds best neuron (min dist-bias) and returns position */ /* finds best neuron (min dist-bias) and returns position */
/* /*
* for frequently chosen neurons, freq[i] is high and bias[i] is * for frequently chosen neurons, freq[i] is high and bias[i] is negative
* negative
*/ */
/* bias[i] = gamma*((1/netsize)-freq[i]) */ /* bias[i] = gamma*((1/netsize)-freq[i]) */

View File

@ -35,19 +35,19 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File; import net.sourceforge.plantuml.security.SFile;
public class BaseFile { public class BaseFile {
private final String basename; private final String basename;
private final File basedir; private final SFile basedir;
public BaseFile() { public BaseFile() {
this.basedir = null; this.basedir = null;
this.basename = null; this.basename = null;
} }
public BaseFile(File file) { public BaseFile(SFile file) {
this.basedir = file.getParentFile(); this.basedir = file.getParentFile();
this.basename = extractBasename(file.getName()); this.basename = extractBasename(file.getName());
} }
@ -72,15 +72,15 @@ public class BaseFile {
return basename; return basename;
} }
public File getBasedir() { public SFile getBasedir() {
return basedir; return basedir;
} }
public File getTraceFile(String tail) { public SFile getTraceFile(String tail) {
if (basedir == null || basename == null) { if (basedir == null || basename == null) {
return new File(tail); return new SFile(tail);
} }
return new File(basedir, basename + "_" + tail); return basedir.file(basename + "_" + tail);
} }
} }

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.util.ArrayList; import java.util.ArrayList;
@ -51,6 +50,7 @@ import net.sourceforge.plantuml.preproc.ReadLineNumbered;
import net.sourceforge.plantuml.preproc.ReadLineReader; import net.sourceforge.plantuml.preproc.ReadLineReader;
import net.sourceforge.plantuml.preproc.UncommentReadLine; import net.sourceforge.plantuml.preproc.UncommentReadLine;
import net.sourceforge.plantuml.preproc2.Preprocessor; import net.sourceforge.plantuml.preproc2.Preprocessor;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.utils.StartUtils; import net.sourceforge.plantuml.utils.StartUtils;
public final class BlockUmlBuilder implements DefinitionsContainer { public final class BlockUmlBuilder implements DefinitionsContainer {
@ -62,7 +62,7 @@ public final class BlockUmlBuilder implements DefinitionsContainer {
private final ImportedFiles importedFiles; private final ImportedFiles importedFiles;
private final String charset; private final String charset;
public BlockUmlBuilder(List<String> config, String charset, Defines defines, Reader readerInit, File newCurrentDir, public BlockUmlBuilder(List<String> config, String charset, Defines defines, Reader readerInit, SFile newCurrentDir,
String desc) throws IOException { String desc) throws IOException {
ReadLineNumbered includer = null; ReadLineNumbered includer = null;
this.defines = defines; this.defines = defines;

View File

@ -45,9 +45,8 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.security.ImageIO;
public class ClipboardLoop { public class ClipboardLoop {

View File

@ -92,8 +92,8 @@ public class DirWatcher2 {
try { try {
final List<GeneratedImage> generatedImages = sourceFileReader final List<GeneratedImage> generatedImages = sourceFileReader
.getGeneratedImages(); .getGeneratedImages();
final Set<File> files = FileWithSuffix.convert(sourceFileReader final Set<File> files = FileWithSuffix
.getIncludedFiles()); .convert(sourceFileReader.getIncludedFiles());
files.add(f); files.add(f);
modifieds.put(f, new FileWatcher(files)); modifieds.put(f, new FileWatcher(files));
return Collections.unmodifiableList(generatedImages); return Collections.unmodifiableList(generatedImages);

View File

@ -42,8 +42,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.core.Diagram; import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.creole.atom.Atom; import net.sourceforge.plantuml.creole.atom.Atom;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
@ -52,6 +50,7 @@ import net.sourceforge.plantuml.graphic.HorizontalAlignment;
import net.sourceforge.plantuml.graphic.Line; import net.sourceforge.plantuml.graphic.Line;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImage; import net.sourceforge.plantuml.ugraphic.UImage;
import net.sourceforge.plantuml.ugraphic.UImageSvg; import net.sourceforge.plantuml.ugraphic.UImageSvg;

View File

@ -42,13 +42,13 @@ import java.awt.RenderingHints;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import net.sourceforge.plantuml.braille.BrailleCharFactory; import net.sourceforge.plantuml.braille.BrailleCharFactory;
import net.sourceforge.plantuml.braille.UGraphicBraille; import net.sourceforge.plantuml.braille.UGraphicBraille;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.png.MetadataTag; import net.sourceforge.plantuml.png.MetadataTag;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svg.SvgGraphics; import net.sourceforge.plantuml.svg.SvgGraphics;
import net.sourceforge.plantuml.ugraphic.UFont; import net.sourceforge.plantuml.ugraphic.UFont;
@ -90,7 +90,7 @@ public enum FileFormat {
} }
final static private BufferedImage imDummy = new BufferedImage(800, 100, BufferedImage.TYPE_INT_RGB); final static private BufferedImage imDummy = new BufferedImage(800, 100, BufferedImage.TYPE_INT_RGB);
final static private Graphics2D gg = imDummy.createGraphics(); final static public Graphics2D gg = imDummy.createGraphics();
static { static {
// KEY_FRACTIONALMETRICS // KEY_FRACTIONALMETRICS
gg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); gg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
@ -188,12 +188,12 @@ public enum FileFormat {
OptionFlags.getInstance().getFileSeparator() + String.format("%03d", cpt) + getFileSuffix()); OptionFlags.getInstance().getFileSeparator() + String.format("%03d", cpt) + getFileSuffix());
} }
private File computeFilename(File pngFile, int i) { private SFile computeFilename(SFile pngFile, int i) {
if (i == 0) { if (i == 0) {
return pngFile; return pngFile;
} }
final File dir = pngFile.getParentFile(); final SFile dir = pngFile.getParentFile();
return new File(dir, computeFilenameInternal(pngFile.getName(), i)); return dir.file(computeFilenameInternal(pngFile.getName(), i));
} }
private String changeName(String fileName, String replacement) { private String changeName(String fileName, String replacement) {
@ -216,7 +216,7 @@ public enum FileFormat {
return this == PNG || this == SVG; return this == PNG || this == SVG;
} }
public boolean equalsMetadata(String currentMetadata, File existingFile) { public boolean equalsMetadata(String currentMetadata, SFile existingFile) {
try { try {
if (this == PNG) { if (this == PNG) {
final MetadataTag tag = new MetadataTag(existingFile, "plantuml"); final MetadataTag tag = new MetadataTag(existingFile, "plantuml");
@ -226,6 +226,9 @@ public enum FileFormat {
} }
if (this == SVG) { if (this == SVG) {
final String svg = FileUtils.readSvg(existingFile); final String svg = FileUtils.readSvg(existingFile);
if (svg == null) {
return false;
}
final String currentSignature = SvgGraphics.getMD5Hex(currentMetadata); final String currentSignature = SvgGraphics.getMD5Hex(currentMetadata);
final int idx = svg.lastIndexOf(SvgGraphics.MD5_HEADER); final int idx = svg.lastIndexOf(SvgGraphics.MD5_HEADER);
if (idx != -1) { if (idx != -1) {

View File

@ -35,24 +35,23 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.security.SFile;
public class FileImageData { public class FileImageData {
public static final int ERROR = 400; public static final int ERROR = 400;
public static final int CRASH = 503; public static final int CRASH = 503;
private final File file; private final SFile file;
private final ImageData imageData; private final ImageData imageData;
public FileImageData(File file, ImageData imageData) { public FileImageData(SFile file, ImageData imageData) {
this.file = file; this.file = file;
this.imageData = imageData; this.imageData = imageData;
} }
public File getFile() { public SFile getFile() {
return file; return file;
} }

View File

@ -35,17 +35,16 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import net.sourceforge.plantuml.security.SFile;
import java.util.StringTokenizer; import net.sourceforge.plantuml.security.SecurityUtils;
public class FileSystem { public class FileSystem {
private final static FileSystem singleton = new FileSystem(); private final static FileSystem singleton = new FileSystem();
private final ThreadLocal<File> currentDir = new ThreadLocal<File>(); private final ThreadLocal<SFile> currentDir = new ThreadLocal<SFile>();
private FileSystem() { private FileSystem() {
reset(); reset();
@ -55,79 +54,63 @@ public class FileSystem {
return singleton; return singleton;
} }
public void setCurrentDir(File dir) { public void setCurrentDir(SFile dir) {
// if (dir == null) { // if (dir == null) {
// throw new IllegalArgumentException(); // throw new IllegalArgumentException();
// } // }
Log.info("Setting current dir: " + dir); if (dir != null) {
Log.info("Setting current dir: " + dir.getAbsolutePath());
}
this.currentDir.set(dir); this.currentDir.set(dir);
} }
public File getCurrentDir() { public SFile getCurrentDir() {
return this.currentDir.get(); return this.currentDir.get();
} }
public File getFile(String nameOrPath) throws IOException { public SFile getFile(String nameOrPath) throws IOException {
if (isAbsolute(nameOrPath)) { if (isAbsolute(nameOrPath)) {
return new File(nameOrPath).getCanonicalFile(); return new SFile(nameOrPath).getCanonicalFile();
} }
final File dir = currentDir.get(); final SFile dir = currentDir.get();
File filecurrent = null; SFile filecurrent = null;
if (dir != null) { if (dir != null) {
filecurrent = new File(dir.getAbsoluteFile(), nameOrPath); filecurrent = dir.getAbsoluteFile().file(nameOrPath);
if (filecurrent.exists()) { if (filecurrent.exists()) {
return filecurrent.getCanonicalFile(); return filecurrent.getCanonicalFile();
} }
} }
for (File d : getPath("plantuml.include.path", true)) { for (SFile d : SecurityUtils.getPath("plantuml.include.path")) {
if (d.isDirectory()) { assert d.isDirectory();
final File file = new File(d, nameOrPath); final SFile file = d.file(nameOrPath);
if (file.exists()) { if (file.exists()) {
return file.getCanonicalFile(); return file.getCanonicalFile();
}
} }
} }
for (File d : getPath("java.class.path", true)) { for (SFile d : SecurityUtils.getPath("java.class.path")) {
if (d.isDirectory()) { assert d.isDirectory();
final File file = new File(d, nameOrPath); final SFile file = d.file(nameOrPath);
if (file.exists()) { if (file.exists()) {
return file.getCanonicalFile(); return file.getCanonicalFile();
}
} }
} }
if (dir == null) { if (dir == null) {
assert filecurrent == null; assert filecurrent == null;
return new File(nameOrPath).getCanonicalFile(); return new SFile(nameOrPath).getCanonicalFile();
} }
assert filecurrent != null; assert filecurrent != null;
return filecurrent; return filecurrent;
} }
public static List<File> getPath(String prop, boolean onlyDir) {
final List<File> result = new ArrayList<File>();
String paths = System.getProperty(prop);
if (paths == null) {
return result;
}
paths = StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(paths);
final StringTokenizer st = new StringTokenizer(paths, System.getProperty("path.separator"));
while (st.hasMoreTokens()) {
final File f = new File(st.nextToken());
if (f.exists() && (onlyDir == false || f.isDirectory())) {
result.add(f);
}
}
return result;
}
private boolean isAbsolute(String nameOrPath) { private boolean isAbsolute(String nameOrPath) {
final File f = new File(nameOrPath); final SFile f = new SFile(nameOrPath);
return f.isAbsolute(); return f.isAbsolute();
} }
public void reset() { public void reset() {
setCurrentDir(new File(".")); setCurrentDir(new SFile("."));
} }
} }

View File

@ -35,23 +35,17 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.ImageIcon; import net.sourceforge.plantuml.security.SFile;
// Used by the Eclipse Plugin, so do not change package location. // Used by the Eclipse Plugin, so do not change package location.
public class FileUtils { public class FileUtils {
@ -62,19 +56,19 @@ public class FileUtils {
counter = new AtomicInteger(0); counter = new AtomicInteger(0);
} }
static public File createTempFile(String prefix, String suffix) throws IOException { static public SFile createTempFile(String prefix, String suffix) throws IOException {
if (suffix.startsWith(".") == false) { if (suffix.startsWith(".") == false) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
if (prefix == null) { if (prefix == null) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
final File f; final SFile f;
if (counter == null) { if (counter == null) {
f = File.createTempFile(prefix, suffix); f = SFile.createTempFile(prefix, suffix);
} else { } else {
final String name = prefix + counter.addAndGet(1) + suffix; final String name = prefix + counter.addAndGet(1) + suffix;
f = new File(name); f = new SFile(name);
} }
Log.info("Creating temporary file: " + f); Log.info("Creating temporary file: " + f);
f.deleteOnExit(); f.deleteOnExit();
@ -91,17 +85,23 @@ public class FileUtils {
fis.close(); fis.close();
} }
static public void copyToFile(File src, File dest) throws IOException { static public void copyToFile(SFile src, SFile dest) throws IOException {
if (dest.isDirectory()) { if (dest.isDirectory()) {
dest = new File(dest, src.getName()); dest = dest.file(src.getName());
} }
final InputStream fis = new BufferedInputStream(new FileInputStream(src)); final InputStream fis = src.openFile();
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest)); if (fis == null) {
throw new FileNotFoundException();
}
final OutputStream fos = dest.createBufferedOutputStream();
copyInternal(fis, fos); copyInternal(fis, fos);
} }
static public void copyToStream(File src, OutputStream os) throws IOException { static public void copyToStream(SFile src, OutputStream os) throws IOException {
final InputStream fis = new BufferedInputStream(new FileInputStream(src)); final InputStream fis = src.openFile();
if (fis == null) {
throw new FileNotFoundException();
}
final OutputStream fos = new BufferedOutputStream(os); final OutputStream fos = new BufferedOutputStream(os);
copyInternal(fis, fos); copyInternal(fis, fos);
} }
@ -112,14 +112,17 @@ public class FileUtils {
copyInternal(fis, fos); copyInternal(fis, fos);
} }
static public void copyToFile(byte[] src, File dest) throws IOException { static public void copyToFile(byte[] src, SFile dest) throws IOException {
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest)); final OutputStream fos = dest.createBufferedOutputStream();
fos.write(src); fos.write(src);
fos.close(); fos.close();
} }
static public String readSvg(File svgFile) throws IOException { static public String readSvg(SFile svgFile) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(svgFile)); final BufferedReader br = svgFile.openBufferedReader();
if (br == null) {
return null;
}
return readSvg(br, false, true); return readSvg(br, false, true);
} }
@ -128,12 +131,15 @@ public class FileUtils {
return readSvg(br, false, false); return readSvg(br, false, false);
} }
static public String readFile(File svgFile) throws IOException { static public String readFile(SFile svgFile) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(svgFile)); final BufferedReader br = svgFile.openBufferedReader();
if (br == null) {
return null;
}
return readSvg(br, true, true); return readSvg(br, true, true);
} }
private static String readSvg(final BufferedReader br, boolean withNewline, boolean withClose) throws IOException { private static String readSvg(BufferedReader br, boolean withNewline, boolean withClose) throws IOException {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
String s; String s;
while ((s = br.readLine()) != null) { while ((s = br.readLine()) != null) {
@ -148,38 +154,4 @@ public class FileUtils {
return sb.toString(); return sb.toString();
} }
// public static BufferedImage ImageIO_read(File f) throws IOException {
// return ImageIO.read(f);
// }
// http://forum.plantuml.net/9048/img-tag-for-sequence-diagram-participants-does-always-render
public synchronized static BufferedImage readRasterImageFromFile(File f) {
// https://www.experts-exchange.com/questions/26171948/Why-are-ImageIO-read-images-losing-their-transparency.html
// https://stackoverflow.com/questions/18743790/can-java-load-images-with-transparency
try {
return readRasterImage(new ImageIcon(f.getAbsolutePath()));
} catch (Exception e) {
return null;
}
}
public synchronized static BufferedImage readRasterImageFromURL(URL url) {
try {
return readRasterImage(new ImageIcon(url));
} catch (Exception e) {
return null;
}
}
private synchronized static BufferedImage readRasterImage(final ImageIcon imageIcon) {
final Image tmpImage = imageIcon.getImage();
final BufferedImage image = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
image.getGraphics().drawImage(tmpImage, 0, 0, null);
tmpImage.flush();
return image;
}
} }

View File

@ -36,13 +36,15 @@
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File; import java.io.File;
import java.io.IOException;
import net.sourceforge.plantuml.core.Diagram; import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.error.PSystemError; import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.security.SFile;
public class GeneratedImageImpl implements GeneratedImage { public class GeneratedImageImpl implements GeneratedImage {
private final File pngFile; private final SFile pngFile;
private final String description; private final String description;
private final BlockUml blockUml; private final BlockUml blockUml;
private final int status; private final int status;
@ -51,7 +53,7 @@ public class GeneratedImageImpl implements GeneratedImage {
return status; return status;
} }
public GeneratedImageImpl(File pngFile, String description, BlockUml blockUml, int status) { public GeneratedImageImpl(SFile pngFile, String description, BlockUml blockUml, int status) {
this.blockUml = blockUml; this.blockUml = blockUml;
this.pngFile = pngFile; this.pngFile = pngFile;
this.description = description; this.description = description;
@ -59,7 +61,7 @@ public class GeneratedImageImpl implements GeneratedImage {
} }
public File getPngFile() { public File getPngFile() {
return pngFile; return pngFile.internal;
} }
public String getDescription() { public String getDescription() {
@ -76,13 +78,17 @@ public class GeneratedImageImpl implements GeneratedImage {
@Override @Override
public String toString() { public String toString() {
return pngFile.getAbsolutePath() + " " + description; return pngFile.getPrintablePath() + " " + description;
} }
public int compareTo(GeneratedImage this2) { public int compareTo(GeneratedImage this2) {
final int cmp = this.pngFile.compareTo(this2.getPngFile()); try {
if (cmp != 0) { final int cmp = this.getPngFile().getCanonicalPath().compareTo(this2.getPngFile().getCanonicalPath());
return cmp; if (cmp != 0) {
return cmp;
}
} catch (IOException e) {
e.printStackTrace();
} }
return this.description.compareTo(this2.getDescription()); return this.description.compareTo(this2.getDescription());
} }

View File

@ -35,20 +35,19 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import net.sourceforge.plantuml.security.SFile;
public class NamedOutputStream extends OutputStream { public class NamedOutputStream extends OutputStream {
private final OutputStream os; private final OutputStream os;
private final BaseFile basefile; private final BaseFile basefile;
public NamedOutputStream(File file) throws FileNotFoundException { public NamedOutputStream(SFile file) throws FileNotFoundException {
this.os = new BufferedOutputStream(new FileOutputStream(file)); this.os = file.createBufferedOutputStream();
this.basefile = new BaseFile(file); this.basefile = new BaseFile(file);
} }

View File

@ -52,6 +52,7 @@ import net.sourceforge.plantuml.command.regex.MyPattern;
import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.command.regex.Pattern2;
import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.stats.StatsUtils; import net.sourceforge.plantuml.stats.StatsUtils;
public class Option { public class Option {
@ -267,8 +268,8 @@ public class Option {
if (i == arg.length) { if (i == arg.length) {
continue; continue;
} }
OptionFlags.getInstance().setLogData( OptionFlags.getInstance()
new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i]))); .setLogData(new SFile(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])));
} else if (s.equalsIgnoreCase("-word")) { } else if (s.equalsIgnoreCase("-word")) {
OptionFlags.getInstance().setWord(true); OptionFlags.getInstance().setWord(true);
OptionFlags.getInstance().setQuiet(true); OptionFlags.getInstance().setQuiet(true);
@ -281,8 +282,6 @@ public class Option {
OptionPrint.printVersion(); OptionPrint.printVersion();
} else if (s.matches("(?i)^-li[sc][ea]n[sc]e\\s*$")) { } else if (s.matches("(?i)^-li[sc][ea]n[sc]e\\s*$")) {
OptionPrint.printLicense(); OptionPrint.printLicense();
} else if (s.equalsIgnoreCase("-checkversion")) {
OptionPrint.checkVersion();
} else if (s.startsWith("-DPLANTUML_LIMIT_SIZE=")) { } else if (s.startsWith("-DPLANTUML_LIMIT_SIZE=")) {
final String v = s.substring("-DPLANTUML_LIMIT_SIZE=".length()); final String v = s.substring("-DPLANTUML_LIMIT_SIZE=".length());
if (v.matches("\\d+")) { if (v.matches("\\d+")) {
@ -294,7 +293,8 @@ public class Option {
manageSkinParam(s.substring(2)); manageSkinParam(s.substring(2));
} else if (s.equalsIgnoreCase("-testdot")) { } else if (s.equalsIgnoreCase("-testdot")) {
OptionPrint.printTestDot(); OptionPrint.printTestDot();
} else if (s.equalsIgnoreCase("-about") || s.equalsIgnoreCase("-author") || s.equalsIgnoreCase("-authors")) { } else if (s.equalsIgnoreCase("-about") || s.equalsIgnoreCase("-author")
|| s.equalsIgnoreCase("-authors")) {
OptionPrint.printAbout(); OptionPrint.printAbout();
} else if (s.equalsIgnoreCase("-help") || s.equalsIgnoreCase("-h") || s.equalsIgnoreCase("-?")) { } else if (s.equalsIgnoreCase("-help") || s.equalsIgnoreCase("-h") || s.equalsIgnoreCase("-?")) {
OptionPrint.printHelp(); OptionPrint.printHelp();
@ -390,23 +390,23 @@ public class Option {
return ftpPort; return ftpPort;
} }
private void addInConfig(final FileReader source) throws IOException { private void addInConfig(BufferedReader br) throws IOException {
BufferedReader br = null; if (br == null) {
return;
}
try { try {
br = new BufferedReader(source);
String s = null; String s = null;
while ((s = br.readLine()) != null) { while ((s = br.readLine()) != null) {
config.add(s); config.add(s);
} }
} finally { } finally {
if (br != null) { br.close();
br.close();
}
} }
} }
public void initConfig(String filename) throws IOException { public void initConfig(String filename) throws IOException {
addInConfig(new FileReader(filename)); final BufferedReader br = new BufferedReader(new FileReader(filename));
addInConfig(br);
} }
private void initInclude(String filename) throws IOException { private void initInclude(String filename) throws IOException {
@ -414,16 +414,16 @@ public class Option {
return; return;
} }
if (filename.contains("*")) { if (filename.contains("*")) {
final FileGroup group = new FileGroup(filename, Collections.<String> emptyList(), null); final FileGroup group = new FileGroup(filename, Collections.<String>emptyList(), null);
for (File f : group.getFiles()) { for (File f : group.getFiles()) {
if (f.exists() && f.canRead()) { if (f.exists() && f.canRead()) {
addInConfig(new FileReader(f)); addInConfig(new BufferedReader(new FileReader(f)));
} }
} }
} else { } else {
final File f = new File(filename); final File f = new File(filename);
if (f.exists() && f.canRead()) { if (f.exists() && f.canRead()) {
addInConfig(new FileReader(f)); addInConfig(new BufferedReader(new FileReader(f)));
} }
} }
} }
@ -467,7 +467,19 @@ public class Option {
return Collections.unmodifiableList(excludes); return Collections.unmodifiableList(excludes);
} }
public Defines getDefaultDefines(File f) { public Defines getDefaultDefines(SFile f) {
final Defines result = Defines.createWithFileName(f);
for (Map.Entry<String, String> ent : defines.entrySet()) {
String value = ent.getValue();
if (value == null) {
value = "";
}
result.define(ent.getKey(), Arrays.asList(value), false, null);
}
return result;
}
public Defines getDefaultDefines(java.io.File f) {
final Defines result = Defines.createWithFileName(f); final Defines result = Defines.createWithFileName(f);
for (Map.Entry<String, String> ent : defines.entrySet()) { for (Map.Entry<String, String> ent : defines.entrySet()) {
String value = ent.getValue(); String value = ent.getValue();

View File

@ -35,14 +35,14 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import net.sourceforge.plantuml.core.Diagram; import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
public class OptionFlags { public class OptionFlags {
@ -129,7 +129,7 @@ public class OptionFlags {
private boolean clipboard; private boolean clipboard;
private String fileSeparator = "_"; private String fileSeparator = "_";
private long timeoutMs = 15 * 60 * 1000L; // 15 minutes private long timeoutMs = 15 * 60 * 1000L; // 15 minutes
private File logData; private SFile logData;
public static OptionFlags getInstance() { public static OptionFlags getInstance() {
return singleton; return singleton;
@ -193,7 +193,7 @@ public class OptionFlags {
private final AtomicBoolean logDataInitized = new AtomicBoolean(false); private final AtomicBoolean logDataInitized = new AtomicBoolean(false);
public void logData(File file, Diagram system) { public void logData(final SFile file, Diagram system) {
final String warnOrError = system.getWarningOrError(); final String warnOrError = system.getWarningOrError();
if (warnOrError == null) { if (warnOrError == null) {
return; return;
@ -202,7 +202,7 @@ public class OptionFlags {
if (logData == null && logDataInitized.get() == false) { if (logData == null && logDataInitized.get() == false) {
final String s = GraphvizUtils.getenvLogData(); final String s = GraphvizUtils.getenvLogData();
if (s != null) { if (s != null) {
setLogData(new File(s)); setLogData(new SFile(s));
} }
logDataInitized.set(true); logDataInitized.set(true);
} }
@ -213,7 +213,7 @@ public class OptionFlags {
// final PSystemError systemError = (PSystemError) system; // final PSystemError systemError = (PSystemError) system;
PrintStream ps = null; PrintStream ps = null;
try { try {
ps = new PrintStream(new FileOutputStream(logData, true)); ps = SecurityUtils.createPrintStream(logData.createFileOutputStream(true));
ps.println("Start of " + file.getName()); ps.println("Start of " + file.getName());
ps.println(warnOrError); ps.println(warnOrError);
ps.println("End of " + file.getName()); ps.println("End of " + file.getName());
@ -229,12 +229,12 @@ public class OptionFlags {
} }
} }
public final void setLogData(File logData) { public final void setLogData(SFile logData) {
this.logData = logData; this.logData = logData;
logData.delete(); logData.delete();
PrintStream ps = null; PrintStream ps = null;
try { try {
ps = new PrintStream(new FileOutputStream(logData)); ps = SecurityUtils.createPrintStream(logData.createFileOutputStream());
ps.println(); ps.println();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Log.error("Cannot open " + logData); Log.error("Cannot open " + logData);

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
@ -48,6 +47,9 @@ import java.util.Map;
import java.util.Properties; import java.util.Properties;
import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityProfile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.syntax.LanguageDescriptor; import net.sourceforge.plantuml.syntax.LanguageDescriptor;
import net.sourceforge.plantuml.version.License; import net.sourceforge.plantuml.version.License;
import net.sourceforge.plantuml.version.PSystemVersion; import net.sourceforge.plantuml.version.PSystemVersion;
@ -78,8 +80,8 @@ public class OptionPrint {
System.out.println("\t(to process files or directories)"); System.out.println("\t(to process files or directories)");
System.out.println(); System.out.println();
System.out.println("You can use the following wildcards in files/dirs:"); System.out.println("You can use the following wildcards in files/dirs:");
System.out.println("\t*\tmeans any characters but '" + File.separator + "'"); System.out.println("\t*\tmeans any characters but '" + SFile.separator + "'");
System.out.println("\t?\tone and only one character but '" + File.separator + "'"); System.out.println("\t?\tone and only one character but '" + SFile.separator + "'");
System.out.println("\t**\tmeans any characters (used to recurse through directories)"); System.out.println("\t**\tmeans any characters (used to recurse through directories)");
System.out.println(); System.out.println();
System.out.println("where options include:"); System.out.println("where options include:");
@ -100,19 +102,19 @@ public class OptionPrint {
System.out.println(" -DVAR1=value\tTo set a preprocessing variable as if '!define VAR1 value' were used"); System.out.println(" -DVAR1=value\tTo set a preprocessing variable as if '!define VAR1 value' were used");
System.out.println(" -Sparam1=value\tTo set a skin parameter as if 'skinparam param1 value' were used"); System.out.println(" -Sparam1=value\tTo set a skin parameter as if 'skinparam param1 value' were used");
System.out.println(" -r[ecurse]\t\trecurse through directories"); System.out.println(" -r[ecurse]\t\trecurse through directories");
// System.out.println(" -config \"file\"\tTo read the provided config file before each diagram"); // System.out.println(" -config \"file\"\tTo read the provided config file
final char separator = File.separatorChar; // before each diagram");
final char separator = SFile.separatorChar;
System.out.println(" -I" + separator + "path" + separator + "to" + separator System.out.println(" -I" + separator + "path" + separator + "to" + separator
+ "file\tTo include file as if '!include file' were used"); + "file\tTo include file as if '!include file' were used");
System.out.println(" -I" + separator + "path" + separator + "to" + separator System.out.println(
+ "*.puml\tTo include files with pattern"); " -I" + separator + "path" + separator + "to" + separator + "*.puml\tTo include files with pattern");
System.out.println(" -charset xxx\tTo use a specific charset (default is " + charset + ")"); System.out.println(" -charset xxx\tTo use a specific charset (default is " + charset + ")");
System.out.println(" -e[x]clude pattern\tTo exclude files that match the provided pattern"); System.out.println(" -e[x]clude pattern\tTo exclude files that match the provided pattern");
System.out.println(" -metadata\t\tTo retrieve PlantUML sources from PNG images"); System.out.println(" -metadata\t\tTo retrieve PlantUML sources from PNG images");
System.out.println(" -nometadata\t\tTo NOT export metadata in PNG/SVG generated files"); System.out.println(" -nometadata\t\tTo NOT export metadata in PNG/SVG generated files");
System.out.println(" -checkmetadata\t\tSkip PNG files that don't need to be regenerated"); System.out.println(" -checkmetadata\t\tSkip PNG files that don't need to be regenerated");
System.out.println(" -version\t\tTo display information about PlantUML and Java versions"); System.out.println(" -version\t\tTo display information about PlantUML and Java versions");
System.out.println(" -checkversion\tTo check if a newer version is available for download");
System.out.println(" -v[erbose]\t\tTo have log information"); System.out.println(" -v[erbose]\t\tTo have log information");
System.out.println(" -quiet\t\tTo NOT print error message into the console"); System.out.println(" -quiet\t\tTo NOT print error message into the console");
System.out.println(" -debugsvek\t\tTo generate intermediate svek files"); System.out.println(" -debugsvek\t\tTo generate intermediate svek files");
@ -120,13 +122,14 @@ public class OptionPrint {
System.out.println(" -testdot\t\tTo test the installation of graphviz"); System.out.println(" -testdot\t\tTo test the installation of graphviz");
System.out.println(" -graphvizdot \"exe\"\tTo specify dot executable"); System.out.println(" -graphvizdot \"exe\"\tTo specify dot executable");
System.out.println(" -p[ipe]\t\tTo use stdin for PlantUML source and stdout for PNG/SVG/EPS generation"); System.out.println(" -p[ipe]\t\tTo use stdin for PlantUML source and stdout for PNG/SVG/EPS generation");
System.out System.out.println(
.println(" -encodesprite 4|8|16[z] \"file\"\tTo encode a sprite at gray level (z for compression) from an image"); " -encodesprite 4|8|16[z] \"file\"\tTo encode a sprite at gray level (z for compression) from an image");
System.out.println(" -computeurl|-encodeurl\tTo compute the encoded URL of a PlantUML source file"); System.out.println(" -computeurl|-encodeurl\tTo compute the encoded URL of a PlantUML source file");
System.out.println(" -decodeurl\t\tTo retrieve the PlantUML source from an encoded URL"); System.out.println(" -decodeurl\t\tTo retrieve the PlantUML source from an encoded URL");
System.out.println(" -syntax\t\tTo report any syntax error from standard input without generating images"); System.out.println(" -syntax\t\tTo report any syntax error from standard input without generating images");
System.out.println(" -language\t\tTo print the list of PlantUML keywords"); System.out.println(" -language\t\tTo print the list of PlantUML keywords");
// System.out.println(" -nosuggestengine\tTo disable the suggest engine when errors in diagrams"); // System.out.println(" -nosuggestengine\tTo disable the suggest engine when
// errors in diagrams");
System.out.println(" -checkonly\t\tTo check the syntax of files without generating images"); System.out.println(" -checkonly\t\tTo check the syntax of files without generating images");
System.out.println(" -failfast\t\tTo stop processing as soon as a syntax error in diagram occurs"); System.out.println(" -failfast\t\tTo stop processing as soon as a syntax error in diagram occurs");
System.out.println(" -failfast2\t\tTo do a first syntax check before processing files, to fail even faster"); System.out.println(" -failfast2\t\tTo do a first syntax check before processing files, to fail even faster");
@ -192,13 +195,22 @@ public class OptionPrint {
public static Collection<String> interestingProperties() { public static Collection<String> interestingProperties() {
final Properties p = System.getProperties(); final Properties p = System.getProperties();
final List<String> list1 = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM", // final List<String> list1 = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM",
"java.runtime.version", "Java Version", "os.name", "Operating System", "file.encoding", // "java.runtime.version", "Java Version", "os.name", "Operating System", "file.encoding",
"Default Encoding", "user.language", "Language", "user.country", "Country"); // "Default Encoding", "user.language", "Language", "user.country", "Country");
final List<String> list2 = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM", // final List<String> list2 = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM",
"java.runtime.version", "Java Version", "os.name", "Operating System", /* "os.version", "OS Version", */ // "java.runtime.version", "Java Version", "os.name", "Operating System", /* "os.version", "OS Version", */
"file.encoding", "Default Encoding", "user.language", "Language", "user.country", "Country"); // "file.encoding", "Default Encoding", "user.language", "Language", "user.country", "Country");
final List<String> all = withIp() ? list1 : list2; // final List<String> all = withIp() ? list1 : list2;
final List<String> all;
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
all = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM", "java.runtime.version",
"Java Version", "os.name", "Operating System", "os.version", "OS Version", "file.encoding",
"Default Encoding", "user.language", "Language", "user.country", "Country");
} else {
all = Arrays.asList("java.runtime.name", "Java Runtime", "java.vm.name", "JVM", "file.encoding",
"Default Encoding", "user.language", "Language", "user.country", "Country");
}
final List<String> result = new ArrayList<String>(); final List<String> result = new ArrayList<String>();
for (int i = 0; i < all.size(); i += 2) { for (int i = 0; i < all.size(); i += 2) {
result.add(all.get(i + 1) + ": " + p.getProperty(all.get(i))); result.add(all.get(i + 1) + ": " + p.getProperty(all.get(i)));
@ -208,27 +220,33 @@ public class OptionPrint {
public static Collection<String> interestingValues() { public static Collection<String> interestingValues() {
final List<String> strings = new ArrayList<String>(); final List<String> strings = new ArrayList<String>();
if (withIp() == false) { // if (withIp() == false) {
strings.add("Machine: " + getHostName()); // strings.add("Machine: " + getHostName());
} // }
// strings.add(" ");
// strings.add("Current Security Profile: " + SecurityUtils.getSecurityProfile());
// strings.add(SecurityUtils.getSecurityProfile().longDescription());
strings.add(" ");
strings.add("PLANTUML_LIMIT_SIZE: " + GraphvizUtils.getenvImageLimit()); strings.add("PLANTUML_LIMIT_SIZE: " + GraphvizUtils.getenvImageLimit());
strings.add("Processors: " + Runtime.getRuntime().availableProcessors()); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
final long freeMemory = Runtime.getRuntime().freeMemory(); strings.add("Processors: " + Runtime.getRuntime().availableProcessors());
final long maxMemory = Runtime.getRuntime().maxMemory(); final long freeMemory = Runtime.getRuntime().freeMemory();
final long totalMemory = Runtime.getRuntime().totalMemory(); final long maxMemory = Runtime.getRuntime().maxMemory();
final long usedMemory = totalMemory - freeMemory; final long totalMemory = Runtime.getRuntime().totalMemory();
final int threadActiveCount = Thread.activeCount(); final long usedMemory = totalMemory - freeMemory;
strings.add("Max Memory: " + format(maxMemory)); final int threadActiveCount = Thread.activeCount();
strings.add("Total Memory: " + format(totalMemory)); strings.add("Max Memory: " + format(maxMemory));
strings.add("Free Memory: " + format(freeMemory)); strings.add("Total Memory: " + format(totalMemory));
strings.add("Used Memory: " + format(usedMemory)); strings.add("Free Memory: " + format(freeMemory));
strings.add("Thread Active Count: " + threadActiveCount); strings.add("Used Memory: " + format(usedMemory));
strings.add("Thread Active Count: " + threadActiveCount);
}
return Collections.unmodifiableCollection(strings); return Collections.unmodifiableCollection(strings);
} }
private static boolean withIp() { // private static boolean withIp() {
return getHostName().startsWith("ip-"); // return getHostName().startsWith("ip-");
} // }
private static String hostname; private static String hostname;
@ -258,30 +276,6 @@ public class OptionPrint {
return String.format(Locale.US, "%,d", value); return String.format(Locale.US, "%,d", value);
} }
public static void checkVersion() throws InterruptedException {
System.out.println(Version.fullDescription());
System.out.println();
final int lastversion = PSystemVersion.extractDownloadableVersion(null, null);
if (lastversion == -1) {
System.out.println("Error");
System.out.println("Cannot connect to http://plantuml.com/");
System.out.println("Maybe you should set your proxy ?");
} else if (lastversion == 0) {
System.out.println("Error");
System.out.println("Cannot retrieve last version from http://plantuml.com/");
} else {
System.out.println("Last available version for download : " + lastversion);
System.out.println();
if (Version.version() >= lastversion) {
System.out.println("Your version is up to date.");
} else {
System.out.println("A newer version is available for download.");
}
}
exit(0);
}
public static void printAbout() throws InterruptedException { public static void printAbout() throws InterruptedException {
for (String s : PSystemVersion.getAuthorsStrings(false)) { for (String s : PSystemVersion.getAuthorsStrings(false)) {
System.out.println(s); System.out.println(s);

View File

@ -61,6 +61,7 @@ import net.sourceforge.plantuml.eggs.PSystemAppleTwoFactory;
import net.sourceforge.plantuml.eggs.PSystemCharlieFactory; import net.sourceforge.plantuml.eggs.PSystemCharlieFactory;
import net.sourceforge.plantuml.eggs.PSystemColorsFactory; import net.sourceforge.plantuml.eggs.PSystemColorsFactory;
import net.sourceforge.plantuml.eggs.PSystemEggFactory; import net.sourceforge.plantuml.eggs.PSystemEggFactory;
import net.sourceforge.plantuml.eggs.PSystemPathFactory;
import net.sourceforge.plantuml.eggs.PSystemRIPFactory; import net.sourceforge.plantuml.eggs.PSystemRIPFactory;
import net.sourceforge.plantuml.eggs.PSystemWelcomeFactory; import net.sourceforge.plantuml.eggs.PSystemWelcomeFactory;
import net.sourceforge.plantuml.error.PSystemError; import net.sourceforge.plantuml.error.PSystemError;
@ -78,6 +79,8 @@ import net.sourceforge.plantuml.openiconic.PSystemOpenIconicFactory;
import net.sourceforge.plantuml.oregon.PSystemOregonFactory; import net.sourceforge.plantuml.oregon.PSystemOregonFactory;
import net.sourceforge.plantuml.project.GanttDiagramFactory; import net.sourceforge.plantuml.project.GanttDiagramFactory;
import net.sourceforge.plantuml.salt.PSystemSaltFactory; import net.sourceforge.plantuml.salt.PSystemSaltFactory;
import net.sourceforge.plantuml.security.SecurityProfile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory; import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory;
import net.sourceforge.plantuml.sprite.ListSpriteDiagramFactory; import net.sourceforge.plantuml.sprite.ListSpriteDiagramFactory;
import net.sourceforge.plantuml.sprite.PSystemListInternalSpritesFactory; import net.sourceforge.plantuml.sprite.PSystemListInternalSpritesFactory;
@ -191,7 +194,9 @@ public class PSystemBuilder {
factories.add(new PSystemAppleTwoFactory()); factories.add(new PSystemAppleTwoFactory());
factories.add(new PSystemRIPFactory()); factories.add(new PSystemRIPFactory());
// factories.add(new PSystemLostFactory()); // factories.add(new PSystemLostFactory());
// factories.add(new PSystemPathFactory()); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
factories.add(new PSystemPathFactory());
}
factories.add(new PSystemOregonFactory()); factories.add(new PSystemOregonFactory());
factories.add(new PSystemCharlieFactory()); factories.add(new PSystemCharlieFactory());
if (License.getCurrent() == License.GPL || License.getCurrent() == License.GPLV2) { if (License.getCurrent() == License.GPL || License.getCurrent() == License.GPLV2) {

View File

@ -35,9 +35,6 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
@ -52,6 +49,7 @@ import net.sourceforge.plantuml.cucadiagram.CucaDiagram;
import net.sourceforge.plantuml.html.CucaDiagramHtmlMaker; import net.sourceforge.plantuml.html.CucaDiagramHtmlMaker;
import net.sourceforge.plantuml.png.PngSplitter; import net.sourceforge.plantuml.png.PngSplitter;
import net.sourceforge.plantuml.project.GanttDiagram; import net.sourceforge.plantuml.project.GanttDiagram;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
import net.sourceforge.plantuml.ugraphic.color.HColorUtils; import net.sourceforge.plantuml.ugraphic.color.HColorUtils;
@ -65,7 +63,7 @@ public class PSystemUtils {
public static List<FileImageData> exportDiagrams(Diagram system, SuggestedFile suggestedFile, public static List<FileImageData> exportDiagrams(Diagram system, SuggestedFile suggestedFile,
FileFormatOption fileFormatOption, boolean checkMetadata) throws IOException { FileFormatOption fileFormatOption, boolean checkMetadata) throws IOException {
final File existingFile = suggestedFile.getFile(0); final SFile existingFile = suggestedFile.getFile(0);
if (checkMetadata && fileFormatOption.getFileFormat().doesSupportMetadata() && existingFile.exists() if (checkMetadata && fileFormatOption.getFileFormat().doesSupportMetadata() && existingFile.exists()
&& system.getNbImages() == 1) { && system.getNbImages() == 1) {
// final String version = Version.versionString(); // final String version = Version.versionString();
@ -76,7 +74,7 @@ public class PSystemUtils {
final boolean sameMetadata = fileFormatOption.getFileFormat().equalsMetadata(system.getMetadata(), final boolean sameMetadata = fileFormatOption.getFileFormat().equalsMetadata(system.getMetadata(),
existingFile); existingFile);
if (sameMetadata) { if (sameMetadata) {
Log.info("Skipping " + existingFile.getAbsolutePath() + " because metadata has not changed."); Log.info("Skipping " + existingFile.getPrintablePath() + " because metadata has not changed.");
return Arrays.asList(new FileImageData(existingFile, null)); return Arrays.asList(new FileImageData(existingFile, null));
} }
} }
@ -105,11 +103,11 @@ public class PSystemUtils {
final int nbImages = system.getNbImages(); final int nbImages = system.getNbImages();
for (int i = 0; i < nbImages; i++) { for (int i = 0; i < nbImages; i++) {
final File f = suggestedFile.getFile(i); final SFile f = suggestedFile.getFile(i);
if (canFileBeWritten(f) == false) { if (canFileBeWritten(f) == false) {
return result; return result;
} }
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); final OutputStream fos = f.createBufferedOutputStream();
ImageData cmap = null; ImageData cmap = null;
try { try {
system.exportDiagram(fos, i, fileFormat); system.exportDiagram(fos, i, fileFormat);
@ -125,8 +123,8 @@ public class PSystemUtils {
return result; return result;
} }
public static boolean canFileBeWritten(final File f) { public static boolean canFileBeWritten(final SFile f) {
Log.info("Creating file: " + f); Log.info("Creating file: " + f.getAbsolutePath());
if (f.exists() && f.canWrite() == false) { if (f.exists() && f.canWrite() == false) {
if (OptionFlags.getInstance().isOverwrite()) { if (OptionFlags.getInstance().isOverwrite()) {
Log.info("Overwrite " + f); Log.info("Overwrite " + f);
@ -134,7 +132,7 @@ public class PSystemUtils {
f.delete(); f.delete();
return true; return true;
} }
Log.error("Cannot write to file " + f); Log.error("Cannot write to file " + f.getAbsolutePath());
return false; return false;
} }
return true; return true;
@ -151,7 +149,7 @@ public class PSystemUtils {
if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) { if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) {
return Collections.emptyList(); return Collections.emptyList();
} }
os = new BufferedOutputStream(new FileOutputStream(suggestedFile.getFile(0))); os = suggestedFile.getFile(0).createBufferedOutputStream();
// system.exportDiagram(os, null, 0, fileFormat); // system.exportDiagram(os, null, 0, fileFormat);
imageData = system.exportDiagram(os, 0, fileFormat); imageData = system.exportDiagram(os, 0, fileFormat);
} finally { } finally {
@ -174,7 +172,7 @@ public class PSystemUtils {
if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) { if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) {
return Collections.emptyList(); return Collections.emptyList();
} }
os = new BufferedOutputStream(new FileOutputStream(suggestedFile.getFile(0))); os = suggestedFile.getFile(0).createBufferedOutputStream();
imageData = cmap = system.exportDiagram(os, 0, fileFormat); imageData = cmap = system.exportDiagram(os, 0, fileFormat);
} finally { } finally {
if (os != null) { if (os != null) {
@ -193,11 +191,11 @@ public class PSystemUtils {
final int nbImages = system.getNbImages(); final int nbImages = system.getNbImages();
for (int i = 0; i < nbImages; i++) { for (int i = 0; i < nbImages; i++) {
final File f = suggestedFile.getFile(i); final SFile f = suggestedFile.getFile(i);
if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(i)) == false) { if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(i)) == false) {
return result; return result;
} }
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); final OutputStream fos = f.createBufferedOutputStream();
ImageData cmap = null; ImageData cmap = null;
try { try {
cmap = system.exportDiagram(fos, i, fileFormat); cmap = system.exportDiagram(fos, i, fileFormat);
@ -230,7 +228,7 @@ public class PSystemUtils {
return Collections.emptyList(); return Collections.emptyList();
} }
// System.err.println("FOO11=" + suggestedFile); // System.err.println("FOO11=" + suggestedFile);
// os = new BufferedOutputStream(new FileOutputStream(suggestedFile)); // os = SecurityUtils.BufferedOutputStream(suggestedFile));
os = new NamedOutputStream(suggestedFile.getFile(0)); os = new NamedOutputStream(suggestedFile.getFile(0));
cmap = system.exportDiagram(os, 0, fileFormat); cmap = system.exportDiagram(os, 0, fileFormat);
} finally { } finally {
@ -238,7 +236,7 @@ public class PSystemUtils {
os.close(); os.close();
} }
} }
List<File> result = Arrays.asList(suggestedFile.getFile(0)); List<SFile> result = Arrays.asList(suggestedFile.getFile(0));
if (cmap != null && cmap.containsCMapData()) { if (cmap != null && cmap.containsCMapData()) {
system.exportCmap(suggestedFile, 0, cmap); system.exportCmap(suggestedFile, 0, cmap);
@ -250,16 +248,18 @@ public class PSystemUtils {
system.getSkinParam().getSplitParam()).getFiles(); system.getSkinParam().getSplitParam()).getFiles();
} }
final List<FileImageData> result2 = new ArrayList<FileImageData>(); final List<FileImageData> result2 = new ArrayList<FileImageData>();
for (File f : result) { for (SFile f : result) {
result2.add(new FileImageData(f, cmap)); result2.add(new FileImageData(f, cmap));
} }
return result2; return result2;
} }
// static private List<FileImageData> exportDiagramsGantt1(GanttDiagram system, SuggestedFile suggestedFile, // static private List<FileImageData> exportDiagramsGantt1(GanttDiagram system,
// SuggestedFile suggestedFile,
// FileFormatOption fileFormat) throws IOException { // FileFormatOption fileFormat) throws IOException {
// if (suggestedFile.getFile(0).exists() && suggestedFile.getFile(0).isDirectory()) { // if (suggestedFile.getFile(0).exists() &&
// suggestedFile.getFile(0).isDirectory()) {
// throw new IllegalArgumentException("File is a directory " + suggestedFile); // throw new IllegalArgumentException("File is a directory " + suggestedFile);
// } // }
// OutputStream os = null; // OutputStream os = null;
@ -268,7 +268,7 @@ public class PSystemUtils {
// if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) { // if (PSystemUtils.canFileBeWritten(suggestedFile.getFile(0)) == false) {
// return Collections.emptyList(); // return Collections.emptyList();
// } // }
// os = new BufferedOutputStream(new FileOutputStream(suggestedFile.getFile(0))); // os = SecurityUtils.BufferedOutputStream(suggestedFile.getFile(0)));
// imageData = system.exportDiagram(os, 0, fileFormat); // imageData = system.exportDiagram(os, 0, fileFormat);
// } finally { // } finally {
// if (os != null) { // if (os != null) {
@ -297,16 +297,16 @@ public class PSystemUtils {
os.close(); os.close();
} }
} }
List<File> result = Arrays.asList(suggestedFile.getFile(0)); List<SFile> result = Arrays.asList(suggestedFile.getFile(0));
if (fileFormat.getFileFormat() == FileFormat.PNG) { if (fileFormat.getFileFormat() == FileFormat.PNG) {
final SplitParam splitParam = new SplitParam(HColorUtils.BLACK, null, 5); final SplitParam splitParam = new SplitParam(HColorUtils.BLACK, null, 5);
result = new PngSplitter(suggestedFile, system.getHorizontalPages(), system.getVerticalPages(), result = new PngSplitter(suggestedFile, system.getHorizontalPages(), system.getVerticalPages(),
system.getMetadata(), system.getDpi(fileFormat), fileFormat.isWithMetadata(), splitParam) system.getMetadata(), system.getDpi(fileFormat), fileFormat.isWithMetadata(), splitParam)
.getFiles(); .getFiles();
} }
final List<FileImageData> result2 = new ArrayList<FileImageData>(); final List<FileImageData> result2 = new ArrayList<FileImageData>();
for (File f : result) { for (SFile f : result) {
result2.add(new FileImageData(f, cmap)); result2.add(new FileImageData(f, cmap));
} }
return result2; return result2;
@ -317,7 +317,7 @@ public class PSystemUtils {
throws IOException { throws IOException {
final String name = suggestedFile.getName(); final String name = suggestedFile.getName();
final int idx = name.lastIndexOf('.'); final int idx = name.lastIndexOf('.');
final File dir = new File(suggestedFile.getParentFile(), name.substring(0, idx)); final SFile dir = suggestedFile.getParentFile().file(name.substring(0, idx));
final CucaDiagramHtmlMaker maker = new CucaDiagramHtmlMaker(system, dir); final CucaDiagramHtmlMaker maker = new CucaDiagramHtmlMaker(system, dir);
return maker.create(); return maker.create();
} }

View File

@ -52,7 +52,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.UIManager; import javax.swing.UIManager;
import net.sourceforge.plantuml.activitydiagram.ActivityDiagramFactory; import net.sourceforge.plantuml.activitydiagram.ActivityDiagramFactory;
@ -65,6 +64,9 @@ import net.sourceforge.plantuml.descdiagram.DescriptionDiagramFactory;
import net.sourceforge.plantuml.ftp.FtpServer; import net.sourceforge.plantuml.ftp.FtpServer;
import net.sourceforge.plantuml.png.MetadataTag; import net.sourceforge.plantuml.png.MetadataTag;
import net.sourceforge.plantuml.preproc.Stdlib; import net.sourceforge.plantuml.preproc.Stdlib;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory; import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory;
import net.sourceforge.plantuml.sprite.SpriteGrayLevel; import net.sourceforge.plantuml.sprite.SpriteGrayLevel;
import net.sourceforge.plantuml.sprite.SpriteUtils; import net.sourceforge.plantuml.sprite.SpriteUtils;
@ -79,7 +81,8 @@ public class Run {
private static Cypher cypher; private static Cypher cypher;
public static void main(String[] argsArray) throws NoPlantumlCompressionException, IOException, InterruptedException { public static void main(String[] argsArray)
throws NoPlantumlCompressionException, IOException, InterruptedException {
System.setProperty("log4j.debug", "false"); System.setProperty("log4j.debug", "false");
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
if (argsArray.length > 0 && argsArray[0].equalsIgnoreCase("-headless")) { if (argsArray.length > 0 && argsArray[0].equalsIgnoreCase("-headless")) {
@ -120,6 +123,7 @@ public class Run {
encodeSprite(option.getResult()); encodeSprite(option.getResult());
return; return;
} }
Log.info("SecurityProfile " + SecurityUtils.getSecurityProfile());
if (OptionFlags.getInstance().isVerbose()) { if (OptionFlags.getInstance().isVerbose()) {
Log.info("PlantUML Version " + Version.versionString()); Log.info("PlantUML Version " + Version.versionString());
Log.info("GraphicsEnvironment.isHeadless() " + GraphicsEnvironment.isHeadless()); Log.info("GraphicsEnvironment.isHeadless() " + GraphicsEnvironment.isHeadless());
@ -270,15 +274,19 @@ public class Run {
final URL source; final URL source;
final String lowerPath = StringUtils.goLowerCase(path); final String lowerPath = StringUtils.goLowerCase(path);
if (lowerPath.startsWith(httpProtocol) || lowerPath.startsWith(httpsProtocol)) { if (lowerPath.startsWith(httpProtocol) || lowerPath.startsWith(httpsProtocol)) {
source = new URL(path); source = new java.net.URL(path);
final String p = source.getPath(); final String p = source.getPath();
fileName = p.substring(p.lastIndexOf('/') + 1, p.length()); fileName = p.substring(p.lastIndexOf('/') + 1, p.length());
} else { } else {
final File f = new File(path); final SFile f = new SFile(path);
source = f.toURI().toURL(); source = f.toURI().toURL();
fileName = f.getName(); fileName = f.getName();
} }
if (source == null) {
return;
}
InputStream stream = null; InputStream stream = null;
final BufferedImage im; final BufferedImage im;
try { try {
@ -359,15 +367,16 @@ public class Run {
new Pipe(option, System.out, System.in, charset).managePipe(error); new Pipe(option, System.out, System.in, charset).managePipe(error);
} }
private static void manageAllFiles(Option option, ErrorStatus error) throws NoPlantumlCompressionException, InterruptedException { private static void manageAllFiles(Option option, ErrorStatus error)
throws NoPlantumlCompressionException, InterruptedException {
File lockFile = null; SFile lockFile = null;
try { try {
if (OptionFlags.getInstance().isWord()) { if (OptionFlags.getInstance().isWord()) {
final File dir = new File(option.getResult().get(0)); final SFile dir = new SFile(option.getResult().get(0));
final File javaIsRunningFile = new File(dir, "javaisrunning.tmp"); final SFile javaIsRunningFile = dir.file("javaisrunning.tmp");
javaIsRunningFile.delete(); javaIsRunningFile.delete();
lockFile = new File(dir, "javaumllock.tmp"); lockFile = dir.file("javaumllock.tmp");
} }
processArgs(option, error); processArgs(option, error);
} finally { } finally {
@ -378,7 +387,8 @@ public class Run {
} }
private static void processArgs(Option option, ErrorStatus error) throws NoPlantumlCompressionException, InterruptedException { private static void processArgs(Option option, ErrorStatus error)
throws NoPlantumlCompressionException, InterruptedException {
if (option.isDecodeurl() == false && option.getNbThreads() > 1 && option.isCheckOnly() == false if (option.isDecodeurl() == false && option.getNbThreads() > 1 && option.isCheckOnly() == false
&& OptionFlags.getInstance().isExtractFromMetadata() == false) { && OptionFlags.getInstance().isExtractFromMetadata() == false) {
multithread(option, error); multithread(option, error);
@ -460,7 +470,7 @@ public class Run {
private static void manageFileInternal(File f, Option option, ErrorStatus error) private static void manageFileInternal(File f, Option option, ErrorStatus error)
throws IOException, InterruptedException { throws IOException, InterruptedException {
Log.info("Working on " + f.getAbsolutePath()); Log.info("Working on " + f.getPath());
if (OptionFlags.getInstance().isExtractFromMetadata()) { if (OptionFlags.getInstance().isExtractFromMetadata()) {
System.out.println("------------------------"); System.out.println("------------------------");
System.out.println(f); System.out.println(f);
@ -468,8 +478,8 @@ public class Run {
System.out.println(); System.out.println();
error.goOk(); error.goOk();
final String data = new MetadataTag(f, "plantuml").getData(); final String data = new MetadataTag(f, "plantuml").getData();
// File file = new File("tmp.txt"); // File file = SecurityUtils.File("tmp.txt");
// PrintWriter pw = new PrintWriter(file, "UTF-8"); // PrintWriter pw = SecurityUtils.PrintWriter(file, "UTF-8");
// pw.println(NastyEncoder.fromISO_8859_1(data)); // pw.println(NastyEncoder.fromISO_8859_1(data));
// pw.close(); // pw.close();
@ -486,7 +496,7 @@ public class Run {
sourceFileReader = new SourceFileReaderCopyCat(option.getDefaultDefines(f), f, outputDir, sourceFileReader = new SourceFileReaderCopyCat(option.getDefaultDefines(f), f, outputDir,
option.getConfig(), option.getCharset(), option.getFileFormatOption()); option.getConfig(), option.getCharset(), option.getFileFormatOption());
} else { } else {
sourceFileReader = new SourceFileReader(option.getDefaultDefines(f), f, outputDir, option.getConfig(), sourceFileReader = new SourceFileReader(option.getDefaultDefines(f), f, null, option.getConfig(),
option.getCharset(), option.getFileFormatOption()); option.getCharset(), option.getFileFormatOption());
} }
} else { } else {
@ -520,7 +530,7 @@ public class Run {
final List<GeneratedImage> result = sourceFileReader.getGeneratedImages(); final List<GeneratedImage> result = sourceFileReader.getGeneratedImages();
final Stdrpt rpt = option.getStdrpt(); final Stdrpt rpt = option.getStdrpt();
if (result.size() == 0) { if (result.size() == 0) {
Log.error("Warning: no image in " + f.getCanonicalPath()); Log.error("Warning: no image in " + f.getPath());
rpt.printInfo(System.err, null); rpt.printInfo(System.err, null);
// error.goNoData(); // error.goNoData();
return; return;
@ -537,9 +547,9 @@ public class Run {
for (BlockUml blockUml : sourceFileReader.getBlocks()) { for (BlockUml blockUml : sourceFileReader.getBlocks()) {
final SuggestedFile suggested = ((SourceFileReaderAbstract) sourceFileReader).getSuggestedFile(blockUml) final SuggestedFile suggested = ((SourceFileReaderAbstract) sourceFileReader).getSuggestedFile(blockUml)
.withPreprocFormat(); .withPreprocFormat();
final File file = suggested.getFile(0); final SFile file = suggested.getFile(0);
Log.info("Export preprocessing source to " + file.getAbsolutePath()); Log.info("Export preprocessing source to " + file.getPrintablePath());
final PrintWriter pw = charset == null ? new PrintWriter(file) : new PrintWriter(file, charset); final PrintWriter pw = charset == null ? file.createPrintWriter() : file.createPrintWriter(charset);
int level = 0; int level = 0;
for (CharSequence cs : blockUml.getDefinition(true)) { for (CharSequence cs : blockUml.getDefinition(true)) {
String s = cs.toString(); String s = cs.toString();
@ -568,7 +578,7 @@ public class Run {
for (GeneratedImage i : list) { for (GeneratedImage i : list) {
final int lineError = i.lineErrorRaw(); final int lineError = i.lineErrorRaw();
if (lineError != -1) { if (lineError != -1) {
Log.error("Error line " + lineError + " in file: " + f.getCanonicalPath()); Log.error("Error line " + lineError + " in file: " + f.getPath());
error.goWithError(); error.goWithError();
return; return;
} }

View File

@ -35,8 +35,7 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File; import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -49,17 +48,19 @@ import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEKeySpec;
import net.sourceforge.plantuml.code.AsciiEncoder; import net.sourceforge.plantuml.code.AsciiEncoder;
import net.sourceforge.plantuml.security.SFile;
public class SignatureUtils { public class SignatureUtils {
// private static byte[] salting(String pass, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, // private static byte[] salting(String pass, byte[] salt) throws
// NoSuchAlgorithmException, InvalidKeySpecException,
// UnsupportedEncodingException { // UnsupportedEncodingException {
// final byte[] tmp = salting2(pass, salt); // final byte[] tmp = salting2(pass, salt);
// return SignatureUtils.getSHA512raw(tmp); // return SignatureUtils.getSHA512raw(tmp);
// } // }
public static synchronized byte[] salting(String pass, byte[] salt) throws NoSuchAlgorithmException, public static synchronized byte[] salting(String pass, byte[] salt)
InvalidKeySpecException { throws NoSuchAlgorithmException, InvalidKeySpecException {
final int iterations = 500; final int iterations = 500;
final int keyLength = 512; final int keyLength = 512;
final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
@ -123,7 +124,8 @@ public class SignatureUtils {
} }
} }
public static synchronized byte[] getMD5raw(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException { public static synchronized byte[] getMD5raw(String s)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); final MessageDigest msgDigest = MessageDigest.getInstance("MD5");
msgDigest.update(s.getBytes("UTF-8")); msgDigest.update(s.getBytes("UTF-8"));
return msgDigest.digest(); return msgDigest.digest();
@ -133,15 +135,15 @@ public class SignatureUtils {
return getSHA512raw(s.getBytes("UTF-8")); return getSHA512raw(s.getBytes("UTF-8"));
} }
public static synchronized byte[] getSHA512raw(byte data[]) throws NoSuchAlgorithmException, public static synchronized byte[] getSHA512raw(byte data[])
UnsupportedEncodingException { throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); final MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
msgDigest.update(data); msgDigest.update(data);
return msgDigest.digest(); return msgDigest.digest();
} }
public static String getSignatureSha512(File f) throws IOException { public static String getSignatureSha512(SFile f) throws IOException {
final InputStream is = new FileInputStream(f); final InputStream is = f.openFile();
try { try {
return getSignatureSha512(is); return getSignatureSha512(is);
} finally { } finally {
@ -180,10 +182,13 @@ public class SignatureUtils {
return s; return s;
} }
public static synchronized String getSignature(File f) throws IOException { public static synchronized String getSignature(SFile f) throws IOException {
try { try {
final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); final MessageDigest msgDigest = MessageDigest.getInstance("MD5");
final FileInputStream is = new FileInputStream(f); final InputStream is = f.openFile();
if (is == null) {
throw new FileNotFoundException();
}
int read = -1; int read = -1;
while ((read = is.read()) != -1) { while ((read = is.read()) != -1) {
msgDigest.update((byte) read); msgDigest.update((byte) read);

View File

@ -36,6 +36,7 @@
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.util.Collections; import java.util.Collections;
@ -43,6 +44,7 @@ import java.util.List;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.preproc.FileWithSuffix; import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
public class SourceFileReader extends SourceFileReaderAbstract implements ISourceFileReader { public class SourceFileReader extends SourceFileReaderAbstract implements ISourceFileReader {
@ -51,33 +53,33 @@ public class SourceFileReader extends SourceFileReaderAbstract implements ISourc
} }
public SourceFileReader(File file, File outputDirectory, String charset) throws IOException { public SourceFileReader(File file, File outputDirectory, String charset) throws IOException {
this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String> emptyList(), charset, this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String>emptyList(), charset,
new FileFormatOption(FileFormat.PNG)); new FileFormatOption(FileFormat.PNG));
} }
public SourceFileReader(final File file, File outputDirectory) throws IOException { public SourceFileReader(final File file, File outputDirectory) throws IOException {
this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String> emptyList(), null, this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String>emptyList(), null,
new FileFormatOption(FileFormat.PNG)); new FileFormatOption(FileFormat.PNG));
} }
public SourceFileReader(final File file, File outputDirectory, FileFormatOption fileFormatOption) public SourceFileReader(final File file, File outputDirectory, FileFormatOption fileFormatOption)
throws IOException { throws IOException {
this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String> emptyList(), null, this(Defines.createWithFileName(file), file, outputDirectory, Collections.<String>emptyList(), null,
fileFormatOption); fileFormatOption);
} }
public SourceFileReader(Defines defines, final File file, File outputDirectory, List<String> config, public SourceFileReader(Defines defines, final File file, File outputDirectory, List<String> config, String charset,
String charset, FileFormatOption fileFormatOption) throws IOException { FileFormatOption fileFormatOption) throws IOException {
this.file = file; this.file = file;
this.fileFormatOption = fileFormatOption; this.fileFormatOption = fileFormatOption;
if (file.exists() == false) { if (file.exists() == false) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
FileSystem.getInstance().setCurrentDir(file.getAbsoluteFile().getParentFile()); FileSystem.getInstance().setCurrentDir(SFile.fromFile(file.getAbsoluteFile().getParentFile()));
if (outputDirectory == null) { if (outputDirectory == null) {
outputDirectory = file.getAbsoluteFile().getParentFile(); outputDirectory = file.getAbsoluteFile().getParentFile();
} else if (outputDirectory.isAbsolute() == false) { } else if (outputDirectory.isAbsolute() == false) {
outputDirectory = FileSystem.getInstance().getFile(outputDirectory.getPath()); outputDirectory = FileSystem.getInstance().getFile(outputDirectory.getPath()).conv();
} }
if (outputDirectory.exists() == false) { if (outputDirectory.exists() == false) {
outputDirectory.mkdirs(); outputDirectory.mkdirs();
@ -85,11 +87,11 @@ public class SourceFileReader extends SourceFileReaderAbstract implements ISourc
this.outputDirectory = outputDirectory; this.outputDirectory = outputDirectory;
final Reader reader = getReader(charset); final Reader reader = getReader(charset);
builder = new BlockUmlBuilder(config, charset, defines, reader, file.getAbsoluteFile() builder = new BlockUmlBuilder(config, charset, defines, reader,
.getParentFile(), FileWithSuffix.getFileName(file)); SFile.fromFile(file.getAbsoluteFile().getParentFile()), FileWithSuffix.getFileName(file));
} }
private File getDirIfDirectory(String newName) { private File getDirIfDirectory(String newName) throws FileNotFoundException {
Log.info("Checking=" + newName); Log.info("Checking=" + newName);
if (endsWithSlashOrAntislash(newName)) { if (endsWithSlashOrAntislash(newName)) {
Log.info("It ends with / so it looks like a directory"); Log.info("It ends with / so it looks like a directory");
@ -137,7 +139,7 @@ public class SourceFileReader extends SourceFileReaderAbstract implements ISourc
} }
@Override @Override
protected SuggestedFile getSuggestedFile(BlockUml blockUml) { protected SuggestedFile getSuggestedFile(BlockUml blockUml) throws FileNotFoundException {
final String newName = blockUml.getFileOrDirname(); final String newName = blockUml.getFileOrDirname();
SuggestedFile suggested = null; SuggestedFile suggested = null;
if (newName != null) { if (newName != null) {
@ -162,5 +164,4 @@ public class SourceFileReader extends SourceFileReaderAbstract implements ISourc
return suggested; return suggested;
} }
} }

View File

@ -35,11 +35,10 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.BufferedOutputStream; import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
@ -54,6 +53,8 @@ import java.util.Set;
import net.sourceforge.plantuml.core.Diagram; import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.error.PSystemError; import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.preproc.FileWithSuffix; import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public abstract class SourceFileReaderAbstract { public abstract class SourceFileReaderAbstract {
@ -85,10 +86,10 @@ public abstract class SourceFileReaderAbstract {
protected Reader getReader(String charset) throws FileNotFoundException, UnsupportedEncodingException { protected Reader getReader(String charset) throws FileNotFoundException, UnsupportedEncodingException {
if (charset == null) { if (charset == null) {
Log.info("Using default charset"); Log.info("Using default charset");
return new InputStreamReader(new FileInputStream(file)); return new InputStreamReader(new BufferedInputStream(new FileInputStream(file)));
} }
Log.info("Using charset " + charset); Log.info("Using charset " + charset);
return new InputStreamReader(new FileInputStream(file), charset); return new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), charset);
} }
public final Set<FileWithSuffix> getIncludedFiles() { public final Set<FileWithSuffix> getIncludedFiles() {
@ -103,11 +104,11 @@ public abstract class SourceFileReaderAbstract {
return newName.endsWith("/") || newName.endsWith("\\"); return newName.endsWith("/") || newName.endsWith("\\");
} }
private List<GeneratedImage> getCrashedImage(BlockUml blockUml, Throwable t, File outputFile) throws IOException { private List<GeneratedImage> getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException {
final GeneratedImage image = new GeneratedImageImpl(outputFile, "Crash Error", blockUml, FileImageData.CRASH); final GeneratedImage image = new GeneratedImageImpl(outputFile, "Crash Error", blockUml, FileImageData.CRASH);
OutputStream os = null; OutputStream os = null;
try { try {
os = new BufferedOutputStream(new FileOutputStream(outputFile)); os = outputFile.createBufferedOutputStream();
UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(), UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(),
UmlDiagram.getFailureText2(t, blockUml.getFlashData())); UmlDiagram.getFailureText2(t, blockUml.getFlashData()));
} finally { } finally {
@ -119,13 +120,13 @@ public abstract class SourceFileReaderAbstract {
return Collections.singletonList(image); return Collections.singletonList(image);
} }
protected void exportWarnOrErrIfWord(final File f, final Diagram system) throws FileNotFoundException { protected void exportWarnOrErrIfWord(final SFile f, final Diagram system) throws FileNotFoundException {
if (OptionFlags.getInstance().isWord()) { if (OptionFlags.getInstance().isWord()) {
final String warnOrError = system.getWarningOrError(); final String warnOrError = system.getWarningOrError();
if (warnOrError != null) { if (warnOrError != null) {
final String name = f.getName().substring(0, f.getName().length() - 4) + ".err"; final String name = f.getName().substring(0, f.getName().length() - 4) + ".err";
final File errorFile = new File(f.getParentFile(), name); final SFile errorFile = f.getParentFile().file(name);
final PrintStream ps = new PrintStream(new FileOutputStream(errorFile)); final PrintStream ps = SecurityUtils.createPrintStream(errorFile.createFileOutputStream());
ps.print(warnOrError); ps.print(warnOrError);
ps.close(); ps.close();
} }
@ -155,7 +156,7 @@ public abstract class SourceFileReaderAbstract {
continue; continue;
} }
OptionFlags.getInstance().logData(file, system); OptionFlags.getInstance().logData(SFile.fromFile(file), system);
final List<FileImageData> exportDiagrams = PSystemUtils.exportDiagrams(system, suggested, fileFormatOption, final List<FileImageData> exportDiagrams = PSystemUtils.exportDiagrams(system, suggested, fileFormatOption,
checkMetadata); checkMetadata);
if (exportDiagrams.size() > 1) { if (exportDiagrams.size() > 1) {
@ -164,7 +165,7 @@ public abstract class SourceFileReaderAbstract {
for (FileImageData fdata : exportDiagrams) { for (FileImageData fdata : exportDiagrams) {
final String desc = "[" + file.getName() + "] " + system.getDescription(); final String desc = "[" + file.getName() + "] " + system.getDescription();
final File f = fdata.getFile(); final SFile f = fdata.getFile();
exportWarnOrErrIfWord(f, system); exportWarnOrErrIfWord(f, system);
final GeneratedImage generatedImage = new GeneratedImageImpl(f, desc, blockUml, fdata.getStatus()); final GeneratedImage generatedImage = new GeneratedImageImpl(f, desc, blockUml, fdata.getStatus());
result.add(generatedImage); result.add(generatedImage);
@ -177,6 +178,6 @@ public abstract class SourceFileReaderAbstract {
return Collections.unmodifiableList(result); return Collections.unmodifiableList(result);
} }
abstract protected SuggestedFile getSuggestedFile(BlockUml blockUml); abstract protected SuggestedFile getSuggestedFile(BlockUml blockUml) throws FileNotFoundException;
} }

View File

@ -41,6 +41,7 @@ import java.util.List;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.preproc.FileWithSuffix; import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
public class SourceFileReaderCopyCat extends SourceFileReaderAbstract implements ISourceFileReader { public class SourceFileReaderCopyCat extends SourceFileReaderAbstract implements ISourceFileReader {
@ -53,15 +54,17 @@ public class SourceFileReaderCopyCat extends SourceFileReaderAbstract implements
} }
final String path = file.getParentFile().getPath(); final String path = file.getParentFile().getPath();
// System.err.println("SourceFileReaderCopyCat::path=" + path); // System.err.println("SourceFileReaderCopyCat::path=" + path);
// System.err.println("SourceFileReaderCopyCat::outputDirectory=" + outputDirectory); // System.err.println("SourceFileReaderCopyCat::outputDirectory=" +
// outputDirectory);
this.outputDirectory = new File(outputDirectory, path).getAbsoluteFile(); this.outputDirectory = new File(outputDirectory, path).getAbsoluteFile();
if (outputDirectory.exists() == false) { if (outputDirectory.exists() == false) {
outputDirectory.mkdirs(); outputDirectory.mkdirs();
} }
// System.err.println("SourceFileReaderCopyCat=" + this.outputDirectory.getPath() + " " // System.err.println("SourceFileReaderCopyCat=" +
// this.outputDirectory.getPath() + " "
// + this.outputDirectory.getAbsolutePath()); // + this.outputDirectory.getAbsolutePath());
builder = new BlockUmlBuilder(config, charset, defines, getReader(charset), file.getAbsoluteFile() builder = new BlockUmlBuilder(config, charset, defines, getReader(charset),
.getParentFile(), FileWithSuffix.getFileName(file)); SFile.fromFile(file.getAbsoluteFile().getParentFile()), FileWithSuffix.getFileName(file));
} }
@Override @Override

View File

@ -41,20 +41,21 @@ import java.util.List;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.preproc.FileWithSuffix; import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
public class SourceFileReaderHardFile extends SourceFileReaderAbstract implements ISourceFileReader { public class SourceFileReaderHardFile extends SourceFileReaderAbstract implements ISourceFileReader {
public SourceFileReaderHardFile(Defines defines, final File file, File outputFile, List<String> config, String charset, public SourceFileReaderHardFile(Defines defines, final File file, File outputFile, List<String> config,
FileFormatOption fileFormatOption) throws IOException { String charset, FileFormatOption fileFormatOption) throws IOException {
this.file = file; this.file = file;
this.fileFormatOption = fileFormatOption; this.fileFormatOption = fileFormatOption;
this.outputFile = outputFile; this.outputFile = outputFile;
if (file.exists() == false) { if (file.exists() == false) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
FileSystem.getInstance().setCurrentDir(file.getAbsoluteFile().getParentFile()); FileSystem.getInstance().setCurrentDir(SFile.fromFile(file.getAbsoluteFile().getParentFile()));
final File parentFile = file.getAbsoluteFile().getParentFile(); final SFile parentFile = SFile.fromFile(file.getAbsoluteFile().getParentFile());
builder = new BlockUmlBuilder(config, charset, defines, getReader(charset), parentFile, builder = new BlockUmlBuilder(config, charset, defines, getReader(charset), parentFile,
FileWithSuffix.getFileName(file)); FileWithSuffix.getFileName(file));
} }

View File

@ -35,9 +35,6 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.StringReader; import java.io.StringReader;
@ -50,6 +47,7 @@ import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.graphic.GraphicStrings; import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.preproc.Defines; import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svek.TextBlockBackcolored; import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity;
@ -74,7 +72,7 @@ public class SourceStringReader {
this(defines, source, "UTF-8", Collections.<String>emptyList()); this(defines, source, "UTF-8", Collections.<String>emptyList());
} }
public SourceStringReader(String source, File newCurrentDir) { public SourceStringReader(String source, SFile newCurrentDir) {
this(Defines.createEmpty(), source, "UTF-8", Collections.<String>emptyList(), newCurrentDir); this(Defines.createEmpty(), source, "UTF-8", Collections.<String>emptyList(), newCurrentDir);
} }
@ -82,7 +80,7 @@ public class SourceStringReader {
this(defines, source, charset, config, FileSystem.getInstance().getCurrentDir()); this(defines, source, charset, config, FileSystem.getInstance().getCurrentDir());
} }
public SourceStringReader(Defines defines, String source, String charset, List<String> config, File newCurrentDir) { public SourceStringReader(Defines defines, String source, String charset, List<String> config, SFile newCurrentDir) {
// // WARNING GLOBAL LOCK HERE // // WARNING GLOBAL LOCK HERE
// synchronized (SourceStringReader.class) { // synchronized (SourceStringReader.class) {
try { try {
@ -106,12 +104,12 @@ public class SourceStringReader {
} }
@Deprecated @Deprecated
public String generateImage(File f) throws IOException { public String generateImage(SFile f) throws IOException {
return outputImage(f).getDescription(); return outputImage(f).getDescription();
} }
public DiagramDescription outputImage(File f) throws IOException { public DiagramDescription outputImage(SFile f) throws IOException {
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); final OutputStream os = f.createBufferedOutputStream();
DiagramDescription result = null; DiagramDescription result = null;
try { try {
result = outputImage(os, 0); result = outputImage(os, 0);
@ -226,8 +224,8 @@ public class SourceStringReader {
private void noStartumlFound(OutputStream os, FileFormatOption fileFormatOption, long seed) throws IOException { private void noStartumlFound(OutputStream os, FileFormatOption fileFormatOption, long seed) throws IOException {
final TextBlockBackcolored error = GraphicStrings.createForError(Arrays.asList("No @startuml/@enduml found"), final TextBlockBackcolored error = GraphicStrings.createForError(Arrays.asList("No @startuml/@enduml found"),
fileFormatOption.isUseRedForError()); fileFormatOption.isUseRedForError());
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, null, null, final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, null, null, 1.0,
1.0, error.getBackcolor()); error.getBackcolor());
imageBuilder.setUDrawable(error); imageBuilder.setUDrawable(error);
imageBuilder.writeImageTOBEMOVED(fileFormatOption, seed, os); imageBuilder.writeImageTOBEMOVED(fileFormatOption, seed, os);
} }

View File

@ -119,7 +119,8 @@ public class Splash extends Window implements MouseListener, MouseMotionListener
private void updateLinkColor(final Color newLink) { private void updateLinkColor(final Color newLink) {
if (link != newLink) { if (link != newLink) {
link = newLink; link = newLink;
this.setCursor(link == LINK_NORMAL ? Cursor.getDefaultCursor() : Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.setCursor(
link == LINK_NORMAL ? Cursor.getDefaultCursor() : Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
repaint(); repaint();
} }
} }
@ -136,7 +137,7 @@ public class Splash extends Window implements MouseListener, MouseMotionListener
public void mouseClicked(MouseEvent event) { public void mouseClicked(MouseEvent event) {
if (link != LINK_NORMAL) { if (link != LINK_NORMAL) {
try { try {
Desktop.getDesktop().browse(new URL("http://plantuml.com").toURI()); Desktop.getDesktop().browse(new URL("https://plantuml.com").toURI());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -35,8 +35,6 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -49,18 +47,10 @@ import net.sourceforge.plantuml.command.regex.Matcher2;
import net.sourceforge.plantuml.command.regex.MyPattern; import net.sourceforge.plantuml.command.regex.MyPattern;
import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.command.regex.Pattern2;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.svek.DotStringFactory;
import net.sourceforge.plantuml.ugraphic.color.ColorMapper;
import net.sourceforge.plantuml.ugraphic.color.HColor;
import net.sourceforge.plantuml.ugraphic.color.HColorBackground;
// Do not move // Do not move
public class StringUtils { public class StringUtils {
public static String getPlateformDependentAbsolutePath(File file) {
return file.getAbsolutePath();
}
final static public List<String> getSplit(Pattern2 pattern, String line) { final static public List<String> getSplit(Pattern2 pattern, String line) {
final Matcher2 m = pattern.matcher(line); final Matcher2 m = pattern.matcher(line);
if (m.find() == false) { if (m.find() == false) {
@ -71,7 +61,6 @@ public class StringUtils {
result.add(m.group(i)); result.add(m.group(i));
} }
return result; return result;
} }
public static boolean isNotEmpty(String input) { public static boolean isNotEmpty(String input) {
@ -338,9 +327,9 @@ public class StringUtils {
if (uml.startsWith("@startuml\ndonors\n")) { if (uml.startsWith("@startuml\ndonors\n")) {
return false; return false;
} }
if (uml.startsWith("@startuml\ncheckversion")) { // if (uml.startsWith("@startuml\ncheckversion")) {
return false; // return false;
} // }
if (uml.startsWith("@startuml\ntestdot\n")) { if (uml.startsWith("@startuml\ntestdot\n")) {
return false; return false;
} }

View File

@ -35,15 +35,15 @@
*/ */
package net.sourceforge.plantuml; package net.sourceforge.plantuml;
import java.io.File; import net.sourceforge.plantuml.security.SFile;
public class SuggestedFile { public class SuggestedFile {
private final FileFormat fileFormat; private final FileFormat fileFormat;
private final int initialCpt; private final int initialCpt;
private final File outputFile; private final SFile outputFile;
private SuggestedFile(File outputFile, FileFormat fileFormat, int initialCpt) { private SuggestedFile(SFile outputFile, FileFormat fileFormat, int initialCpt) {
if (outputFile.getName().endsWith(fileFormat.getFileSuffix())) { if (outputFile.getName().endsWith(fileFormat.getFileSuffix())) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
@ -58,14 +58,18 @@ public class SuggestedFile {
@Override @Override
public String toString() { public String toString() {
return outputFile.getAbsolutePath() + "[" + initialCpt + "]"; return outputFile.getPrintablePath() + "[" + initialCpt + "]";
} }
public static SuggestedFile fromOutputFile(File outputFile, FileFormat fileFormat) { public static SuggestedFile fromOutputFile(SFile outputFile, FileFormat fileFormat) {
return fromOutputFile(outputFile, fileFormat, 0); return fromOutputFile(outputFile, fileFormat, 0);
} }
public File getParentFile() { public static SuggestedFile fromOutputFile(java.io.File outputFile, FileFormat fileFormat) {
return fromOutputFile(outputFile, fileFormat, 0);
}
public SFile getParentFile() {
return outputFile.getParentFile(); return outputFile.getParentFile();
} }
@ -73,17 +77,21 @@ public class SuggestedFile {
return outputFile.getName(); return outputFile.getName();
} }
public File getFile(int cpt) { public SFile getFile(int cpt) {
final String newName = fileFormat.changeName(outputFile.getName(), initialCpt + cpt); final String newName = fileFormat.changeName(outputFile.getName(), initialCpt + cpt);
return new File(outputFile.getParentFile(), newName); return outputFile.getParentFile().file(newName);
} }
public static SuggestedFile fromOutputFile(File outputFile, FileFormat fileFormat, int initialCpt) { public static SuggestedFile fromOutputFile(SFile outputFile, FileFormat fileFormat, int initialCpt) {
return new SuggestedFile(outputFile, fileFormat, initialCpt); return new SuggestedFile(outputFile, fileFormat, initialCpt);
} }
public File getTmpFile() { public static SuggestedFile fromOutputFile(java.io.File outputFile, FileFormat fileFormat, int initialCpt) {
return new File(getParentFile(), getName() + ".tmp"); return new SuggestedFile(SFile.fromFile(outputFile), fileFormat, initialCpt);
}
public SFile getTmpFile() {
return getParentFile().file(getName() + ".tmp");
} }
} }

View File

@ -44,10 +44,13 @@ public class SvgString {
private final double scale; private final double scale;
public SvgString(String svg, double scale) { public SvgString(String svg, double scale) {
if (svg == null) {
throw new IllegalArgumentException();
}
this.svg = svg; this.svg = svg;
this.scale = scale; this.scale = scale;
} }
public String getMD5Hex() { public String getMD5Hex() {
return SignatureUtils.getMD5Hex(svg); return SignatureUtils.getMD5Hex(svg);
} }

View File

@ -39,18 +39,14 @@ import java.awt.Color;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO;
import javax.script.ScriptException; import javax.script.ScriptException;
import net.sourceforge.plantuml.anim.Animation; import net.sourceforge.plantuml.anim.Animation;
@ -73,6 +69,9 @@ import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.graphic.UDrawable; import net.sourceforge.plantuml.graphic.UDrawable;
import net.sourceforge.plantuml.mjpeg.MJPEGGenerator; import net.sourceforge.plantuml.mjpeg.MJPEGGenerator;
import net.sourceforge.plantuml.pdf.PdfConverter; import net.sourceforge.plantuml.pdf.PdfConverter;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.sprite.Sprite; import net.sourceforge.plantuml.sprite.Sprite;
import net.sourceforge.plantuml.svek.EmptySvgException; import net.sourceforge.plantuml.svek.EmptySvgException;
import net.sourceforge.plantuml.svek.GraphvizCrash; import net.sourceforge.plantuml.svek.GraphvizCrash;
@ -261,7 +260,7 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
} }
private static void exportDiagramErrorText(OutputStream os, Throwable exception, List<String> strings) { private static void exportDiagramErrorText(OutputStream os, Throwable exception, List<String> strings) {
final PrintWriter pw = new PrintWriter(os); final PrintWriter pw = SecurityUtils.createPrintWriter(os);
exception.printStackTrace(pw); exception.printStackTrace(pw);
pw.println(); pw.println();
pw.println(); pw.println();
@ -312,7 +311,7 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
} }
private void exportDiagramInternalMjpeg(OutputStream os) throws IOException { private void exportDiagramInternalMjpeg(OutputStream os) throws IOException {
final File f = new File("c:/test.avi"); final SFile f = new SFile("c:/test.avi");
final int nb = 150; final int nb = 150;
final double framerate = 30; final double framerate = 30;
final MJPEGGenerator m = new MJPEGGenerator(f, 640, 480, framerate, nb); final MJPEGGenerator m = new MJPEGGenerator(f, 640, 480, framerate, nb);
@ -335,9 +334,9 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
private Dimension2D lastInfo; private Dimension2D lastInfo;
private ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException { private ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException {
final File svg = FileUtils.createTempFile("pdf", ".svf"); final SFile svg = FileUtils.createTempFile("pdf", ".svf");
final File pdfFile = FileUtils.createTempFile("pdf", ".pdf"); final SFile pdfFile = FileUtils.createTempFile("pdf", ".pdf");
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg)); final OutputStream fos = svg.createBufferedOutputStream();
final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG)); final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG));
fos.close(); fos.close();
PdfConverter.convert(svg, pdfFile); PdfConverter.convert(svg, pdfFile);
@ -351,13 +350,13 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
final protected void exportCmap(SuggestedFile suggestedFile, int index, final ImageData cmapdata) final protected void exportCmap(SuggestedFile suggestedFile, int index, final ImageData cmapdata)
throws FileNotFoundException { throws FileNotFoundException {
final String name = changeName(suggestedFile.getFile(index).getAbsolutePath()); final String name = changeName(suggestedFile.getFile(index).getAbsolutePath());
final File cmapFile = new File(name); final SFile cmapFile = new SFile(name);
PrintWriter pw = null; PrintWriter pw = null;
try { try {
if (PSystemUtils.canFileBeWritten(cmapFile) == false) { if (PSystemUtils.canFileBeWritten(cmapFile) == false) {
return; return;
} }
pw = new PrintWriter(cmapFile); pw = cmapFile.createPrintWriter();
pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6))); pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6)));
pw.close(); pw.close();
} finally { } finally {

View File

@ -39,7 +39,6 @@ import java.awt.geom.Line2D;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.ugraphic.MinMax; import net.sourceforge.plantuml.ugraphic.MinMax;
import net.sourceforge.plantuml.ugraphic.UBackground; import net.sourceforge.plantuml.ugraphic.UBackground;

View File

@ -58,7 +58,6 @@ import net.sourceforge.plantuml.creole.Parser;
import net.sourceforge.plantuml.creole.Sheet; import net.sourceforge.plantuml.creole.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1; import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.SheetBlock2; import net.sourceforge.plantuml.creole.SheetBlock2;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration; import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment; import net.sourceforge.plantuml.graphic.HorizontalAlignment;

View File

@ -60,7 +60,6 @@ import net.sourceforge.plantuml.creole.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1; import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.SheetBlock2; import net.sourceforge.plantuml.creole.SheetBlock2;
import net.sourceforge.plantuml.creole.Stencil; import net.sourceforge.plantuml.creole.Stencil;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration; import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment; import net.sourceforge.plantuml.graphic.HorizontalAlignment;
@ -251,7 +250,13 @@ public class FtileBox extends AbstractFtile {
} else { } else {
ug = ug.apply(borderColor); ug = ug.apply(borderColor);
} }
ug = ug.apply(backColor.bg()).apply(thickness); if (backColor == null) {
ug = ug.apply(new HColorNone().bg());
} else {
ug = ug.apply(backColor.bg());
}
ug = ug.apply(thickness);
rect.drawU(ug); rect.drawU(ug);
if (horizontalAlignment == HorizontalAlignment.LEFT) { if (horizontalAlignment == HorizontalAlignment.LEFT) {

View File

@ -35,9 +35,9 @@
*/ */
package net.sourceforge.plantuml.ant; package net.sourceforge.plantuml.ant;
import java.io.File; import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -49,6 +49,9 @@ import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileList; import org.apache.tools.ant.types.FileList;
import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.FileSet;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public class CheckZipTask extends Task { public class CheckZipTask extends Task {
private String zipfile = null; private String zipfile = null;
@ -76,7 +79,7 @@ public class CheckZipTask extends Task {
myLog("Check " + zipfile); myLog("Check " + zipfile);
try { try {
loadZipFile(new File(zipfile)); loadZipFile(new SFile(zipfile));
for (FileList fileList : filelists) { for (FileList fileList : filelists) {
manageFileList(fileList); manageFileList(fileList);
} }
@ -106,11 +109,15 @@ public class CheckZipTask extends Task {
private final List<String> entries = new ArrayList<String>(); private final List<String> entries = new ArrayList<String>();
private void loadZipFile(File file) throws IOException { private void loadZipFile(SFile file) throws IOException {
this.entries.clear(); this.entries.clear();
final PrintWriter pw = new PrintWriter("tmp.txt"); final PrintWriter pw = SecurityUtils.createPrintWriter("tmp.txt");
final ZipInputStream zis = new ZipInputStream(new FileInputStream(file)); final InputStream tmp = file.openFile();
if (tmp == null) {
throw new FileNotFoundException();
}
final ZipInputStream zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry(); ZipEntry ze = zis.getNextEntry();
while (ze != null) { while (ze != null) {

View File

@ -211,8 +211,8 @@ public class PlantUmlTask extends Task {
return false; return false;
} }
private boolean doFile(final File f, final SourceFileReader sourceFileReader) throws IOException, private boolean doFile(final File f, final SourceFileReader sourceFileReader)
InterruptedException { throws IOException, InterruptedException {
final Collection<GeneratedImage> result = sourceFileReader.getGeneratedImages(); final Collection<GeneratedImage> result = sourceFileReader.getGeneratedImages();
boolean error = false; boolean error = false;
for (GeneratedImage g : result) { for (GeneratedImage g : result) {

View File

@ -40,7 +40,6 @@ import java.io.OutputStream;
import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.TikzFontDistortion; import net.sourceforge.plantuml.TikzFontDistortion;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.posimo.DotPath; import net.sourceforge.plantuml.posimo.DotPath;
import net.sourceforge.plantuml.ugraphic.AbstractCommonUGraphic; import net.sourceforge.plantuml.ugraphic.AbstractCommonUGraphic;

View File

@ -48,7 +48,6 @@ import net.sourceforge.plantuml.classdiagram.command.CommandCreateElementFull2;
import net.sourceforge.plantuml.classdiagram.command.CommandCreateElementFull2.Mode; import net.sourceforge.plantuml.classdiagram.command.CommandCreateElementFull2.Mode;
import net.sourceforge.plantuml.classdiagram.command.CommandDiamondAssociation; import net.sourceforge.plantuml.classdiagram.command.CommandDiamondAssociation;
import net.sourceforge.plantuml.classdiagram.command.CommandHideShow2; import net.sourceforge.plantuml.classdiagram.command.CommandHideShow2;
import net.sourceforge.plantuml.classdiagram.command.CommandImport;
import net.sourceforge.plantuml.classdiagram.command.CommandLayoutNewLine; import net.sourceforge.plantuml.classdiagram.command.CommandLayoutNewLine;
import net.sourceforge.plantuml.classdiagram.command.CommandLinkClass; import net.sourceforge.plantuml.classdiagram.command.CommandLinkClass;
import net.sourceforge.plantuml.classdiagram.command.CommandLinkLollipop; import net.sourceforge.plantuml.classdiagram.command.CommandLinkLollipop;
@ -137,8 +136,6 @@ public class ClassDiagramFactory extends UmlDiagramFactory {
cmds.add(new CommandLinkClass(UmlDiagramType.CLASS)); cmds.add(new CommandLinkClass(UmlDiagramType.CLASS));
cmds.add(new CommandLinkLollipop(UmlDiagramType.CLASS)); cmds.add(new CommandLinkLollipop(UmlDiagramType.CLASS));
cmds.add(new CommandImport());
final CommandFactoryTipOnEntity factoryTipOnEntityCommand = new CommandFactoryTipOnEntity("a", new RegexLeaf( final CommandFactoryTipOnEntity factoryTipOnEntityCommand = new CommandFactoryTipOnEntity("a", new RegexLeaf(
"ENTITY", "(" + CommandCreateClass.CODE_NO_DOTDOT + "|[%g][^%g]+[%g])::([%g][^%g]+[%g]|[^%s]+)")); "ENTITY", "(" + CommandCreateClass.CODE_NO_DOTDOT + "|[%g][^%g]+[%g])::([%g][^%g]+[%g]|[^%s]+)"));
cmds.add(factoryTipOnEntityCommand.createMultiLine(true)); cmds.add(factoryTipOnEntityCommand.createMultiLine(true));

View File

@ -1,128 +0,0 @@
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*
*
*/
package net.sourceforge.plantuml.classdiagram.command;
import java.io.File;
import java.io.IOException;
import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.classdiagram.ClassDiagram;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.Code;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.cucadiagram.Link;
import net.sourceforge.plantuml.cucadiagram.LinkDecor;
import net.sourceforge.plantuml.cucadiagram.LinkType;
public class CommandImport extends SingleLineCommand2<ClassDiagram> {
public CommandImport() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandImport.class.getName(), //
RegexLeaf.start(), //
new RegexLeaf("import"), //
RegexLeaf.spaceOneOrMore(), //
new RegexLeaf("[%g]?"), //
new RegexLeaf("NAME", "([^%g]+)"), //
new RegexLeaf("[%g]?"), RegexLeaf.end()); //
}
@Override
protected CommandExecutionResult executeArg(ClassDiagram diagram, LineLocation location, RegexResult arg) {
final String arg0 = arg.get("NAME", 0);
try {
final File f = FileSystem.getInstance().getFile(arg0);
if (f.isFile()) {
includeSimpleFile(diagram, f);
} else if (f.isDirectory()) {
includeDirectory(diagram, f);
}
} catch (IOException e) {
e.printStackTrace();
return CommandExecutionResult.error("IO error " + e);
}
return CommandExecutionResult.ok();
}
private void includeDirectory(ClassDiagram classDiagram, File dir) throws IOException {
for (File f : dir.listFiles()) {
includeSimpleFile(classDiagram, f);
}
}
private void includeSimpleFile(ClassDiagram classDiagram, File f) throws IOException {
if (StringUtils.goLowerCase(f.getName()).endsWith(".java")) {
includeFileJava(classDiagram, f);
}
// if (f.getName().goLowerCase().endsWith(".sql")) {
// includeFileSql(f);
// }
}
private void includeFileJava(ClassDiagram diagram, final File f) throws IOException {
final JavaFile javaFile = new JavaFile(f);
for (JavaClass cl : javaFile.getJavaClasses()) {
final String idShort = cl.getName();
final Code name = diagram.buildCode(idShort);
final IEntity ent1 = diagram.getOrCreateLeaf(diagram.buildLeafIdent(idShort), name, cl.getType(), null);
for (String p : cl.getParents()) {
final IEntity ent2 = diagram.getOrCreateLeaf(diagram.buildLeafIdent(p), diagram.buildCode(p), cl.getParentType(), null);
final Link link = new Link(ent2, ent1, new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS), Display.NULL,
2, diagram.getSkinParam().getCurrentStyleBuilder());
diagram.addLink(link);
}
}
}
// private void includeFileSql(final File f) throws IOException {
// new SqlImporter(getSystem(), f).process();
// }
}

View File

@ -1,88 +0,0 @@
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*
*
*/
package net.sourceforge.plantuml.classdiagram.command;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.cucadiagram.LeafType;
class JavaClass {
private final String name;
private final String javaPackage;
private final List<String> parents = new ArrayList<String>();
private final LeafType type;
private final LeafType parentType;
public JavaClass(String javaPackage, String name, String p, LeafType type, LeafType parentType) {
this.name = name;
this.javaPackage = javaPackage;
if (p == null) {
p = "";
}
final StringTokenizer st = new StringTokenizer(StringUtils.trin(p), ",");
while (st.hasMoreTokens()) {
this.parents.add(StringUtils.trin(st.nextToken()).replaceAll("\\<.*", ""));
}
this.type = type;
this.parentType = parentType;
}
public final String getName() {
return name;
}
public final LeafType getType() {
return type;
}
public final List<String> getParents() {
return Collections.unmodifiableList(parents);
}
public final LeafType getParentType() {
return parentType;
}
public final String getJavaPackage() {
return javaPackage;
}
}

View File

@ -1,112 +0,0 @@
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*
*
*/
package net.sourceforge.plantuml.classdiagram.command;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.command.regex.Matcher2;
import net.sourceforge.plantuml.command.regex.MyPattern;
import net.sourceforge.plantuml.command.regex.Pattern2;
import net.sourceforge.plantuml.cucadiagram.LeafType;
class JavaFile {
private static final Pattern2 classDefinition = MyPattern
.cmpile("^(?:public[%s]+|abstract[%s]+|final[%s]+)*(class|interface|enum|annotation)[%s]+(\\w+)(?:.*\\b(extends|implements)[%s]+([\\w%s,]+))?");
private static final Pattern2 packageDefinition = MyPattern.cmpile("^package[%s]+([\\w+.]+)[%s]*;");
private final List<JavaClass> all = new ArrayList<JavaClass>();
public JavaFile(File f) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
initFromReader(br);
} finally {
if (br != null) {
br.close();
}
}
}
private void initFromReader(BufferedReader br) throws IOException {
String javaPackage = null;
String s;
while ((s = br.readLine()) != null) {
s = StringUtils.trin(s);
final Matcher2 matchPackage = packageDefinition.matcher(s);
if (matchPackage.find()) {
javaPackage = matchPackage.group(1);
} else {
final Matcher2 matchClassDefinition = classDefinition.matcher(s);
if (matchClassDefinition.find()) {
final String n = matchClassDefinition.group(2);
final String p = matchClassDefinition.group(4);
final LeafType type = LeafType.valueOf(StringUtils.goUpperCase(matchClassDefinition.group(1)));
final LeafType parentType = getParentType(type, matchClassDefinition.group(3));
all.add(new JavaClass(javaPackage, n, p, type, parentType));
}
}
}
}
static LeafType getParentType(LeafType type, String extendsOrImplements) {
if (extendsOrImplements == null) {
return null;
}
if (type == LeafType.CLASS) {
if (extendsOrImplements.equals("extends")) {
return LeafType.CLASS;
}
return LeafType.INTERFACE;
}
return LeafType.INTERFACE;
}
public List<JavaClass> getJavaClasses() {
return Collections.unmodifiableList(all);
}
}

View File

@ -36,8 +36,6 @@
package net.sourceforge.plantuml.command; package net.sourceforge.plantuml.command;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -50,6 +48,7 @@ import net.sourceforge.plantuml.BackSlash;
import net.sourceforge.plantuml.LineLocation; import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.StringLocated; import net.sourceforge.plantuml.StringLocated;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.security.SFile;
public class BlocLines implements Iterable<StringLocated> { public class BlocLines implements Iterable<StringLocated> {
@ -66,8 +65,11 @@ public class BlocLines implements Iterable<StringLocated> {
return sb.toString(); return sb.toString();
} }
public static BlocLines load(File f, LineLocation location) throws IOException { public static BlocLines load(SFile f, LineLocation location) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(f)); final BufferedReader br = f.openBufferedReader();
if (br == null) {
return null;
}
return loadInternal(br, location); return loadInternal(br, location);
} }

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml.command; package net.sourceforge.plantuml.command;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;

View File

@ -35,15 +35,12 @@
*/ */
package net.sourceforge.plantuml.command; package net.sourceforge.plantuml.command;
import java.io.File; import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.FileSystem; import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.FileUtils; import net.sourceforge.plantuml.FileUtils;
import net.sourceforge.plantuml.LineLocation; import net.sourceforge.plantuml.LineLocation;
@ -53,7 +50,8 @@ import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat; import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf; import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult; import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.preproc.FileWithSuffix; import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.sprite.Sprite; import net.sourceforge.plantuml.sprite.Sprite;
import net.sourceforge.plantuml.sprite.SpriteImage; import net.sourceforge.plantuml.sprite.SpriteImage;
import net.sourceforge.plantuml.sprite.SpriteSvg; import net.sourceforge.plantuml.sprite.SpriteSvg;
@ -88,24 +86,32 @@ public class CommandSpriteFile extends SingleLineCommand2<UmlDiagram> {
sprite = new SpriteImage(ImageIO.read(is)); sprite = new SpriteImage(ImageIO.read(is));
} else if (src.contains("~")) { } else if (src.contains("~")) {
final int idx = src.lastIndexOf("~"); final int idx = src.lastIndexOf("~");
final File f = FileSystem.getInstance().getFile(src.substring(0, idx)); final SFile f = FileSystem.getInstance().getFile(src.substring(0, idx));
if (f.exists() == false) { if (f.exists() == false) {
return CommandExecutionResult.error("File does not exist: " + src); return CommandExecutionResult.error("Cannot read: " + src);
} }
final String name = src.substring(idx + 1); final String name = src.substring(idx + 1);
sprite = getImageFromZip(f, name); sprite = getImageFromZip(f, name);
if (sprite == null) { if (sprite == null) {
return CommandExecutionResult.error("No image " + name + " in " + FileWithSuffix.getFileName(f)); return CommandExecutionResult.error("Cannot read: " + src);
} }
} else { } else {
final File f = FileSystem.getInstance().getFile(src); final SFile f = FileSystem.getInstance().getFile(src);
if (f.exists() == false) { if (f.exists() == false) {
return CommandExecutionResult.error("File does not exist: " + src); return CommandExecutionResult.error("Cannot read: " + src);
} }
if (isSvg(f.getName())) { if (isSvg(f.getName())) {
sprite = new SpriteSvg(f); final String tmp = FileUtils.readSvg(f);
if (tmp == null) {
return CommandExecutionResult.error("Cannot read: " + src);
}
sprite = new SpriteSvg(tmp);
} else { } else {
sprite = new SpriteImage(FileUtils.readRasterImageFromFile(f)); final BufferedImage tmp = f.readRasterImageFromFile();
if (tmp == null) {
return CommandExecutionResult.error("Cannot read: " + src);
}
sprite = new SpriteImage(tmp);
} }
} }
} catch (IOException e) { } catch (IOException e) {
@ -116,10 +122,14 @@ public class CommandSpriteFile extends SingleLineCommand2<UmlDiagram> {
return CommandExecutionResult.ok(); return CommandExecutionResult.ok();
} }
private Sprite getImageFromZip(File f, String name) throws IOException { private Sprite getImageFromZip(SFile f, String name) throws IOException {
final InputStream tmp = f.openFile();
if (tmp == null) {
return null;
}
ZipInputStream zis = null; ZipInputStream zis = null;
try { try {
zis = new ZipInputStream(new FileInputStream(f)); zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry(); ZipEntry ze = zis.getNextEntry();
while (ze != null) { while (ze != null) {

View File

@ -40,14 +40,10 @@ import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileSystem; import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.FileUtils; import net.sourceforge.plantuml.FileUtils;
@ -60,6 +56,11 @@ import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.ImgValign; import net.sourceforge.plantuml.graphic.ImgValign;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TileImageSvg; import net.sourceforge.plantuml.graphic.TileImageSvg;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SURL;
import net.sourceforge.plantuml.security.SecurityProfile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.ugraphic.UFont; import net.sourceforge.plantuml.ugraphic.UFont;
import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImage; import net.sourceforge.plantuml.ugraphic.UImage;
@ -106,24 +107,38 @@ public class AtomImg extends AbstractAtom implements Atom {
// Check if valid URL // Check if valid URL
if (src.startsWith("http:") || src.startsWith("https:")) { if (src.startsWith("http:") || src.startsWith("https:")) {
if (src.endsWith(".svg")) { if (src.endsWith(".svg")) {
return buildSvgFromUrl(src, fc, new URL(src), scale, url); return buildSvgFromUrl(src, fc, SURL.create(src), scale, url);
} }
return buildRasterFromUrl(src, fc, new URL(src), scale, url); return buildRasterFromUrl(src, fc, SURL.create(src), scale, url);
} }
final File f = FileSystem.getInstance().getFile(src); final SFile f = FileSystem.getInstance().getFile(src);
if (f.exists() == false) { if (f.exists() == false) {
return AtomText.create("(File not found: " + f.getCanonicalPath() + ")", fc); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
return AtomText.create("(File not found: " + f.getPrintablePath() + ")", fc);
}
return AtomText.create("(Cannot decode)", fc);
} }
if (f.getName().endsWith(".svg")) { if (f.getName().endsWith(".svg")) {
return new AtomImgSvg(new TileImageSvg(f)); final String tmp = FileUtils.readSvg(f);
if (tmp == null) {
return AtomText.create("(Cannot decode)", fc);
}
return new AtomImgSvg(new TileImageSvg(tmp));
} }
final BufferedImage read = FileUtils.readRasterImageFromFile(f); final BufferedImage read = f.readRasterImageFromFile();
if (read == null) { if (read == null) {
return AtomText.create("(Cannot decode: " + f.getCanonicalPath() + ")", fc); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
return AtomText.create("(Cannot decode: " + f.getPrintablePath() + ")", fc);
}
return AtomText.create("(Cannot decode)", fc);
} }
return new AtomImg(FileUtils.readRasterImageFromFile(f), scale, url, src); return new AtomImg(f.readRasterImageFromFile(), scale, url, src);
} catch (IOException e) { } catch (IOException e) {
return AtomText.create("ERROR " + e.toString(), fc); e.printStackTrace();
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
return AtomText.create("ERROR " + e.toString(), fc);
}
return AtomText.create("ERROR", fc);
} }
} }
@ -136,17 +151,23 @@ public class AtomImg extends AbstractAtom implements Atom {
return new AtomImg(read, scale, url, null); return new AtomImg(read, scale, url, null);
} }
private static Atom buildRasterFromUrl(String text, final FontConfiguration fc, URL source, double scale, Url url) private static Atom buildRasterFromUrl(String text, final FontConfiguration fc, SURL source, double scale, Url url)
throws IOException { throws IOException {
final BufferedImage read = FileUtils.readRasterImageFromURL(source); if (source == null) {
return AtomText.create("(Cannot decode: " + text + ")", fc);
}
final BufferedImage read = source.readRasterImageFromURL();
if (read == null) { if (read == null) {
return AtomText.create("(Cannot decode: " + text + ")", fc); return AtomText.create("(Cannot decode: " + text + ")", fc);
} }
return new AtomImg(read, scale, url, source.getPath()); return new AtomImg(read, scale, url, "http");
} }
private static Atom buildSvgFromUrl(String text, final FontConfiguration fc, URL source, double scale, Url url) private static Atom buildSvgFromUrl(String text, final FontConfiguration fc, SURL source, double scale, Url url)
throws IOException { throws IOException {
if (source == null) {
return AtomText.create("(Cannot decode SVG: " + text + ")", fc);
}
final byte[] read = getFile(source); final byte[] read = getFile(source);
if (read == null) { if (read == null) {
return AtomText.create("(Cannot decode SVG: " + text + ")", fc); return AtomText.create("(Cannot decode SVG: " + text + ")", fc);
@ -155,13 +176,16 @@ public class AtomImg extends AbstractAtom implements Atom {
} }
// Added by Alain Corbiere // Added by Alain Corbiere
private static byte[] getFile(URL url) { private static byte[] getFile(SURL url) {
final ByteArrayOutputStream image = new ByteArrayOutputStream();
try { try {
InputStream input = null; InputStream input = null;
try { try {
final URLConnection connection = url.openConnection(); final URLConnection connection = url.openConnection();
if (connection == null) {
return null;
}
input = connection.getInputStream(); input = connection.getInputStream();
final ByteArrayOutputStream image = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024]; final byte[] buffer = new byte[1024];
int read; int read;
while ((read = input.read(buffer)) > 0) { while ((read = input.read(buffer)) > 0) {
@ -174,7 +198,7 @@ public class AtomImg extends AbstractAtom implements Atom {
input.close(); input.close();
} }
} }
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }

View File

@ -78,6 +78,7 @@ import net.sourceforge.plantuml.graphic.HorizontalAlignment;
import net.sourceforge.plantuml.graphic.ImgValign; import net.sourceforge.plantuml.graphic.ImgValign;
import net.sourceforge.plantuml.math.ScientificEquationSafe; import net.sourceforge.plantuml.math.ScientificEquationSafe;
import net.sourceforge.plantuml.openiconic.OpenIcon; import net.sourceforge.plantuml.openiconic.OpenIcon;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.sprite.Sprite; import net.sourceforge.plantuml.sprite.Sprite;
import net.sourceforge.plantuml.ugraphic.color.HColor; import net.sourceforge.plantuml.ugraphic.color.HColor;
import net.sourceforge.plantuml.utils.CharHidder; import net.sourceforge.plantuml.utils.CharHidder;
@ -160,7 +161,9 @@ public class StripeSimple implements Stripe {
this.commands.add(CommandCreoleFontFamilyChange.createEol()); this.commands.add(CommandCreoleFontFamilyChange.createEol());
this.commands.add(CommandCreoleMonospaced.create(skinParam.getMonospacedFamily())); this.commands.add(CommandCreoleMonospaced.create(skinParam.getMonospacedFamily()));
this.commands.add(CommandCreoleUrl.create(skinParam)); this.commands.add(CommandCreoleUrl.create(skinParam));
this.commands.add(CommandCreoleSvgAttributeChange.create()); if (SecurityUtils.allowSvgText()) {
this.commands.add(CommandCreoleSvgAttributeChange.create());
}
this.header = style.getHeader(fontConfiguration, context); this.header = style.getHeader(fontConfiguration, context);

View File

@ -65,7 +65,7 @@ import net.sourceforge.plantuml.ugraphic.UGraphic;
public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPorts { public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPorts {
private TextBlock area2; private TextBlock area;
private final FontConfiguration titleConfig; private final FontConfiguration titleConfig;
private final List<CharSequence> rawBody; private final List<CharSequence> rawBody;
private final FontParam fontParam; private final FontParam fontParam;
@ -78,6 +78,7 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
private final Stereotype stereotype; private final Stereotype stereotype;
private final ILeaf entity; private final ILeaf entity;
private final boolean inEllipse; private final boolean inEllipse;
private final double minClassWidth;
public BodyEnhanced(List<String> rawBody, FontParam fontParam, ISkinParam skinParam, boolean manageModifier, public BodyEnhanced(List<String> rawBody, FontParam fontParam, ISkinParam skinParam, boolean manageModifier,
Stereotype stereotype, ILeaf entity) { Stereotype stereotype, ILeaf entity) {
@ -93,10 +94,18 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
this.manageModifier = manageModifier; this.manageModifier = manageModifier;
this.entity = entity; this.entity = entity;
this.inEllipse = false; this.inEllipse = false;
this.minClassWidth = 0;
} }
public BodyEnhanced(Display display, FontParam fontParam, ISkinParam skinParam, HorizontalAlignment align, public BodyEnhanced(Display display, FontParam fontParam, ISkinParam skinParam, HorizontalAlignment align,
Stereotype stereotype, boolean manageHorizontalLine, boolean manageModifier, ILeaf entity) { Stereotype stereotype, boolean manageHorizontalLine, boolean manageModifier, ILeaf entity) {
this(display, fontParam, skinParam, align, stereotype, manageHorizontalLine, manageHorizontalLine, entity, 0);
}
public BodyEnhanced(Display display, FontParam fontParam, ISkinParam skinParam, HorizontalAlignment align,
Stereotype stereotype, boolean manageHorizontalLine, boolean manageModifier, ILeaf entity,
double minClassWidth) {
this.minClassWidth = minClassWidth;
this.entity = entity; this.entity = entity;
this.stereotype = stereotype; this.stereotype = stereotype;
this.rawBody = new ArrayList<CharSequence>(); this.rawBody = new ArrayList<CharSequence>();
@ -137,8 +146,8 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
} }
private TextBlock getArea(StringBounder stringBounder) { private TextBlock getArea(StringBounder stringBounder) {
if (area2 != null) { if (area != null) {
return area2; return area;
} }
urls.clear(); urls.clear();
final List<TextBlock> blocks = new ArrayList<TextBlock>(); final List<TextBlock> blocks = new ArrayList<TextBlock>();
@ -187,12 +196,16 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
new MethodsOrFieldsArea(members, fontParam, skinParam, align, stereotype, entity), separator, title)); new MethodsOrFieldsArea(members, fontParam, skinParam, align, stereotype, entity), separator, title));
if (blocks.size() == 1) { if (blocks.size() == 1) {
this.area2 = blocks.get(0); this.area = blocks.get(0);
} else { } else {
this.area2 = new TextBlockVertical2(blocks, align); this.area = new TextBlockVertical2(blocks, align);
}
if (minClassWidth > 0) {
this.area = TextBlockUtils.withMinWidth(this.area, minClassWidth,
skinParam.getDefaultTextAlignment(HorizontalAlignment.LEFT));
} }
return area2; return area;
} }
private static List<CharSequence> buildAllTree(String init, ListIterator<CharSequence> it) { private static List<CharSequence> buildAllTree(String init, ListIterator<CharSequence> it) {

View File

@ -37,7 +37,6 @@ package net.sourceforge.plantuml.cucadiagram;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -60,6 +59,7 @@ import net.sourceforge.plantuml.cucadiagram.dot.CucaDiagramTxtMaker;
import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory; import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory;
import net.sourceforge.plantuml.graphic.USymbol; import net.sourceforge.plantuml.graphic.USymbol;
import net.sourceforge.plantuml.jdot.CucaDiagramFileMakerJDot; import net.sourceforge.plantuml.jdot.CucaDiagramFileMakerJDot;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.skin.VisibilityModifier; import net.sourceforge.plantuml.skin.VisibilityModifier;
import net.sourceforge.plantuml.statediagram.StateDiagram; import net.sourceforge.plantuml.statediagram.StateDiagram;
import net.sourceforge.plantuml.svek.CucaDiagramFileMaker; import net.sourceforge.plantuml.svek.CucaDiagramFileMaker;
@ -624,7 +624,7 @@ public abstract class CucaDiagram extends UmlDiagram implements GroupHierarchy,
try { try {
createFilesTxt(os, index, fileFormat); createFilesTxt(os, index, fileFormat);
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(new PrintStream(os)); t.printStackTrace(SecurityUtils.createPrintStream(os));
} }
return ImageDataSimple.ok(); return ImageDataSimple.ok();
} }

View File

@ -35,10 +35,11 @@
*/ */
package net.sourceforge.plantuml.cucadiagram; package net.sourceforge.plantuml.cucadiagram;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import net.sourceforge.plantuml.security.SFile;
public class GroupPrinter { public class GroupPrinter {
private final PrintWriter pw; private final PrintWriter pw;
@ -83,9 +84,9 @@ public class GroupPrinter {
pw.println("<li>" + leaf.getCodeGetName()); pw.println("<li>" + leaf.getCodeGetName());
} }
public static void print(File f, IGroup rootGroup) { public static void print(SFile f, IGroup rootGroup) {
try { try {
final PrintWriter pw = new PrintWriter(f); final PrintWriter pw = f.createPrintWriter();
pw.println("<html>"); pw.println("<html>");
new GroupPrinter(pw).printGroup(rootGroup); new GroupPrinter(pw).printGroup(rootGroup);
pw.println("</html>"); pw.println("</html>");

View File

@ -44,6 +44,7 @@ import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.OptionFlags; import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SFile;
abstract class AbstractGraphviz implements Graphviz { abstract class AbstractGraphviz implements Graphviz {
@ -58,8 +59,8 @@ abstract class AbstractGraphviz implements Graphviz {
private static String findExecutableOnPath(String name) { private static String findExecutableOnPath(String name) {
final String path = System.getenv("PATH"); final String path = System.getenv("PATH");
if (path != null) { if (path != null) {
for (String dirname : path.split(File.pathSeparator)) { for (String dirname : path.split(SFile.pathSeparator)) {
File file = new File(dirname, name); final File file = new File(dirname, name);
if (file.isFile() && file.canExecute()) { if (file.isFile() && file.canExecute()) {
return file.getAbsolutePath(); return file.getAbsolutePath();
} }
@ -98,7 +99,8 @@ abstract class AbstractGraphviz implements Graphviz {
} }
if (getExeState() != ExeState.OK) { if (getExeState() != ExeState.OK) {
// createPngNoGraphviz(os, new FileFormatOption(FileFormat.valueOf(type[0].goUpperCase()))); // createPngNoGraphviz(os, new
// FileFormatOption(FileFormat.valueOf(type[0].goUpperCase())));
throw new IllegalStateException(); throw new IllegalStateException();
} }
final String cmd[] = getCommandLine(); final String cmd[] = getCommandLine();

View File

@ -36,10 +36,8 @@
package net.sourceforge.plantuml.cucadiagram.dot; package net.sourceforge.plantuml.cucadiagram.dot;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -61,6 +59,8 @@ import net.sourceforge.plantuml.posimo.Block;
import net.sourceforge.plantuml.posimo.Cluster; import net.sourceforge.plantuml.posimo.Cluster;
import net.sourceforge.plantuml.posimo.GraphvizSolverB; import net.sourceforge.plantuml.posimo.GraphvizSolverB;
import net.sourceforge.plantuml.posimo.Path; import net.sourceforge.plantuml.posimo.Path;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.ugraphic.UTranslate; import net.sourceforge.plantuml.ugraphic.UTranslate;
import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt; import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt;
@ -152,11 +152,11 @@ public final class CucaDiagramTxtMaker {
} }
} }
public List<File> createFiles(File suggestedFile) throws IOException { public List<SFile> createFiles(SFile suggestedFile) throws IOException {
if (fileFormat == FileFormat.UTXT) { if (fileFormat == FileFormat.UTXT) {
globalUg.getCharArea().print(new PrintStream(suggestedFile, "UTF-8")); globalUg.getCharArea().print(suggestedFile.createPrintStream("UTF-8"));
} else { } else {
globalUg.getCharArea().print(new PrintStream(suggestedFile)); globalUg.getCharArea().print(suggestedFile.createPrintStream());
} }
return Collections.singletonList(suggestedFile); return Collections.singletonList(suggestedFile);
} }
@ -196,7 +196,7 @@ public final class CucaDiagramTxtMaker {
} }
public void createFiles(OutputStream os, int index) { public void createFiles(OutputStream os, int index) {
globalUg.getCharArea().print(new PrintStream(os)); globalUg.getCharArea().print(SecurityUtils.createPrintStream(os));
} }
} }

View File

@ -35,20 +35,21 @@
*/ */
package net.sourceforge.plantuml.cucadiagram.dot; package net.sourceforge.plantuml.cucadiagram.dot;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.PrintWriter; import java.io.PrintWriter;
import net.sourceforge.plantuml.security.SFile;
public class DebugTrace { public class DebugTrace {
private static final File out = new File("debug" + System.currentTimeMillis() + ".txt"); private static final SFile out = new SFile("debug" + System.currentTimeMillis() + ".txt");
private static PrintWriter pw; private static PrintWriter pw;
private synchronized static PrintWriter getPrintWriter() { private synchronized static PrintWriter getPrintWriter() {
if (pw == null) { if (pw == null) {
try { try {
pw = new PrintWriter(out); pw = out.createPrintWriter();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
} }

View File

@ -51,7 +51,6 @@ import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.cucadiagram.IGroup; import net.sourceforge.plantuml.cucadiagram.IGroup;
import net.sourceforge.plantuml.cucadiagram.ILeaf; import net.sourceforge.plantuml.cucadiagram.ILeaf;
import net.sourceforge.plantuml.cucadiagram.Link; import net.sourceforge.plantuml.cucadiagram.Link;
import net.sourceforge.plantuml.cucadiagram.LinkDecor;
import net.sourceforge.plantuml.cucadiagram.PortionShower; import net.sourceforge.plantuml.cucadiagram.PortionShower;
import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory; import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory;
import net.sourceforge.plantuml.svek.DotMode; import net.sourceforge.plantuml.svek.DotMode;

View File

@ -44,8 +44,10 @@ import java.util.regex.Pattern;
import net.sourceforge.plantuml.ISkinParam; import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityProfile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.vizjs.GraphvizJs; import net.sourceforge.plantuml.vizjs.GraphvizJs;
import net.sourceforge.plantuml.vizjs.VizJsEngine; import net.sourceforge.plantuml.vizjs.VizJsEngine;
@ -55,7 +57,7 @@ public class GraphvizUtils {
private static int DOT_VERSION_LIMIT = 226; private static int DOT_VERSION_LIMIT = 226;
private static boolean isWindows() { private static boolean isWindows() {
return File.separatorChar == '\\'; return SFile.separatorChar == '\\';
} }
private static String dotExecutable; private static String dotExecutable;
@ -131,35 +133,19 @@ public class GraphvizUtils {
if (local != null) { if (local != null) {
return local; return local;
} }
final String env = getenv("PLANTUML_LIMIT_SIZE"); final String env = SecurityUtils.getenv("PLANTUML_LIMIT_SIZE");
if (StringUtils.isNotEmpty(env) && env.matches("\\d+")) { if (StringUtils.isNotEmpty(env) && env.matches("\\d+")) {
return Integer.parseInt(env); return Integer.parseInt(env);
} }
return 4096; return 4096;
} }
public static boolean getJavascriptUnsecure() {
final String env = getenv("PLANTUML_JAVASCRIPT_UNSECURE");
if ("true".equalsIgnoreCase(env)) {
return true;
}
return OptionFlags.ALLOW_INCLUDE;
}
public static String getenvDefaultConfigFilename() { public static String getenvDefaultConfigFilename() {
return getenv("PLANTUML_DEFAULT_CONFIG_FILENAME"); return SecurityUtils.getenv("PLANTUML_DEFAULT_CONFIG_FILENAME");
} }
public static String getenvLogData() { public static String getenvLogData() {
return getenv("PLANTUML_LOGDATA"); return SecurityUtils.getenv("PLANTUML_LOGDATA");
}
public static String getenv(String name) {
final String env = System.getProperty(name);
if (StringUtils.isNotEmpty(env)) {
return env;
}
return System.getenv(name);
} }
private static String dotVersion = null; private static String dotVersion = null;
@ -220,15 +206,16 @@ public class GraphvizUtils {
return error; return error;
} }
final String ent = GraphvizUtils.getenvGraphvizDot();
if (ent == null) {
result.add("The environment variable GRAPHVIZ_DOT has not been set");
} else {
result.add("The environment variable GRAPHVIZ_DOT has been set to " + ent);
}
final File dotExe = GraphvizUtils.getDotExe(); final File dotExe = GraphvizUtils.getDotExe();
result.add("Dot executable is " + dotExe); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
final String ent = GraphvizUtils.getenvGraphvizDot();
if (ent == null) {
result.add("The environment variable GRAPHVIZ_DOT has not been set");
} else {
result.add("The environment variable GRAPHVIZ_DOT has been set to " + ent);
}
result.add("Dot executable is " + dotExe);
}
final ExeState exeState = ExeState.checkFile(dotExe); final ExeState exeState = ExeState.checkFile(dotExe);
if (exeState == ExeState.OK) { if (exeState == ExeState.OK) {

View File

@ -35,15 +35,15 @@
*/ */
package net.sourceforge.plantuml.cucadiagram.dot; package net.sourceforge.plantuml.cucadiagram.dot;
import java.io.File;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SFile;
public class GraphvizVersionFinder { public class GraphvizVersionFinder {
final private File dotExe; final private SFile dotExe;
final public static GraphvizVersion DEFAULT = new GraphvizVersion() { final public static GraphvizVersion DEFAULT = new GraphvizVersion() {
public boolean useShield() { public boolean useShield() {
return true; return true;
@ -66,7 +66,7 @@ public class GraphvizVersionFinder {
} }
}; };
public GraphvizVersionFinder(File dotExe) { public GraphvizVersionFinder(SFile dotExe) {
this.dotExe = dotExe; this.dotExe = dotExe;
} }

View File

@ -39,6 +39,8 @@ import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import net.sourceforge.plantuml.security.SFile;
public class GraphvizVersions { public class GraphvizVersions {
private final static GraphvizVersions singleton = new GraphvizVersions(); private final static GraphvizVersions singleton = new GraphvizVersions();
@ -66,7 +68,7 @@ public class GraphvizVersions {
} }
static GraphvizVersion checkVersionSlow(String pathExecutable) { static GraphvizVersion checkVersionSlow(String pathExecutable) {
final GraphvizVersionFinder finder = new GraphvizVersionFinder(new File(pathExecutable)); final GraphvizVersionFinder finder = new GraphvizVersionFinder(new SFile(pathExecutable));
return finder.getVersion(); return finder.getVersion();
} }

View File

@ -60,7 +60,7 @@ class GraphvizWindows extends AbstractGraphviz {
private File specificDotExeSlow() { private File specificDotExeSlow() {
for (File tmp : new File("c:/").listFiles(new FileFilter() { for (File tmp : new File("c:/").listFiles(new FileFilter() {
public boolean accept(File pathname) { public boolean accept(java.io.File pathname) {
return pathname.isDirectory() && pathname.canRead(); return pathname.isDirectory() && pathname.canRead();
} }
})) { })) {
@ -78,7 +78,7 @@ class GraphvizWindows extends AbstractGraphviz {
} }
final List<File> dots = new ArrayList<File>(); final List<File> dots = new ArrayList<File>();
final File[] files = dir.listFiles(new FileFilter() { final File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) { public boolean accept(java.io.File pathname) {
return pathname.isDirectory() && StringUtils.goLowerCase(pathname.getName()).startsWith("graphviz"); return pathname.isDirectory() && StringUtils.goLowerCase(pathname.getName()).startsWith("graphviz");
} }
}); });

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml.cucadiagram.dot; package net.sourceforge.plantuml.cucadiagram.dot;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@ -45,6 +44,7 @@ import java.util.concurrent.locks.ReentrantLock;
import net.sourceforge.plantuml.OptionFlags; import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.api.MyRunnable; import net.sourceforge.plantuml.api.MyRunnable;
import net.sourceforge.plantuml.api.TimeoutExecutor; import net.sourceforge.plantuml.api.TimeoutExecutor;
import net.sourceforge.plantuml.security.SFile;
public class ProcessRunner { public class ProcessRunner {
@ -64,7 +64,7 @@ public class ProcessRunner {
return run(in, redirection, null); return run(in, redirection, null);
} }
public ProcessState run(byte in[], OutputStream redirection, File dir) { public ProcessState run(byte in[], OutputStream redirection, SFile dir) {
if (this.state.differs(ProcessState.INIT())) { if (this.state.differs(ProcessState.INIT())) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
@ -96,14 +96,14 @@ public class ProcessRunner {
class MainThread implements MyRunnable { class MainThread implements MyRunnable {
private final String[] cmd; private final String[] cmd;
private final File dir; private final SFile dir;
private final OutputStream redirection; private final OutputStream redirection;
private final byte[] in; private final byte[] in;
private volatile Process process; private volatile Process process;
private volatile ThreadStream errorStream; private volatile ThreadStream errorStream;
private volatile ThreadStream outStream; private volatile ThreadStream outStream;
public MainThread(String[] cmd, File dir, OutputStream redirection, byte[] in) { public MainThread(String[] cmd, SFile dir, OutputStream redirection, byte[] in) {
this.cmd = cmd; this.cmd = cmd;
this.dir = dir; this.dir = dir;
this.redirection = redirection; this.redirection = redirection;
@ -160,7 +160,7 @@ public class ProcessRunner {
private void startThreads() { private void startThreads() {
try { try {
process = Runtime.getRuntime().exec(cmd, null, dir); process = Runtime.getRuntime().exec(cmd, null, dir == null ? null : dir.conv());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
changeState.lock(); changeState.lock();

View File

@ -43,9 +43,10 @@ import java.io.InputStream;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.math.BigInteger; import java.math.BigInteger;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import net.sourceforge.plantuml.security.ImageIO;
public class Dedication { public class Dedication {
private final String name; private final String name;

View File

@ -42,8 +42,6 @@ import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.AbstractPSystem; import net.sourceforge.plantuml.AbstractPSystem;
import net.sourceforge.plantuml.BackSlash; import net.sourceforge.plantuml.BackSlash;
import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormat;
@ -52,6 +50,7 @@ import net.sourceforge.plantuml.UmlDiagram;
import net.sourceforge.plantuml.api.ImageDataSimple; import net.sourceforge.plantuml.api.ImageDataSimple;
import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.svek.GraphvizCrash; import net.sourceforge.plantuml.svek.GraphvizCrash;
public class PSystemDitaa extends AbstractPSystem { public class PSystemDitaa extends AbstractPSystem {

View File

@ -72,25 +72,25 @@ public class PSystemDonors extends AbstractPSystem {
private static final int COLS = 6; private static final int COLS = 6;
private static final int FREE_LINES = 6; private static final int FREE_LINES = 6;
public static final String DONORS = "6rWB02mFUBXRGOc9nbfsvvsjZ9-86KqYM9ud58U1HJpT3OW_mBtJutuZ_KLqfNlVD2FQiZN5USOGiI3e" public static final String DONORS = "6tOB0AmEUFDMA37HMBjrivhoM7AcIGJByuJYCB28fxi1yGUuTthSRwI_YAvqxvjcH5ksfZZF628M13sU"
+ "yJIvPjZctXu8Sw9y2FxT21uW0qH9r4QrBFUas6sRAaDAyEyxN_abw1tUiK6YkKgZnP5xPFSBxs-6ytpJ" + "9jSCszpR0s7EZ1V1dJc2dWyV88ghDl8ZTUGuzq0i5Tr_cRWztJekLC6nQeHoeBYruNrdR9wTnXUl7atG"
+ "67hf6R0ygdwAxcl_T-agw_AgAipItGgCmAZJ2DLvIp77TFz7WJjEmKvGHOybntGgvpeSggY0LoSy1XPf" + "Hk37mBxwVrE7hCj3LPYbknNFOp4g6g4wB_GKSwnp_qSL5w9Wtw7gOSindRgu3eSgAk3L2O-1HPh1RUEy"
+ "1ZUFyshKP5HCQXCfaTOe8s9q9hJcfFPPiY63n2_r0xpPN66fu4meZb4IT7qzjtVRGFFB95v4mH0B3WlC" + "MZGP5PFOH4geDaeG4eCPEd9I-mBvGGQ9N-e5j6cjhY6HFQ2upXI9hjjo1xODDBzIugNW3xvWyy0SIZdS"
+ "ePJ3kq3nSoD18YX0eNaMlR6L1qkUk61H2YtimnyQoO57AfdJqI8HyW0A8fx11P9Ug5KJpaui1bGHoHQz" + "9oXnRiIGyFEWeMqLlR4rHvOySS1G3YtipH-Av4Zl8PbLXXQ9W1ee27aO1oIZK8Scd1rR3AYw1riCQ92g"
+ "bgJgqdY8T5o7vIczDXhk0OiG2yu2QWZoF-Y2JuzL7qsTusfe9FKqoLkrTQXVYVVGDYFwfXvD4jLdVzFC" + "g_qct7qSbgTeRZJS1HO15fm5r13aVz0JFgEll6IopwUYbf2dIRogRKJzgdW_RJEYR_RH950-xA5PiLy5"
+ "4NU1iaMgQwlFCLxp2CZTKYkl-3BgoEO0pxvxLvFrZnR8Zq2trKGj-RFi2mi9Y6ih-o1TvuQBHo_2CHio" + "ojP3EbjUn_oheqFUDMJbqMz67TbSWxlivj8mlxH0_GXqsvoe9Bw-A0iBIGZNbdeXNUVcAxKNuOGDAHNh"
+ "JQpZTxFjDVs5hbXbep9MW4L-EhykDI715heoUGHwGgk2PfrFDDBI-lsYnvUD-uHhAYpk7Q3tKJRd-V_T" + "v5riUOt-eIjIsOHOpWuMyhH_NMrA1bleogKQUaEhEiqwdsX93VNtGnuTEjy5rrIRtJjCxv4s5_d_NRSq"
+ "xcLcA0xGqJApeEiHAihLjEefjY22Cq8NXjm4oHKuRwxRSVEwoA_wWE3DPGJYi26qGRm-Gkcw569rhEh6" + "CnG7wCGKiw3h0aNdQ5hr5nk8uBJGXI4t0V84ofV9BNzPFiGVzG71MqW4eh1HqWd-_4Xvo8KBCx2gMrAC"
+ "D2E0sTFAkKY4BH5GertGlQYIYPJrRe_JrPc-RCpS9trmtMymHd5C9pGMaRjt8JqCArIZMT-iVKXp2gxo" + "0EPFAUT98kY42FKw13sCAfb8cRj-XadFicLZRfdqmPKr62C_ffEAa_3TNE0HXjLgqKmtQnzXbU0Ll4xo"
+ "EiwhxZNUhsBRty9xqeVq_2C3VgPt1YBbHposhVoZIBUEYbcifMxMvRkw7nmyTCU2CrYqX1bjjaEcGU5i" + "gdkDzgiKiIsyProarWyPY3FC6H4fFwBOjhHBmaCTXLci9JTryJtT3WuUkdl16InQnOmsso5BGk5iCixK"
+ "CixKhqn-MZBy7OUivlU6PgyWUYTiX0Wpci7jhSarDRbC8cWwo_6n2uWYjNZ5hhXm1qBTB2l55ZR5oZDM" + "Mum-D1Z-Za8sQVVcfbv1-Awm4TpCQ0QtboOtrEGI2R_bBCV35e0IS_6ANL7XKaBLB2kLhMi9aoDMZqE6"
+ "Zq92ViTyWaZbNJYjM6lk9ZmZUnJKuRmxLYthrw6MRG7LvZ11HbgeQgIQ8tqja85hTNeMMmVRdnPOCBRn" + "_4xq2IoLU-5fnuxcxiGpnAEW3kVTiUfKVqvftXPGGqmJPAI5CcT8auUj1J9mh4xFIXjWzrCx5enjVh9Y"
+ "g8eLX-8x9jgltA1W2imKuNvH48boGLfABp59JE1__lnAFRclWutlZFB9E4ZsaCH05N9rnechfe7p65R6" + "pQ7ujebOumODKs2wYF160v582kebUib9OW3VTVcLUgIlWu_lwcd5E4XQI6AW2bATyODJq_3v34rZlKR_"
+ "Ues_Nszjzmh-_7iTRN9gYsT-YY1w3fBZtqbnp8LIrl4qobzdmsB08LPmqKR1bLkMtWmaBDY1TsPHZmyp" + "jxMsMtR-_7iTsUJK6VUwYY1w3YBnRwS07UKa8dWQyFwMZv1t2gmQNNfGX2jtARqPI5YmczwPHJqwp6ZS"
+ "6ZSnMMvQBdh5zg4gVZkv0HVp8JRikCYaEKOikTBRRZseuhRlU6Dna8FYxwBAk4okSlKQ654WjhuN9prs" + "yMAvERdevTk7glxkv3PSB0RViE8YaoQVVOcJrdRre8hQllkDnK4E7NyNLQPaSfLBQs14WzZMNfpqs6sc"
+ "6sLuoYe5M50Tjmci_Ugtqonl6dFUeLGtN0RopO6SAlK8BQofQSrO26mGOtvlOJ-LzFXF1lh5jTQFlNhe" + "uYwh5U31xBXCOErNJy_DD5uovhfZgMvu7CWM8ZAa67ryiQQczN4Yi5awytjBsv3CwB_1Y7vHhUcnLm_z"
+ "EQYyXtU3Xczxa7x6I31S9EsOeBVqEPc1XsyOv8svEV7fOicLYsuOTe5WXVr6NoOB2I_iQ9LBDDSUNdFw" + "1-NtM15e-BQ5Ciw91CD5we61VdEVanbqyms7l30r9pfTBBvoqMt3pXUiiD_4ZyX2mWlRccaYhBLtgpdz"
+ "vLtEQZjow1QoZrQZ-OMYYfY1N5YirTM9XLAE1r8a1NFsbl42QGUzmIKz0JX5mV7-xaCulT3yY6RjuncD" + "OgwA2G00"; + "QIwUi-t8qRUGVM8scbx8guWPoC9YWvwTM2ZbU215KZ1dRvae8ksWDxYiHm2Tec3yVnc4euNcHsHMcMTl" + "57FP9cC_bFBc_GC0";
/* /*
* Special thanks to our sponsors and donors: * Special thanks to our sponsors and donors:

View File

@ -43,14 +43,13 @@ import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.AbstractPSystem; import net.sourceforge.plantuml.AbstractPSystem;
import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.graphic.GraphicPosition; import net.sourceforge.plantuml.graphic.GraphicPosition;
import net.sourceforge.plantuml.graphic.GraphicStrings; import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.svek.TextBlockBackcolored; import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity;

View File

@ -40,7 +40,6 @@ import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -76,6 +75,7 @@ import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.graphic.TextBlockRaw; import net.sourceforge.plantuml.graphic.TextBlockRaw;
import net.sourceforge.plantuml.graphic.TextBlockUtils; import net.sourceforge.plantuml.graphic.TextBlockUtils;
import net.sourceforge.plantuml.graphic.VerticalAlignment; import net.sourceforge.plantuml.graphic.VerticalAlignment;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.svek.TextBlockBackcolored; import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.MinMax; import net.sourceforge.plantuml.ugraphic.MinMax;
@ -203,15 +203,15 @@ public abstract class PSystemError extends AbstractPSystem {
final UGraphicTxt ugt = new UGraphicTxt(); final UGraphicTxt ugt = new UGraphicTxt();
final UmlCharArea area = ugt.getCharArea(); final UmlCharArea area = ugt.getCharArea();
area.drawStringsLR(getPureAsciiFormatted(), 0, 0); area.drawStringsLR(getPureAsciiFormatted(), 0, 0);
area.print(new PrintStream(os)); area.print(SecurityUtils.createPrintStream(os));
return new ImageDataSimple(1, 1); return new ImageDataSimple(1, 1);
} }
final TextBlockBackcolored result = getGraphicalFormatted(); final TextBlockBackcolored result = getGraphicalFormatted();
TextBlock udrawable; TextBlock udrawable;
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, getMetadata(),
false, null, getMetadata(), null, 1.0, result.getBackcolor()); null, 1.0, result.getBackcolor());
imageBuilder.setRandomPixel(true); imageBuilder.setRandomPixel(true);
if (getSource().getTotalLineCount() < 5) { if (getSource().getTotalLineCount() < 5) {
udrawable = addWelcome(result); udrawable = addWelcome(result);

View File

@ -54,6 +54,7 @@ import java.util.StringTokenizer;
import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileUtils; import net.sourceforge.plantuml.FileUtils;
import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SecurityUtils;
class FtpLoop implements Runnable { class FtpLoop implements Runnable {
enum Mode { enum Mode {
@ -74,7 +75,7 @@ class FtpLoop implements Runnable {
this.incoming = socket; this.incoming = socket;
this.ftpServer = ftpServer; this.ftpServer = ftpServer;
this.br = new BufferedReader(new InputStreamReader(incoming.getInputStream(), ftpServer.getCharset())); this.br = new BufferedReader(new InputStreamReader(incoming.getInputStream(), ftpServer.getCharset()));
this.pw = new PrintWriter(incoming.getOutputStream(), true); this.pw = SecurityUtils.createPrintWriter(incoming.getOutputStream(), true);
} }
// http://www.ncftp.com/libncftp/doc/ftp_overview.html // http://www.ncftp.com/libncftp/doc/ftp_overview.html
@ -178,7 +179,8 @@ class FtpLoop implements Runnable {
private void localLog(String s) { private void localLog(String s) {
} }
private void retr(final String fileName, Socket soc) throws UnknownHostException, IOException, InterruptedException { private void retr(final String fileName, Socket soc)
throws UnknownHostException, IOException, InterruptedException {
final OutputStream os = soc.getOutputStream(); final OutputStream os = soc.getOutputStream();
final byte[] data = connexion.getData(fileName); final byte[] data = connexion.getData(fileName);
@ -291,7 +293,7 @@ class FtpLoop implements Runnable {
} }
private void list(final Socket soc) throws IOException { private void list(final Socket soc) throws IOException {
final PrintWriter listing = new PrintWriter(soc.getOutputStream(), true); final PrintWriter listing = SecurityUtils.createPrintWriter(soc.getOutputStream(), true);
final Collection<String> files = connexion.getFiles(); final Collection<String> files = connexion.getFiles();
if (files.size() > 0) { if (files.size() > 0) {
int total = 0; int total = 0;

View File

@ -43,7 +43,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO; import net.sourceforge.plantuml.security.ImageIO;
public class IconLoader { public class IconLoader {

View File

@ -36,12 +36,7 @@
package net.sourceforge.plantuml.graphic; package net.sourceforge.plantuml.graphic;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import net.sourceforge.plantuml.FileSystem; import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.FileUtils; import net.sourceforge.plantuml.FileUtils;
@ -49,12 +44,15 @@ import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.command.regex.Matcher2; import net.sourceforge.plantuml.command.regex.Matcher2;
import net.sourceforge.plantuml.command.regex.MyPattern; import net.sourceforge.plantuml.command.regex.MyPattern;
import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.command.regex.Pattern2;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SURL;
public class Img implements HtmlCommand { public class Img implements HtmlCommand {
final static private Pattern2 srcPattern = MyPattern.cmpile("(?i)src[%s]*=[%s]*[\"%q]?([^%s\">]+)[\"%q]?"); final static private Pattern2 srcPattern = MyPattern.cmpile("(?i)src[%s]*=[%s]*[\"%q]?([^%s\">]+)[\"%q]?");
final static private Pattern2 vspacePattern = MyPattern.cmpile("(?i)vspace[%s]*=[%s]*[\"%q]?(\\d+)[\"%q]?"); final static private Pattern2 vspacePattern = MyPattern.cmpile("(?i)vspace[%s]*=[%s]*[\"%q]?(\\d+)[\"%q]?");
final static private Pattern2 valignPattern = MyPattern.cmpile("(?i)valign[%s]*=[%s]*[\"%q]?(top|bottom|middle)[\"%q]?"); final static private Pattern2 valignPattern = MyPattern
.cmpile("(?i)valign[%s]*=[%s]*[\"%q]?(top|bottom|middle)[\"%q]?");
final static private Pattern2 noSrcColonPattern = MyPattern.cmpile("(?i)" + Splitter.imgPatternNoSrcColon); final static private Pattern2 noSrcColonPattern = MyPattern.cmpile("(?i)" + Splitter.imgPatternNoSrcColon);
private final TextBlock tileImage; private final TextBlock tileImage;
@ -96,29 +94,36 @@ public class Img implements HtmlCommand {
} }
final String src = m.group(1); final String src = m.group(1);
try { try {
final File f = FileSystem.getInstance().getFile(src); final SFile f = FileSystem.getInstance().getFile(src);
if (f.exists() == false) { if (f.exists() == false) {
// Check if valid URL // Check if valid URL
if (src.startsWith("http:") || src.startsWith("https:")) { if (src.startsWith("http:") || src.startsWith("https:")) {
// final byte image[] = getFile(src); final SURL tmp = SURL.create(src);
// final BufferedImage read = ImageIO.read(new ByteArrayInputStream(image)); if (tmp == null) {
final BufferedImage read = FileUtils.readRasterImageFromURL(new URL(src)); return new Text("(Cannot decode: " + src + ")");
}
final BufferedImage read = tmp.readRasterImageFromURL();
if (read == null) { if (read == null) {
return new Text("(Cannot decode: " + src + ")"); return new Text("(Cannot decode: " + src + ")");
} }
return new Img(new TileImage(read, valign, vspace)); return new Img(new TileImage(read, valign, vspace));
} }
return new Text("(File not found: " + f + ")"); return new Text("(Cannot decode: " + f + ")");
} }
if (f.getName().endsWith(".svg")) { if (f.getName().endsWith(".svg")) {
return new Img(new TileImageSvg(f)); final String tmp = FileUtils.readSvg(f);
if (tmp == null) {
return new Text("(Cannot decode: " + f + ")");
}
return new Img(new TileImageSvg(tmp));
} }
final BufferedImage read = FileUtils.readRasterImageFromFile(f); final BufferedImage read = f.readRasterImageFromFile();
if (read == null) { if (read == null) {
return new Text("(Cannot decode: " + f + ")"); return new Text("(Cannot decode: " + f + ")");
} }
return new Img(new TileImage(FileUtils.readRasterImageFromFile(f), valign, vspace)); return new Img(new TileImage(f.readRasterImageFromFile(), valign, vspace));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace();
return new Text("ERROR " + e.toString()); return new Text("ERROR " + e.toString());
} }
} }
@ -127,27 +132,4 @@ public class Img implements HtmlCommand {
return tileImage; return tileImage;
} }
// Added by Alain Corbiere
static byte[] getFile(String host) throws IOException {
final ByteArrayOutputStream image = new ByteArrayOutputStream();
InputStream input = null;
try {
final URL url = new URL(host);
final URLConnection connection = url.openConnection();
input = connection.getInputStream();
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0) {
image.write(buffer, 0, read);
}
image.close();
return image.toByteArray();
} finally {
if (input != null) {
input.close();
}
}
}
// End
} }

View File

@ -41,7 +41,7 @@ import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UTranslate; import net.sourceforge.plantuml.ugraphic.UTranslate;
class TextBlockMinWidth extends AbstractTextBlock implements TextBlock { class TextBlockMinWidth extends AbstractTextBlock implements TextBlock {
private final TextBlock textBlock; private final TextBlock textBlock;
private final double minWidth; private final double minWidth;
@ -61,9 +61,15 @@ class TextBlockMinWidth extends AbstractTextBlock implements TextBlock {
public void drawU(UGraphic ug) { public void drawU(UGraphic ug) {
if (horizontalAlignment == HorizontalAlignment.LEFT) { if (horizontalAlignment == HorizontalAlignment.LEFT) {
textBlock.drawU(ug); textBlock.drawU(ug);
} else if (horizontalAlignment == HorizontalAlignment.CENTER) {
final Dimension2D dimText = textBlock.calculateDimension(ug.getStringBounder());
final Dimension2D dimFull = calculateDimension(ug.getStringBounder());
final double diffx = dimFull.getWidth() - dimText.getWidth();
textBlock.drawU(ug.apply(UTranslate.dx(diffx / 2)));
} else if (horizontalAlignment == HorizontalAlignment.RIGHT) { } else if (horizontalAlignment == HorizontalAlignment.RIGHT) {
final Dimension2D dim = textBlock.calculateDimension(ug.getStringBounder()); final Dimension2D dimText = textBlock.calculateDimension(ug.getStringBounder());
final double diffx = minWidth - dim.getWidth(); final Dimension2D dimFull = calculateDimension(ug.getStringBounder());
final double diffx = dimFull.getWidth() - dimText.getWidth();
textBlock.drawU(ug.apply(UTranslate.dx(diffx))); textBlock.drawU(ug.apply(UTranslate.dx(diffx)));
} else { } else {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();

View File

@ -37,17 +37,16 @@ package net.sourceforge.plantuml.graphic;
import java.awt.Font; import java.awt.Font;
import java.awt.FontMetrics; import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext; import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics; import java.awt.font.LineMetrics;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import net.sourceforge.plantuml.ColorParam; import net.sourceforge.plantuml.ColorParam;
import net.sourceforge.plantuml.CornerParam; import net.sourceforge.plantuml.CornerParam;
import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.ISkinParam; import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.LineParam; import net.sourceforge.plantuml.LineParam;
import net.sourceforge.plantuml.SkinParam; import net.sourceforge.plantuml.SkinParam;
@ -176,13 +175,6 @@ public class TextBlockUtils {
return limitFinder.getMinMax(); return limitFinder.getMinMax();
} }
private static final Graphics2D gg;
static {
final BufferedImage imDummy = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
gg = imDummy.createGraphics();
}
public static boolean isEmpty(TextBlock text, StringBounder dummyStringBounder) { public static boolean isEmpty(TextBlock text, StringBounder dummyStringBounder) {
if (text == null) { if (text == null) {
return true; return true;
@ -192,15 +184,15 @@ public class TextBlockUtils {
} }
public static FontRenderContext getFontRenderContext() { public static FontRenderContext getFontRenderContext() {
return gg.getFontRenderContext(); return FileFormat.gg.getFontRenderContext();
} }
public static LineMetrics getLineMetrics(UFont font, String text) { public static LineMetrics getLineMetrics(UFont font, String text) {
return font.getLineMetrics(gg, text); return font.getLineMetrics(FileFormat.gg, text);
} }
public static FontMetrics getFontMetrics(Font font) { public static FontMetrics getFontMetrics(Font font) {
return gg.getFontMetrics(font); return FileFormat.gg.getFontMetrics(font);
} }
public static TextBlock fullInnerPosition(final TextBlock bloc, final String display) { public static TextBlock fullInnerPosition(final TextBlock bloc, final String display) {

View File

@ -36,11 +36,8 @@
package net.sourceforge.plantuml.graphic; package net.sourceforge.plantuml.graphic;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.io.File;
import java.io.IOException;
import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileUtils;
import net.sourceforge.plantuml.SvgString; import net.sourceforge.plantuml.SvgString;
import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImageSvg; import net.sourceforge.plantuml.ugraphic.UImageSvg;
@ -49,10 +46,6 @@ public class TileImageSvg extends AbstractTextBlock implements TextBlock {
private final UImageSvg svg; private final UImageSvg svg;
public TileImageSvg(File svgFile) throws IOException {
this(FileUtils.readSvg(svgFile));
}
public TileImageSvg(String svg) { public TileImageSvg(String svg) {
this.svg = new UImageSvg(new SvgString(svg, 1)); this.svg = new UImageSvg(new SvgString(svg, 1));
} }

View File

@ -136,7 +136,7 @@ public class UnusedSpace {
// int cpt = 1; // int cpt = 1;
// try { // try {
// ImageIO.write(im, "png", new File("c:/img" + cpt + ".png")); // ImageIO.write(im, "png", SecurityUtils.File("c:/img" + cpt + ".png"));
// cpt++; // cpt++;
// } catch (IOException e) { // } catch (IOException e) {
// e.printStackTrace(); // e.printStackTrace();

View File

@ -49,7 +49,6 @@ import net.sourceforge.plantuml.creole.CreoleMode;
import net.sourceforge.plantuml.creole.Parser; import net.sourceforge.plantuml.creole.Parser;
import net.sourceforge.plantuml.creole.Sheet; import net.sourceforge.plantuml.creole.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1; import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration; import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment; import net.sourceforge.plantuml.graphic.HorizontalAlignment;

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml.html; package net.sourceforge.plantuml.html;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
@ -52,13 +51,14 @@ import net.sourceforge.plantuml.cucadiagram.LeafType;
import net.sourceforge.plantuml.cucadiagram.Link; import net.sourceforge.plantuml.cucadiagram.Link;
import net.sourceforge.plantuml.cucadiagram.Member; import net.sourceforge.plantuml.cucadiagram.Member;
import net.sourceforge.plantuml.cucadiagram.Stereotype; import net.sourceforge.plantuml.cucadiagram.Stereotype;
import net.sourceforge.plantuml.security.SFile;
public final class CucaDiagramHtmlMaker { public final class CucaDiagramHtmlMaker {
private final CucaDiagram diagram; private final CucaDiagram diagram;
private final File dir; private final SFile dir;
public CucaDiagramHtmlMaker(CucaDiagram diagram, File dir) { public CucaDiagramHtmlMaker(CucaDiagram diagram, SFile dir) {
this.diagram = diagram; this.diagram = diagram;
this.dir = dir; this.dir = dir;
} }
@ -68,8 +68,8 @@ public final class CucaDiagramHtmlMaker {
if (dir.exists() == false) { if (dir.exists() == false) {
throw new IOException("Cannot create " + dir); throw new IOException("Cannot create " + dir);
} }
final File f = new File(dir, "index.html"); final SFile f = dir.file("index.html");
final PrintWriter pw = new PrintWriter(f); final PrintWriter pw = f.createPrintWriter();
pw.println("<html>"); pw.println("<html>");
printAllType(pw, LeafType.ENUM); printAllType(pw, LeafType.ENUM);
printAllType(pw, LeafType.INTERFACE); printAllType(pw, LeafType.INTERFACE);
@ -92,7 +92,8 @@ public final class CucaDiagramHtmlMaker {
pw.println(LinkHtmlPrinter.htmlLink(ent)); pw.println(LinkHtmlPrinter.htmlLink(ent));
pw.println("</li>"); pw.println("</li>");
} }
// for (Map.Entry<Code, IEntity> ent : new TreeMap<Code, IEntity>(diagram.getLeafs()).entrySet()) { // for (Map.Entry<Code, IEntity> ent : new TreeMap<Code,
// IEntity>(diagram.getLeafs()).entrySet()) {
// if (ent.getValue().getEntityType() != type) { // if (ent.getValue().getEntityType() != type) {
// continue; // continue;
// } // }
@ -114,8 +115,8 @@ public final class CucaDiagramHtmlMaker {
} }
private void export(IEntity entity) throws IOException { private void export(IEntity entity) throws IOException {
final File f = new File(dir, LinkHtmlPrinter.urlOf(entity)); final SFile f = dir.file(LinkHtmlPrinter.urlOf(entity));
final PrintWriter pw = new PrintWriter(f); final PrintWriter pw = f.createPrintWriter();
pw.println("<html>"); pw.println("<html>");
pw.println("<title>" + StringUtils.unicodeForHtml(entity.getCodeGetName()) + "</title>"); pw.println("<title>" + StringUtils.unicodeForHtml(entity.getCodeGetName()) + "</title>");
pw.println("<h2>" + entity.getLeafType().toHtml() + "</h2>"); pw.println("<h2>" + entity.getLeafType().toHtml() + "</h2>");
@ -209,8 +210,7 @@ public final class CucaDiagramHtmlMaker {
if (link.contains(ent) == false) { if (link.contains(ent) == false) {
continue; continue;
} }
if (link.getEntity1().getLeafType() == LeafType.NOTE if (link.getEntity1().getLeafType() == LeafType.NOTE || link.getEntity2().getLeafType() == LeafType.NOTE) {
|| link.getEntity2().getLeafType() == LeafType.NOTE) {
result.add(link.getOther(ent)); result.add(link.getOther(ent));
} }
} }
@ -223,8 +223,7 @@ public final class CucaDiagramHtmlMaker {
if (link.contains(ent) == false) { if (link.contains(ent) == false) {
continue; continue;
} }
if (link.getEntity1().getLeafType() == LeafType.NOTE if (link.getEntity1().getLeafType() == LeafType.NOTE || link.getEntity2().getLeafType() == LeafType.NOTE) {
|| link.getEntity2().getLeafType() == LeafType.NOTE) {
continue; continue;
} }
result.add(link); result.add(link);

View File

@ -1,11 +1,8 @@
package net.sourceforge.plantuml.jasic; package net.sourceforge.plantuml.jasic;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -105,29 +102,6 @@ import java.util.Map;
*/ */
public class Jasic { public class Jasic {
/**
* Runs the interpreter as a command-line app. Takes one argument: a path to a script file to load and run. The
* script should contain one statement per line.
*
* @param args
* Command-line arguments.
*/
public static void main(String[] args) {
// Just show the usage and quit if a script wasn't provided.
if (args.length != 1) {
System.out.println("Usage: jasic <script>");
System.out.println("Where <script> is a relative path to a .jas script to run.");
return;
}
// Read the file.
String contents = readFile(args[0]);
// Run it.
Jasic jasic = new Jasic();
jasic.interpret(contents);
}
// Tokenizing (lexing) ----------------------------------------------------- // Tokenizing (lexing) -----------------------------------------------------
/** /**
@ -829,43 +803,4 @@ public class Jasic {
private int currentStatement; private int currentStatement;
// Utility stuff -----------------------------------------------------------
/**
* Reads the file from the given path and returns its contents as a single string.
*
* @param path
* Path to the text file to read.
* @return The contents of the file or null if the load failed.
* @throws IOException
*/
private static String readFile(String path) {
try {
FileInputStream stream = new FileInputStream(path);
try {
InputStreamReader input = new InputStreamReader(stream, Charset.defaultCharset());
Reader reader = new BufferedReader(input);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
// HACK: The parser expects every statement to end in a newline,
// even the very last one, so we'll just tack one on here in
// case the file doesn't have one.
builder.append("\n");
return builder.toString();
} finally {
stream.close();
}
} catch (IOException ex) {
return null;
}
}
} }

View File

@ -40,8 +40,6 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Properties; import java.util.Properties;
import javax.imageio.ImageIO;
import jcckit.GraphicsPlotCanvas; import jcckit.GraphicsPlotCanvas;
import jcckit.data.DataPlot; import jcckit.data.DataPlot;
import jcckit.util.ConfigParameters; import jcckit.util.ConfigParameters;
@ -51,6 +49,7 @@ import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.api.ImageDataSimple; import net.sourceforge.plantuml.api.ImageDataSimple;
import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.security.ImageIO;
public class PSystemJcckit extends AbstractPSystem { public class PSystemJcckit extends AbstractPSystem {

View File

@ -45,7 +45,6 @@ import net.sourceforge.plantuml.creole.CreoleMode;
import net.sourceforge.plantuml.creole.Parser; import net.sourceforge.plantuml.creole.Parser;
import net.sourceforge.plantuml.creole.Sheet; import net.sourceforge.plantuml.creole.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1; import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.AbstractTextBlock; import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.FontConfiguration; import net.sourceforge.plantuml.graphic.FontConfiguration;

View File

@ -43,8 +43,6 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Arrays; import java.util.Arrays;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
@ -54,6 +52,7 @@ import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.eps.EpsGraphics; import net.sourceforge.plantuml.eps.EpsGraphics;
import net.sourceforge.plantuml.graphic.GraphicStrings; import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.graphic.TextBlock; import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity;

View File

@ -57,7 +57,11 @@ import net.sourceforge.plantuml.graphic.InnerStrategy;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TextBlock; import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.style.ClockwiseTopRightBottomLeft; import net.sourceforge.plantuml.style.ClockwiseTopRightBottomLeft;
import net.sourceforge.plantuml.style.PName;
import net.sourceforge.plantuml.style.SName;
import net.sourceforge.plantuml.style.Style;
import net.sourceforge.plantuml.style.StyleBuilder; import net.sourceforge.plantuml.style.StyleBuilder;
import net.sourceforge.plantuml.style.StyleSignature;
import net.sourceforge.plantuml.svek.TextBlockBackcolored; import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.MinMax; import net.sourceforge.plantuml.ugraphic.MinMax;
@ -94,15 +98,21 @@ public class MindMapDiagram extends UmlDiagram {
final ISkinParam skinParam = getSkinParam(); final ISkinParam skinParam = getSkinParam();
final int margin1; final int margin1;
final int margin2; final int margin2;
final HColor backgroundColor;
if (SkinParam.USE_STYLES()) { if (SkinParam.USE_STYLES()) {
margin1 = SkinParam.zeroMargin(10); margin1 = SkinParam.zeroMargin(10);
margin2 = SkinParam.zeroMargin(10); margin2 = SkinParam.zeroMargin(10);
final Style style = StyleSignature.of(SName.root, SName.document, SName.mindmapDiagram)
.getMergedStyle(skinParam.getCurrentStyleBuilder());
backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getIHtmlColorSet());
} else { } else {
margin1 = 10; margin1 = 10;
margin2 = 10; margin2 = 10;
backgroundColor = skinParam.getBackgroundColor(false);
} }
final ImageBuilder imageBuilder = ImageBuilder.buildB(skinParam.getColorMapper(), skinParam.handwritten(), ClockwiseTopRightBottomLeft.margin1margin2((double) margin1, (double) margin2), final ImageBuilder imageBuilder = ImageBuilder.buildBB(skinParam.getColorMapper(), skinParam.handwritten(),
null, fileFormatOption.isWithMetadata() ? getMetadata() : null, "", dpiFactor, skinParam.getBackgroundColor(false)); ClockwiseTopRightBottomLeft.margin1margin2(margin1, margin2), null,
fileFormatOption.isWithMetadata() ? getMetadata() : null, "", dpiFactor, backgroundColor);
TextBlock result = getTextBlock(); TextBlock result = getTextBlock();
result = new AnnotatedWorker(this, skinParam, fileFormatOption.getDefaultStringBounder()).addAdd(result); result = new AnnotatedWorker(this, skinParam, fileFormatOption.getDefaultStringBounder()).addAdd(result);

File diff suppressed because it is too large Load Diff

View File

@ -48,7 +48,6 @@ import java.util.regex.Pattern;
import net.sourceforge.plantuml.AnnotatedWorker; import net.sourceforge.plantuml.AnnotatedWorker;
import net.sourceforge.plantuml.ColorParam; import net.sourceforge.plantuml.ColorParam;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.ISkinParam; import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.Scale; import net.sourceforge.plantuml.Scale;
@ -196,8 +195,8 @@ public class NwDiagram extends UmlDiagram {
margin1 = 0; margin1 = 0;
margin2 = 0; margin2 = 0;
} }
final ImageBuilder imageBuilder = ImageBuilder.buildB(new ColorMapperIdentity(), false, ClockwiseTopRightBottomLeft.margin1margin2((double) margin1, (double) margin2), final ImageBuilder imageBuilder = ImageBuilder.buildB(new ColorMapperIdentity(), false,
null, "", "", dpiFactor, null); ClockwiseTopRightBottomLeft.margin1margin2(margin1, margin2), null, "", "", dpiFactor, null);
TextBlock result = getTextBlock(); TextBlock result = getTextBlock();
result = new AnnotatedWorker(this, skinParam, fileFormatOption.getDefaultStringBounder()).addAdd(result); result = new AnnotatedWorker(this, skinParam, fileFormatOption.getDefaultStringBounder()).addAdd(result);
imageBuilder.setUDrawable(result); imageBuilder.setUDrawable(result);

View File

@ -37,7 +37,6 @@ package net.sourceforge.plantuml.openiconic;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -50,6 +49,7 @@ import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TextBlock; import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.openiconic.data.DummyIcon; import net.sourceforge.plantuml.openiconic.data.DummyIcon;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.color.HColor; import net.sourceforge.plantuml.ugraphic.color.HColor;
@ -100,8 +100,8 @@ public class OpenIcon {
} }
} }
void saveCopy(File fnew) throws IOException { void saveCopy(SFile fnew) throws IOException {
final PrintWriter pw = new PrintWriter(fnew); final PrintWriter pw = fnew.createPrintWriter();
pw.println(rawData.get(0)); pw.println(rawData.get(0));
pw.println(svgPath.toSvg()); pw.println(svgPath.toSvg());
pw.println(rawData.get(rawData.size() - 1)); pw.println(rawData.get(rawData.size() - 1));

View File

@ -35,12 +35,13 @@
*/ */
package net.sourceforge.plantuml.pdf; package net.sourceforge.plantuml.pdf;
import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import net.sourceforge.plantuml.security.SFile;
public class PdfConverter { public class PdfConverter {
public static void convert(File svgFile, File pdfFile) { public static void convert(SFile svgFile, SFile pdfFile) {
if (svgFile.exists() == false) { if (svgFile.exists() == false) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();

View File

@ -35,11 +35,9 @@
*/ */
package net.sourceforge.plantuml.png; package net.sourceforge.plantuml.png;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader; import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
@ -47,17 +45,20 @@ import javax.imageio.stream.ImageInputStream;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class Metadata { public class Metadata {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
final Metadata meta = new Metadata(); final Metadata meta = new Metadata();
final int length = args.length; final int length = args.length;
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
meta.readAndDisplayMetadata(new File(args[i])); meta.readAndDisplayMetadata(new SFile(args[i]));
} }
} }
public void readAndDisplayMetadata(File file) throws IOException { public void readAndDisplayMetadata(SFile file) throws IOException {
final ImageInputStream iis = ImageIO.createImageInputStream(file); final ImageInputStream iis = ImageIO.createImageInputStream(file);
final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

View File

@ -35,12 +35,11 @@
*/ */
package net.sourceforge.plantuml.png; package net.sourceforge.plantuml.png;
import java.io.File; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Iterator; import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader; import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
@ -48,12 +47,20 @@ import javax.imageio.stream.ImageInputStream;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class MetadataTag { public class MetadataTag {
private final Object source; private final Object source;
private final String tag; private final String tag;
public MetadataTag(File file, String tag) { public MetadataTag(SFile file, String tag) throws FileNotFoundException {
this.source = file.conv();
this.tag = tag;
}
public MetadataTag(java.io.File file, String tag) {
this.source = file; this.source = file;
this.tag = tag; this.tag = tag;
} }

View File

@ -36,21 +36,18 @@
package net.sourceforge.plantuml.png; package net.sourceforge.plantuml.png;
import java.awt.image.RenderedImage; import java.awt.image.RenderedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class PngIO { public class PngIO {
private static final String copyleft = "Generated by http://plantuml.com"; private static final String copyleft = "Generated by http://plantuml.com";
public static void write(RenderedImage image, File file, int dpi) throws IOException { public static void write(RenderedImage image, SFile file, int dpi) throws IOException {
write(image, file, null, dpi); write(image, file, null, dpi);
} }
@ -58,10 +55,10 @@ public class PngIO {
write(image, os, null, dpi); write(image, os, null, dpi);
} }
public static void write(RenderedImage image, File file, String metadata, int dpi) throws IOException { public static void write(RenderedImage image, SFile file, String metadata, int dpi) throws IOException {
OutputStream os = null; OutputStream os = null;
try { try {
os = new BufferedOutputStream(new FileOutputStream(file)); os = file.createBufferedOutputStream();
write(image, os, metadata, dpi); write(image, os, metadata, dpi);
} finally { } finally {
if (os != null) { if (os != null) {

View File

@ -41,13 +41,13 @@ import java.io.OutputStream;
import java.util.Iterator; import java.util.Iterator;
import javax.imageio.IIOImage; import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter; import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.ImageOutputStream;
import com.sun.imageio.plugins.png.PNGMetadata; import com.sun.imageio.plugins.png.PNGMetadata;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.security.ImageIO;
public class PngIOMetadata { public class PngIOMetadata {

View File

@ -37,21 +37,20 @@ package net.sourceforge.plantuml.png;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.SplitParam; import net.sourceforge.plantuml.SplitParam;
import net.sourceforge.plantuml.SuggestedFile; import net.sourceforge.plantuml.SuggestedFile;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class PngSplitter { public class PngSplitter {
private final List<File> files = new ArrayList<File>(); private final List<SFile> files = new ArrayList<SFile>();
public PngSplitter(SuggestedFile pngFile, int horizontalPages, int verticalPages, String source, int dpi, public PngSplitter(SuggestedFile pngFile, int horizontalPages, int verticalPages, String source, int dpi,
boolean isWithMetadata, SplitParam splitParam) throws IOException { boolean isWithMetadata, SplitParam splitParam) throws IOException {
@ -61,7 +60,7 @@ public class PngSplitter {
} }
Log.info("Splitting " + horizontalPages + " x " + verticalPages); Log.info("Splitting " + horizontalPages + " x " + verticalPages);
final File full = pngFile.getTmpFile(); // new File(pngFile.getParentFile(), pngFile.getName() + ".tmp"); final SFile full = pngFile.getTmpFile(); // SecurityUtils.File(pngFile.getParentFile(), pngFile.getName() + ".tmp");
// Thread.yield(); // Thread.yield();
full.delete(); full.delete();
// Thread.yield(); // Thread.yield();
@ -80,7 +79,7 @@ public class PngSplitter {
int x = 0; int x = 0;
for (int i = 0; i < horizontalPages; i++) { for (int i = 0; i < horizontalPages; i++) {
for (int j = 0; j < verticalPages; j++) { for (int j = 0; j < verticalPages; j++) {
final File f = pngFile.getFile(x++); final SFile f = pngFile.getFile(x++);
this.files.add(f); this.files.add(f);
final int width = horizontalSegment.getLen(i); final int width = horizontalSegment.getLen(i);
final int height = verticalSegment.getLen(j); final int height = verticalSegment.getLen(j);
@ -116,7 +115,7 @@ public class PngSplitter {
Log.info("End of splitting"); Log.info("End of splitting");
} }
public List<File> getFiles() { public List<SFile> getFiles() {
return Collections.unmodifiableList(files); return Collections.unmodifiableList(files);
} }

View File

@ -37,10 +37,7 @@ package net.sourceforge.plantuml.posimo;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Collection; import java.util.Collection;
@ -52,6 +49,7 @@ import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.cucadiagram.dot.Graphviz; import net.sourceforge.plantuml.cucadiagram.dot.Graphviz;
import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;
import net.sourceforge.plantuml.cucadiagram.dot.ProcessState; import net.sourceforge.plantuml.cucadiagram.dot.ProcessState;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svek.MinFinder; import net.sourceforge.plantuml.svek.MinFinder;
import net.sourceforge.plantuml.svek.SvgResult; import net.sourceforge.plantuml.svek.SvgResult;
import net.sourceforge.plantuml.svek.YDelta; import net.sourceforge.plantuml.svek.YDelta;
@ -59,10 +57,10 @@ import net.sourceforge.plantuml.svek.YDelta;
public class GraphvizSolverB { public class GraphvizSolverB {
// static private void traceDotString(String dotString) throws IOException { // static private void traceDotString(String dotString) throws IOException {
// final File f = new File("dottmpfile" + UniqueSequence.getValue() + ".tmp"); // final File f = SecurityUtils.File("dottmpfile" + UniqueSequence.getValue() + ".tmp");
// PrintWriter pw = null; // PrintWriter pw = null;
// try { // try {
// pw = new PrintWriter(new FileWriter(f)); // pw = SecurityUtils.PrintWriter(new FileWriter(f));
// pw.print(dotString); // pw.print(dotString);
// Log.info("Creating file " + f); // Log.info("Creating file " + f);
// } finally { // } finally {
@ -73,10 +71,10 @@ public class GraphvizSolverB {
// } // }
// //
// static private void traceSvgString(String svg) throws IOException { // static private void traceSvgString(String svg) throws IOException {
// final File f = new File("svgtmpfile" + UniqueSequence.getValue() + ".svg"); // final File f = SecurityUtils.File("svgtmpfile" + UniqueSequence.getValue() + ".svg");
// PrintWriter pw = null; // PrintWriter pw = null;
// try { // try {
// pw = new PrintWriter(new FileWriter(f)); // pw = SecurityUtils.PrintWriter(new FileWriter(f));
// pw.print(svg); // pw.print(svg);
// Log.info("Creating file " + f); // Log.info("Creating file " + f);
// } finally { // } finally {
@ -97,7 +95,7 @@ public class GraphvizSolverB {
// Log.println("dotString=" + dotString); // Log.println("dotString=" + dotString);
// exportPng(dotString, new File("png", "test1.png")); // exportPng(dotString, SecurityUtils.File("png", "test1.png"));
final Graphviz graphviz = GraphvizUtils.create(null, dotString, "svg"); final Graphviz graphviz = GraphvizUtils.create(null, dotString, "svg");
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -222,9 +220,9 @@ public class GraphvizSolverB {
return result; return result;
} }
private void exportPng(final String dotString, File f) throws IOException { private void exportPng(final String dotString, SFile f) throws IOException {
final Graphviz graphviz = GraphvizUtils.create(null, dotString, "png"); final Graphviz graphviz = GraphvizUtils.create(null, dotString, "png");
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); final OutputStream os = f.createBufferedOutputStream();
final ProcessState state = graphviz.createFile3(os); final ProcessState state = graphviz.createFile3(os);
os.close(); os.close();
if (state.differs(ProcessState.TERMINATED_OK())) { if (state.differs(ProcessState.TERMINATED_OK())) {

View File

@ -35,7 +35,6 @@
*/ */
package net.sourceforge.plantuml.preproc; package net.sourceforge.plantuml.preproc;
import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -53,6 +52,9 @@ import java.util.regex.Pattern;
import net.sourceforge.plantuml.AParentFolder; import net.sourceforge.plantuml.AParentFolder;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.api.ApiWarning; import net.sourceforge.plantuml.api.ApiWarning;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityProfile;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.tim.EaterException; import net.sourceforge.plantuml.tim.EaterException;
import net.sourceforge.plantuml.tim.TMemory; import net.sourceforge.plantuml.tim.TMemory;
import net.sourceforge.plantuml.tim.TVariableScope; import net.sourceforge.plantuml.tim.TVariableScope;
@ -106,14 +108,31 @@ public class Defines implements Truth {
return result; return result;
} }
public static Defines createWithFileName(File file) { public static Defines createWithFileName(SFile file) {
if (file == null) { if (file == null) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
final Defines result = createEmpty(); final Defines result = createEmpty();
result.overrideFilename(file.getName()); result.overrideFilename(file.getName());
result.environment.put("filedate", new Date(file.lastModified()).toString()); result.environment.put("filedate", new Date(file.lastModified()).toString());
result.environment.put("dirpath", file.getAbsoluteFile().getParentFile().getAbsolutePath().replace('\\', '/')); if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
result.environment.put("dirpath",
file.getAbsoluteFile().getParentFile().getAbsolutePath().replace('\\', '/'));
}
return result;
}
public static Defines createWithFileName(java.io.File file) {
if (file == null) {
throw new IllegalArgumentException();
}
final Defines result = createEmpty();
result.overrideFilename(file.getName());
result.environment.put("filedate", new Date(file.lastModified()).toString());
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
result.environment.put("dirpath",
file.getAbsoluteFile().getParentFile().getAbsolutePath().replace('\\', '/'));
}
return result; return result;
} }

View File

@ -37,6 +37,7 @@
package net.sourceforge.plantuml.preproc; package net.sourceforge.plantuml.preproc;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -50,6 +51,7 @@ import net.sourceforge.plantuml.AFile;
import net.sourceforge.plantuml.AFileRegular; import net.sourceforge.plantuml.AFileRegular;
import net.sourceforge.plantuml.AParentFolder; import net.sourceforge.plantuml.AParentFolder;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.security.SFile;
public class FileWithSuffix { public class FileWithSuffix {
@ -70,15 +72,19 @@ public class FileWithSuffix {
if (file == null) { if (file == null) {
return null; return null;
} }
final InputStream tmp = file.openFile();
if (tmp == null) {
return null;
}
if (entry == null) { if (entry == null) {
if (charset == null) { if (charset == null) {
Log.info("Using default charset"); Log.info("Using default charset");
return new InputStreamReader(file.open()); return new InputStreamReader(tmp);
} }
Log.info("Using charset " + charset); Log.info("Using charset " + charset);
return new InputStreamReader(file.open(), charset); return new InputStreamReader(tmp, charset);
} }
final InputStream is = getDataFromZip(file.open(), entry); final InputStream is = getDataFromZip(tmp, entry);
if (is == null) { if (is == null) {
return null; return null;
} }
@ -111,11 +117,11 @@ public class FileWithSuffix {
return file != null && file.isOk(); return file != null && file.isOk();
} }
FileWithSuffix(File file, String suffix) { FileWithSuffix(SFile file, String suffix) {
this.file = new AFileRegular(file); this.file = new AFileRegular(file);
this.suffix = suffix; this.suffix = suffix;
this.entry = null; this.entry = null;
this.description = getFileName(file); this.description = file.getName();
} }
FileWithSuffix(String description, String suffix, AFile file, String entry) { FileWithSuffix(String description, String suffix, AFile file, String entry) {
@ -188,10 +194,10 @@ public class FileWithSuffix {
return false; return false;
} }
public static Set<File> convert(Set<FileWithSuffix> all) { public static Set<File> convert(Set<FileWithSuffix> all) throws FileNotFoundException {
final Set<File> result = new HashSet<File>(); final Set<File> result = new HashSet<File>();
for (FileWithSuffix f : all) { for (FileWithSuffix f : all) {
result.add(f.file.getUnderlyingFile()); result.add(f.file.getUnderlyingFile().conv());
} }
return result; return result;
} }

View File

@ -36,7 +36,6 @@
*/ */
package net.sourceforge.plantuml.preproc; package net.sourceforge.plantuml.preproc;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -45,16 +44,17 @@ import net.sourceforge.plantuml.AFile;
import net.sourceforge.plantuml.AFileRegular; import net.sourceforge.plantuml.AFileRegular;
import net.sourceforge.plantuml.AFileZipEntry; import net.sourceforge.plantuml.AFileZipEntry;
import net.sourceforge.plantuml.AParentFolder; import net.sourceforge.plantuml.AParentFolder;
import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.OptionFlags; import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public class ImportedFiles { public class ImportedFiles {
private final List<File> imported; private final List<SFile> imported;
private final AParentFolder currentDir; private final AParentFolder currentDir;
private ImportedFiles(List<File> imported, AParentFolder currentDir) { private ImportedFiles(List<SFile> imported, AParentFolder currentDir) {
this.imported = imported; this.imported = imported;
this.currentDir = currentDir; this.currentDir = currentDir;
} }
@ -67,7 +67,7 @@ public class ImportedFiles {
} }
public static ImportedFiles createImportedFiles(AParentFolder newCurrentDir) { public static ImportedFiles createImportedFiles(AParentFolder newCurrentDir) {
return new ImportedFiles(new ArrayList<File>(), newCurrentDir); return new ImportedFiles(new ArrayList<SFile>(), newCurrentDir);
} }
@Override @Override
@ -80,17 +80,18 @@ public class ImportedFiles {
// Log.info("ImportedFiles::getAFile currentDir = " + currentDir); // Log.info("ImportedFiles::getAFile currentDir = " + currentDir);
final AParentFolder dir = currentDir; final AParentFolder dir = currentDir;
if (dir == null || isAbsolute(nameOrPath)) { if (dir == null || isAbsolute(nameOrPath)) {
return new AFileRegular(new File(nameOrPath).getCanonicalFile()); return new AFileRegular(new SFile(nameOrPath).getCanonicalFile());
} }
// final File filecurrent = new File(dir.getAbsoluteFile(), nameOrPath); // final File filecurrent = SecurityUtils.File(dir.getAbsoluteFile(),
// nameOrPath);
final AFile filecurrent = dir.getAFile(nameOrPath); final AFile filecurrent = dir.getAFile(nameOrPath);
Log.info("ImportedFiles::getAFile filecurrent = " + filecurrent); Log.info("ImportedFiles::getAFile filecurrent = " + filecurrent);
if (filecurrent != null && filecurrent.isOk()) { if (filecurrent != null && filecurrent.isOk()) {
return filecurrent; return filecurrent;
} }
for (File d : getPath()) { for (SFile d : getPath()) {
if (d.isDirectory()) { if (d.isDirectory()) {
final File file = new File(d, nameOrPath); final SFile file = d.file(nameOrPath);
if (file.exists()) { if (file.exists()) {
return new AFileRegular(file.getCanonicalFile()); return new AFileRegular(file.getCanonicalFile());
} }
@ -104,23 +105,23 @@ public class ImportedFiles {
return filecurrent; return filecurrent;
} }
public List<File> getPath() { public List<SFile> getPath() {
final List<File> result = new ArrayList<File>(imported); final List<SFile> result = new ArrayList<SFile>(imported);
result.addAll(includePath()); result.addAll(includePath());
result.addAll(FileSystem.getPath("java.class.path", true)); result.addAll(SecurityUtils.getPath("java.class.path"));
return result; return result;
} }
private List<File> includePath() { private List<SFile> includePath() {
return FileSystem.getPath("plantuml.include.path", true); return SecurityUtils.getPath("plantuml.include.path");
} }
private boolean isAbsolute(String nameOrPath) { private boolean isAbsolute(String nameOrPath) {
final File f = new File(nameOrPath); final SFile f = new SFile(nameOrPath);
return f.isAbsolute(); return f.isAbsolute();
} }
public void add(File file) { public void add(SFile file) {
this.imported.add(file); this.imported.add(file);
} }
@ -150,7 +151,7 @@ public class ImportedFiles {
return true; return true;
} }
if (file != null) { if (file != null) {
final File folder = file.getSystemFolder(); final SFile folder = file.getSystemFolder();
// System.err.println("canonicalPath=" + path + " " + folder + " " + // System.err.println("canonicalPath=" + path + " " + folder + " " +
// INCLUDE_PATH); // INCLUDE_PATH);
if (includePath().contains(folder)) { if (includePath().contains(folder)) {

View File

@ -39,10 +39,10 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.net.URL;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.StringLocated; import net.sourceforge.plantuml.StringLocated;
import net.sourceforge.plantuml.security.SURL;
import net.sourceforge.plantuml.utils.StartUtils; import net.sourceforge.plantuml.utils.StartUtils;
public class StartDiagramExtractReader implements ReadLine { public class StartDiagramExtractReader implements ReadLine {
@ -54,7 +54,7 @@ public class StartDiagramExtractReader implements ReadLine {
return new StartDiagramExtractReader(getReadLine(f2, s, charset), f2.getSuffix()); return new StartDiagramExtractReader(getReadLine(f2, s, charset), f2.getSuffix());
} }
public static StartDiagramExtractReader build(URL url, StringLocated s, String uid, String charset) { public static StartDiagramExtractReader build(SURL url, StringLocated s, String uid, String charset) {
return new StartDiagramExtractReader(getReadLine(url, s, charset), uid); return new StartDiagramExtractReader(getReadLine(url, s, charset), uid);
} }
@ -117,16 +117,18 @@ public class StartDiagramExtractReader implements ReadLine {
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(is), description)); return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(is), description));
} }
private static ReadLine getReadLine(URL url, StringLocated s, String charset) { private static ReadLine getReadLine(SURL url, StringLocated s, String charset) {
try { try {
final InputStream tmp = url.openStream();
if (tmp == null) {
return new ReadLineSimple(s, "Cannot connect");
}
if (charset == null) { if (charset == null) {
Log.info("Using default charset"); Log.info("Using default charset");
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(url.openStream()), return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(tmp), url.toString()));
url.toString()));
} }
Log.info("Using charset " + charset); Log.info("Using charset " + charset);
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(url.openStream(), charset), return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(tmp, charset), url.toString()));
url.toString()));
} catch (IOException e) { } catch (IOException e) {
return new ReadLineSimple(s, e.toString()); return new ReadLineSimple(s, e.toString());
} }
@ -137,7 +139,7 @@ public class StartDiagramExtractReader implements ReadLine {
return containsStartDiagram(r); return containsStartDiagram(r);
} }
static public boolean containsStartDiagram(URL url, StringLocated s, String charset) throws IOException { static public boolean containsStartDiagram(SURL url, StringLocated s, String charset) throws IOException {
final ReadLine r = getReadLine(url, s, charset); final ReadLine r = getReadLine(url, s, charset);
return containsStartDiagram(r); return containsStartDiagram(r);
} }

View File

@ -3,7 +3,6 @@ package net.sourceforge.plantuml.preproc;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -23,6 +22,7 @@ import java.util.regex.Pattern;
import net.sourceforge.plantuml.Log; import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.brotli.BrotliInputStream; import net.sourceforge.plantuml.brotli.BrotliInputStream;
import net.sourceforge.plantuml.security.SFile;
public class Stdlib { public class Stdlib {
@ -250,9 +250,9 @@ public class Stdlib {
if (filename.equals(SEPARATOR)) { if (filename.equals(SEPARATOR)) {
return; return;
} }
final File f = new File("stdlib/" + name + "/" + filename + ".puml"); final SFile f = new SFile("stdlib/" + name + "/" + filename + ".puml");
f.getParentFile().mkdirs(); f.getParentFile().mkdirs();
final PrintWriter fos = new PrintWriter(f); final PrintWriter fos = f.createPrintWriter();
while (true) { while (true) {
final String s = dataStream.readUTF(); final String s = dataStream.readUTF();
if (s.equals(SEPARATOR)) { if (s.equals(SEPARATOR)) {

View File

@ -39,7 +39,6 @@ package net.sourceforge.plantuml.preproc2;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -51,6 +50,7 @@ import net.sourceforge.plantuml.preproc.ReadLineReader;
import net.sourceforge.plantuml.preproc.ReadLineSimple; import net.sourceforge.plantuml.preproc.ReadLineSimple;
import net.sourceforge.plantuml.preproc.StartDiagramExtractReader; import net.sourceforge.plantuml.preproc.StartDiagramExtractReader;
import net.sourceforge.plantuml.preproc.Stdlib; import net.sourceforge.plantuml.preproc.Stdlib;
import net.sourceforge.plantuml.security.SURL;
import net.sourceforge.plantuml.tim.EaterException; import net.sourceforge.plantuml.tim.EaterException;
public class PreprocessorUtils { public class PreprocessorUtils {
@ -113,13 +113,16 @@ public class PreprocessorUtils {
} }
} }
public static ReadLine getReaderIncludeUrl2(final URL url, StringLocated s, String suf, String charset) public static ReadLine getReaderIncludeUrl2(final SURL url, StringLocated s, String suf, String charset)
throws EaterException { throws EaterException {
try { try {
if (StartDiagramExtractReader.containsStartDiagram(url, s, charset)) { if (StartDiagramExtractReader.containsStartDiagram(url, s, charset)) {
return StartDiagramExtractReader.build(url, s, suf, charset); return StartDiagramExtractReader.build(url, s, suf, charset);
} }
final InputStream is = url.openStream(); final InputStream is = url.openStream();
if (is == null) {
throw EaterException.located("Cannot open URL");
}
if (charset == null) { if (charset == null) {
Log.info("Using default charset"); Log.info("Using default charset");
return ReadLineReader.create(new InputStreamReader(is), url.toString(), s.getLocation()); return ReadLineReader.create(new InputStreamReader(is), url.toString(), s.getLocation());

Some files were not shown because too many files have changed in this diff Show More