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>
<artifactId>plantuml</artifactId>
<version>1.2020.11-SNAPSHOT</version>
<version>1.2020.12-SNAPSHOT</version>
<packaging>jar</packaging>
<name>PlantUML</name>

View File

@ -3,11 +3,10 @@ package ext.plantuml.com.ctreber.acearth.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.security.ImageIO;
import ext.plantuml.com.ctreber.acearth.renderer.RenderTarget;
@ -30,10 +29,8 @@ public class PixelCanvas implements RenderTarget {
* <p>
* Construct a canvas of the specified size.
*
* @param pWidth
* Width
* @param pHeight
* Height
* @param pWidth Width
* @param pHeight Height
*/
public PixelCanvas(int pWidth, int pHeight) {
fImageWidth = pWidth;
@ -61,10 +58,6 @@ public class PixelCanvas implements RenderTarget {
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 {
ImageIO.write(fEarthImage2, "png", os);
}

View File

@ -17,11 +17,6 @@
package ext.plantuml.com.google.zxing.client.j2se;
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;

View File

@ -18,8 +18,6 @@
*/
package jcckit.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
@ -31,19 +29,6 @@ import java.util.Properties;
public class PropertiesBasedConfigData extends FlatConfigData {
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.
* The path is undefined.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,19 +35,19 @@
*/
package net.sourceforge.plantuml;
import java.io.File;
import net.sourceforge.plantuml.security.SFile;
public class BaseFile {
private final String basename;
private final File basedir;
private final SFile basedir;
public BaseFile() {
this.basedir = null;
this.basename = null;
}
public BaseFile(File file) {
public BaseFile(SFile file) {
this.basedir = file.getParentFile();
this.basename = extractBasename(file.getName());
}
@ -72,15 +72,15 @@ public class BaseFile {
return basename;
}
public File getBasedir() {
public SFile getBasedir() {
return basedir;
}
public File getTraceFile(String tail) {
public SFile getTraceFile(String tail) {
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;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
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.UncommentReadLine;
import net.sourceforge.plantuml.preproc2.Preprocessor;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.utils.StartUtils;
public final class BlockUmlBuilder implements DefinitionsContainer {
@ -62,7 +62,7 @@ public final class BlockUmlBuilder implements DefinitionsContainer {
private final ImportedFiles importedFiles;
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 {
ReadLineNumbered includer = null;
this.defines = defines;

View File

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

View File

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

View File

@ -42,8 +42,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.creole.atom.Atom;
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.StringBounder;
import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImage;
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.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import net.sourceforge.plantuml.braille.BrailleCharFactory;
import net.sourceforge.plantuml.braille.UGraphicBraille;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.png.MetadataTag;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svg.SvgGraphics;
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 Graphics2D gg = imDummy.createGraphics();
final static public Graphics2D gg = imDummy.createGraphics();
static {
// KEY_FRACTIONALMETRICS
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());
}
private File computeFilename(File pngFile, int i) {
private SFile computeFilename(SFile pngFile, int i) {
if (i == 0) {
return pngFile;
}
final File dir = pngFile.getParentFile();
return new File(dir, computeFilenameInternal(pngFile.getName(), i));
final SFile dir = pngFile.getParentFile();
return dir.file(computeFilenameInternal(pngFile.getName(), i));
}
private String changeName(String fileName, String replacement) {
@ -216,7 +216,7 @@ public enum FileFormat {
return this == PNG || this == SVG;
}
public boolean equalsMetadata(String currentMetadata, File existingFile) {
public boolean equalsMetadata(String currentMetadata, SFile existingFile) {
try {
if (this == PNG) {
final MetadataTag tag = new MetadataTag(existingFile, "plantuml");
@ -226,6 +226,9 @@ public enum FileFormat {
}
if (this == SVG) {
final String svg = FileUtils.readSvg(existingFile);
if (svg == null) {
return false;
}
final String currentSignature = SvgGraphics.getMD5Hex(currentMetadata);
final int idx = svg.lastIndexOf(SvgGraphics.MD5_HEADER);
if (idx != -1) {

View File

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

View File

@ -35,17 +35,16 @@
*/
package net.sourceforge.plantuml;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public class 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() {
reset();
@ -55,79 +54,63 @@ public class FileSystem {
return singleton;
}
public void setCurrentDir(File dir) {
public void setCurrentDir(SFile dir) {
// if (dir == null) {
// throw new IllegalArgumentException();
// }
Log.info("Setting current dir: " + dir);
if (dir != null) {
Log.info("Setting current dir: " + dir.getAbsolutePath());
}
this.currentDir.set(dir);
}
public File getCurrentDir() {
public SFile getCurrentDir() {
return this.currentDir.get();
}
public File getFile(String nameOrPath) throws IOException {
public SFile getFile(String nameOrPath) throws IOException {
if (isAbsolute(nameOrPath)) {
return new File(nameOrPath).getCanonicalFile();
return new SFile(nameOrPath).getCanonicalFile();
}
final File dir = currentDir.get();
File filecurrent = null;
final SFile dir = currentDir.get();
SFile filecurrent = null;
if (dir != null) {
filecurrent = new File(dir.getAbsoluteFile(), nameOrPath);
filecurrent = dir.getAbsoluteFile().file(nameOrPath);
if (filecurrent.exists()) {
return filecurrent.getCanonicalFile();
}
}
for (File d : getPath("plantuml.include.path", true)) {
if (d.isDirectory()) {
final File file = new File(d, nameOrPath);
if (file.exists()) {
return file.getCanonicalFile();
}
for (SFile d : SecurityUtils.getPath("plantuml.include.path")) {
assert d.isDirectory();
final SFile file = d.file(nameOrPath);
if (file.exists()) {
return file.getCanonicalFile();
}
}
for (File d : getPath("java.class.path", true)) {
if (d.isDirectory()) {
final File file = new File(d, nameOrPath);
if (file.exists()) {
return file.getCanonicalFile();
}
for (SFile d : SecurityUtils.getPath("java.class.path")) {
assert d.isDirectory();
final SFile file = d.file(nameOrPath);
if (file.exists()) {
return file.getCanonicalFile();
}
}
if (dir == null) {
assert filecurrent == null;
return new File(nameOrPath).getCanonicalFile();
return new SFile(nameOrPath).getCanonicalFile();
}
assert filecurrent != null;
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) {
final File f = new File(nameOrPath);
final SFile f = new SFile(nameOrPath);
return f.isAbsolute();
}
public void reset() {
setCurrentDir(new File("."));
setCurrentDir(new SFile("."));
}
}

View File

@ -35,23 +35,17 @@
*/
package net.sourceforge.plantuml;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
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.
public class FileUtils {
@ -62,19 +56,19 @@ public class FileUtils {
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) {
throw new IllegalArgumentException();
}
if (prefix == null) {
throw new IllegalArgumentException();
}
final File f;
final SFile f;
if (counter == null) {
f = File.createTempFile(prefix, suffix);
f = SFile.createTempFile(prefix, suffix);
} else {
final String name = prefix + counter.addAndGet(1) + suffix;
f = new File(name);
f = new SFile(name);
}
Log.info("Creating temporary file: " + f);
f.deleteOnExit();
@ -91,17 +85,23 @@ public class FileUtils {
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()) {
dest = new File(dest, src.getName());
dest = dest.file(src.getName());
}
final InputStream fis = new BufferedInputStream(new FileInputStream(src));
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest));
final InputStream fis = src.openFile();
if (fis == null) {
throw new FileNotFoundException();
}
final OutputStream fos = dest.createBufferedOutputStream();
copyInternal(fis, fos);
}
static public void copyToStream(File src, OutputStream os) throws IOException {
final InputStream fis = new BufferedInputStream(new FileInputStream(src));
static public void copyToStream(SFile src, OutputStream os) throws IOException {
final InputStream fis = src.openFile();
if (fis == null) {
throw new FileNotFoundException();
}
final OutputStream fos = new BufferedOutputStream(os);
copyInternal(fis, fos);
}
@ -112,14 +112,17 @@ public class FileUtils {
copyInternal(fis, fos);
}
static public void copyToFile(byte[] src, File dest) throws IOException {
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest));
static public void copyToFile(byte[] src, SFile dest) throws IOException {
final OutputStream fos = dest.createBufferedOutputStream();
fos.write(src);
fos.close();
}
static public String readSvg(File svgFile) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(svgFile));
static public String readSvg(SFile svgFile) throws IOException {
final BufferedReader br = svgFile.openBufferedReader();
if (br == null) {
return null;
}
return readSvg(br, false, true);
}
@ -128,12 +131,15 @@ public class FileUtils {
return readSvg(br, false, false);
}
static public String readFile(File svgFile) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(svgFile));
static public String readFile(SFile svgFile) throws IOException {
final BufferedReader br = svgFile.openBufferedReader();
if (br == null) {
return null;
}
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();
String s;
while ((s = br.readLine()) != null) {
@ -148,38 +154,4 @@ public class FileUtils {
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;
import java.io.File;
import java.io.IOException;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.security.SFile;
public class GeneratedImageImpl implements GeneratedImage {
private final File pngFile;
private final SFile pngFile;
private final String description;
private final BlockUml blockUml;
private final int status;
@ -51,7 +53,7 @@ public class GeneratedImageImpl implements GeneratedImage {
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.pngFile = pngFile;
this.description = description;
@ -59,7 +61,7 @@ public class GeneratedImageImpl implements GeneratedImage {
}
public File getPngFile() {
return pngFile;
return pngFile.internal;
}
public String getDescription() {
@ -76,13 +78,17 @@ public class GeneratedImageImpl implements GeneratedImage {
@Override
public String toString() {
return pngFile.getAbsolutePath() + " " + description;
return pngFile.getPrintablePath() + " " + description;
}
public int compareTo(GeneratedImage this2) {
final int cmp = this.pngFile.compareTo(this2.getPngFile());
if (cmp != 0) {
return cmp;
try {
final int cmp = this.getPngFile().getCanonicalPath().compareTo(this2.getPngFile().getCanonicalPath());
if (cmp != 0) {
return cmp;
}
} catch (IOException e) {
e.printStackTrace();
}
return this.description.compareTo(this2.getDescription());
}

View File

@ -35,20 +35,19 @@
*/
package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import net.sourceforge.plantuml.security.SFile;
public class NamedOutputStream extends OutputStream {
private final OutputStream os;
private final BaseFile basefile;
public NamedOutputStream(File file) throws FileNotFoundException {
this.os = new BufferedOutputStream(new FileOutputStream(file));
public NamedOutputStream(SFile file) throws FileNotFoundException {
this.os = file.createBufferedOutputStream();
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.cucadiagram.dot.GraphvizUtils;
import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.stats.StatsUtils;
public class Option {
@ -267,8 +268,8 @@ public class Option {
if (i == arg.length) {
continue;
}
OptionFlags.getInstance().setLogData(
new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])));
OptionFlags.getInstance()
.setLogData(new SFile(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])));
} else if (s.equalsIgnoreCase("-word")) {
OptionFlags.getInstance().setWord(true);
OptionFlags.getInstance().setQuiet(true);
@ -281,8 +282,6 @@ public class Option {
OptionPrint.printVersion();
} else if (s.matches("(?i)^-li[sc][ea]n[sc]e\\s*$")) {
OptionPrint.printLicense();
} else if (s.equalsIgnoreCase("-checkversion")) {
OptionPrint.checkVersion();
} else if (s.startsWith("-DPLANTUML_LIMIT_SIZE=")) {
final String v = s.substring("-DPLANTUML_LIMIT_SIZE=".length());
if (v.matches("\\d+")) {
@ -294,7 +293,8 @@ public class Option {
manageSkinParam(s.substring(2));
} else if (s.equalsIgnoreCase("-testdot")) {
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();
} else if (s.equalsIgnoreCase("-help") || s.equalsIgnoreCase("-h") || s.equalsIgnoreCase("-?")) {
OptionPrint.printHelp();
@ -390,23 +390,23 @@ public class Option {
return ftpPort;
}
private void addInConfig(final FileReader source) throws IOException {
BufferedReader br = null;
private void addInConfig(BufferedReader br) throws IOException {
if (br == null) {
return;
}
try {
br = new BufferedReader(source);
String s = null;
while ((s = br.readLine()) != null) {
config.add(s);
}
} finally {
if (br != null) {
br.close();
}
br.close();
}
}
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 {
@ -414,16 +414,16 @@ public class Option {
return;
}
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()) {
if (f.exists() && f.canRead()) {
addInConfig(new FileReader(f));
addInConfig(new BufferedReader(new FileReader(f)));
}
}
} else {
final File f = new File(filename);
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);
}
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);
for (Map.Entry<String, String> ent : defines.entrySet()) {
String value = ent.getValue();

View File

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

View File

@ -35,7 +35,6 @@
*/
package net.sourceforge.plantuml;
import java.io.File;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
@ -48,6 +47,9 @@ import java.util.Map;
import java.util.Properties;
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.version.License;
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();
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?\tone and only one character but '" + File.separator + "'");
System.out.println("\t*\tmeans any characters but '" + SFile.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();
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(" -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(" -config \"file\"\tTo read the provided config file before each diagram");
final char separator = File.separatorChar;
// System.out.println(" -config \"file\"\tTo read the provided config file
// before each diagram");
final char separator = SFile.separatorChar;
System.out.println(" -I" + separator + "path" + separator + "to" + separator
+ "file\tTo include file as if '!include file' were used");
System.out.println(" -I" + separator + "path" + separator + "to" + separator
+ "*.puml\tTo include files with pattern");
System.out.println(
" -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(" -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(" -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(" -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(" -quiet\t\tTo NOT print error message into the console");
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(" -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(" -encodesprite 4|8|16[z] \"file\"\tTo encode a sprite at gray level (z for compression) from an image");
System.out.println(
" -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(" -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(" -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(" -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");
@ -192,13 +195,22 @@ public class OptionPrint {
public static Collection<String> interestingProperties() {
final Properties p = System.getProperties();
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",
"Default Encoding", "user.language", "Language", "user.country", "Country");
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", */
"file.encoding", "Default Encoding", "user.language", "Language", "user.country", "Country");
final List<String> all = withIp() ? list1 : list2;
// 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",
// "Default Encoding", "user.language", "Language", "user.country", "Country");
// 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", */
// "file.encoding", "Default Encoding", "user.language", "Language", "user.country", "Country");
// 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>();
for (int i = 0; i < all.size(); i += 2) {
result.add(all.get(i + 1) + ": " + p.getProperty(all.get(i)));
@ -208,27 +220,33 @@ public class OptionPrint {
public static Collection<String> interestingValues() {
final List<String> strings = new ArrayList<String>();
if (withIp() == false) {
strings.add("Machine: " + getHostName());
}
// if (withIp() == false) {
// 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("Processors: " + Runtime.getRuntime().availableProcessors());
final long freeMemory = Runtime.getRuntime().freeMemory();
final long maxMemory = Runtime.getRuntime().maxMemory();
final long totalMemory = Runtime.getRuntime().totalMemory();
final long usedMemory = totalMemory - freeMemory;
final int threadActiveCount = Thread.activeCount();
strings.add("Max Memory: " + format(maxMemory));
strings.add("Total Memory: " + format(totalMemory));
strings.add("Free Memory: " + format(freeMemory));
strings.add("Used Memory: " + format(usedMemory));
strings.add("Thread Active Count: " + threadActiveCount);
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
strings.add("Processors: " + Runtime.getRuntime().availableProcessors());
final long freeMemory = Runtime.getRuntime().freeMemory();
final long maxMemory = Runtime.getRuntime().maxMemory();
final long totalMemory = Runtime.getRuntime().totalMemory();
final long usedMemory = totalMemory - freeMemory;
final int threadActiveCount = Thread.activeCount();
strings.add("Max Memory: " + format(maxMemory));
strings.add("Total Memory: " + format(totalMemory));
strings.add("Free Memory: " + format(freeMemory));
strings.add("Used Memory: " + format(usedMemory));
strings.add("Thread Active Count: " + threadActiveCount);
}
return Collections.unmodifiableCollection(strings);
}
private static boolean withIp() {
return getHostName().startsWith("ip-");
}
// private static boolean withIp() {
// return getHostName().startsWith("ip-");
// }
private static String hostname;
@ -258,30 +276,6 @@ public class OptionPrint {
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 {
for (String s : PSystemVersion.getAuthorsStrings(false)) {
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.PSystemColorsFactory;
import net.sourceforge.plantuml.eggs.PSystemEggFactory;
import net.sourceforge.plantuml.eggs.PSystemPathFactory;
import net.sourceforge.plantuml.eggs.PSystemRIPFactory;
import net.sourceforge.plantuml.eggs.PSystemWelcomeFactory;
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.project.GanttDiagramFactory;
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.sprite.ListSpriteDiagramFactory;
import net.sourceforge.plantuml.sprite.PSystemListInternalSpritesFactory;
@ -191,7 +194,9 @@ public class PSystemBuilder {
factories.add(new PSystemAppleTwoFactory());
factories.add(new PSystemRIPFactory());
// factories.add(new PSystemLostFactory());
// factories.add(new PSystemPathFactory());
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) {
factories.add(new PSystemPathFactory());
}
factories.add(new PSystemOregonFactory());
factories.add(new PSystemCharlieFactory());
if (License.getCurrent() == License.GPL || License.getCurrent() == License.GPLV2) {

View File

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

View File

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

View File

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

View File

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

View File

@ -35,11 +35,10 @@
*/
package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
@ -54,6 +53,8 @@ import java.util.Set;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.security.SecurityUtils;
public abstract class SourceFileReaderAbstract {
@ -85,10 +86,10 @@ public abstract class SourceFileReaderAbstract {
protected Reader getReader(String charset) throws FileNotFoundException, UnsupportedEncodingException {
if (charset == null) {
Log.info("Using default charset");
return new InputStreamReader(new FileInputStream(file));
return new InputStreamReader(new BufferedInputStream(new FileInputStream(file)));
}
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() {
@ -103,11 +104,11 @@ public abstract class SourceFileReaderAbstract {
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);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(outputFile));
os = outputFile.createBufferedOutputStream();
UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(),
UmlDiagram.getFailureText2(t, blockUml.getFlashData()));
} finally {
@ -119,13 +120,13 @@ public abstract class SourceFileReaderAbstract {
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()) {
final String warnOrError = system.getWarningOrError();
if (warnOrError != null) {
final String name = f.getName().substring(0, f.getName().length() - 4) + ".err";
final File errorFile = new File(f.getParentFile(), name);
final PrintStream ps = new PrintStream(new FileOutputStream(errorFile));
final SFile errorFile = f.getParentFile().file(name);
final PrintStream ps = SecurityUtils.createPrintStream(errorFile.createFileOutputStream());
ps.print(warnOrError);
ps.close();
}
@ -155,7 +156,7 @@ public abstract class SourceFileReaderAbstract {
continue;
}
OptionFlags.getInstance().logData(file, system);
OptionFlags.getInstance().logData(SFile.fromFile(file), system);
final List<FileImageData> exportDiagrams = PSystemUtils.exportDiagrams(system, suggested, fileFormatOption,
checkMetadata);
if (exportDiagrams.size() > 1) {
@ -164,7 +165,7 @@ public abstract class SourceFileReaderAbstract {
for (FileImageData fdata : exportDiagrams) {
final String desc = "[" + file.getName() + "] " + system.getDescription();
final File f = fdata.getFile();
final SFile f = fdata.getFile();
exportWarnOrErrIfWord(f, system);
final GeneratedImage generatedImage = new GeneratedImageImpl(f, desc, blockUml, fdata.getStatus());
result.add(generatedImage);
@ -177,6 +178,6 @@ public abstract class SourceFileReaderAbstract {
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.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
public class SourceFileReaderCopyCat extends SourceFileReaderAbstract implements ISourceFileReader {
@ -53,15 +54,17 @@ public class SourceFileReaderCopyCat extends SourceFileReaderAbstract implements
}
final String path = file.getParentFile().getPath();
// 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();
if (outputDirectory.exists() == false) {
outputDirectory.mkdirs();
}
// System.err.println("SourceFileReaderCopyCat=" + this.outputDirectory.getPath() + " "
// System.err.println("SourceFileReaderCopyCat=" +
// this.outputDirectory.getPath() + " "
// + this.outputDirectory.getAbsolutePath());
builder = new BlockUmlBuilder(config, charset, defines, getReader(charset), file.getAbsoluteFile()
.getParentFile(), FileWithSuffix.getFileName(file));
builder = new BlockUmlBuilder(config, charset, defines, getReader(charset),
SFile.fromFile(file.getAbsoluteFile().getParentFile()), FileWithSuffix.getFileName(file));
}
@Override

View File

@ -41,20 +41,21 @@ import java.util.List;
import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.preproc.FileWithSuffix;
import net.sourceforge.plantuml.security.SFile;
public class SourceFileReaderHardFile extends SourceFileReaderAbstract implements ISourceFileReader {
public SourceFileReaderHardFile(Defines defines, final File file, File outputFile, List<String> config, String charset,
FileFormatOption fileFormatOption) throws IOException {
public SourceFileReaderHardFile(Defines defines, final File file, File outputFile, List<String> config,
String charset, FileFormatOption fileFormatOption) throws IOException {
this.file = file;
this.fileFormatOption = fileFormatOption;
this.outputFile = outputFile;
if (file.exists() == false) {
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,
FileWithSuffix.getFileName(file));
}

View File

@ -35,9 +35,6 @@
*/
package net.sourceforge.plantuml;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
@ -50,6 +47,7 @@ import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.preproc.Defines;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity;
@ -74,7 +72,7 @@ public class SourceStringReader {
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);
}
@ -82,7 +80,7 @@ public class SourceStringReader {
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
// synchronized (SourceStringReader.class) {
try {
@ -106,12 +104,12 @@ public class SourceStringReader {
}
@Deprecated
public String generateImage(File f) throws IOException {
public String generateImage(SFile f) throws IOException {
return outputImage(f).getDescription();
}
public DiagramDescription outputImage(File f) throws IOException {
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
public DiagramDescription outputImage(SFile f) throws IOException {
final OutputStream os = f.createBufferedOutputStream();
DiagramDescription result = null;
try {
result = outputImage(os, 0);
@ -226,8 +224,8 @@ public class SourceStringReader {
private void noStartumlFound(OutputStream os, FileFormatOption fileFormatOption, long seed) throws IOException {
final TextBlockBackcolored error = GraphicStrings.createForError(Arrays.asList("No @startuml/@enduml found"),
fileFormatOption.isUseRedForError());
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, null, null,
1.0, error.getBackcolor());
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, null, null, 1.0,
error.getBackcolor());
imageBuilder.setUDrawable(error);
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) {
if (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();
}
}
@ -136,7 +137,7 @@ public class Splash extends Window implements MouseListener, MouseMotionListener
public void mouseClicked(MouseEvent event) {
if (link != LINK_NORMAL) {
try {
Desktop.getDesktop().browse(new URL("http://plantuml.com").toURI());
Desktop.getDesktop().browse(new URL("https://plantuml.com").toURI());
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -35,8 +35,6 @@
*/
package net.sourceforge.plantuml;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
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.Pattern2;
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
public class StringUtils {
public static String getPlateformDependentAbsolutePath(File file) {
return file.getAbsolutePath();
}
final static public List<String> getSplit(Pattern2 pattern, String line) {
final Matcher2 m = pattern.matcher(line);
if (m.find() == false) {
@ -71,7 +61,6 @@ public class StringUtils {
result.add(m.group(i));
}
return result;
}
public static boolean isNotEmpty(String input) {
@ -338,9 +327,9 @@ public class StringUtils {
if (uml.startsWith("@startuml\ndonors\n")) {
return false;
}
if (uml.startsWith("@startuml\ncheckversion")) {
return false;
}
// if (uml.startsWith("@startuml\ncheckversion")) {
// return false;
// }
if (uml.startsWith("@startuml\ntestdot\n")) {
return false;
}

View File

@ -35,15 +35,15 @@
*/
package net.sourceforge.plantuml;
import java.io.File;
import net.sourceforge.plantuml.security.SFile;
public class SuggestedFile {
private final FileFormat fileFormat;
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())) {
throw new IllegalArgumentException();
}
@ -58,14 +58,18 @@ public class SuggestedFile {
@Override
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);
}
public File getParentFile() {
public static SuggestedFile fromOutputFile(java.io.File outputFile, FileFormat fileFormat) {
return fromOutputFile(outputFile, fileFormat, 0);
}
public SFile getParentFile() {
return outputFile.getParentFile();
}
@ -73,17 +77,21 @@ public class SuggestedFile {
return outputFile.getName();
}
public File getFile(int cpt) {
public SFile getFile(int 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);
}
public File getTmpFile() {
return new File(getParentFile(), getName() + ".tmp");
public static SuggestedFile fromOutputFile(java.io.File outputFile, FileFormat fileFormat, int initialCpt) {
return new SuggestedFile(SFile.fromFile(outputFile), fileFormat, initialCpt);
}
public SFile getTmpFile() {
return getParentFile().file(getName() + ".tmp");
}
}

View File

@ -44,6 +44,9 @@ public class SvgString {
private final double scale;
public SvgString(String svg, double scale) {
if (svg == null) {
throw new IllegalArgumentException();
}
this.svg = svg;
this.scale = scale;
}

View File

@ -39,18 +39,14 @@ import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.imageio.ImageIO;
import javax.script.ScriptException;
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.mjpeg.MJPEGGenerator;
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.svek.EmptySvgException;
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) {
final PrintWriter pw = new PrintWriter(os);
final PrintWriter pw = SecurityUtils.createPrintWriter(os);
exception.printStackTrace(pw);
pw.println();
pw.println();
@ -312,7 +311,7 @@ public abstract class UmlDiagram extends TitledDiagram implements Diagram, Annot
}
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 double framerate = 30;
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 ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException {
final File svg = FileUtils.createTempFile("pdf", ".svf");
final File pdfFile = FileUtils.createTempFile("pdf", ".pdf");
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg));
final SFile svg = FileUtils.createTempFile("pdf", ".svf");
final SFile pdfFile = FileUtils.createTempFile("pdf", ".pdf");
final OutputStream fos = svg.createBufferedOutputStream();
final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG));
fos.close();
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)
throws FileNotFoundException {
final String name = changeName(suggestedFile.getFile(index).getAbsolutePath());
final File cmapFile = new File(name);
final SFile cmapFile = new SFile(name);
PrintWriter pw = null;
try {
if (PSystemUtils.canFileBeWritten(cmapFile) == false) {
return;
}
pw = new PrintWriter(cmapFile);
pw = cmapFile.createPrintWriter();
pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6)));
pw.close();
} finally {

View File

@ -39,7 +39,6 @@ import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.ugraphic.MinMax;
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.SheetBlock1;
import net.sourceforge.plantuml.creole.SheetBlock2;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration;
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.SheetBlock2;
import net.sourceforge.plantuml.creole.Stencil;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment;
@ -251,7 +250,13 @@ public class FtileBox extends AbstractFtile {
} else {
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);
if (horizontalAlignment == HorizontalAlignment.LEFT) {

View File

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

View File

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

View File

@ -40,7 +40,6 @@ import java.io.OutputStream;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.TikzFontDistortion;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.posimo.DotPath;
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.CommandDiamondAssociation;
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.CommandLinkClass;
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 CommandLinkLollipop(UmlDiagramType.CLASS));
cmds.add(new CommandImport());
final CommandFactoryTipOnEntity factoryTipOnEntityCommand = new CommandFactoryTipOnEntity("a", new RegexLeaf(
"ENTITY", "(" + CommandCreateClass.CODE_NO_DOTDOT + "|[%g][^%g]+[%g])::([%g][^%g]+[%g]|[^%s]+)"));
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;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -50,6 +48,7 @@ import net.sourceforge.plantuml.BackSlash;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.StringLocated;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.security.SFile;
public class BlocLines implements Iterable<StringLocated> {
@ -66,8 +65,11 @@ public class BlocLines implements Iterable<StringLocated> {
return sb.toString();
}
public static BlocLines load(File f, LineLocation location) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(f));
public static BlocLines load(SFile f, LineLocation location) throws IOException {
final BufferedReader br = f.openBufferedReader();
if (br == null) {
return null;
}
return loadInternal(br, location);
}

View File

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

View File

@ -35,15 +35,12 @@
*/
package net.sourceforge.plantuml.command;
import java.io.File;
import java.io.FileInputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.FileSystem;
import net.sourceforge.plantuml.FileUtils;
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.RegexLeaf;
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.SpriteImage;
import net.sourceforge.plantuml.sprite.SpriteSvg;
@ -88,24 +86,32 @@ public class CommandSpriteFile extends SingleLineCommand2<UmlDiagram> {
sprite = new SpriteImage(ImageIO.read(is));
} else if (src.contains("~")) {
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) {
return CommandExecutionResult.error("File does not exist: " + src);
return CommandExecutionResult.error("Cannot read: " + src);
}
final String name = src.substring(idx + 1);
sprite = getImageFromZip(f, name);
if (sprite == null) {
return CommandExecutionResult.error("No image " + name + " in " + FileWithSuffix.getFileName(f));
return CommandExecutionResult.error("Cannot read: " + src);
}
} else {
final File f = FileSystem.getInstance().getFile(src);
final SFile f = FileSystem.getInstance().getFile(src);
if (f.exists() == false) {
return CommandExecutionResult.error("File does not exist: " + src);
return CommandExecutionResult.error("Cannot read: " + src);
}
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 {
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) {
@ -116,10 +122,14 @@ public class CommandSpriteFile extends SingleLineCommand2<UmlDiagram> {
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;
try {
zis = new ZipInputStream(new FileInputStream(f));
zis = new ZipInputStream(tmp);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {

View File

@ -40,14 +40,10 @@ import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileSystem;
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.StringBounder;
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.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImage;
@ -106,24 +107,38 @@ public class AtomImg extends AbstractAtom implements Atom {
// Check if valid URL
if (src.startsWith("http:") || src.startsWith("https:")) {
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) {
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")) {
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) {
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) {
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);
}
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 {
final BufferedImage read = FileUtils.readRasterImageFromURL(source);
if (source == null) {
return AtomText.create("(Cannot decode: " + text + ")", fc);
}
final BufferedImage read = source.readRasterImageFromURL();
if (read == null) {
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 {
if (source == null) {
return AtomText.create("(Cannot decode SVG: " + text + ")", fc);
}
final byte[] read = getFile(source);
if (read == null) {
return AtomText.create("(Cannot decode SVG: " + text + ")", fc);
@ -155,13 +176,16 @@ public class AtomImg extends AbstractAtom implements Atom {
}
// Added by Alain Corbiere
private static byte[] getFile(URL url) {
final ByteArrayOutputStream image = new ByteArrayOutputStream();
private static byte[] getFile(SURL url) {
try {
InputStream input = null;
try {
final URLConnection connection = url.openConnection();
if (connection == null) {
return null;
}
input = connection.getInputStream();
final ByteArrayOutputStream image = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0) {
@ -174,7 +198,7 @@ public class AtomImg extends AbstractAtom implements Atom {
input.close();
}
}
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}

View File

@ -78,6 +78,7 @@ import net.sourceforge.plantuml.graphic.HorizontalAlignment;
import net.sourceforge.plantuml.graphic.ImgValign;
import net.sourceforge.plantuml.math.ScientificEquationSafe;
import net.sourceforge.plantuml.openiconic.OpenIcon;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.sprite.Sprite;
import net.sourceforge.plantuml.ugraphic.color.HColor;
import net.sourceforge.plantuml.utils.CharHidder;
@ -160,7 +161,9 @@ public class StripeSimple implements Stripe {
this.commands.add(CommandCreoleFontFamilyChange.createEol());
this.commands.add(CommandCreoleMonospaced.create(skinParam.getMonospacedFamily()));
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);

View File

@ -65,7 +65,7 @@ import net.sourceforge.plantuml.ugraphic.UGraphic;
public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPorts {
private TextBlock area2;
private TextBlock area;
private final FontConfiguration titleConfig;
private final List<CharSequence> rawBody;
private final FontParam fontParam;
@ -78,6 +78,7 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
private final Stereotype stereotype;
private final ILeaf entity;
private final boolean inEllipse;
private final double minClassWidth;
public BodyEnhanced(List<String> rawBody, FontParam fontParam, ISkinParam skinParam, boolean manageModifier,
Stereotype stereotype, ILeaf entity) {
@ -93,10 +94,18 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
this.manageModifier = manageModifier;
this.entity = entity;
this.inEllipse = false;
this.minClassWidth = 0;
}
public BodyEnhanced(Display display, FontParam fontParam, ISkinParam skinParam, HorizontalAlignment align,
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.stereotype = stereotype;
this.rawBody = new ArrayList<CharSequence>();
@ -137,8 +146,8 @@ public class BodyEnhanced extends AbstractTextBlock implements TextBlock, WithPo
}
private TextBlock getArea(StringBounder stringBounder) {
if (area2 != null) {
return area2;
if (area != null) {
return area;
}
urls.clear();
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));
if (blocks.size() == 1) {
this.area2 = blocks.get(0);
this.area = blocks.get(0);
} 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) {

View File

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

View File

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

View File

@ -44,6 +44,7 @@ import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.OptionFlags;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SFile;
abstract class AbstractGraphviz implements Graphviz {
@ -58,8 +59,8 @@ abstract class AbstractGraphviz implements Graphviz {
private static String findExecutableOnPath(String name) {
final String path = System.getenv("PATH");
if (path != null) {
for (String dirname : path.split(File.pathSeparator)) {
File file = new File(dirname, name);
for (String dirname : path.split(SFile.pathSeparator)) {
final File file = new File(dirname, name);
if (file.isFile() && file.canExecute()) {
return file.getAbsolutePath();
}
@ -98,7 +99,8 @@ abstract class AbstractGraphviz implements Graphviz {
}
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();
}
final String cmd[] = getCommandLine();

View File

@ -36,10 +36,8 @@
package net.sourceforge.plantuml.cucadiagram.dot;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
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.GraphvizSolverB;
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.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) {
globalUg.getCharArea().print(new PrintStream(suggestedFile, "UTF-8"));
globalUg.getCharArea().print(suggestedFile.createPrintStream("UTF-8"));
} else {
globalUg.getCharArea().print(new PrintStream(suggestedFile));
globalUg.getCharArea().print(suggestedFile.createPrintStream());
}
return Collections.singletonList(suggestedFile);
}
@ -196,7 +196,7 @@ public final class CucaDiagramTxtMaker {
}
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;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import net.sourceforge.plantuml.security.SFile;
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 synchronized static PrintWriter getPrintWriter() {
if (pw == null) {
try {
pw = new PrintWriter(out);
pw = out.createPrintWriter();
} 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.ILeaf;
import net.sourceforge.plantuml.cucadiagram.Link;
import net.sourceforge.plantuml.cucadiagram.LinkDecor;
import net.sourceforge.plantuml.cucadiagram.PortionShower;
import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory;
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.Log;
import net.sourceforge.plantuml.OptionFlags;
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.VizJsEngine;
@ -55,7 +57,7 @@ public class GraphvizUtils {
private static int DOT_VERSION_LIMIT = 226;
private static boolean isWindows() {
return File.separatorChar == '\\';
return SFile.separatorChar == '\\';
}
private static String dotExecutable;
@ -131,35 +133,19 @@ public class GraphvizUtils {
if (local != null) {
return local;
}
final String env = getenv("PLANTUML_LIMIT_SIZE");
final String env = SecurityUtils.getenv("PLANTUML_LIMIT_SIZE");
if (StringUtils.isNotEmpty(env) && env.matches("\\d+")) {
return Integer.parseInt(env);
}
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() {
return getenv("PLANTUML_DEFAULT_CONFIG_FILENAME");
return SecurityUtils.getenv("PLANTUML_DEFAULT_CONFIG_FILENAME");
}
public static String getenvLogData() {
return 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);
return SecurityUtils.getenv("PLANTUML_LOGDATA");
}
private static String dotVersion = null;
@ -220,15 +206,16 @@ public class GraphvizUtils {
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();
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);
if (exeState == ExeState.OK) {

View File

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

View File

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

View File

@ -60,7 +60,7 @@ class GraphvizWindows extends AbstractGraphviz {
private File specificDotExeSlow() {
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();
}
})) {
@ -78,7 +78,7 @@ class GraphvizWindows extends AbstractGraphviz {
}
final List<File> dots = new ArrayList<File>();
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");
}
});

View File

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

View File

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

View File

@ -42,8 +42,6 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.AbstractPSystem;
import net.sourceforge.plantuml.BackSlash;
import net.sourceforge.plantuml.FileFormat;
@ -52,6 +50,7 @@ import net.sourceforge.plantuml.UmlDiagram;
import net.sourceforge.plantuml.api.ImageDataSimple;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.svek.GraphvizCrash;
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 FREE_LINES = 6;
public static final String DONORS = "6rWB02mFUBXRGOc9nbfsvvsjZ9-86KqYM9ud58U1HJpT3OW_mBtJutuZ_KLqfNlVD2FQiZN5USOGiI3e"
+ "yJIvPjZctXu8Sw9y2FxT21uW0qH9r4QrBFUas6sRAaDAyEyxN_abw1tUiK6YkKgZnP5xPFSBxs-6ytpJ"
+ "67hf6R0ygdwAxcl_T-agw_AgAipItGgCmAZJ2DLvIp77TFz7WJjEmKvGHOybntGgvpeSggY0LoSy1XPf"
+ "1ZUFyshKP5HCQXCfaTOe8s9q9hJcfFPPiY63n2_r0xpPN66fu4meZb4IT7qzjtVRGFFB95v4mH0B3WlC"
+ "ePJ3kq3nSoD18YX0eNaMlR6L1qkUk61H2YtimnyQoO57AfdJqI8HyW0A8fx11P9Ug5KJpaui1bGHoHQz"
+ "bgJgqdY8T5o7vIczDXhk0OiG2yu2QWZoF-Y2JuzL7qsTusfe9FKqoLkrTQXVYVVGDYFwfXvD4jLdVzFC"
+ "4NU1iaMgQwlFCLxp2CZTKYkl-3BgoEO0pxvxLvFrZnR8Zq2trKGj-RFi2mi9Y6ih-o1TvuQBHo_2CHio"
+ "JQpZTxFjDVs5hbXbep9MW4L-EhykDI715heoUGHwGgk2PfrFDDBI-lsYnvUD-uHhAYpk7Q3tKJRd-V_T"
+ "xcLcA0xGqJApeEiHAihLjEefjY22Cq8NXjm4oHKuRwxRSVEwoA_wWE3DPGJYi26qGRm-Gkcw569rhEh6"
+ "D2E0sTFAkKY4BH5GertGlQYIYPJrRe_JrPc-RCpS9trmtMymHd5C9pGMaRjt8JqCArIZMT-iVKXp2gxo"
+ "EiwhxZNUhsBRty9xqeVq_2C3VgPt1YBbHposhVoZIBUEYbcifMxMvRkw7nmyTCU2CrYqX1bjjaEcGU5i"
+ "CixKhqn-MZBy7OUivlU6PgyWUYTiX0Wpci7jhSarDRbC8cWwo_6n2uWYjNZ5hhXm1qBTB2l55ZR5oZDM"
+ "Zq92ViTyWaZbNJYjM6lk9ZmZUnJKuRmxLYthrw6MRG7LvZ11HbgeQgIQ8tqja85hTNeMMmVRdnPOCBRn"
+ "g8eLX-8x9jgltA1W2imKuNvH48boGLfABp59JE1__lnAFRclWutlZFB9E4ZsaCH05N9rnechfe7p65R6"
+ "Ues_Nszjzmh-_7iTRN9gYsT-YY1w3fBZtqbnp8LIrl4qobzdmsB08LPmqKR1bLkMtWmaBDY1TsPHZmyp"
+ "6ZSnMMvQBdh5zg4gVZkv0HVp8JRikCYaEKOikTBRRZseuhRlU6Dna8FYxwBAk4okSlKQ654WjhuN9prs"
+ "6sLuoYe5M50Tjmci_Ugtqonl6dFUeLGtN0RopO6SAlK8BQofQSrO26mGOtvlOJ-LzFXF1lh5jTQFlNhe"
+ "EQYyXtU3Xczxa7x6I31S9EsOeBVqEPc1XsyOv8svEV7fOicLYsuOTe5WXVr6NoOB2I_iQ9LBDDSUNdFw"
+ "vLtEQZjow1QoZrQZ-OMYYfY1N5YirTM9XLAE1r8a1NFsbl42QGUzmIKz0JX5mV7-xaCulT3yY6RjuncD" + "OgwA2G00";
public static final String DONORS = "6tOB0AmEUFDMA37HMBjrivhoM7AcIGJByuJYCB28fxi1yGUuTthSRwI_YAvqxvjcH5ksfZZF628M13sU"
+ "9jSCszpR0s7EZ1V1dJc2dWyV88ghDl8ZTUGuzq0i5Tr_cRWztJekLC6nQeHoeBYruNrdR9wTnXUl7atG"
+ "Hk37mBxwVrE7hCj3LPYbknNFOp4g6g4wB_GKSwnp_qSL5w9Wtw7gOSindRgu3eSgAk3L2O-1HPh1RUEy"
+ "MZGP5PFOH4geDaeG4eCPEd9I-mBvGGQ9N-e5j6cjhY6HFQ2upXI9hjjo1xODDBzIugNW3xvWyy0SIZdS"
+ "9oXnRiIGyFEWeMqLlR4rHvOySS1G3YtipH-Av4Zl8PbLXXQ9W1ee27aO1oIZK8Scd1rR3AYw1riCQ92g"
+ "g_qct7qSbgTeRZJS1HO15fm5r13aVz0JFgEll6IopwUYbf2dIRogRKJzgdW_RJEYR_RH950-xA5PiLy5"
+ "ojP3EbjUn_oheqFUDMJbqMz67TbSWxlivj8mlxH0_GXqsvoe9Bw-A0iBIGZNbdeXNUVcAxKNuOGDAHNh"
+ "v5riUOt-eIjIsOHOpWuMyhH_NMrA1bleogKQUaEhEiqwdsX93VNtGnuTEjy5rrIRtJjCxv4s5_d_NRSq"
+ "CnG7wCGKiw3h0aNdQ5hr5nk8uBJGXI4t0V84ofV9BNzPFiGVzG71MqW4eh1HqWd-_4Xvo8KBCx2gMrAC"
+ "0EPFAUT98kY42FKw13sCAfb8cRj-XadFicLZRfdqmPKr62C_ffEAa_3TNE0HXjLgqKmtQnzXbU0Ll4xo"
+ "gdkDzgiKiIsyProarWyPY3FC6H4fFwBOjhHBmaCTXLci9JTryJtT3WuUkdl16InQnOmsso5BGk5iCixK"
+ "Mum-D1Z-Za8sQVVcfbv1-Awm4TpCQ0QtboOtrEGI2R_bBCV35e0IS_6ANL7XKaBLB2kLhMi9aoDMZqE6"
+ "_4xq2IoLU-5fnuxcxiGpnAEW3kVTiUfKVqvftXPGGqmJPAI5CcT8auUj1J9mh4xFIXjWzrCx5enjVh9Y"
+ "pQ7ujebOumODKs2wYF160v582kebUib9OW3VTVcLUgIlWu_lwcd5E4XQI6AW2bATyODJq_3v34rZlKR_"
+ "jxMsMtR-_7iTsUJK6VUwYY1w3YBnRwS07UKa8dWQyFwMZv1t2gmQNNfGX2jtARqPI5YmczwPHJqwp6ZS"
+ "yMAvERdevTk7glxkv3PSB0RViE8YaoQVVOcJrdRre8hQllkDnK4E7NyNLQPaSfLBQs14WzZMNfpqs6sc"
+ "uYwh5U31xBXCOErNJy_DD5uovhfZgMvu7CWM8ZAa67ryiQQczN4Yi5awytjBsv3CwB_1Y7vHhUcnLm_z"
+ "1-NtM15e-BQ5Ciw91CD5we61VdEVanbqyms7l30r9pfTBBvoqMt3pXUiiD_4ZyX2mWlRccaYhBLtgpdz"
+ "QIwUi-t8qRUGVM8scbx8guWPoC9YWvwTM2ZbU215KZ1dRvae8ksWDxYiHm2Tec3yVnc4euNcHsHMcMTl" + "57FP9cC_bFBc_GC0";
/*
* Special thanks to our sponsors and donors:

View File

@ -43,14 +43,13 @@ import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.AbstractPSystem;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.graphic.GraphicPosition;
import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder;
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.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
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.TextBlockUtils;
import net.sourceforge.plantuml.graphic.VerticalAlignment;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.MinMax;
@ -203,15 +203,15 @@ public abstract class PSystemError extends AbstractPSystem {
final UGraphicTxt ugt = new UGraphicTxt();
final UmlCharArea area = ugt.getCharArea();
area.drawStringsLR(getPureAsciiFormatted(), 0, 0);
area.print(new PrintStream(os));
area.print(SecurityUtils.createPrintStream(os));
return new ImageDataSimple(1, 1);
}
final TextBlockBackcolored result = getGraphicalFormatted();
TextBlock udrawable;
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(),
false, null, getMetadata(), null, 1.0, result.getBackcolor());
final ImageBuilder imageBuilder = ImageBuilder.buildA(new ColorMapperIdentity(), false, null, getMetadata(),
null, 1.0, result.getBackcolor());
imageBuilder.setRandomPixel(true);
if (getSource().getTotalLineCount() < 5) {
udrawable = addWelcome(result);

View File

@ -54,6 +54,7 @@ import java.util.StringTokenizer;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileUtils;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.SecurityUtils;
class FtpLoop implements Runnable {
enum Mode {
@ -74,7 +75,7 @@ class FtpLoop implements Runnable {
this.incoming = socket;
this.ftpServer = ftpServer;
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
@ -178,7 +179,8 @@ class FtpLoop implements Runnable {
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 byte[] data = connexion.getData(fileName);
@ -291,7 +293,7 @@ class FtpLoop implements Runnable {
}
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();
if (files.size() > 0) {
int total = 0;

View File

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

View File

@ -36,12 +36,7 @@
package net.sourceforge.plantuml.graphic;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
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.FileUtils;
@ -49,12 +44,15 @@ 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.security.SFile;
import net.sourceforge.plantuml.security.SURL;
public class Img implements HtmlCommand {
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 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);
private final TextBlock tileImage;
@ -96,29 +94,36 @@ public class Img implements HtmlCommand {
}
final String src = m.group(1);
try {
final File f = FileSystem.getInstance().getFile(src);
final SFile f = FileSystem.getInstance().getFile(src);
if (f.exists() == false) {
// Check if valid URL
if (src.startsWith("http:") || src.startsWith("https:")) {
// final byte image[] = getFile(src);
// final BufferedImage read = ImageIO.read(new ByteArrayInputStream(image));
final BufferedImage read = FileUtils.readRasterImageFromURL(new URL(src));
final SURL tmp = SURL.create(src);
if (tmp == null) {
return new Text("(Cannot decode: " + src + ")");
}
final BufferedImage read = tmp.readRasterImageFromURL();
if (read == null) {
return new Text("(Cannot decode: " + src + ")");
}
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")) {
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) {
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) {
e.printStackTrace();
return new Text("ERROR " + e.toString());
}
}
@ -127,27 +132,4 @@ public class Img implements HtmlCommand {
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.UTranslate;
class TextBlockMinWidth extends AbstractTextBlock implements TextBlock {
class TextBlockMinWidth extends AbstractTextBlock implements TextBlock {
private final TextBlock textBlock;
private final double minWidth;
@ -61,9 +61,15 @@ class TextBlockMinWidth extends AbstractTextBlock implements TextBlock {
public void drawU(UGraphic ug) {
if (horizontalAlignment == HorizontalAlignment.LEFT) {
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) {
final Dimension2D dim = textBlock.calculateDimension(ug.getStringBounder());
final double diffx = minWidth - dim.getWidth();
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)));
} else {
throw new UnsupportedOperationException();

View File

@ -37,17 +37,16 @@ package net.sourceforge.plantuml.graphic;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import net.sourceforge.plantuml.ColorParam;
import net.sourceforge.plantuml.CornerParam;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.ISkinParam;
import net.sourceforge.plantuml.LineParam;
import net.sourceforge.plantuml.SkinParam;
@ -176,13 +175,6 @@ public class TextBlockUtils {
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) {
if (text == null) {
return true;
@ -192,15 +184,15 @@ public class TextBlockUtils {
}
public static FontRenderContext getFontRenderContext() {
return gg.getFontRenderContext();
return FileFormat.gg.getFontRenderContext();
}
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) {
return gg.getFontMetrics(font);
return FileFormat.gg.getFontMetrics(font);
}
public static TextBlock fullInnerPosition(final TextBlock bloc, final String display) {

View File

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

View File

@ -136,7 +136,7 @@ public class UnusedSpace {
// int cpt = 1;
// try {
// ImageIO.write(im, "png", new File("c:/img" + cpt + ".png"));
// ImageIO.write(im, "png", SecurityUtils.File("c:/img" + cpt + ".png"));
// cpt++;
// } catch (IOException e) {
// 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.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment;

View File

@ -35,7 +35,6 @@
*/
package net.sourceforge.plantuml.html;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.Member;
import net.sourceforge.plantuml.cucadiagram.Stereotype;
import net.sourceforge.plantuml.security.SFile;
public final class CucaDiagramHtmlMaker {
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.dir = dir;
}
@ -68,8 +68,8 @@ public final class CucaDiagramHtmlMaker {
if (dir.exists() == false) {
throw new IOException("Cannot create " + dir);
}
final File f = new File(dir, "index.html");
final PrintWriter pw = new PrintWriter(f);
final SFile f = dir.file("index.html");
final PrintWriter pw = f.createPrintWriter();
pw.println("<html>");
printAllType(pw, LeafType.ENUM);
printAllType(pw, LeafType.INTERFACE);
@ -92,7 +92,8 @@ public final class CucaDiagramHtmlMaker {
pw.println(LinkHtmlPrinter.htmlLink(ent));
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) {
// continue;
// }
@ -114,8 +115,8 @@ public final class CucaDiagramHtmlMaker {
}
private void export(IEntity entity) throws IOException {
final File f = new File(dir, LinkHtmlPrinter.urlOf(entity));
final PrintWriter pw = new PrintWriter(f);
final SFile f = dir.file(LinkHtmlPrinter.urlOf(entity));
final PrintWriter pw = f.createPrintWriter();
pw.println("<html>");
pw.println("<title>" + StringUtils.unicodeForHtml(entity.getCodeGetName()) + "</title>");
pw.println("<h2>" + entity.getLeafType().toHtml() + "</h2>");
@ -209,8 +210,7 @@ public final class CucaDiagramHtmlMaker {
if (link.contains(ent) == false) {
continue;
}
if (link.getEntity1().getLeafType() == LeafType.NOTE
|| link.getEntity2().getLeafType() == LeafType.NOTE) {
if (link.getEntity1().getLeafType() == LeafType.NOTE || link.getEntity2().getLeafType() == LeafType.NOTE) {
result.add(link.getOther(ent));
}
}
@ -223,8 +223,7 @@ public final class CucaDiagramHtmlMaker {
if (link.contains(ent) == false) {
continue;
}
if (link.getEntity1().getLeafType() == LeafType.NOTE
|| link.getEntity2().getLeafType() == LeafType.NOTE) {
if (link.getEntity1().getLeafType() == LeafType.NOTE || link.getEntity2().getLeafType() == LeafType.NOTE) {
continue;
}
result.add(link);

View File

@ -1,11 +1,8 @@
package net.sourceforge.plantuml.jasic;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -105,29 +102,6 @@ import java.util.Map;
*/
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) -----------------------------------------------------
/**
@ -829,43 +803,4 @@ public class Jasic {
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.util.Properties;
import javax.imageio.ImageIO;
import jcckit.GraphicsPlotCanvas;
import jcckit.data.DataPlot;
import jcckit.util.ConfigParameters;
@ -51,6 +49,7 @@ import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.api.ImageDataSimple;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.security.ImageIO;
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.Sheet;
import net.sourceforge.plantuml.creole.SheetBlock1;
import net.sourceforge.plantuml.creole.legacy.CreoleParser;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.FontConfiguration;

View File

@ -43,8 +43,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
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.graphic.GraphicStrings;
import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.ugraphic.ImageBuilder;
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.TextBlock;
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.StyleSignature;
import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.ImageBuilder;
import net.sourceforge.plantuml.ugraphic.MinMax;
@ -94,15 +98,21 @@ public class MindMapDiagram extends UmlDiagram {
final ISkinParam skinParam = getSkinParam();
final int margin1;
final int margin2;
final HColor backgroundColor;
if (SkinParam.USE_STYLES()) {
margin1 = 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 {
margin1 = 10;
margin2 = 10;
backgroundColor = skinParam.getBackgroundColor(false);
}
final ImageBuilder imageBuilder = ImageBuilder.buildB(skinParam.getColorMapper(), skinParam.handwritten(), ClockwiseTopRightBottomLeft.margin1margin2((double) margin1, (double) margin2),
null, fileFormatOption.isWithMetadata() ? getMetadata() : null, "", dpiFactor, skinParam.getBackgroundColor(false));
final ImageBuilder imageBuilder = ImageBuilder.buildBB(skinParam.getColorMapper(), skinParam.handwritten(),
ClockwiseTopRightBottomLeft.margin1margin2(margin1, margin2), null,
fileFormatOption.isWithMetadata() ? getMetadata() : null, "", dpiFactor, backgroundColor);
TextBlock result = getTextBlock();
result = new AnnotatedWorker(this, skinParam, fileFormatOption.getDefaultStringBounder()).addAdd(result);

View File

@ -14,109 +14,100 @@ import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
/**
*
* @author monceaux
*/
public class MJPEGGenerator
{
/*
* Info needed for MJPEG AVI
*
* - size of file minus "RIFF & 4 byte file size"
*
*/
public class MJPEGGenerator {
/*
* Info needed for MJPEG AVI
*
* - size of file minus "RIFF & 4 byte file size"
*
*/
int width = 0;
int height = 0;
double framerate = 0;
int numFrames = 0;
File aviFile = null;
FileOutputStream aviOutput = null;
FileChannel aviChannel = null;
int width = 0;
int height = 0;
double framerate = 0;
int numFrames = 0;
SFile aviFile = null;
FileOutputStream aviOutput = null;
FileChannel aviChannel = null;
long riffOffset = 0;
long aviMovieOffset = 0;
long riffOffset = 0;
long aviMovieOffset = 0;
AVIIndexList indexlist = null;
AVIIndexList indexlist = null;
/** Creates a new instance of MJPEGGenerator */
public MJPEGGenerator(File aviFile, int width, int height, double framerate, int numFrames) throws IOException
{
this.aviFile = aviFile;
this.width = width;
this.height = height;
this.framerate = framerate;
this.numFrames = numFrames;
aviOutput = new FileOutputStream(aviFile);
aviChannel = aviOutput.getChannel();
/** Creates a new instance of MJPEGGenerator */
public MJPEGGenerator(SFile aviFile, int width, int height, double framerate, int numFrames) throws IOException {
this.aviFile = aviFile;
this.width = width;
this.height = height;
this.framerate = framerate;
this.numFrames = numFrames;
aviOutput = aviFile.createFileOutputStream();
aviChannel = aviOutput.getChannel();
RIFFHeader rh = new RIFFHeader();
aviOutput.write(rh.toBytes());
aviOutput.write(new AVIMainHeader().toBytes());
aviOutput.write(new AVIStreamList().toBytes());
aviOutput.write(new AVIStreamHeader().toBytes());
aviOutput.write(new AVIStreamFormat().toBytes());
aviOutput.write(new AVIJunk().toBytes());
aviMovieOffset = aviChannel.position();
aviOutput.write(new AVIMovieList().toBytes());
indexlist = new AVIIndexList();
}
RIFFHeader rh = new RIFFHeader();
aviOutput.write(rh.toBytes());
aviOutput.write(new AVIMainHeader().toBytes());
aviOutput.write(new AVIStreamList().toBytes());
aviOutput.write(new AVIStreamHeader().toBytes());
aviOutput.write(new AVIStreamFormat().toBytes());
aviOutput.write(new AVIJunk().toBytes());
aviMovieOffset = aviChannel.position();
aviOutput.write(new AVIMovieList().toBytes());
indexlist = new AVIIndexList();
}
public void addImage(Image image) throws IOException
{
byte[] fcc = new byte[]{'0','0','d','b'};
byte[] imagedata = writeImageToBytes(image);
int useLength = imagedata.length;
long position = aviChannel.position();
int extra = (useLength+(int)position) % 4;
if(extra > 0)
useLength = useLength + extra;
public void addImage(Image image) throws IOException {
byte[] fcc = new byte[] { '0', '0', 'd', 'b' };
byte[] imagedata = writeImageToBytes(image);
int useLength = imagedata.length;
long position = aviChannel.position();
int extra = (useLength + (int) position) % 4;
if (extra > 0)
useLength = useLength + extra;
indexlist.addAVIIndex((int)position,useLength);
indexlist.addAVIIndex((int) position, useLength);
aviOutput.write(fcc);
aviOutput.write(intBytes(swapInt(useLength)));
aviOutput.write(imagedata);
if(extra > 0)
{
for(int i = 0; i < extra; i++)
aviOutput.write(0);
}
imagedata = null;
}
aviOutput.write(fcc);
aviOutput.write(intBytes(swapInt(useLength)));
aviOutput.write(imagedata);
if (extra > 0) {
for (int i = 0; i < extra; i++)
aviOutput.write(0);
}
imagedata = null;
}
public void finishAVI() throws IOException
{
byte[] indexlistBytes = indexlist.toBytes();
aviOutput.write(indexlistBytes);
aviOutput.close();
long size = aviFile.length();
RandomAccessFile raf = new RandomAccessFile(aviFile, "rw");
raf.seek(4);
raf.write(intBytes(swapInt((int)size - 8)));
raf.seek(aviMovieOffset+4);
raf.write(intBytes(swapInt((int)(size - 8 - aviMovieOffset - indexlistBytes.length))));
raf.close();
}
public void finishAVI() throws IOException {
byte[] indexlistBytes = indexlist.toBytes();
aviOutput.write(indexlistBytes);
aviOutput.close();
long size = aviFile.length();
RandomAccessFile raf = new RandomAccessFile(aviFile.conv(), "rw");
raf.seek(4);
raf.write(intBytes(swapInt((int) size - 8)));
raf.seek(aviMovieOffset + 4);
raf.write(intBytes(swapInt((int) (size - 8 - aviMovieOffset - indexlistBytes.length))));
raf.close();
}
// public void writeAVI(File file) throws Exception
// {
// OutputStream os = new FileOutputStream(file);
// OutputStream os = SecurityUtils.FileOutputStream(file);
//
// // RIFFHeader
// // AVIMainHeader
@ -126,450 +117,375 @@ public class MJPEGGenerator
// // write 00db and image bytes...
// }
public static int swapInt(int v)
{
return (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
}
public static int swapInt(int v) {
return (v >>> 24) | (v << 24) | ((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
}
public static short swapShort(short v)
{
return (short)((v >>> 8) | (v << 8));
}
public static short swapShort(short v) {
return (short) ((v >>> 8) | (v << 8));
}
public static byte[] intBytes(int i)
{
byte[] b = new byte[4];
b[0] = (byte)(i >>> 24);
b[1] = (byte)((i >>> 16) & 0x000000FF);
b[2] = (byte)((i >>> 8) & 0x000000FF);
b[3] = (byte)(i & 0x000000FF);
public static byte[] intBytes(int i) {
byte[] b = new byte[4];
b[0] = (byte) (i >>> 24);
b[1] = (byte) ((i >>> 16) & 0x000000FF);
b[2] = (byte) ((i >>> 8) & 0x000000FF);
b[3] = (byte) (i & 0x000000FF);
return b;
}
return b;
}
public static byte[] shortBytes(short i)
{
byte[] b = new byte[2];
b[0] = (byte)(i >>> 8);
b[1] = (byte)(i & 0x000000FF);
public static byte[] shortBytes(short i) {
byte[] b = new byte[2];
b[0] = (byte) (i >>> 8);
b[1] = (byte) (i & 0x000000FF);
return b;
}
return b;
}
private class RIFFHeader
{
public byte[] fcc = new byte[]{'R','I','F','F'};
public int fileSize = 0;
public byte[] fcc2 = new byte[]{'A','V','I',' '};
public byte[] fcc3 = new byte[]{'L','I','S','T'};
public int listSize = 200;
public byte[] fcc4 = new byte[]{'h','d','r','l'};
private class RIFFHeader {
public byte[] fcc = new byte[] { 'R', 'I', 'F', 'F' };
public int fileSize = 0;
public byte[] fcc2 = new byte[] { 'A', 'V', 'I', ' ' };
public byte[] fcc3 = new byte[] { 'L', 'I', 'S', 'T' };
public int listSize = 200;
public byte[] fcc4 = new byte[] { 'h', 'd', 'r', 'l' };
public RIFFHeader()
{
public RIFFHeader() {
}
}
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(fileSize)));
baos.write(fcc2);
baos.write(fcc3);
baos.write(intBytes(swapInt(listSize)));
baos.write(fcc4);
baos.close();
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(fileSize)));
baos.write(fcc2);
baos.write(fcc3);
baos.write(intBytes(swapInt(listSize)));
baos.write(fcc4);
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIMainHeader
{
/*
*
FOURCC fcc;
DWORD cb;
DWORD dwMicroSecPerFrame;
DWORD dwMaxBytesPerSec;
DWORD dwPaddingGranularity;
DWORD dwFlags;
DWORD dwTotalFrames;
DWORD dwInitialFrames;
DWORD dwStreams;
DWORD dwSuggestedBufferSize;
DWORD dwWidth;
DWORD dwHeight;
DWORD dwReserved[4];
*/
private class AVIMainHeader {
/*
*
* FOURCC fcc; DWORD cb; DWORD dwMicroSecPerFrame; DWORD dwMaxBytesPerSec; DWORD
* dwPaddingGranularity; DWORD dwFlags; DWORD dwTotalFrames; DWORD
* dwInitialFrames; DWORD dwStreams; DWORD dwSuggestedBufferSize; DWORD dwWidth;
* DWORD dwHeight; DWORD dwReserved[4];
*/
public byte[] fcc = new byte[]{'a','v','i','h'};
public int cb = 56;
public int dwMicroSecPerFrame = 0; // (1 / frames per sec) * 1,000,000
public int dwMaxBytesPerSec = 10000000;
public int dwPaddingGranularity = 0;
public int dwFlags = 65552;
public int dwTotalFrames = 0; // replace with correct value
public int dwInitialFrames = 0;
public int dwStreams = 1;
public int dwSuggestedBufferSize = 0;
public int dwWidth = 0; // replace with correct value
public int dwHeight = 0; // replace with correct value
public int[] dwReserved = new int[4];
public byte[] fcc = new byte[] { 'a', 'v', 'i', 'h' };
public int cb = 56;
public int dwMicroSecPerFrame = 0; // (1 / frames per sec) * 1,000,000
public int dwMaxBytesPerSec = 10000000;
public int dwPaddingGranularity = 0;
public int dwFlags = 65552;
public int dwTotalFrames = 0; // replace with correct value
public int dwInitialFrames = 0;
public int dwStreams = 1;
public int dwSuggestedBufferSize = 0;
public int dwWidth = 0; // replace with correct value
public int dwHeight = 0; // replace with correct value
public int[] dwReserved = new int[4];
public AVIMainHeader()
{
dwMicroSecPerFrame = (int)((1.0/framerate)*1000000.0);
dwWidth = width;
dwHeight = height;
dwTotalFrames = numFrames;
}
public AVIMainHeader() {
dwMicroSecPerFrame = (int) ((1.0 / framerate) * 1000000.0);
dwWidth = width;
dwHeight = height;
dwTotalFrames = numFrames;
}
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(intBytes(swapInt(dwMicroSecPerFrame)));
baos.write(intBytes(swapInt(dwMaxBytesPerSec)));
baos.write(intBytes(swapInt(dwPaddingGranularity)));
baos.write(intBytes(swapInt(dwFlags)));
baos.write(intBytes(swapInt(dwTotalFrames)));
baos.write(intBytes(swapInt(dwInitialFrames)));
baos.write(intBytes(swapInt(dwStreams)));
baos.write(intBytes(swapInt(dwSuggestedBufferSize)));
baos.write(intBytes(swapInt(dwWidth)));
baos.write(intBytes(swapInt(dwHeight)));
baos.write(intBytes(swapInt(dwReserved[0])));
baos.write(intBytes(swapInt(dwReserved[1])));
baos.write(intBytes(swapInt(dwReserved[2])));
baos.write(intBytes(swapInt(dwReserved[3])));
baos.close();
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(intBytes(swapInt(dwMicroSecPerFrame)));
baos.write(intBytes(swapInt(dwMaxBytesPerSec)));
baos.write(intBytes(swapInt(dwPaddingGranularity)));
baos.write(intBytes(swapInt(dwFlags)));
baos.write(intBytes(swapInt(dwTotalFrames)));
baos.write(intBytes(swapInt(dwInitialFrames)));
baos.write(intBytes(swapInt(dwStreams)));
baos.write(intBytes(swapInt(dwSuggestedBufferSize)));
baos.write(intBytes(swapInt(dwWidth)));
baos.write(intBytes(swapInt(dwHeight)));
baos.write(intBytes(swapInt(dwReserved[0])));
baos.write(intBytes(swapInt(dwReserved[1])));
baos.write(intBytes(swapInt(dwReserved[2])));
baos.write(intBytes(swapInt(dwReserved[3])));
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIStreamList
{
public byte[] fcc = new byte[]{'L','I','S','T'};
public int size = 124;
public byte[] fcc2 = new byte[]{'s','t','r','l'};
private class AVIStreamList {
public byte[] fcc = new byte[] { 'L', 'I', 'S', 'T' };
public int size = 124;
public byte[] fcc2 = new byte[] { 's', 't', 'r', 'l' };
public AVIStreamList()
{
public AVIStreamList() {
}
}
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(size)));
baos.write(fcc2);
baos.close();
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(size)));
baos.write(fcc2);
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIStreamHeader
{
/*
FOURCC fcc;
DWORD cb;
FOURCC fccType;
FOURCC fccHandler;
DWORD dwFlags;
WORD wPriority;
WORD wLanguage;
DWORD dwInitialFrames;
DWORD dwScale;
DWORD dwRate;
DWORD dwStart;
DWORD dwLength;
DWORD dwSuggestedBufferSize;
DWORD dwQuality;
DWORD dwSampleSize;
struct {
short int left;
short int top;
short int right;
short int bottom;
} rcFrame;
*/
private class AVIStreamHeader {
/*
* FOURCC fcc; DWORD cb; FOURCC fccType; FOURCC fccHandler; DWORD dwFlags; WORD
* wPriority; WORD wLanguage; DWORD dwInitialFrames; DWORD dwScale; DWORD
* dwRate; DWORD dwStart; DWORD dwLength; DWORD dwSuggestedBufferSize; DWORD
* dwQuality; DWORD dwSampleSize; struct { short int left; short int top; short
* int right; short int bottom; } rcFrame;
*/
public byte[] fcc = new byte[]{'s','t','r','h'};
public int cb = 64;
public byte[] fccType = new byte[]{'v','i','d','s'};
public byte[] fccHandler = new byte[]{'M','J','P','G'};
public int dwFlags = 0;
public short wPriority = 0;
public short wLanguage = 0;
public int dwInitialFrames = 0;
public int dwScale = 0; // microseconds per frame
public int dwRate = 1000000; // dwRate / dwScale = frame rate
public int dwStart = 0;
public int dwLength = 0; // num frames
public int dwSuggestedBufferSize = 0;
public int dwQuality = -1;
public int dwSampleSize = 0;
public int left = 0;
public int top = 0;
public int right = 0;
public int bottom = 0;
public byte[] fcc = new byte[] { 's', 't', 'r', 'h' };
public int cb = 64;
public byte[] fccType = new byte[] { 'v', 'i', 'd', 's' };
public byte[] fccHandler = new byte[] { 'M', 'J', 'P', 'G' };
public int dwFlags = 0;
public short wPriority = 0;
public short wLanguage = 0;
public int dwInitialFrames = 0;
public int dwScale = 0; // microseconds per frame
public int dwRate = 1000000; // dwRate / dwScale = frame rate
public int dwStart = 0;
public int dwLength = 0; // num frames
public int dwSuggestedBufferSize = 0;
public int dwQuality = -1;
public int dwSampleSize = 0;
public int left = 0;
public int top = 0;
public int right = 0;
public int bottom = 0;
public AVIStreamHeader()
{
dwScale = (int)((1.0/framerate)*1000000.0);
dwLength = numFrames;
}
public AVIStreamHeader() {
dwScale = (int) ((1.0 / framerate) * 1000000.0);
dwLength = numFrames;
}
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(fccType);
baos.write(fccHandler);
baos.write(intBytes(swapInt(dwFlags)));
baos.write(shortBytes(swapShort(wPriority)));
baos.write(shortBytes(swapShort(wLanguage)));
baos.write(intBytes(swapInt(dwInitialFrames)));
baos.write(intBytes(swapInt(dwScale)));
baos.write(intBytes(swapInt(dwRate)));
baos.write(intBytes(swapInt(dwStart)));
baos.write(intBytes(swapInt(dwLength)));
baos.write(intBytes(swapInt(dwSuggestedBufferSize)));
baos.write(intBytes(swapInt(dwQuality)));
baos.write(intBytes(swapInt(dwSampleSize)));
baos.write(intBytes(swapInt(left)));
baos.write(intBytes(swapInt(top)));
baos.write(intBytes(swapInt(right)));
baos.write(intBytes(swapInt(bottom)));
baos.close();
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(fccType);
baos.write(fccHandler);
baos.write(intBytes(swapInt(dwFlags)));
baos.write(shortBytes(swapShort(wPriority)));
baos.write(shortBytes(swapShort(wLanguage)));
baos.write(intBytes(swapInt(dwInitialFrames)));
baos.write(intBytes(swapInt(dwScale)));
baos.write(intBytes(swapInt(dwRate)));
baos.write(intBytes(swapInt(dwStart)));
baos.write(intBytes(swapInt(dwLength)));
baos.write(intBytes(swapInt(dwSuggestedBufferSize)));
baos.write(intBytes(swapInt(dwQuality)));
baos.write(intBytes(swapInt(dwSampleSize)));
baos.write(intBytes(swapInt(left)));
baos.write(intBytes(swapInt(top)));
baos.write(intBytes(swapInt(right)));
baos.write(intBytes(swapInt(bottom)));
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIStreamFormat
{
/*
FOURCC fcc;
DWORD cb;
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
*/
private class AVIStreamFormat {
/*
* FOURCC fcc; DWORD cb; DWORD biSize; LONG biWidth; LONG biHeight; WORD
* biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG
* biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant;
*/
public byte[] fcc = new byte[]{'s','t','r','f'};
public int cb = 40;
public int biSize = 40; // same as cb
public int biWidth = 0;
public int biHeight = 0;
public short biPlanes = 1;
public short biBitCount = 24;
public byte[] biCompression = new byte[]{'M','J','P','G'};
public int biSizeImage = 0; // width x height in pixels
public int biXPelsPerMeter = 0;
public int biYPelsPerMeter = 0;
public int biClrUsed = 0;
public int biClrImportant = 0;
public byte[] fcc = new byte[] { 's', 't', 'r', 'f' };
public int cb = 40;
public int biSize = 40; // same as cb
public int biWidth = 0;
public int biHeight = 0;
public short biPlanes = 1;
public short biBitCount = 24;
public byte[] biCompression = new byte[] { 'M', 'J', 'P', 'G' };
public int biSizeImage = 0; // width x height in pixels
public int biXPelsPerMeter = 0;
public int biYPelsPerMeter = 0;
public int biClrUsed = 0;
public int biClrImportant = 0;
public AVIStreamFormat() {
biWidth = width;
biHeight = height;
biSizeImage = width * height;
}
public AVIStreamFormat()
{
biWidth = width;
biHeight = height;
biSizeImage = width * height;
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(intBytes(swapInt(biSize)));
baos.write(intBytes(swapInt(biWidth)));
baos.write(intBytes(swapInt(biHeight)));
baos.write(shortBytes(swapShort(biPlanes)));
baos.write(shortBytes(swapShort(biBitCount)));
baos.write(biCompression);
baos.write(intBytes(swapInt(biSizeImage)));
baos.write(intBytes(swapInt(biXPelsPerMeter)));
baos.write(intBytes(swapInt(biYPelsPerMeter)));
baos.write(intBytes(swapInt(biClrUsed)));
baos.write(intBytes(swapInt(biClrImportant)));
baos.close();
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
baos.write(intBytes(swapInt(biSize)));
baos.write(intBytes(swapInt(biWidth)));
baos.write(intBytes(swapInt(biHeight)));
baos.write(shortBytes(swapShort(biPlanes)));
baos.write(shortBytes(swapShort(biBitCount)));
baos.write(biCompression);
baos.write(intBytes(swapInt(biSizeImage)));
baos.write(intBytes(swapInt(biXPelsPerMeter)));
baos.write(intBytes(swapInt(biYPelsPerMeter)));
baos.write(intBytes(swapInt(biClrUsed)));
baos.write(intBytes(swapInt(biClrImportant)));
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIMovieList {
public byte[] fcc = new byte[] { 'L', 'I', 'S', 'T' };
public int listSize = 0;
public byte[] fcc2 = new byte[] { 'm', 'o', 'v', 'i' };
// 00db size jpg image data ...
private class AVIMovieList
{
public byte[] fcc = new byte[]{'L','I','S','T'};
public int listSize = 0;
public byte[] fcc2 = new byte[]{'m','o','v','i'};
// 00db size jpg image data ...
public AVIMovieList() {
public AVIMovieList()
{
}
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(listSize)));
baos.write(fcc2);
baos.close();
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(listSize)));
baos.write(fcc2);
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIIndexList {
public byte[] fcc = new byte[] { 'i', 'd', 'x', '1' };
public int cb = 0;
public ArrayList ind = new ArrayList();
private class AVIIndexList
{
public byte[] fcc = new byte[]{'i','d','x','1'};
public int cb = 0;
public ArrayList ind = new ArrayList();
public AVIIndexList() {
public AVIIndexList()
{
}
}
public void addAVIIndex(AVIIndex ai) {
ind.add(ai);
}
public void addAVIIndex(AVIIndex ai)
{
ind.add(ai);
}
public void addAVIIndex(int dwOffset, int dwSize) {
ind.add(new AVIIndex(dwOffset, dwSize));
}
public void addAVIIndex(int dwOffset, int dwSize)
{
ind.add(new AVIIndex(dwOffset, dwSize));
}
public byte[] toBytes() throws IOException {
cb = 16 * ind.size();
public byte[] toBytes() throws IOException
{
cb = 16 * ind.size();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
for (int i = 0; i < ind.size(); i++) {
AVIIndex in = (AVIIndex) ind.get(i);
baos.write(in.toBytes());
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(cb)));
for(int i = 0; i < ind.size(); i++)
{
AVIIndex in = (AVIIndex)ind.get(i);
baos.write(in.toBytes());
}
baos.close();
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIIndex {
public byte[] fcc = new byte[] { '0', '0', 'd', 'b' };
public int dwFlags = 16;
public int dwOffset = 0;
public int dwSize = 0;
private class AVIIndex
{
public byte[] fcc = new byte[]{'0','0','d','b'};
public int dwFlags = 16;
public int dwOffset = 0;
public int dwSize = 0;
public AVIIndex(int dwOffset, int dwSize) {
this.dwOffset = dwOffset;
this.dwSize = dwSize;
}
public AVIIndex(int dwOffset, int dwSize)
{
this.dwOffset = dwOffset;
this.dwSize = dwSize;
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(dwFlags)));
baos.write(intBytes(swapInt(dwOffset)));
baos.write(intBytes(swapInt(dwSize)));
baos.close();
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(dwFlags)));
baos.write(intBytes(swapInt(dwOffset)));
baos.write(intBytes(swapInt(dwSize)));
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private class AVIJunk {
public byte[] fcc = new byte[] { 'J', 'U', 'N', 'K' };
public int size = 1808;
public byte[] data = new byte[size];
private class AVIJunk
{
public byte[] fcc = new byte[]{'J','U','N','K'};
public int size = 1808;
public byte[] data = new byte[size];
public AVIJunk() {
Arrays.fill(data, (byte) 0);
}
public AVIJunk()
{
Arrays.fill(data,(byte)0);
}
public byte[] toBytes() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(size)));
baos.write(data);
baos.close();
public byte[] toBytes() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(fcc);
baos.write(intBytes(swapInt(size)));
baos.write(data);
baos.close();
return baos.toByteArray();
}
}
return baos.toByteArray();
}
}
private byte[] writeImageToBytes(Image image) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Graphics2D g = bi.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
ImageIO.write(bi, "jpg", baos);
baos.close();
bi = null;
g = null;
private byte[] writeImageToBytes(Image image) throws IOException
{
BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Graphics2D g = bi.createGraphics();
g.drawImage(image,0,0,width,height,null);
ImageIO.write(bi,"jpg",baos);
baos.close();
bi = null;
g = null;
return baos.toByteArray();
}
return baos.toByteArray();
}
public static void main(String[] args) throws Exception
{
double framerate = 12.0;
double transitionDuration = 1; // seconds
double slideDuration = 3; // seconds
File photoDir = new File(args[0]);
File[] files = photoDir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
if(StringUtils.goLowerCase(name).endsWith("jpg"))
return true;
return false;
}
});
int numFrames = (int)(files.length * framerate * (slideDuration + transitionDuration) + (transitionDuration * framerate));
MJPEGGenerator m = new MJPEGGenerator(new File(args[1]), 640, 480, framerate, numFrames);
for(int i = 0; i < files.length; i++)
{
System.out.println("processing file "+i);
ImageIcon ii = new ImageIcon(files[i].getCanonicalPath());
m.addImage(ii.getImage());
}
m.finishAVI();
}
// public static void main(String[] args) throws Exception {
// double framerate = 12.0;
// double transitionDuration = 1; // seconds
// double slideDuration = 3; // seconds
//
// File photoDir = SecurityUtils.file(args[0]);
// File[] files = photoDir.listFiles(new FilenameFilter() {
// public boolean accept(java.io.File dir, String name) {
// if (StringUtils.goLowerCase(name).endsWith("jpg"))
// return true;
// return false;
// }
// });
//
// int numFrames = (int) (files.length * framerate * (slideDuration + transitionDuration)
// + (transitionDuration * framerate));
// MJPEGGenerator m = new MJPEGGenerator(SecurityUtils.file(args[1]), 640, 480, framerate, numFrames);
// for (int i = 0; i < files.length; i++) {
// System.out.println("processing file " + i);
// ImageIcon ii = new ImageIcon(files[i].getCanonicalPath());
// m.addImage(ii.getImage());
// }
// m.finishAVI();
// }
}

View File

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

View File

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

View File

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

View File

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

View File

@ -35,12 +35,11 @@
*/
package net.sourceforge.plantuml.png;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
@ -48,12 +47,20 @@ import javax.imageio.stream.ImageInputStream;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class MetadataTag {
private final Object source;
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.tag = tag;
}

View File

@ -36,21 +36,18 @@
package net.sourceforge.plantuml.png;
import java.awt.image.RenderedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.security.ImageIO;
import net.sourceforge.plantuml.security.SFile;
public class PngIO {
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);
}
@ -58,10 +55,10 @@ public class PngIO {
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;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
os = file.createBufferedOutputStream();
write(image, os, metadata, dpi);
} finally {
if (os != null) {

View File

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

View File

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

View File

@ -37,10 +37,7 @@ package net.sourceforge.plantuml.posimo;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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.GraphvizUtils;
import net.sourceforge.plantuml.cucadiagram.dot.ProcessState;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.svek.MinFinder;
import net.sourceforge.plantuml.svek.SvgResult;
import net.sourceforge.plantuml.svek.YDelta;
@ -59,10 +57,10 @@ import net.sourceforge.plantuml.svek.YDelta;
public class GraphvizSolverB {
// 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;
// try {
// pw = new PrintWriter(new FileWriter(f));
// pw = SecurityUtils.PrintWriter(new FileWriter(f));
// pw.print(dotString);
// Log.info("Creating file " + f);
// } finally {
@ -73,10 +71,10 @@ public class GraphvizSolverB {
// }
//
// 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;
// try {
// pw = new PrintWriter(new FileWriter(f));
// pw = SecurityUtils.PrintWriter(new FileWriter(f));
// pw.print(svg);
// Log.info("Creating file " + f);
// } finally {
@ -97,7 +95,7 @@ public class GraphvizSolverB {
// 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 ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -222,9 +220,9 @@ public class GraphvizSolverB {
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 OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
final OutputStream os = f.createBufferedOutputStream();
final ProcessState state = graphviz.createFile3(os);
os.close();
if (state.differs(ProcessState.TERMINATED_OK())) {

View File

@ -35,7 +35,6 @@
*/
package net.sourceforge.plantuml.preproc;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
@ -53,6 +52,9 @@ import java.util.regex.Pattern;
import net.sourceforge.plantuml.AParentFolder;
import net.sourceforge.plantuml.Log;
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.TMemory;
import net.sourceforge.plantuml.tim.TVariableScope;
@ -106,14 +108,31 @@ public class Defines implements Truth {
return result;
}
public static Defines createWithFileName(File file) {
public static Defines createWithFileName(SFile file) {
if (file == null) {
throw new IllegalArgumentException();
}
final Defines result = createEmpty();
result.overrideFilename(file.getName());
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;
}

View File

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

View File

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

View File

@ -39,10 +39,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.StringLocated;
import net.sourceforge.plantuml.security.SURL;
import net.sourceforge.plantuml.utils.StartUtils;
public class StartDiagramExtractReader implements ReadLine {
@ -54,7 +54,7 @@ public class StartDiagramExtractReader implements ReadLine {
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);
}
@ -117,16 +117,18 @@ public class StartDiagramExtractReader implements ReadLine {
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 {
final InputStream tmp = url.openStream();
if (tmp == null) {
return new ReadLineSimple(s, "Cannot connect");
}
if (charset == null) {
Log.info("Using default charset");
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(url.openStream()),
url.toString()));
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(tmp), url.toString()));
}
Log.info("Using charset " + charset);
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(url.openStream(), charset),
url.toString()));
return new UncommentReadLine(ReadLineReader.create(new InputStreamReader(tmp, charset), url.toString()));
} catch (IOException e) {
return new ReadLineSimple(s, e.toString());
}
@ -137,7 +139,7 @@ public class StartDiagramExtractReader implements ReadLine {
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);
return containsStartDiagram(r);
}

View File

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

View File

@ -39,7 +39,6 @@ package net.sourceforge.plantuml.preproc2;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
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.StartDiagramExtractReader;
import net.sourceforge.plantuml.preproc.Stdlib;
import net.sourceforge.plantuml.security.SURL;
import net.sourceforge.plantuml.tim.EaterException;
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 {
try {
if (StartDiagramExtractReader.containsStartDiagram(url, s, charset)) {
return StartDiagramExtractReader.build(url, s, suf, charset);
}
final InputStream is = url.openStream();
if (is == null) {
throw EaterException.located("Cannot open URL");
}
if (charset == null) {
Log.info("Using default charset");
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