From: zapata Date: Sun, 18 Sep 2005 15:01:27 +0000 (+0000) Subject: misc. fixes X-Git-Tag: LATEST_MERGED_1_1~97 X-Git-Url: http://erislabs.net/gitweb/?p=mir.git;a=commitdiff_plain;h=1f0ad3f2013909116569c243abbc02dde6c7161a misc. fixes --- diff --git a/source/mir/media/image/ImageMagickImageProcessor.java b/source/mir/media/image/ImageMagickImageProcessor.java index 38386347..9db2f474 100755 --- a/source/mir/media/image/ImageMagickImageProcessor.java +++ b/source/mir/media/image/ImageMagickImageProcessor.java @@ -41,20 +41,19 @@ import java.io.*; 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 , 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; @@ -65,98 +64,112 @@ public class ImageMagickImageProcessor implements ImageProcessor * 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; @@ -164,29 +177,33 @@ public class ImageMagickImageProcessor implements ImageProcessor } 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(); @@ -195,15 +212,13 @@ public class ImageMagickImageProcessor implements ImageProcessor /** * 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; } @@ -215,53 +230,50 @@ public class ImageMagickImageProcessor implements ImageProcessor 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()); + } } } @@ -269,18 +281,20 @@ public class ImageMagickImageProcessor implements ImageProcessor /** * 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(); } @@ -301,37 +315,35 @@ public class ImageMagickImageProcessor implements ImageProcessor 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(); @@ -339,8 +351,18 @@ public class ImageMagickImageProcessor implements ImageProcessor 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); diff --git a/source/mir/misc/StringUtil.java b/source/mir/misc/StringUtil.java index b05c748f..11b599fa 100755 --- a/source/mir/misc/StringUtil.java +++ b/source/mir/misc/StringUtil.java @@ -41,7 +41,7 @@ import java.util.TimeZone; /** * 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 * */ @@ -260,7 +260,7 @@ public final class StringUtil { * in den html-tag

* 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

"); } @@ -269,7 +269,7 @@ public final class StringUtil { * in den html-tag
* 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
"); } @@ -278,7 +278,7 @@ public final class StringUtil { * 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,"$0"); } @@ -288,7 +288,7 @@ public final class StringUtil { * 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," $0"); } @@ -298,7 +298,7 @@ public final class StringUtil { * 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,"$0"); } @@ -311,7 +311,7 @@ public final class StringUtil { * @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," $0"); } @@ -328,51 +328,17 @@ public final class StringUtil { * @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 @@ -394,8 +360,9 @@ public final class StringUtil { 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; } @@ -403,7 +370,6 @@ public final class StringUtil { * 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(); diff --git a/source/mir/util/ExecFunctions.java b/source/mir/util/ExecFunctions.java index bc6d8647..34ce35da 100755 --- a/source/mir/util/ExecFunctions.java +++ b/source/mir/util/ExecFunctions.java @@ -34,18 +34,15 @@ import java.io.IOException; /** * 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)); } @@ -55,27 +52,25 @@ public class ExecFunctions * 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; } @@ -85,22 +80,21 @@ public class ExecFunctions * 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); } } - + } diff --git a/source/mir/util/FileRoutines.java b/source/mir/util/FileRoutines.java index 4c414b0a..32a964a4 100755 --- a/source/mir/util/FileRoutines.java +++ b/source/mir/util/FileRoutines.java @@ -31,14 +31,7 @@ package mir.util; 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; @@ -49,28 +42,29 @@ public class FileRoutines { 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(); @@ -81,6 +75,9 @@ public class FileRoutines { } } + /** + * Copy a directory recursively + */ public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException { int i; File sourceFile; @@ -90,9 +87,9 @@ public class FileRoutines { if (!aDestinationDirectory.exists()) aDestinationDirectory.mkdirs(); - for (i=0; i0) { + int count = inputStream.read(buffer); + while (count > 0) { outputStream.write(buffer, 0, count); - count=inputStream.read(buffer); + count = inputStream.read(buffer); } } finally { @@ -188,17 +193,17 @@ public class FileRoutines { * Return all files in a directory * * @param aDirectory The directory to list - * @param aFilter the filter to apply to files - * @return a List of filenames of type String + * @param aFilter the filter to apply to files + * @return a List of filenames of type String */ 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); } /** @@ -207,10 +212,10 @@ public class FileRoutines { */ 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) { @@ -222,7 +227,7 @@ public class FileRoutines { * {@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) { @@ -230,41 +235,27 @@ public class FileRoutines { 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 diff --git a/source/mir/util/HTTPClientHelper.java b/source/mir/util/HTTPClientHelper.java index be02f67e..84bee4f9 100755 --- a/source/mir/util/HTTPClientHelper.java +++ b/source/mir/util/HTTPClientHelper.java @@ -41,28 +41,28 @@ import org.apache.commons.httpclient.methods.GetMethod; 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(); diff --git a/source/mircoders/entity/EntityImages.java b/source/mircoders/entity/EntityImages.java index 0c8f28ef..21404d68 100755 --- a/source/mircoders/entity/EntityImages.java +++ b/source/mircoders/entity/EntityImages.java @@ -80,16 +80,16 @@ public class EntityImages extends EntityUploadedMedia 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(); } diff --git a/source/mircoders/global/ProducerEngine.java b/source/mircoders/global/ProducerEngine.java index 201183aa..d60345bd 100755 --- a/source/mircoders/global/ProducerEngine.java +++ b/source/mircoders/global/ProducerEngine.java @@ -273,6 +273,8 @@ public class ProducerEngine { } }; result = producer.execute(productionContext); + productionContext = null; + producer = null; try { MirGlobal.localizer().producers().afterProducerTask(factoryName, verb); } diff --git a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java index e0153914..5313a1d1 100755 --- a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java @@ -479,15 +479,14 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { 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) { @@ -513,8 +512,10 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { 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"); @@ -574,15 +575,14 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { 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()); diff --git a/source/mircoders/localizer/basic/MirBasicLocalizer.java b/source/mircoders/localizer/basic/MirBasicLocalizer.java index aeaa1b85..156cc1cb 100755 --- a/source/mircoders/localizer/basic/MirBasicLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicLocalizer.java @@ -31,8 +31,6 @@ package mircoders.localizer.basic; import mircoders.localizer.*; -import java.io.File; - public class MirBasicLocalizer implements MirLocalizer { public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc { diff --git a/source/mircoders/localizer/basic/MirBasicWriterEngine.java b/source/mircoders/localizer/basic/MirBasicWriterEngine.java index 693e19b1..8b248317 100755 --- a/source/mircoders/localizer/basic/MirBasicWriterEngine.java +++ b/source/mircoders/localizer/basic/MirBasicWriterEngine.java @@ -33,10 +33,15 @@ import mir.config.MirPropertiesConfiguration; 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;