import java.util.StringTokenizer;
-
/**
* Image processing by calling the ImageMagick command line progrmas
* "convert" and "identify". The main task of this class is to scale
* images. The path to ImageMagick commandline programs can be
* specified in the coonfiguration file.
+ *
* @author <grok@no-log.org>, the Mir-coders group
*/
-public class ImageMagickImageProcessor implements ImageProcessor
-{
- protected static MirPropertiesConfiguration configuration =
- MirPropertiesConfiguration.instance();
- static final LoggerWrapper logger =
- new LoggerWrapper("media.image.imagemagick");
+public class ImageMagickImageProcessor implements ImageProcessor {
+ protected static MirPropertiesConfiguration configuration =
+ MirPropertiesConfiguration.instance();
+ static final LoggerWrapper logger =
+ new LoggerWrapper("media.image.imagemagick");
private ImageFile sourceImage;
private ImageFile scaledImage;
* image. It can also scale images using ImageMagick. Intended for
* use in the ImageMagickImageProcessor class.
*/
- static class ImageFile
- {
- /** path to the file represented by this class */
+ static class ImageFile {
+ /**
+ * path to the file represented by this class
+ */
File file;
- /** whether the file must be deleted on cleanup */
- boolean fileIsTemp=false;
- /** image information is stored here to avoid multiple costly calls to
- * "identify" */
+ /**
+ * whether the file must be deleted on cleanup
+ */
+ boolean fileIsTemp = false;
+ /**
+ * image information is stored here to avoid multiple costly calls to
+ * "identify"
+ */
int width;
int height;
- /** Image type as returned by identify %m : "PNG", "GIF", ... */
+ /**
+ * Image type as returned by identify %m : "PNG", "GIF", ...
+ */
String type;
- /** number of scenes in image >1 (typically animated gif) */
+ /**
+ * number of scenes in image >1 (typically animated gif)
+ */
boolean isAnimation;
- /** Empty constructor automatically creates a temporary file
- * that will later hold an image */
- ImageFile() throws IOException
- {
- file=File.createTempFile("mirimage","");
- fileIsTemp=true;
+ /**
+ * Empty constructor automatically creates a temporary file
+ * that will later hold an image
+ */
+ ImageFile() throws IOException {
+ file = File.createTempFile("mirimage", "");
+ fileIsTemp = true;
}
- /** if the file doesn't already have an image in it
- * we don't want to read its information */
- ImageFile(File file,boolean doReadInfo) throws IOException
- {
- this.file=file;
- if(doReadInfo){readInfo();}
+
+ /**
+ * if the file doesn't already have an image in it
+ * we don't want to read its information
+ */
+ ImageFile(File file, boolean doReadInfo) throws IOException {
+ this.file = file;
+ if (doReadInfo) {
+ readInfo();
+ }
}
- ImageFile(File file) throws IOException
- {
- this(file,true);
+
+ ImageFile(File file) throws IOException {
+ this(file, true);
}
- /** delete temporary files */
- public void cleanup()
- {
+
+ /**
+ * delete temporary files
+ */
+ public void cleanup() {
logger.debug("ImageFile.cleanup()");
- if(fileIsTemp)
- {
- logger.debug("deleting:"+file);
+ if (fileIsTemp) {
+ logger.debug("deleting:" + file);
file.delete();
- file=null;
- fileIsTemp=false;
+ file = null;
+ fileIsTemp = false;
}
}
- void debugOutput()
- {
- logger.debug(" filename:"+file+
- " Info:"+
- " width:"+width+
- " height:"+height+
- " type:"+type+
- " isAnimation:"+isAnimation);
+
+ void debugOutput() {
+ logger.debug(" filename:" + file +
+ " Info:" +
+ " width:" + width +
+ " height:" + height +
+ " type:" + type +
+ " isAnimation:" + isAnimation);
}
- private void checkFile() throws IOException
- {
- if(file==null || !file.exists())
- {
- String message="ImageFile.checkFile file \""+file+
- "\" does not exist";
+
+ private void checkFile() throws IOException {
+ if (file == null || !file.exists()) {
+ String message = "ImageFile.checkFile file \"" + file +
+ "\" does not exist";
logger.error(message);
throw new IOException(message);
}
}
- /** Uses the imagemagick "identify" command to retreive image information */
- public void readInfo() throws IOException
- {
+ /**
+ * Uses the imagemagick "identify" command to retreive image information
+ */
+ public void readInfo() throws IOException {
checkFile();
- String infoString=ExecFunctions.execIntoString
- (getImageMagickPath()+
- "identify "+
- file.getAbsolutePath()+" "+
- "-format \"%w %h %m %n \"");// extra space, for multiframe (animations)
+ String infoString = ExecFunctions.execIntoString
+ (getImageMagickPath() +
+ "identify " +
+ file.getAbsolutePath() + " " +
+ "-format \"%w %h %m %n \"");// extra space, for multiframe (animations)
StringTokenizer st = new StringTokenizer(infoString);
- width =Integer.parseInt(st.nextToken());
- height =Integer.parseInt(st.nextToken());
- type = st.nextToken() ;
- isAnimation=Integer.parseInt(st.nextToken())>1;
- }
-
- public ImageFile scale(float aScalingFactor) throws IOException
- {
+ width = Integer.parseInt(st.nextToken());
+ height = Integer.parseInt(st.nextToken());
+ type = st.nextToken();
+ isAnimation = Integer.parseInt(st.nextToken()) > 1;
+ }
+
+ public ImageFile scale(float aScalingFactor) throws IOException {
logger.debug("ImageFile.scale");
checkFile();
- ImageFile result=new ImageFile();
- String command=getImageMagickPath()+"convert "+
- file.getAbsolutePath()+" "+
- "-scale "+
- new Float(aScalingFactor*100).toString()+"% "+
- result.file.getAbsolutePath();
- logger.debug("ImageFile.scale:command:"+command);
+ ImageFile result = new ImageFile();
+ String command = getImageMagickPath() + "convert " +
+ file.getAbsolutePath() + " " +
+ "-scale " +
+ Float.toString(aScalingFactor * 100) + "% " +
+ result.file.getAbsolutePath();
+ logger.debug("ImageFile.scale:command:" + command);
ExecFunctions.simpleExec(command);
result.readInfo();
return result;
}
public ImageMagickImageProcessor(InputStream inputImageStream)
- throws IOException
- {
+ throws IOException {
logger.debug("ImageMagickImageProcessor(stream)");
- sourceImage=new ImageFile();
- // copy stream into temporary file
- StreamCopier.copy(inputImageStream,new FileOutputStream(sourceImage.file));
+ sourceImage = new ImageFile();
+ // copy stream into temporary file
+
+ FileOutputStream outputStream = new FileOutputStream(sourceImage.file);
+ try {
+ StreamCopier.copy(inputImageStream, outputStream);
+ }
+ finally {
+ outputStream.close();
+ }
sourceImage.readInfo();
sourceImage.debugOutput();
}
- public ImageMagickImageProcessor(File aFile) throws IOException
- {
+ public ImageMagickImageProcessor(File aFile) throws IOException {
logger.debug("ImageMagickImageProcessor(file)");
- sourceImage=new ImageFile(aFile);
+ sourceImage = new ImageFile(aFile);
sourceImage.debugOutput();
}
/**
- * Deletes temporary files
+ * Deletes temporary files
*/
- public void cleanup()
- {
+ public void cleanup() {
logger.debug("ImageMagickImageProcessor.cleanup()");
sourceImage.cleanup();
scaledImage.cleanup();
/**
* Path to ImageMagick commandline programs
*/
- private static String getImageMagickPath()
- {
- String result=configuration.getString("Producer.Image.ImageMagickPath");
+ private static String getImageMagickPath() {
+ String result = configuration.getString("Producer.Image.ImageMagickPath");
// we want the path to finish by "/", so add it if it's missing
- if(result.length()!=0 && !result.endsWith("/"))
- {
- result=result.concat("/");
+ if (result.length() != 0 && !result.endsWith("/")) {
+ result = result.concat("/");
}
- logger.debug("getImageMagickPath:"+result);
+ logger.debug("getImageMagickPath:" + result);
return result;
}
descaleImage(aMaxSize, aMaxSize, aMinDescale, 0);
}
- public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc
- {
+ public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc {
descaleImage(aMaxSize, aMaxSize, 0, aMinResize);
}
- public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize)
- throws MediaExc
- {
+ public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize)
+ throws MediaExc {
descaleImage(aMaxSize, aMaxSize, aMinDescale, aMinResize);
}
- /** {@inheritDoc} */
- public void descaleImage(int aMaxWidth, int aMaxHeight,
- float aMinDescale, int aMinResize) throws MediaExc
- {
+ /**
+ * {@inheritDoc}
+ */
+ public void descaleImage(int aMaxWidth, int aMaxHeight,
+ float aMinDescale, int aMinResize) throws MediaExc {
float scale;
- logger.debug("descaleImage:"+
- " aMaxWidth:"+aMaxWidth+
- ", aMaxHeight:"+aMaxHeight+
- ", aMinDescale:"+aMinDescale+
- ", aMinResize:"+aMinResize);
- if ((aMaxWidth >0 && getWidth ()>aMaxWidth +aMinResize-1) ||
- (aMaxHeight>0 && getHeight()>aMaxHeight+aMinResize-1))
- {
+ logger.debug("descaleImage:" +
+ " aMaxWidth:" + aMaxWidth +
+ ", aMaxHeight:" + aMaxHeight +
+ ", aMinDescale:" + aMinDescale +
+ ", aMinResize:" + aMinResize);
+ if ((aMaxWidth > 0 && getWidth() > aMaxWidth + aMinResize - 1) ||
+ (aMaxHeight > 0 && getHeight() > aMaxHeight + aMinResize - 1)) {
logger.debug("descaleImage: image needs scaling");
- scale=1;
+ scale = 1;
- if (aMaxWidth>0 && getWidth()>aMaxWidth)
- {
+ if (aMaxWidth > 0 && getWidth() > aMaxWidth) {
scale = Math.min(scale, (float) aMaxWidth / (float) getWidth());
}
- if (aMaxHeight>0 && getHeight()>aMaxHeight)
- {
+ if (aMaxHeight > 0 && getHeight() > aMaxHeight) {
scale = Math.min(scale, (float) aMaxHeight / (float) getHeight());
}
- if (1-scale>aMinDescale)
- {
+ if (1 - scale > aMinDescale) {
scaleImage(scale);
}
- }
- else
- {
+ } else {
logger.debug("descaleImage: image size is ok, not scaling image");
- try{scaledImage=new ImageFile(sourceImage.file);}
- catch(IOException e){throw new MediaExc(e.toString());}
+ try {
+ scaledImage = new ImageFile(sourceImage.file);
+ }
+ catch (IOException e) {
+ throw new MediaExc(e.toString());
+ }
}
}
/**
* Scales image by a factor using the convert ImageMagick command
*/
- public void scaleImage(float aScalingFactor)
- throws MediaExc
- {
- logger.debug("scaleImage:"+aScalingFactor);
- try
- {
+ public void scaleImage(float aScalingFactor)
+ throws MediaExc {
+ logger.debug("scaleImage:" + aScalingFactor);
+ try {
// first cleanup previous temp scaledimage file if necesary
- if(scaledImage!=null){scaledImage.cleanup();}
+ if (scaledImage != null) {
+ scaledImage.cleanup();
+ }
// now create temp file and execute convert
- scaledImage=sourceImage.scale(aScalingFactor);
+ scaledImage = sourceImage.scale(aScalingFactor);
+ }
+ catch (Exception e) {
+ throw new MediaExc(e.toString());
}
- catch(Exception e){throw new MediaExc(e.toString());}
logger.debug(" scaledImage:");
scaledImage.debugOutput();
}
return scaledImage.height;
}
- public void writeScaledData(OutputStream aStream, String anImageType)
- throws MediaExc
- {
+ public void writeScaledData(OutputStream aStream, String anImageType)
+ throws MediaExc {
// we can't asume that requested "anImageType" is the same as the
// scaled image type, so we have to convert
- try
- {
+ try {
// if image is an animation and target type doesn't support
// animations, then just use first frame
- String frame="";
+ String frame = "";
scaledImage.debugOutput();
- if(scaledImage.isAnimation && !anImageType.equals("GIF"))
- {
- frame="[0]";
+ if (scaledImage.isAnimation && !anImageType.equals("GIF")) {
+ frame = "[0]";
}
// ImageMagick "convert" into temp file
- File temp=File.createTempFile("mirimage","");
- String command=getImageMagickPath()+"convert "+
- scaledImage.file.getAbsolutePath()+frame+" "+
- anImageType+":"+temp.getAbsolutePath();
- logger.debug("writeScaledData command:"+command);
+ File temp = File.createTempFile("mirimage", "");
+ String command = getImageMagickPath() + "convert " +
+ scaledImage.file.getAbsolutePath() + frame + " " +
+ anImageType + ":" + temp.getAbsolutePath();
+ logger.debug("writeScaledData command:" + command);
ExecFunctions.simpleExec(command);
// copy temp file into stream
- StreamCopier.copy(new FileInputStream(temp),aStream);
+ StreamCopier.copy(new FileInputStream(temp), aStream);
temp.delete();
}
- catch(Exception e){throw new MediaExc(e.toString());}
+ catch (Exception e) {
+ throw new MediaExc(e.toString());
+ }
}
- public byte[] getScaledData(String anImageType) throws MediaExc
- {
+ public byte[] getScaledData(String anImageType) throws MediaExc {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
writeScaledData(outputStream, anImageType);
return outputStream.toByteArray();
public void writeScaledData(File aFile, String anImageType) throws MediaExc {
try {
- writeScaledData(new BufferedOutputStream
- (new FileOutputStream(aFile),8192), anImageType);
+ OutputStream stream = new BufferedOutputStream(new FileOutputStream(aFile), 8192);
+
+ try {
+ writeScaledData(stream, anImageType);
+ }
+ finally {
+ try {
+ stream.close();
+ }
+ catch (Throwable t) {
+ }
+ }
}
catch (FileNotFoundException f) {
throw new MediaFailure(f);
/**
* Statische Hilfsmethoden zur Stringbehandlung
*
- * @version $Id: StringUtil.java,v 1.33.2.6 2005/02/10 16:22:30 rhindes Exp $
+ * @version $Id: StringUtil.java,v 1.33.2.7 2005/09/18 15:01:27 zapata Exp $
* @author mir-coders group
*
*/
* in den html-tag <p>
* nur sinnvoll, wenn text nicht im html-format eingegeben
*/
- public static String convertNewline2P(String haystack) {
+ private static String convertNewline2P(String haystack) {
return re_brbr2p.substituteAll(haystack,"\n</p><p>");
}
* in den html-tag <br>
* nur sinnvoll, wenn text nicht im html-format eingegeben
*/
- public static String convertNewline2Break(String haystack) {
+ private static String convertNewline2Break(String haystack) {
return re_newline2br.substituteAll(haystack,"$0<br />");
}
* in einen klickbaren link um
* nur sinnvoll, wenn text nicht im html-format eingegeben
*/
- public static String createMailLinks(String haystack) {
+ private static String createMailLinks(String haystack) {
return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
}
* in einen klickbaren link um
* nur sinnvoll, wenn text nicht im html-format eingegeben
*/
- public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
+ private static String createMailLinks(String haystack, String imageRoot, String mailImage) {
return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
}
* in einen klickbaren link um
* nur sinnvoll, wenn text nicht im html-format eingegeben
*/
- public static String createURLLinks(String haystack) {
+ private static String createURLLinks(String haystack) {
return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
}
* @param extImage the url of the icon to show next to the link
* @return a String containing the url
*/
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
+ private static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
if (title == null) {
return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
}
* @param intImage unused
* @return a String containing the url
*/
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
+ private static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
return createURLLinks(haystack, title, imageRoot, extImage);
}
/**
* this method deletes all html tags
*/
- public static final String removeHTMLTags(String haystack){
+ public static String removeHTMLTags(String haystack){
return re_tags.substituteAll(haystack,"");
}
- /**
- * this method deletes all but the approved tags html tags
- * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
- */
- public static String approveHTMLTags(String haystack){
- try {
- String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
- String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
- String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
-
- // kill all the bad tags that have attributes
- String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
- RE regex = new RE(s,RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the bad tags that are attributeless
- regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which have a javascript attribute like onLoad
- regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which include a url to an unacceptable protocol
- regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- return haystack;
- } catch(REException ex){
- ex.printStackTrace();
- return null;
- }
- }
-
/**
* createHTML ruft alle regex-methoden zum unwandeln eines nicht
public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
content=convertNewline2Break(content);
content=convertNewline2P(content);
- content=createMailLinks(content,producerDocRoot,mailImage);
- content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
+ content=createMailLinks(content, producerDocRoot,mailImage);
+ content=createURLLinks(content, null, producerDocRoot, extImage, intImage);
+
return content;
}
* Converts mir's horrible internal date format (yyyy-MM-dd HH:mm:ss+zz) into a java Date
*
* @param anInternalDate
- * @return
*/
public static Date convertMirInternalDateToDate(String anInternalDate) {
Calendar calendar = new GregorianCalendar();
/**
* Execute system commands. Warning: the current implementation is
- * unix specific.
+ * unix specific.
*/
-public class ExecFunctions
-{
+public class ExecFunctions {
/**
* Executes a full command (including arguments) in a subshell
* and returns the output of the command in a string. Output is
* redirected into a temporary fil which is then read into the string
*/
- public static String execIntoString(String command)
- throws IOException
- {
+ public static String execIntoString(String command) throws IOException {
return new String(execIntoByteArray(command));
}
* bytes. Output is redirected into a temporary file which is then
* read into an array of bytes
*/
- public static byte[] execIntoByteArray(String command)
- throws IOException
- {
- File commandOutput=File.createTempFile("mircmd","");
+ public static byte[] execIntoByteArray(String command) throws IOException {
+ File commandOutput = File.createTempFile("mircmd", "");
int exitStatus;
- try
- {
+ try {
// WARNING: unix specific
- exitStatus=Runtime.getRuntime().exec(new String[]{
- "/bin/sh","-c",
- command+" "+
- ">"+commandOutput.getAbsolutePath()
+ exitStatus = Runtime.getRuntime().exec(new String[]{
+ "/bin/sh", "-c",
+ command + " " +
+ ">" + commandOutput.getAbsolutePath()
}).waitFor();
}
- catch(InterruptedException e){ throw new IOException(e.toString());}
- if(exitStatus!=0)
- {
- throw new IOException("command exit satus:"+exitStatus);
+ catch (InterruptedException e) {
+ throw new IOException(e.toString());
}
- byte [] result = FileRoutines.readFileIntoByteArray
- (commandOutput.getAbsolutePath());
+ if (exitStatus != 0) {
+ throw new IOException("command exit satus:" + exitStatus);
+ }
+ byte[] result = FileRoutines.readFileIntoByteArray
+ (commandOutput.getAbsolutePath());
commandOutput.delete();
return result;
}
* Standard input and output go to /dev/null
*/
public static void simpleExec(String command)
- throws IOException
- {
+ throws IOException {
int exitStatus;
- try
- {
+ try {
// WARNING: unix specific
- exitStatus=Runtime.getRuntime().exec(new String[]{
- "/bin/sh","-c",
- command+" "+">/dev/null 2>/dev/null"
+ exitStatus = Runtime.getRuntime().exec(new String[]{
+ "/bin/sh", "-c",
+ command + " " + ">/dev/null 2>/dev/null"
}).waitFor();
}
- catch(InterruptedException e){ throw new IOException(e.toString());}
- if(exitStatus!=0)
- {
- throw new IOException("command exit satus:"+exitStatus);
+ catch (InterruptedException e) {
+ throw new IOException(e.toString());
+ }
+ if (exitStatus != 0) {
+ throw new IOException("command exit satus:" + exitStatus);
}
}
-
+
}
import gnu.regexp.RE;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
+import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
protected FileRoutines() {
}
+ /**
+ * Copy a file
+ */
public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException {
BufferedInputStream inputStream;
BufferedOutputStream outputStream;
int nrBytesRead;
byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE];
- inputStream = new BufferedInputStream(
- new FileInputStream(aSourceFile));
+ inputStream = new BufferedInputStream(new FileInputStream(aSourceFile));
try {
File directory = new File(aDestinationFile.getParent());
- if (directory!=null && !directory.exists()){
- directory.mkdirs();
+ if (directory != null && !directory.exists()) {
+ directory.mkdirs();
}
- outputStream = new BufferedOutputStream(
- new FileOutputStream(aDestinationFile),8192);
+ outputStream = new BufferedOutputStream(new FileOutputStream(aDestinationFile), 8192);
try {
do {
nrBytesRead = inputStream.read(buffer);
- if (nrBytesRead>0)
+ if (nrBytesRead > 0)
outputStream.write(buffer, 0, nrBytesRead);
}
- while (nrBytesRead>=0);
+ while (nrBytesRead >= 0);
}
finally {
outputStream.close();
}
}
+ /**
+ * Copy a directory recursively
+ */
public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException {
int i;
File sourceFile;
if (!aDestinationDirectory.exists())
aDestinationDirectory.mkdirs();
- for (i=0; i<files.length; i++) {
+ for (i = 0; i < files.length; i++) {
sourceFile = files[i];
- destinationFile=new File(aDestinationDirectory, sourceFile.getName());
+ destinationFile = new File(aDestinationDirectory, sourceFile.getName());
if (sourceFile.isDirectory()) {
if (!destinationFile.exists())
destinationFile.mkdir();
}
}
+ /**
+ * Copy a file or directory. If the source is a file and the destination
+ * a directory, the file is copied using the same file name into the\
+ * directory.
+ *
+ * @param aSource the source file
+ * @param aDestination the destination file
+ */
public static void copy(File aSource, File aDestination) throws IOException {
if (aSource.isDirectory()) {
copyDirectory(aSource, aDestination);
FileInputStream inputStream = new FileInputStream(aSource);
FileOutputStream outputStream = new FileOutputStream(aDestination);
try {
- int count=inputStream.read(buffer);
- while (count>0) {
+ int count = inputStream.read(buffer);
+ while (count > 0) {
outputStream.write(buffer, 0, count);
- count=inputStream.read(buffer);
+ count = inputStream.read(buffer);
}
}
finally {
* Return all files in a directory
*
* @param aDirectory The directory to list
- * @param aFilter the filter to apply to files
- * @return a <code>List</code> of filenames of type <code>String</code>
+ * @param aFilter the filter to apply to files
+ * @return a <code>List</code> of filenames of type <code>String</code>
*/
public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) {
Object[] contents = aDirectory.list(aFilter);
- if (contents==null) {
+ if (contents == null) {
return Collections.EMPTY_LIST;
}
- return Arrays.asList(contents);
+ return Arrays.asList(contents);
}
/**
*/
public static String getExtension(String aPath) {
int position = aPath.lastIndexOf('.');
- if (position>=0) {
- return aPath.substring(position+1);
+ if (position >= 0) {
+ return aPath.substring(position + 1);
}
- return "";
+ return "";
}
public static boolean isAbsolutePath(String aPath) {
* {@link File}.
*
* @param aBasePath The base path to use for relative paths
- * @param aPath The path to transform
+ * @param aPath The path to transform
* @return An absolute representation of the supplied path
*/
public static File getAbsoluteOrRelativeFile(File aBasePath, String aPath) {
return new File(aPath);
}
- return new File(aBasePath, aPath);
+ return new File(aBasePath, aPath);
}
/**
- * Reads the content of a file into a string
- *
- * TODO: The encoding to be used has not been taken into account: the routine now
- * assumes the file is encoded according to the JVM/platform default
- */
- public static String readFileIntoString(String fileName) throws IOException {
- return new String(readFileIntoByteArray(fileName));
- }
+ * Reads the content of a file into an array of bytes
+ */
+ public static byte[] readFileIntoByteArray(String fileName) throws IOException {
+ InputStream input = new FileInputStream(fileName);
+ ByteArrayOutputStream result = new ByteArrayOutputStream();
- /**
- * Reads the content of a file into an array of bytes
- *
- * TODO: add a loop: {@link java.io.InputStream#available()} is not
- * the total number of bytes left in the stream, but depends on buffering
- * etc.
- */
- public static byte[] readFileIntoByteArray(String fileName) throws IOException {
- InputStream input = new FileInputStream(fileName);
- int size= input.available();
- byte result[] = new byte[size];
- input.read(result);
+ IORoutines.copyStream(input, result);
- return result;
- }
+ return result.toByteArray();
+ }
/**
* Creates all parent directories of a file if they do not exist
*/
- public static void createParentDirectories(File aFile) {
- if (aFile.getParentFile()!=null && !aFile.getParentFile().exists()) {
- aFile.getParentFile().mkdirs();
- }
- }
- }
\ No newline at end of file
+ public static void createParentDirectories(File aFile) {
+ if (aFile.getParentFile() != null && !aFile.getParentFile().exists()) {
+ aFile.getParentFile().mkdirs();
+ }
+ }
+}
\ No newline at end of file
public class HTTPClientHelper {
private HttpClient client;
private HttpMethod method;
-
+
public HTTPClientHelper() {
- client = new HttpClient();
- client.setConnectionTimeout(5000);
- client.setTimeout(5000);
+ client = new HttpClient();
+ client.setConnectionTimeout(5000);
+ client.setTimeout(5000);
}
- public InputStream getUrl(String anUrl) throws UtilExc{
- try{
+ public InputStream getUrl(String anUrl) throws UtilExc {
+ try {
method = new GetMethod(anUrl);
method.setFollowRedirects(true);
method.setStrictMode(false);
client.executeMethod(method);
- InputStream inputStream = method.getResponseBodyAsStream();
+ InputStream inputStream = method.getResponseBodyAsStream();
return inputStream;
}
- catch (IOException e){
- throw new UtilExc(e.getMessage());
+ catch (IOException e) {
+ throw new UtilExc(e.getMessage());
}
}
-
+
public void releaseHTTPConnection() {
method.releaseConnection();
method.recycle();
processor.writeScaledData(imageData, type);
database.setBinaryField("image_data", getId(), imageData.toByteArray());
- setFieldValue("img_height", new Integer(processor.getScaledHeight()).toString());
- setFieldValue("img_width", new Integer(processor.getScaledWidth()).toString());
+ setFieldValue("img_height", Integer.toString(processor.getScaledHeight()));
+ setFieldValue("img_width", Integer.toString(processor.getScaledWidth()));
imageData.reset();
processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
processor.writeScaledData(imageData, type);
database.setBinaryField("icon_data", getId(), imageData.toByteArray());
- setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
- setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
+ setFieldValue("icon_height", Integer.toString(processor.getScaledHeight()));
+ setFieldValue("icon_width", Integer.toString(processor.getScaledWidth()));
processor.cleanup();
update();
}
}
};
result = producer.execute(productionContext);
+ productionContext = null;
+ producer = null;
try {
MirGlobal.localizer().producers().afterProducerTask(factoryName, verb);
}
public Object getValue(EntityAdapter anEntityAdapter) {
try {
- ArrayList extraTable = new ArrayList();
- extraTable.add("content_x_topic cxt");
+
String condition = "cxt.content_id="+anEntityAdapter.get("id")+
" and cxt.topic_id=t.id";
if (topicCondition!=null && topicCondition.length()>0)
condition = "(" + topicCondition + ") and " + condition;
- return anEntityAdapter.getComplexRelation("t", extraTable,
+ return anEntityAdapter.getComplexRelation("t", Collections.singletonList("content_x_topic cxt"),
condition, topicOrder, "topic" );
}
catch (Throwable t) {
try {
String condition = "cxm.content_id="+ anEntityAdapter.get("id") +
" and cxm.media_id = m.id";
- if (published)
+
+ if (published) {
condition = "is_published='t' and " + condition;
+ }
List extraTables = new ArrayList();
extraTables.add("content_x_media cxm");
public Object getValue(EntityAdapter anEntityAdapter) {
try {
- String condition = "cxm.comment_id="+ anEntityAdapter.get("id") +
- " and cxm.media_id = m.id";
- if (published)
- condition = "is_published='t' and " + condition;
+ String condition = "cxm.comment_id = " + anEntityAdapter.get("id") + " and cxm.media_id = m.id";
- List extraTables = new ArrayList();
- extraTables.add("comment_x_media cxm");
- return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);
+ if (published) {
+ condition = "is_published='t' and " + condition;
+ }
+ return anEntityAdapter.getComplexRelation("m", Collections.singletonList("comment_x_media cxm"),
+ condition, "id", definition);
}
catch (Throwable t) {
throw new RuntimeException(t.getMessage());
import mircoders.localizer.*;
-import java.io.File;
-
public class MirBasicLocalizer implements MirLocalizer {
public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc {
import mir.generator.WriterEngine;
import mir.log.LoggerWrapper;
import mir.util.FileRoutines;
-import mircoders.global.MirGlobal;
import mircoders.localizer.MirLocalizerFailure;
-import java.io.*;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.Writer;
public class MirBasicWriterEngine implements WriterEngine {
private String defaultEncoding;